package events import ( "context" "encoding/json/jsontext" json "encoding/json/v2" "fmt" "time" "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/events/internal/store" ) // The source and type of the event a schedule stores for each slot. const ( scheduleSource = "schedule" scheduleType = "schedule.tick" ) // minInterval keeps a schedule from firing faster than the dispatcher can use. const minInterval = time.Minute // scheduleCheck is how often Work looks for due slots. const scheduleCheck = 10 * time.Second // dueSlot returns the start of the latest slot of length every that began // after since and not after now. Slots are aligned to the clock, so every // process computes the same ones; slots missed while the process was down // collapse into this one. func dueSlot(now, since time.Time, every time.Duration) (time.Time, bool) { slot := now.Truncate(every) return slot, slot.After(since) } // tick stores the event for each schedule whose slot is due. The slot's start // is part of the source event id, so a restart or a second process storing the // same slot conflicts instead of firing twice. func (m *Module) tick(ctx context.Context, now time.Time) error { triggers, err := m.store.ScheduledTriggers(ctx, m.orgID) if err != nil { return err } for _, t := range triggers { slot, due := dueSlot(now, t.ScheduleSince.Time, time.Duration(t.ScheduleEverySeconds.Int64)*time.Second) if !due { continue } fields, err := json.Marshal(map[string]string{"trigger": t.Name, "slot": slot.UTC().Format(time.RFC3339)}) if err != nil { return fmt.Errorf("encode tick: %w", err) } isNew, err := m.inserter.Insert(ctx, tickEvent(m.orgID, t.Name, slot, fields)) if err != nil { return err } if isNew { m.log.InfoContext(ctx, "schedule fired", "trigger", t.Name, "slot", slot) } } return nil } func tickEvent(orgID, trigger string, slot time.Time, fields jsontext.Value) store.Event { e := store.Event{ ID: uuid.New(), OrgID: orgID, Source: scheduleSource, Type: scheduleType, SourceEventID: trigger + "@" + slot.UTC().Format(time.RFC3339), Fields: fields, } e.OccurredAt.Time, e.OccurredAt.Valid = slot, true return e }