Files
archie/modules/events/schedule.go
T

84 lines
2.6 KiB
Go

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"
)
// scheduleType is the type of the event a schedule stores for each slot. The
// event has no source.
const 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(scheduleFields(t.ID, slot))
if err != nil {
return fmt.Errorf("encode tick: %w", err)
}
isNew, err := m.inserter.Insert(ctx, tickEvent(m.orgID, t.ID, slot, fields))
if err != nil {
return err
}
if isNew {
m.log.InfoContext(ctx, "schedule fired", "trigger", t.ID, "slot", slot)
}
}
return nil
}
// scheduleFields are the fields of a schedule's tick. Every schedule's ticks
// share a type and have no source, so a scheduled trigger's filter matches its
// own id here.
func scheduleFields(trigger uuid.UUID, slot time.Time) map[string]string {
fields := scheduleFilter(trigger)
fields["slot"] = slot.UTC().Format(time.RFC3339)
return fields
}
// scheduleFilter is the filter of the scheduled trigger with the given id.
func scheduleFilter(trigger uuid.UUID) map[string]string {
return map[string]string{"trigger_id": trigger.String()}
}
func tickEvent(orgID string, trigger uuid.UUID, slot time.Time, fields jsontext.Value) store.Event {
e := store.Event{
ID: uuid.New(), OrgID: orgID, DeclaredEventType: scheduleType,
SourceEventID: trigger.String() + "@" + slot.UTC().Format(time.RFC3339), Fields: fields,
}
e.OccurredAt.Time, e.OccurredAt.Valid = slot, true
return e
}