diff --git a/modules/events/drafting.go b/modules/events/drafting.go new file mode 100644 index 000000000..6aa61d582 --- /dev/null +++ b/modules/events/drafting.go @@ -0,0 +1,92 @@ +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" +) + +// Group is a set of unmatched events that share a key, with the trigger it +// proposes. +type Group struct { + ID uuid.UUID + Source string + EventType string + Filter map[string]string + Count int64 + FirstSeen time.Time + LastSeen time.Time +} + +// Group returns the group id names, whether or not a trigger now covers it. +func (m *Module) Group(ctx context.Context, id uuid.UUID) (Group, bool, error) { + g, ok, err := m.store.GroupByID(ctx, m.orgID, id) + if err != nil || !ok { + return Group{}, false, err + } + var filter map[string]string + if err := json.Unmarshal(g.Filter, &filter); err != nil { + return Group{}, false, fmt.Errorf("group %s filter: %w", id, err) + } + return Group{ + ID: g.ID, Source: g.Source, EventType: g.EventType, Filter: filter, + Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen, + }, true, nil +} + +// Stored is an event as a run receives it: its id and the run input a trigger +// would have started a run with. +type Stored struct { + ID uuid.UUID + ReceivedAt time.Time + Input jsontext.Value +} + +// GroupEvents returns up to limit stored events of a group, newest first. +func (m *Module) GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]Stored, error) { + rows, err := m.store.GroupEvents(ctx, m.orgID, id, limit) + if err != nil { + return nil, err + } + out := make([]Stored, 0, len(rows)) + for _, e := range rows { + out = append(out, Stored{ID: e.ID, ReceivedAt: e.ReceivedAt, Input: runInput(e)}) + } + return out, nil +} + +// Replayed records that a dry run of a draft trigger replayed an event, so the +// run's trail names that event as its origin. +func (m *Module) Replayed(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error { + return m.store.RecordReplay(ctx, eventID, "draft:"+trigger, runID) +} + +// TriggerSpec is an event trigger to save. +type TriggerSpec struct { + Name string + Source string + EventType string + Filter map[string]string + Workflow string +} + +// SaveTrigger creates or replaces an event trigger. +func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error { + if !validName.MatchString(t.Name) || t.Source == "" || t.EventType == "" || t.Workflow == "" { + return fmt.Errorf("a trigger needs a lowercase name, a source, an event type and a workflow") + } + filter, err := json.Marshal(t.Filter) + if err != nil { + return fmt.Errorf("encode filter: %w", err) + } + return m.store.UpsertTrigger(ctx, store.Trigger{ + OrgID: m.orgID, Name: t.Name, Source: t.Source, EventType: t.EventType, + Filter: filter, Workflow: t.Workflow, Enabled: true, + }) +} diff --git a/modules/events/internal/store/drafting.go b/modules/events/internal/store/drafting.go new file mode 100644 index 000000000..02c23d7b2 --- /dev/null +++ b/modules/events/internal/store/drafting.go @@ -0,0 +1,51 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + + "github.com/google/uuid" +) + +// GroupByID returns one group, listed or not. +func (s *Store) GroupByID(ctx context.Context, orgID string, id uuid.UUID) (Group, bool, error) { + var g Group + err := s.db.GetContext(ctx, &g, ` + SELECT id, source, event_type, filter, count, first_seen, last_seen + FROM events.groups WHERE org_id = $1 AND id = $2`, orgID, id) + if errors.Is(err, sql.ErrNoRows) { + return Group{}, false, nil + } + if err != nil { + return Group{}, false, fmt.Errorf("read group: %w", err) + } + return g, true, nil +} + +// GroupEvents returns the stored events of a group, newest first. +func (s *Store) GroupEvents(ctx context.Context, orgID string, id uuid.UUID, limit int) ([]Event, error) { + var out []Event + if err := s.db.SelectContext(ctx, &out, ` + SELECT e.id, e.org_id, e.source, e.type, e.source_event_id, e.link_key, e.linked_to, e.fields, e.occurred_at, + e.received_at, e.matched, e.dispatched_at, e.own, e.origin_run_id, e.group_key, e.group_filter + FROM events.events e + JOIN events.groups g ON g.org_id = e.org_id AND g.key = e.group_key + WHERE g.org_id = $1 AND g.id = $2 ORDER BY e.received_at DESC LIMIT $3`, orgID, id, limit); err != nil { + return nil, fmt.Errorf("list group events: %w", err) + } + return out, nil +} + +// RecordReplay notes that a dry run replayed an event for a draft trigger, so +// the run's origin reads as that event. The latest replay for a trigger wins. +func (s *Store) RecordReplay(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error { + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO events.dispatches (event_id, trigger, run_id) VALUES ($1, $2, $3) + ON CONFLICT (event_id, trigger) DO UPDATE SET run_id = EXCLUDED.run_id, created_at = now()`, + eventID, trigger, runID); err != nil { + return fmt.Errorf("record replay: %w", err) + } + return nil +}