From 1c10378a40626449cb471ce3021a8a08efbf54fd Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 24 Nov 2026 06:14:33 +1100 Subject: [PATCH] refactor(events,proposals,runs,ui): rename declared event type fields to declared_event_type (#2128) --- api/openapi.yaml | 38 +++--- e2e/archie-smoke.cjs | 2 +- .../platform/pg/migrations/00003_events.sql | 106 ++++++++-------- modules/events/api.go | 88 +++++++------- modules/events/api_capture.go | 6 +- modules/events/drafting.go | 32 ++--- modules/events/events.go | 10 +- modules/events/grouping.go | 14 +-- modules/events/internal/store/capture.go | 4 +- modules/events/internal/store/drafting.go | 6 +- modules/events/internal/store/groups.go | 28 ++--- modules/events/internal/store/store.go | 115 +++++++++--------- modules/events/linkcode_test.go | 2 +- modules/events/schedule.go | 2 +- modules/events/trigger_test.go | 22 ++-- modules/proposals/api.go | 12 +- modules/proposals/trigger.go | 18 +-- modules/runs/trail.go | 10 +- ui/src/captures/event-types.ts | 6 +- ui/src/captures/state.ts | 2 +- ui/src/events/EventList.vue | 10 +- ui/src/events/TriggerList.vue | 12 +- ui/src/events/trigger.ts | 2 +- ui/src/lib/api.ts | 12 +- ui/src/proposals/ProposalPage.vue | 2 +- ui/src/runs/RunPage.vue | 2 +- ui/src/workflows/use-workflow-list.ts | 2 +- ui/test/event-types.test.ts | 6 +- 28 files changed, 292 insertions(+), 279 deletions(-) diff --git a/api/openapi.yaml b/api/openapi.yaml index f57230f14..8f9678860 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1458,7 +1458,7 @@ components: type: string content_type: type: string - event_type: + event_type_id: type: string headers: type: string @@ -1596,6 +1596,8 @@ components: EventsEventView: additionalProperties: false properties: + declared_event_type: + type: string dispatched_at: format: date-time type: string @@ -1616,13 +1618,11 @@ components: type: string source_id: type: string - type: - type: string verification: type: string required: - id - - type + - declared_event_type - fields - received_at - matched @@ -1743,7 +1743,7 @@ components: EventsProposedTrigger: additionalProperties: false properties: - event_type: + declared_event_type: type: string filter: {} source: @@ -1754,7 +1754,7 @@ components: required: - source_id - source - - event_type + - declared_event_type - filter type: object EventsSavedID: @@ -1871,11 +1871,11 @@ components: EventsTriggerBody: additionalProperties: false properties: + declared_event_type: + description: The event kind declared by the connector that fires it; fixed when every is set + type: string disabled: type: boolean - event_type: - description: The event type that fires it; fixed when every is set - type: string event_type_id: description: Fire only for events identified as this event type of the source format: uuid @@ -1937,10 +1937,10 @@ components: EventsTriggerView: additionalProperties: false properties: + declared_event_type: + type: string enabled: type: boolean - event_type: - type: string event_type_id: type: string every: @@ -1974,7 +1974,7 @@ components: required: - id - name - - event_type + - declared_event_type - filter - workflow_id - workflow @@ -3568,12 +3568,12 @@ components: ProposalsTrigger: additionalProperties: false properties: + declared_event_type: + type: string dry_event_id: type: string dry_run: $ref: "#/components/schemas/RunsDryReport" - event_type: - type: string filter: {} group_id: type: string @@ -3599,7 +3599,7 @@ components: - group_id - name - source_id - - event_type + - declared_event_type - filter - workflow - policy_kind @@ -4022,6 +4022,8 @@ components: RunsOrigin: additionalProperties: false properties: + declared_event_type: + type: string event_id: type: string fields: {} @@ -4037,13 +4039,11 @@ components: type: string trigger_id: type: string - type: - type: string required: - event_id - source_id - source - - type + - declared_event_type - fields - received_at - trigger_id @@ -6345,7 +6345,7 @@ paths: type: string - explode: false in: query - name: type + name: declared_event_type schema: type: string - description: Only events a trigger did or didn't match diff --git a/e2e/archie-smoke.cjs b/e2e/archie-smoke.cjs index 018273f8a..7981b8010 100644 --- a/e2e/archie-smoke.cjs +++ b/e2e/archie-smoke.cjs @@ -53,7 +53,7 @@ async function main() { assert.equal(trail.run.workflow_version, saved.version, "Run used the wrong workflow version"); assert.equal(trail.origin?.trigger_id, created.id, "Run trail is missing the schedule trigger"); assert.ok(trail.origin?.event_id, "Run trail is missing the originating event"); - assert.equal(trail.origin.type, "schedule.tick"); + assert.equal(trail.origin.declared_event_type, "schedule.tick"); const messages = await request("/api/composer/messages"); assert.equal(messages.filter((m) => m.run_id === run.id && m.title === name).length, 1, "Expected one composer notification linked to the run"); diff --git a/internal/platform/pg/migrations/00003_events.sql b/internal/platform/pg/migrations/00003_events.sql index 20399c952..a69eb908b 100644 --- a/internal/platform/pg/migrations/00003_events.sql +++ b/internal/platform/pg/migrations/00003_events.sql @@ -46,34 +46,37 @@ CREATE TABLE events.event_types ( UNIQUE (org_id, source_id, name) ); +-- An event is one delivered or scheduled occurrence. declared_event_type holds +-- the event kind declared by the connector (or a built-in kind), matched by +-- value, and is not a reference to events.event_types. CREATE TABLE events.events ( - id uuid PRIMARY KEY, - org_id text NOT NULL, - source_id uuid REFERENCES events.sources (id) ON DELETE SET NULL, - type text NOT NULL, - source_event_id text NOT NULL, - link_key text, - linked_to uuid REFERENCES events.events (id), - fields jsonb NOT NULL, - occurred_at timestamptz, - received_at timestamptz NOT NULL DEFAULT now(), - dispatched_at timestamptz, - matched boolean NOT NULL DEFAULT false, - own boolean NOT NULL DEFAULT false, - origin_run_id uuid, - group_key text, - group_filter jsonb, - body bytea, - verification text NOT NULL DEFAULT '' CHECK (verification IN ('', 'signed', 'token', 'unsigned')), - headers jsonb, - remote_addr text NOT NULL DEFAULT '', - event_type_id uuid REFERENCES events.event_types (id) ON DELETE SET NULL, + id uuid PRIMARY KEY, + org_id text NOT NULL, + source_id uuid REFERENCES events.sources (id) ON DELETE SET NULL, + declared_event_type text NOT NULL, + source_event_id text NOT NULL, + link_key text, + linked_to uuid REFERENCES events.events (id), + fields jsonb NOT NULL, + occurred_at timestamptz, + received_at timestamptz NOT NULL DEFAULT now(), + dispatched_at timestamptz, + matched boolean NOT NULL DEFAULT false, + own boolean NOT NULL DEFAULT false, + origin_run_id uuid, + group_key text, + group_filter jsonb, + body bytea, + verification text NOT NULL DEFAULT '' CHECK (verification IN ('', 'signed', 'token', 'unsigned')), + headers jsonb, + remote_addr text NOT NULL DEFAULT '', + event_type_id uuid REFERENCES events.event_types (id) ON DELETE SET NULL, UNIQUE (org_id, source_id, source_event_id) ); -- A schedule tick has no source, and NULL ids never conflict in the unique -- constraint above, so each slot is made unique here. CREATE UNIQUE INDEX events_schedule_slot ON events.events (org_id, source_event_id) - WHERE source_id IS NULL AND type = 'schedule.tick'; + WHERE source_id IS NULL AND declared_event_type = 'schedule.tick'; CREATE INDEX events_undispatched ON events.events (received_at) WHERE (dispatched_at IS NULL); CREATE INDEX events_link ON events.events (org_id, source_id, link_key, received_at) WHERE (link_key IS NOT NULL); @@ -96,23 +99,25 @@ CREATE TABLE events.mappings ( -- label that can change. A deleted trigger keeps its row, so its dispatches -- still show what started them, and its name can be given to a new trigger. -- Deleting it clears its source, event type and mapping, so it doesn't stop --- them being deleted. +-- them being deleted. declared_event_type holds the event kind declared by the +-- connector (or a built-in kind), matched by value, and is not a reference to +-- events.event_types. CREATE TABLE events.triggers ( - id uuid PRIMARY KEY, - org_id text NOT NULL, - name text NOT NULL, - source_id uuid REFERENCES events.sources (id), - event_type text NOT NULL, - filter jsonb NOT NULL DEFAULT '{}', - workflow_id uuid NOT NULL, - enabled boolean NOT NULL DEFAULT true, - updated_at timestamptz NOT NULL DEFAULT now(), - schedule_every_s integer CHECK (schedule_every_s >= 60), - schedule_since timestamptz, - approved boolean NOT NULL DEFAULT true, - event_type_id uuid REFERENCES events.event_types (id) ON DELETE RESTRICT, - mapping_id uuid REFERENCES events.mappings (id) ON DELETE RESTRICT, - deleted_at timestamptz, + id uuid PRIMARY KEY, + org_id text NOT NULL, + name text NOT NULL, + source_id uuid REFERENCES events.sources (id), + declared_event_type text NOT NULL, + filter jsonb NOT NULL DEFAULT '{}', + workflow_id uuid NOT NULL, + enabled boolean NOT NULL DEFAULT true, + updated_at timestamptz NOT NULL DEFAULT now(), + schedule_every_s integer CHECK (schedule_every_s >= 60), + schedule_since timestamptz, + approved boolean NOT NULL DEFAULT true, + event_type_id uuid REFERENCES events.event_types (id) ON DELETE RESTRICT, + mapping_id uuid REFERENCES events.mappings (id) ON DELETE RESTRICT, + deleted_at timestamptz, CHECK (deleted_at IS NOT NULL OR (source_id IS NULL) = (schedule_every_s IS NOT NULL)) ); CREATE UNIQUE INDEX triggers_live_name ON events.triggers (org_id, name) WHERE (deleted_at IS NULL); @@ -138,18 +143,21 @@ CREATE TABLE events.replays ( created_at timestamptz NOT NULL DEFAULT now() ); --- A group collects the unmatched events that share a key. Its source, event --- type and filter describe the trigger it suggests. +-- A group collects the unmatched events that share a key. Its source, +-- declared event type and filter describe the trigger it suggests. +-- declared_event_type holds the event kind declared by the connector (or a +-- built-in kind), matched by value, and is not a reference to +-- events.event_types. CREATE TABLE events.groups ( - id uuid PRIMARY KEY, - org_id text NOT NULL, - key text NOT NULL, - source_id uuid NOT NULL REFERENCES events.sources (id) ON DELETE CASCADE, - event_type text NOT NULL, - filter jsonb NOT NULL, - count bigint NOT NULL, - first_seen timestamptz NOT NULL, - last_seen timestamptz NOT NULL, + id uuid PRIMARY KEY, + org_id text NOT NULL, + key text NOT NULL, + source_id uuid NOT NULL REFERENCES events.sources (id) ON DELETE CASCADE, + declared_event_type text NOT NULL, + filter jsonb NOT NULL, + count bigint NOT NULL, + first_seen timestamptz NOT NULL, + last_seen timestamptz NOT NULL, UNIQUE (org_id, key) ); diff --git a/modules/events/api.go b/modules/events/api.go index 680906679..3f9ecb222 100644 --- a/modules/events/api.go +++ b/modules/events/api.go @@ -244,13 +244,13 @@ func (m *Module) setHMAC(src *store.Source, set SourceSettings, stored *store.So // triggerBody is a trigger as the API saves it. type triggerBody struct { - Name string `json:"name" doc:"Lowercase letters, digits and hyphens, unique among the triggers"` - SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source whose events fire it; none when every is set"` - EventType string `json:"event_type,omitzero" doc:"The event type that fires it; fixed when every is set"` - Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"` - WorkflowID string `json:"workflow_id" format:"uuid" doc:"The workflow each match runs"` - Disabled bool `json:"disabled,omitzero"` - Every string `json:"every,omitzero" doc:"Fire on an interval instead of on events, such as 1h" example:"1h"` + Name string `json:"name" doc:"Lowercase letters, digits and hyphens, unique among the triggers"` + SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source whose events fire it; none when every is set"` + DeclaredEventType string `json:"declared_event_type,omitzero" doc:"The event kind declared by the connector that fires it; fixed when every is set"` + Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"` + WorkflowID string `json:"workflow_id" format:"uuid" doc:"The workflow each match runs"` + Disabled bool `json:"disabled,omitzero"` + Every string `json:"every,omitzero" doc:"Fire on an interval instead of on events, such as 1h" example:"1h"` // EventTypeID restricts the trigger to events identified as that event // type, and MappingID reads their payload for the run. EventTypeID string `json:"event_type_id,omitzero" format:"uuid" doc:"Fire only for events identified as this event type of the source"` @@ -322,10 +322,10 @@ func (m *Module) triggerOf(ctx context.Context, current store.Trigger, req trigg return store.Trigger{}, err } if every.Valid { - req.SourceID, req.EventType = "", scheduleType + req.SourceID, req.DeclaredEventType = "", scheduleType req.Filter = scheduleFilter(current.ID) } - if !validName.MatchString(req.Name) || (req.SourceID == "" && !every.Valid) || (req.EventType == "" && req.EventTypeID == "") || req.WorkflowID == "" { + if !validName.MatchString(req.Name) || (req.SourceID == "" && !every.Valid) || (req.DeclaredEventType == "" && req.EventTypeID == "") || req.WorkflowID == "" { return store.Trigger{}, huma.Error400BadRequest("a trigger needs a lowercase name, a workflow, and either a source and event type or an every interval") } sourceID, err := m.triggerSource(ctx, req.SourceID) @@ -336,7 +336,7 @@ func (m *Module) triggerOf(ctx context.Context, current store.Trigger, req trigg if err != nil { return store.Trigger{}, huma.Error400BadRequest("a workflow id is a UUID", &huma.ErrorDetail{Location: "body.workflow_id", Message: "a workflow id is a UUID"}) } - typeID, mappingID, err := m.checkTargets(ctx, sourceID, req.EventType, workflow, req.EventTypeID, req.MappingID) + typeID, mappingID, err := m.checkTargets(ctx, sourceID, req.DeclaredEventType, workflow, req.EventTypeID, req.MappingID) if err != nil { return store.Trigger{}, err } @@ -345,7 +345,7 @@ func (m *Module) triggerOf(ctx context.Context, current store.Trigger, req trigg return store.Trigger{}, huma.Error400BadRequest(err.Error()) } return store.Trigger{ - ID: current.ID, OrgID: m.orgID, Name: req.Name, SourceID: sourceID, EventType: req.EventType, + ID: current.ID, OrgID: m.orgID, Name: req.Name, SourceID: sourceID, DeclaredEventType: req.DeclaredEventType, Filter: filter, WorkflowID: workflow, Enabled: !req.Disabled, Approved: current.Approved && !req.Pending, EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every, }, nil @@ -376,7 +376,7 @@ func (m *Module) triggerSource(ctx context.Context, raw string) (uuid.NullUUID, // checkTargets refuses a trigger whose workflow can't be started or whose // event type, mapping or connector event type doesn't exist. -func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, eventType string, workflow uuid.UUID, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) { +func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, declaredEventType string, workflow uuid.UUID, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) { if typeID, mapID, err = m.checkBinding(ctx, sourceID, eventTypeID, mappingID); err != nil { return typeID, mapID, err } @@ -386,8 +386,8 @@ func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, event } return typeID, mapID, huma.Error500InternalServerError("couldn't check the workflow", err) } - if eventType != "" { - err = m.checkEventType(ctx, sourceID, eventType) + if declaredEventType != "" { + err = m.checkEventType(ctx, sourceID, declaredEventType) } return typeID, mapID, err } @@ -429,11 +429,11 @@ func (m *Module) checkBinding(ctx context.Context, sourceID uuid.NullUUID, event return typeID, mapID, nil } -// checkEventType refuses a trigger on an event type that the source's +// checkEventType refuses a trigger on a declared event type that the source's // connector doesn't declare, so the trigger can't be saved when it could never // fire, and a trigger on a source the caller can't use. Schedule triggers have // no source. -func (m *Module) checkEventType(ctx context.Context, sourceID uuid.NullUUID, eventType string) error { +func (m *Module) checkEventType(ctx context.Context, sourceID uuid.NullUUID, declaredEventType string) error { if !sourceID.Valid { return nil } @@ -452,10 +452,10 @@ func (m *Module) checkEventType(ctx context.Context, sourceID uuid.NullUUID, eve return huma.Error500InternalServerError("couldn't read what the connector declares", err) } if !ok { - return refuse("body.event_type", fmt.Sprintf("connector %q isn't accepted or has never loaded, so its event types aren't known", src.Connector)) + return refuse("body.declared_event_type", fmt.Sprintf("connector %q isn't accepted or has never loaded, so its event types aren't known", src.Connector)) } - if _, declared := caps.Event(eventType); !declared { - return refuse("body.event_type", fmt.Sprintf("connector %q declares no event type %q", src.Connector, eventType)) + if _, declared := caps.Event(declaredEventType); !declared { + return refuse("body.declared_event_type", fmt.Sprintf("connector %q declares no event type %q", src.Connector, declaredEventType)) } return nil } @@ -507,10 +507,10 @@ type groupView struct { } type proposedTrigger struct { - SourceID uuid.UUID `json:"source_id"` - Source string `json:"source" doc:"The source's label"` - EventType string `json:"event_type"` - Filter jsontext.Value `json:"filter"` + SourceID uuid.UUID `json:"source_id"` + Source string `json:"source" doc:"The source's label"` + DeclaredEventType string `json:"declared_event_type"` + Filter jsontext.Value `json:"filter"` } func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]groupView], error) { @@ -527,7 +527,7 @@ func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]grou for _, g := range groups { out = append(out, groupView{ ID: g.ID, Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen, - Proposed: proposedTrigger{SourceID: g.SourceID, Source: labels[g.SourceID], EventType: g.EventType, Filter: g.Filter}, + Proposed: proposedTrigger{SourceID: g.SourceID, Source: labels[g.SourceID], DeclaredEventType: g.DeclaredEventType, Filter: g.Filter}, }) } return httpapi.OK(out), nil @@ -601,10 +601,10 @@ type triggerView struct { ID uuid.UUID `json:"id"` Name string `json:"name"` // SourceID is empty for a scheduled trigger. Source is the source's label. - SourceID string `json:"source_id,omitempty"` - Source string `json:"source,omitempty"` - EventType string `json:"event_type"` - Filter map[string]string `json:"filter"` + SourceID string `json:"source_id,omitempty"` + Source string `json:"source,omitempty"` + DeclaredEventType string `json:"declared_event_type"` + Filter map[string]string `json:"filter"` // WorkflowID is the workflow the trigger starts, and Workflow its name. WorkflowID uuid.UUID `json:"workflow_id"` Workflow string `json:"workflow"` @@ -632,7 +632,7 @@ func statusOf(t store.Trigger) string { // viewOfTrigger is the API's form of a stored trigger. Unsigned is set by the // caller, which knows the sources. func viewOfTrigger(t store.Trigger) (triggerView, error) { - view := triggerView{ID: t.ID, Name: t.Name, EventType: t.EventType, WorkflowID: t.WorkflowID, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)} + view := triggerView{ID: t.ID, Name: t.Name, DeclaredEventType: t.DeclaredEventType, WorkflowID: t.WorkflowID, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)} if len(t.Filter) > 0 { if err := json.Unmarshal(t.Filter, &view.Filter); err != nil { return view, fmt.Errorf("filter of %s: %w", t.Name, err) @@ -702,14 +702,14 @@ func (m *Module) triggers(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]tr } type recentInput struct { - Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"` - SourceID string `query:"source_id" format:"uuid"` - Type string `query:"type"` - Matched string `query:"matched" enum:"true,false" doc:"Only events a trigger did or didn't match"` + Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"` + SourceID string `query:"source_id" format:"uuid"` + DeclaredEventType string `query:"declared_event_type"` + Matched string `query:"matched" enum:"true,false" doc:"Only events a trigger did or didn't match"` } func (m *Module) recent(ctx context.Context, in *recentInput) (*httpapi.Reply[[]eventView], error) { - filter := store.EventFilter{Type: in.Type, Limit: in.Limit} + filter := store.EventFilter{DeclaredEventType: in.DeclaredEventType, Limit: in.Limit} if in.SourceID != "" { id, err := uuid.Parse(in.SourceID) if err != nil { @@ -805,15 +805,15 @@ func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[even type eventView struct { ID uuid.UUID `json:"id"` // SourceID is empty for a schedule tick. Source is the source's label. - SourceID *uuid.UUID `json:"source_id,omitempty"` - Source string `json:"source,omitempty"` - Type string `json:"type"` - Fields jsontext.Value `json:"fields"` - LinkedTo *uuid.UUID `json:"linked_to,omitempty"` - OccurredAt *time.Time `json:"occurred_at,omitempty"` - ReceivedAt time.Time `json:"received_at"` - Matched bool `json:"matched"` - DispatchedAt *time.Time `json:"dispatched_at,omitempty"` + SourceID *uuid.UUID `json:"source_id,omitempty"` + Source string `json:"source,omitempty"` + DeclaredEventType string `json:"declared_event_type"` + Fields jsontext.Value `json:"fields"` + LinkedTo *uuid.UUID `json:"linked_to,omitempty"` + OccurredAt *time.Time `json:"occurred_at,omitempty"` + ReceivedAt time.Time `json:"received_at"` + Matched bool `json:"matched"` + DispatchedAt *time.Time `json:"dispatched_at,omitempty"` // Verification is how the delivery was verified: signed, token or unsigned. // It is empty for an event a connector streamed. Verification string `json:"verification,omitempty"` @@ -822,7 +822,7 @@ type eventView struct { func viewOf(e store.Event, labels map[uuid.UUID]string) eventView { v := eventView{ Verification: e.Verification, - ID: e.ID, Source: labels[e.SourceID.UUID], Type: e.Type, Fields: e.Fields, LinkedTo: e.LinkedTo, + ID: e.ID, Source: labels[e.SourceID.UUID], DeclaredEventType: e.DeclaredEventType, Fields: e.Fields, LinkedTo: e.LinkedTo, ReceivedAt: e.ReceivedAt, Matched: e.Matched, } if e.SourceID.Valid { diff --git a/modules/events/api_capture.go b/modules/events/api_capture.go index 73c6592d1..5690fd793 100644 --- a/modules/events/api_capture.go +++ b/modules/events/api_capture.go @@ -63,8 +63,8 @@ type captureView struct { Body string `json:"body"` // Verification is how the delivery was verified: signed, token or unsigned. Verification string `json:"verification" enum:"signed,token,unsigned,"` - // EventType is the id of the event type the delivery was identified as. - EventType string `json:"event_type,omitempty"` + // EventTypeID is the id of the event type the delivery was identified as. + EventTypeID string `json:"event_type_id,omitempty"` } type capturesInput struct { @@ -108,7 +108,7 @@ func captureOf(e store.Event, labels map[uuid.UUID]string) captureView { v.SourceID = &e.SourceID.UUID } if e.EventTypeID.Valid { - v.EventType = e.EventTypeID.UUID.String() + v.EventTypeID = e.EventTypeID.UUID.String() } return v } diff --git a/modules/events/drafting.go b/modules/events/drafting.go index 09486b5fb..c0df4211e 100644 --- a/modules/events/drafting.go +++ b/modules/events/drafting.go @@ -19,13 +19,13 @@ type Group struct { ID uuid.UUID // SourceID is the source whose events the group collects, and Source its // label. - SourceID uuid.UUID - Source string - EventType string - Filter map[string]string - Count int64 - FirstSeen time.Time - LastSeen time.Time + SourceID uuid.UUID + Source string + DeclaredEventType string + Filter map[string]string + Count int64 + FirstSeen time.Time + LastSeen time.Time } // Group returns the group id names, whether a trigger now covers it. @@ -43,7 +43,7 @@ func (m *Module) Group(ctx context.Context, id uuid.UUID) (Group, bool, error) { return Group{}, false, fmt.Errorf("group %s source: %w", id, err) } return Group{ - ID: g.ID, SourceID: g.SourceID, Source: src.Label, EventType: g.EventType, Filter: filter, + ID: g.ID, SourceID: g.SourceID, Source: src.Label, DeclaredEventType: g.DeclaredEventType, Filter: filter, Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen, }, true, nil } @@ -88,19 +88,19 @@ func (m *Module) TriggerNamed(ctx context.Context, name string) (uuid.UUID, bool // TriggerSpec is an event trigger to save. The caller chooses its ID, so // saving it again replaces it instead of adding a second trigger. type TriggerSpec struct { - ID uuid.UUID - Name string - SourceID uuid.UUID - EventType string - Filter map[string]string + ID uuid.UUID + Name string + SourceID uuid.UUID + DeclaredEventType string + Filter map[string]string // WorkflowID is the workflow the trigger starts. WorkflowID uuid.UUID } // SaveTrigger creates or replaces an event trigger. func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error { - if t.ID == uuid.Nil || !validName.MatchString(t.Name) || t.SourceID == uuid.Nil || t.EventType == "" || t.WorkflowID == uuid.Nil { - return fmt.Errorf("a trigger needs an id, a lowercase name, a source, an event type and a workflow") + if t.ID == uuid.Nil || !validName.MatchString(t.Name) || t.SourceID == uuid.Nil || t.DeclaredEventType == "" || t.WorkflowID == uuid.Nil { + return fmt.Errorf("a trigger needs an id, a lowercase name, a source, a declared event type and a workflow") } if err := m.runs.CheckTrigger(ctx, m.orgID, t.WorkflowID); err != nil { return err @@ -110,7 +110,7 @@ func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error { return fmt.Errorf("encode filter: %w", err) } return m.store.UpsertTrigger(ctx, store.Trigger{ - ID: t.ID, OrgID: m.orgID, Name: t.Name, SourceID: uuid.NullUUID{UUID: t.SourceID, Valid: true}, EventType: t.EventType, + ID: t.ID, OrgID: m.orgID, Name: t.Name, SourceID: uuid.NullUUID{UUID: t.SourceID, Valid: true}, DeclaredEventType: t.DeclaredEventType, Filter: filter, WorkflowID: t.WorkflowID, Enabled: true, Approved: true, }) } diff --git a/modules/events/events.go b/modules/events/events.go index 5c984f45f..e5bbcc4c5 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -598,7 +598,7 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { // Archie's own message coming back starts nothing and proposes nothing. return false, nil } - switch e.Type { + switch e.DeclaredEventType { case answerType: return false, m.answer(ctx, e) case linkType: @@ -611,7 +611,7 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { if err != nil || linked { return false, err } - triggers, err := store.Triggers(ctx, tx, e.OrgID, e.SourceID, e.Type, e.EventTypeID) + triggers, err := store.Triggers(ctx, tx, e.OrgID, e.SourceID, e.DeclaredEventType, e.EventTypeID) if err != nil { return false, err } @@ -703,7 +703,7 @@ func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event) return err } if created { - m.log.InfoContext(ctx, "unmatched events started a group", "source", e.SourceID.UUID, "type", e.Type) + m.log.InfoContext(ctx, "unmatched events started a group", "source", e.SourceID.UUID, "declared_event_type", e.DeclaredEventType) } return nil } @@ -740,7 +740,7 @@ func (m *Module) Origin(ctx context.Context, runID uuid.UUID) (runs.Origin, bool return runs.Origin{}, ok, err } return runs.Origin{ - EventID: o.EventID, SourceID: o.SourceID.UUID, Source: o.Source, Type: o.Type, Fields: o.Fields, + EventID: o.EventID, SourceID: o.SourceID.UUID, Source: o.Source, DeclaredEventType: o.DeclaredEventType, Fields: o.Fields, ReceivedAt: o.ReceivedAt, TriggerID: o.TriggerID.UUID, Trigger: o.Trigger, Filter: o.Filter, }, true, nil } @@ -753,7 +753,7 @@ func runInput(e store.Event) jsontext.Value { // payload under "mapped" when there are any. func runInputWith(e store.Event, mapped map[string]any) jsontext.Value { doc := map[string]any{"event": map[string]any{ - "id": e.ID, "source_id": e.SourceID.UUID, "type": e.Type, "fields": e.Fields, "occurred_at": e.OccurredAt.Time, + "id": e.ID, "source_id": e.SourceID.UUID, "declared_event_type": e.DeclaredEventType, "fields": e.Fields, "occurred_at": e.OccurredAt.Time, }} if mapped != nil { doc["mapped"] = mapped diff --git a/modules/events/grouping.go b/modules/events/grouping.go index 74df52079..050bab4c3 100644 --- a/modules/events/grouping.go +++ b/modules/events/grouping.go @@ -21,10 +21,10 @@ import ( // "labels" covers every label. var defaultKeyFields = []string{"alertname", "name", "labels", "severity", "service", "host", "instance"} -// groupKey is the identity events of one kind share: source, type and the -// values at keyFields. It also returns those values as the filter of the -// trigger the group proposes. -func groupKey(sourceID uuid.UUID, eventType string, fields jsontext.Value, keyFields []string) (string, map[string]string) { +// groupKey is the identity events of one kind share: source, declared event type +// and the values at keyFields. It also returns those values as the filter of +// the trigger the group proposes. +func groupKey(sourceID uuid.UUID, declaredEventType string, fields jsontext.Value, keyFields []string) (string, map[string]string) { if len(keyFields) == 0 { keyFields = defaultKeyFields } @@ -35,7 +35,7 @@ func groupKey(sourceID uuid.UUID, eventType string, fields jsontext.Value, keyFi } slices.Sort(paths) var b strings.Builder - b.WriteString(sourceID.String() + "\x00" + eventType) + b.WriteString(sourceID.String() + "\x00" + declaredEventType) for _, p := range paths { b.WriteString("\x00" + p + "=" + filter[p]) } @@ -59,8 +59,8 @@ func keyPaths(src store.Source) []string { // fixed here, once, from the source's key fields. func newRow(orgID string, src store.Source, e connectors.Event, body []byte, own bool, runID uuid.UUID) store.Event { row := store.Event{ - ID: uuid.New(), OrgID: orgID, SourceID: uuid.NullUUID{UUID: src.ID, Valid: true}, Type: e.Type, SourceEventID: e.SourceEventID, - Fields: e.Fields, Body: body, Own: own, + ID: uuid.New(), OrgID: orgID, SourceID: uuid.NullUUID{UUID: src.ID, Valid: true}, + DeclaredEventType: e.Type, SourceEventID: e.SourceEventID, Fields: e.Fields, Body: body, Own: own, } row.LinkKey.String, row.LinkKey.Valid = e.LinkKey, e.LinkKey != "" row.OccurredAt.Time, row.OccurredAt.Valid = e.OccurredAt, !e.OccurredAt.IsZero() diff --git a/modules/events/internal/store/capture.go b/modules/events/internal/store/capture.go index 9f06f8c05..8a999868a 100644 --- a/modules/events/internal/store/capture.go +++ b/modules/events/internal/store/capture.go @@ -65,8 +65,8 @@ func classifySource(err error) error { func (s *Store) Captures(ctx context.Context, orgID, person string, limit int) ([]Event, error) { var out []Event if err := s.db.SelectContext(ctx, &out, ` - SELECT id, org_id, source_id, type, source_event_id, fields, body, headers, remote_addr, verification, - event_type_id, received_at, occurred_at + SELECT id, org_id, source_id, declared_event_type, source_event_id, fields, body, headers, remote_addr, + verification, event_type_id, received_at, occurred_at FROM events.events WHERE org_id = $1 AND headers IS NOT NULL AND `+visibleSource+` ORDER BY received_at DESC, id LIMIT $3`, orgID, person, limit); err != nil { diff --git a/modules/events/internal/store/drafting.go b/modules/events/internal/store/drafting.go index a7d276679..fafba202e 100644 --- a/modules/events/internal/store/drafting.go +++ b/modules/events/internal/store/drafting.go @@ -13,7 +13,7 @@ import ( 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_id, event_type, filter, count, first_seen, last_seen + SELECT id, source_id, declared_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 @@ -28,8 +28,8 @@ func (s *Store) GroupByID(ctx context.Context, orgID string, id uuid.UUID) (Grou 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_id, 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 + SELECT e.id, e.org_id, e.source_id, e.declared_event_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 { diff --git a/modules/events/internal/store/groups.go b/modules/events/internal/store/groups.go index e00b07752..68b12fa41 100644 --- a/modules/events/internal/store/groups.go +++ b/modules/events/internal/store/groups.go @@ -24,16 +24,16 @@ func (s *Store) SetKeyFields(ctx context.Context, orgID string, id uuid.UUID, pa return nil } -// Group is the events no trigger matched that share a key. Its source, type -// and filter are the trigger it proposes. +// Group is the events no trigger matched that share a key. Its source, +// declared event type and filter are the trigger it proposes. type Group struct { - ID uuid.UUID `db:"id"` - SourceID uuid.UUID `db:"source_id"` - EventType string `db:"event_type"` - Filter jsontext.Value `db:"filter"` - Count int64 `db:"count"` - FirstSeen time.Time `db:"first_seen"` - LastSeen time.Time `db:"last_seen"` + ID uuid.UUID `db:"id"` + SourceID uuid.UUID `db:"source_id"` + DeclaredEventType string `db:"declared_event_type"` + Filter jsontext.Value `db:"filter"` + Count int64 `db:"count"` + FirstSeen time.Time `db:"first_seen"` + LastSeen time.Time `db:"last_seen"` } // NoteUnmatched adds an event no trigger matched to the group its key names, @@ -45,14 +45,14 @@ func NoteUnmatched(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) { } var created bool err := tx.QueryRowxContext(ctx, ` - INSERT INTO events.groups (id, org_id, key, source_id, event_type, filter, count, first_seen, last_seen) + INSERT INTO events.groups (id, org_id, key, source_id, declared_event_type, filter, count, first_seen, last_seen) VALUES ($1, $2, $3, $4, $5, $6, 1, $7, $7) ON CONFLICT (org_id, key) DO UPDATE SET count = events.groups.count + 1, first_seen = LEAST(events.groups.first_seen, EXCLUDED.first_seen), last_seen = GREATEST(events.groups.last_seen, EXCLUDED.last_seen) RETURNING xmax = 0`, - uuid.New(), e.OrgID, e.GroupKey.String, e.SourceID.UUID, e.Type, e.GroupFilter, e.ReceivedAt).Scan(&created) + uuid.New(), e.OrgID, e.GroupKey.String, e.SourceID.UUID, e.DeclaredEventType, e.GroupFilter, e.ReceivedAt).Scan(&created) if err != nil { return false, fmt.Errorf("group event: %w", err) } @@ -61,16 +61,16 @@ func NoteUnmatched(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) { // Groups returns the groups no trigger covers, newest activity first, for the // sources the person may see. A group stops being listed once a trigger exists -// for its source, type and filter. +// for its source, declared event type and filter. func (s *Store) Groups(ctx context.Context, orgID, person string, limit int) ([]Group, error) { var out []Group if err := s.db.SelectContext(ctx, &out, ` - SELECT g.id, g.source_id, g.event_type, g.filter, g.count, g.first_seen, g.last_seen + SELECT g.id, g.source_id, g.declared_event_type, g.filter, g.count, g.first_seen, g.last_seen FROM events.groups g WHERE g.org_id = $1 AND `+visibleSource+` AND NOT EXISTS ( SELECT 1 FROM events.triggers t WHERE t.org_id = g.org_id AND t.deleted_at IS NULL AND t.source_id = g.source_id - AND t.event_type = g.event_type AND t.filter = g.filter) + AND t.declared_event_type = g.declared_event_type AND t.filter = g.filter) ORDER BY g.last_seen DESC LIMIT $3`, orgID, person, limit); err != nil { return nil, fmt.Errorf("list groups: %w", err) } diff --git a/modules/events/internal/store/store.go b/modules/events/internal/store/store.go index bc606c554..382fd09ba 100644 --- a/modules/events/internal/store/store.go +++ b/modules/events/internal/store/store.go @@ -45,6 +45,8 @@ type Source struct { // last segment of the URL deliveries post to, unique across the instance. Label string `db:"label"` WebhookPath string `db:"webhook_path"` + // Connector is the connector's immutable package identifier, never renamed + // and never given to a different package. Connector string `db:"connector"` TokenSHA256 string `db:"token_sha256"` // Verification is the scheme that deliveries must pass: Token, HMAC or None. @@ -81,12 +83,12 @@ type Event struct { OrgID string `db:"org_id"` // SourceID is null for a schedule tick, and for an event whose source was // deleted. - SourceID uuid.NullUUID `db:"source_id"` - Type string `db:"type"` - SourceEventID string `db:"source_event_id"` - LinkKey sql.NullString `db:"link_key"` - LinkedTo *uuid.UUID `db:"linked_to"` - Fields jsontext.Value `db:"fields"` + SourceID uuid.NullUUID `db:"source_id"` + DeclaredEventType string `db:"declared_event_type"` + SourceEventID string `db:"source_event_id"` + LinkKey sql.NullString `db:"link_key"` + LinkedTo *uuid.UUID `db:"linked_to"` + Fields jsontext.Value `db:"fields"` // Body is the payload as it arrived: the webhook body, or the batch a // listening connector streamed. It is what an audit reads when the // parsed fields leave a question open. @@ -130,11 +132,11 @@ type Trigger struct { // triggers. Name string `db:"name"` // SourceID is null for a scheduled trigger, which has no source. - SourceID uuid.NullUUID `db:"source_id"` - EventType string `db:"event_type"` - Filter jsontext.Value `db:"filter"` - WorkflowID uuid.UUID `db:"workflow_id"` - Enabled bool `db:"enabled"` + SourceID uuid.NullUUID `db:"source_id"` + DeclaredEventType string `db:"declared_event_type"` + Filter jsontext.Value `db:"filter"` + WorkflowID uuid.UUID `db:"workflow_id"` + Enabled bool `db:"enabled"` // ScheduleEverySeconds is the interval a scheduled trigger fires on; it // is null for a trigger that fires on events. ScheduleEverySeconds sql.NullInt64 `db:"schedule_every_s"` @@ -148,8 +150,8 @@ type Trigger struct { MappingID uuid.NullUUID `db:"mapping_id"` } -const triggerColumns = `id, org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, - mapping_id, schedule_every_s, schedule_since` +const triggerColumns = `id, org_id, name, source_id, declared_event_type, filter, workflow_id, enabled, approved, + event_type_id, mapping_id, schedule_every_s, schedule_since` // Store is the events module's Postgres store. type Store struct { @@ -260,12 +262,12 @@ func (s *Store) UpdateSource(ctx context.Context, src Source) error { // event was new. func (s *Store) Insert(ctx context.Context, e Event) (bool, error) { res, err := s.db.NamedExecContext(ctx, ` - INSERT INTO events.events (id, org_id, source_id, type, source_event_id, link_key, fields, body, occurred_at, - own, origin_run_id, group_key, group_filter, verification, headers, remote_addr, - event_type_id) - VALUES (:id, :org_id, :source_id, :type, :source_event_id, :link_key, :fields, :body, :occurred_at, - :own, :origin_run_id, :group_key, :group_filter, :verification, :headers, :remote_addr, - :event_type_id) + INSERT INTO events.events (id, org_id, source_id, declared_event_type, source_event_id, link_key, fields, body, + occurred_at, own, origin_run_id, group_key, group_filter, verification, headers, + remote_addr, event_type_id) + VALUES (:id, :org_id, :source_id, :declared_event_type, :source_event_id, :link_key, :fields, :body, + :occurred_at, :own, :origin_run_id, :group_key, :group_filter, :verification, :headers, + :remote_addr, :event_type_id) ON CONFLICT DO NOTHING`, e) if err != nil { return false, fmt.Errorf("store event: %w", err) @@ -289,8 +291,9 @@ func (s *Store) Dispatch(ctx context.Context, fn func(tx *sqlx.Tx, e Event) (mat defer func() { _ = tx.Rollback() }() var e Event err = tx.GetContext(ctx, &e, ` - SELECT id, org_id, source_id, type, source_event_id, link_key, linked_to, fields, body, occurred_at, - received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter, event_type_id + SELECT id, org_id, source_id, declared_event_type, source_event_id, link_key, linked_to, fields, body, + occurred_at, received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter, + event_type_id FROM events.events WHERE dispatched_at IS NULL ORDER BY received_at FOR UPDATE SKIP LOCKED LIMIT 1`) if errors.Is(err, sql.ErrNoRows) { @@ -344,18 +347,19 @@ func SetEventPayload(ctx context.Context, tx *sqlx.Tx, e Event) error { return nil } -// Triggers returns the armed triggers that fire for one source and event type, -// and for the custom type the event was identified as, if any. A schedule tick -// has no source and matches the triggers that have none. -func Triggers(ctx context.Context, tx *sqlx.Tx, orgID string, sourceID uuid.NullUUID, eventType string, typeID uuid.NullUUID) ([]Trigger, error) { +// Triggers returns the armed triggers that fire for one source and declared +// event type, and for the custom type the event was identified as, if any. A +// schedule tick has no source and matches the triggers that have none. +func Triggers(ctx context.Context, tx *sqlx.Tx, orgID string, sourceID uuid.NullUUID, declaredEventType string, typeID uuid.NullUUID) ([]Trigger, error) { var out []Trigger if err := tx.SelectContext(ctx, &out, ` SELECT `+triggerColumns+` FROM events.triggers - WHERE org_id = $1 AND deleted_at IS NULL AND source_id IS NOT DISTINCT FROM $2 AND (event_type = $3 OR event_type = '') + WHERE org_id = $1 AND deleted_at IS NULL AND source_id IS NOT DISTINCT FROM $2 + AND (declared_event_type = $3 OR declared_event_type = '') AND enabled AND approved AND (event_type_id IS NULL OR event_type_id = $4) ORDER BY name`, - orgID, sourceID, eventType, typeID); err != nil { + orgID, sourceID, declaredEventType, typeID); err != nil { return nil, fmt.Errorf("read triggers: %w", err) } return out, nil @@ -403,15 +407,15 @@ func RecordNoRun(ctx context.Context, tx *sqlx.Tx, eventID, triggerID uuid.UUID, // trigger was deleted. func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error { res, err := s.db.NamedExecContext(ctx, ` - INSERT INTO events.triggers (id, org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, - event_type_id, mapping_id, schedule_every_s, schedule_since) - VALUES (:id, :org_id, :name, :source_id, :event_type, :filter, :workflow_id, :enabled, :approved, - :event_type_id, :mapping_id, + INSERT INTO events.triggers (id, org_id, name, source_id, declared_event_type, filter, workflow_id, enabled, + approved, event_type_id, mapping_id, schedule_every_s, schedule_since) + VALUES (:id, :org_id, :name, :source_id, :declared_event_type, :filter, :workflow_id, :enabled, + :approved, :event_type_id, :mapping_id, CAST(:schedule_every_s AS integer), CASE WHEN CAST(:schedule_every_s AS integer) IS NULL THEN NULL ELSE now() END) ON CONFLICT (id) DO UPDATE - SET name = EXCLUDED.name, source_id = EXCLUDED.source_id, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter, - workflow_id = EXCLUDED.workflow_id, enabled = EXCLUDED.enabled, approved = EXCLUDED.approved, - event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id, + SET name = EXCLUDED.name, source_id = EXCLUDED.source_id, declared_event_type = EXCLUDED.declared_event_type, + filter = EXCLUDED.filter, workflow_id = EXCLUDED.workflow_id, enabled = EXCLUDED.enabled, + approved = EXCLUDED.approved, event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id, schedule_since = CASE WHEN EXCLUDED.schedule_every_s IS NULL THEN NULL WHEN events.triggers.schedule_every_s IS NOT DISTINCT FROM EXCLUDED.schedule_every_s @@ -444,10 +448,10 @@ func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger, // EventFilter narrows the events a list returns. A zero field doesn't filter, // and Matched distinguishes events a trigger started a run for from the rest. type EventFilter struct { - SourceID uuid.NullUUID - Type string - Matched *bool - Limit int + SourceID uuid.NullUUID + DeclaredEventType string + Matched *bool + Limit int } // visibleSource holds for a row whose source the person in $2 may see: it has @@ -460,14 +464,14 @@ const visibleSource = `(source_id IS NULL OR EXISTS ( func (s *Store) Recent(ctx context.Context, orgID, person string, f EventFilter) ([]Event, error) { var out []Event if err := s.db.SelectContext(ctx, &out, ` - SELECT id, org_id, source_id, type, source_event_id, link_key, linked_to, fields, occurred_at, - received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter + SELECT id, org_id, source_id, declared_event_type, source_event_id, link_key, linked_to, fields, + occurred_at, received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter FROM events.events WHERE org_id = $1 AND `+visibleSource+` AND ($3::uuid IS NULL OR source_id = $3) - AND ($4 = '' OR type = $4) + AND ($4 = '' OR declared_event_type = $4) AND ($5::boolean IS NULL OR matched = $5) - ORDER BY received_at DESC LIMIT $6`, orgID, person, f.SourceID, f.Type, f.Matched, f.Limit); err != nil { + ORDER BY received_at DESC LIMIT $6`, orgID, person, f.SourceID, f.DeclaredEventType, f.Matched, f.Limit); err != nil { return nil, fmt.Errorf("list events: %w", err) } return out, nil @@ -478,8 +482,8 @@ func (s *Store) Recent(ctx context.Context, orgID, person string, f EventFilter) func (s *Store) Event(ctx context.Context, orgID, person string, id uuid.UUID) (Event, error) { var e Event err := s.db.GetContext(ctx, &e, ` - SELECT id, org_id, source_id, type, source_event_id, link_key, linked_to, fields, body, occurred_at, - received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter, + SELECT id, org_id, source_id, declared_event_type, source_event_id, link_key, linked_to, fields, body, + occurred_at, received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter, verification, headers, remote_addr, event_type_id FROM events.events WHERE org_id = $1 AND `+visibleSource+` AND id = $3`, orgID, person, id) if errors.Is(err, sql.ErrNoRows) { @@ -528,15 +532,15 @@ func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error // Origin is the event and trigger that started a run. TriggerID is null for a // replay, whose trigger isn't saved. type Origin struct { - EventID uuid.UUID `db:"event_id"` - SourceID uuid.NullUUID `db:"source_id"` - Source string `db:"source"` - Type string `db:"type"` - Fields jsontext.Value `db:"fields"` - ReceivedAt time.Time `db:"received_at"` - TriggerID uuid.NullUUID `db:"trigger_id"` - Trigger string `db:"trigger"` - Filter jsontext.Value `db:"filter"` + EventID uuid.UUID `db:"event_id"` + SourceID uuid.NullUUID `db:"source_id"` + Source string `db:"source"` + DeclaredEventType string `db:"declared_event_type"` + Fields jsontext.Value `db:"fields"` + ReceivedAt time.Time `db:"received_at"` + TriggerID uuid.NullUUID `db:"trigger_id"` + Trigger string `db:"trigger"` + Filter jsontext.Value `db:"filter"` } // OriginOf returns what started a run; ok is false when no trigger did. @@ -550,8 +554,9 @@ func (s *Store) OriginOf(ctx context.Context, orgID string, runID uuid.UUID) (Or UNION ALL SELECT r.event_id, NULL::uuid, r.label, '{}'::jsonb FROM events.replays r WHERE r.run_id = $2 ) - SELECT e.id AS event_id, e.source_id, COALESCE(src.label, CASE WHEN e.type = 'schedule.tick' THEN 'schedule' ELSE '' END) AS source, e.type, e.fields, - e.received_at, o.trigger_id, o.trigger, o.filter + SELECT e.id AS event_id, e.source_id, + COALESCE(src.label, CASE WHEN e.declared_event_type = 'schedule.tick' THEN 'schedule' ELSE '' END) AS source, + e.declared_event_type, e.fields, e.received_at, o.trigger_id, o.trigger, o.filter FROM o JOIN events.events e ON e.id = o.event_id LEFT JOIN events.sources src ON src.id = e.source_id diff --git a/modules/events/linkcode_test.go b/modules/events/linkcode_test.go index cd21d7a2d..a156155c7 100644 --- a/modules/events/linkcode_test.go +++ b/modules/events/linkcode_test.go @@ -36,7 +36,7 @@ func TestRedactLinkCode(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - e := store.Event{Type: linkType, Fields: []byte(tt.fields)} + e := store.Event{DeclaredEventType: linkType, Fields: []byte(tt.fields)} if tt.body != "" { e.Body = []byte(tt.body) } diff --git a/modules/events/schedule.go b/modules/events/schedule.go index b7252c505..a63c4888d 100644 --- a/modules/events/schedule.go +++ b/modules/events/schedule.go @@ -75,7 +75,7 @@ func scheduleFilter(trigger uuid.UUID) map[string]string { func tickEvent(orgID string, trigger uuid.UUID, slot time.Time, fields jsontext.Value) store.Event { e := store.Event{ - ID: uuid.New(), OrgID: orgID, Type: scheduleType, + 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 diff --git a/modules/events/trigger_test.go b/modules/events/trigger_test.go index 652ed2fdf..f235c4ad4 100644 --- a/modules/events/trigger_test.go +++ b/modules/events/trigger_test.go @@ -46,22 +46,22 @@ func TestSavingATriggerChecksItsEventType(t *testing.T) { "pager": {Events: []connectors.Capability{{Name: "incident.opened"}}}, } tests := []struct { - name string - source uuid.NullUUID - connector string - eventType string - wantAt string + name string + source uuid.NullUUID + connector string + declaredEventType string + wantAt string }{ - {name: "a declared event type is accepted", source: hookSource, connector: "pager", eventType: "incident.opened"}, - {name: "an undeclared event type is refused", source: hookSource, connector: "pager", eventType: "incident.closed", wantAt: "body.event_type"}, - {name: "a connector that never loaded is refused", source: hookSource, connector: "other", eventType: "incident.opened", wantAt: "body.event_type"}, - {name: "an unknown source is refused", source: uuid.NullUUID{UUID: uuid.New(), Valid: true}, connector: "pager", eventType: "incident.opened", wantAt: "body.source_id"}, - {name: "a schedule is exempt", connector: "pager", eventType: scheduleType}, + {name: "a declared event type is accepted", source: hookSource, connector: "pager", declaredEventType: "incident.opened"}, + {name: "an undeclared event type is refused", source: hookSource, connector: "pager", declaredEventType: "incident.closed", wantAt: "body.declared_event_type"}, + {name: "a connector that never loaded is refused", source: hookSource, connector: "other", declaredEventType: "incident.opened", wantAt: "body.declared_event_type"}, + {name: "an unknown source is refused", source: uuid.NullUUID{UUID: uuid.New(), Valid: true}, connector: "pager", declaredEventType: "incident.opened", wantAt: "body.source_id"}, + {name: "a schedule is exempt", connector: "pager", declaredEventType: scheduleType}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &Module{reader: oneSource{connector: tt.connector}, connectors: declaredEvents{caps: caps}} - err := m.checkEventType(t.Context(), tt.source, tt.eventType) + err := m.checkEventType(t.Context(), tt.source, tt.declaredEventType) if tt.wantAt == "" { if err != nil { t.Fatalf("checkEventType: %v", err) diff --git a/modules/proposals/api.go b/modules/proposals/api.go index 0046eff9d..f9f6d8f3f 100644 --- a/modules/proposals/api.go +++ b/modules/proposals/api.go @@ -92,11 +92,11 @@ type View struct { // Trigger is the trigger a trigger proposal adds. type Trigger struct { - GroupID uuid.UUID `json:"group_id"` - Name string `json:"name"` - SourceID uuid.UUID `json:"source_id"` - EventType string `json:"event_type"` - Filter jsontext.Value `json:"filter"` + GroupID uuid.UUID `json:"group_id"` + Name string `json:"name"` + SourceID uuid.UUID `json:"source_id"` + DeclaredEventType string `json:"declared_event_type"` + Filter jsontext.Value `json:"filter"` // Workflow is the workflow document the trigger would start. Workflow string `json:"workflow"` PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"` @@ -198,7 +198,7 @@ func (m *Module) triggerView(ctx context.Context, p store.Proposal) (Trigger, er return Trigger{}, err } t := Trigger{ - GroupID: c.GroupID, Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: filter, + GroupID: c.GroupID, Name: c.Name, SourceID: c.SourceID, DeclaredEventType: c.DeclaredEventType, Filter: filter, Workflow: c.Workflow, PolicyKind: c.PolicyKind, Policy: c.Policy, DryEventID: c.DryEventID, InstalledVersion: c.InstalledVersion, } diff --git a/modules/proposals/trigger.go b/modules/proposals/trigger.go index 92f365bde..8df33b630 100644 --- a/modules/proposals/trigger.go +++ b/modules/proposals/trigger.go @@ -34,9 +34,9 @@ type triggerChange struct { SourceID uuid.UUID `json:"source_id"` // SourceLabel is the source's label when the proposal was made, kept for // display after the source is renamed. - SourceLabel string `json:"source_label,omitempty"` - EventType string `json:"event_type"` - Filter map[string]string `json:"filter"` + SourceLabel string `json:"source_label,omitempty"` + DeclaredEventType string `json:"declared_event_type"` + Filter map[string]string `json:"filter"` // Workflow is the workflow document the trigger starts. Workflow string `json:"workflow"` PolicyKind string `json:"policy_kind"` @@ -73,7 +73,7 @@ func (c triggerChange) summarize() string { if source == "" { source = c.SourceID.String() } - fmt.Fprintf(&b, "When %s sends %s", source, c.EventType) + fmt.Fprintf(&b, "When %s sends %s", source, c.DeclaredEventType) if len(c.Filter) > 0 { pairs := make([]string, 0, len(c.Filter)) for k, v := range c.Filter { @@ -117,7 +117,7 @@ func (c triggerChange) needs() string { // defaultName uses part of the group ID to distinguish groups with the same // source and event type. func defaultName(g events.Group) string { - slug := strings.Trim(nameChars.ReplaceAllString(strings.ToLower(g.Source+"-"+g.EventType), "-"), "-") + slug := strings.Trim(nameChars.ReplaceAllString(strings.ToLower(g.Source+"-"+g.DeclaredEventType), "-"), "-") if len(slug) > 50 { slug = strings.Trim(slug[:50], "-") } @@ -165,7 +165,7 @@ func (m *Module) proposeTrigger(ctx context.Context, g events.Group) (store.Prop return store.Proposal{}, fmt.Errorf("read the group's events: %w", err) } change := triggerChange{ - GroupID: g.ID, TriggerID: uuid.New(), Name: defaultName(g), SourceID: g.SourceID, SourceLabel: g.Source, EventType: g.EventType, Filter: g.Filter, + GroupID: g.ID, TriggerID: uuid.New(), Name: defaultName(g), SourceID: g.SourceID, SourceLabel: g.Source, DeclaredEventType: g.DeclaredEventType, Filter: g.Filter, Workflow: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules, } raw, err := json.Marshal(change) @@ -173,7 +173,7 @@ func (m *Module) proposeTrigger(ctx context.Context, g events.Group) (store.Prop return store.Proposal{}, fmt.Errorf("encode the trigger: %w", err) } evidence := map[string]any{"group": map[string]any{ - "source_id": g.SourceID, "event_type": g.EventType, "filter": g.Filter, "count": g.Count, + "source_id": g.SourceID, "declared_event_type": g.DeclaredEventType, "filter": g.Filter, "count": g.Count, "first_seen": g.FirstSeen, "last_seen": g.LastSeen, }} prompted := make([]uuid.UUID, 0, len(stored)) @@ -193,7 +193,7 @@ func (m *Module) proposeTrigger(ctx context.Context, g events.Group) (store.Prop } p := store.Proposal{ ID: uuid.New(), OrgID: m.orgID, Kind: KindTrigger, Needs: change.needs(), - Title: "Handle " + g.EventType + " from " + g.Source, + Title: "Handle " + g.DeclaredEventType + " from " + g.Source, Summary: change.summarize(), Evidence: evidenceRaw, Change: raw, TargetKind: "event_group", TargetID: g.ID.String(), PromptedBy: promptedRaw, ProposedByID: callerID(ctx), @@ -291,7 +291,7 @@ func (m *Module) publishTrigger(ctx context.Context, p store.Proposal) error { return err } if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{ - ID: c.TriggerID, Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: c.Filter, WorkflowID: workflow, + ID: c.TriggerID, Name: c.Name, SourceID: c.SourceID, DeclaredEventType: c.DeclaredEventType, Filter: c.Filter, WorkflowID: workflow, }); err != nil { return fmt.Errorf("save the trigger: %w", err) } diff --git a/modules/runs/trail.go b/modules/runs/trail.go index 38be87557..095c0b3fe 100644 --- a/modules/runs/trail.go +++ b/modules/runs/trail.go @@ -27,11 +27,11 @@ type Origin struct { EventID uuid.UUID `json:"event_id"` // SourceID is the nil UUID for a schedule tick. Source is the source's // label. - SourceID uuid.UUID `json:"source_id"` - Source string `json:"source"` - Type string `json:"type"` - Fields jsontext.Value `json:"fields"` - ReceivedAt time.Time `json:"received_at"` + SourceID uuid.UUID `json:"source_id"` + Source string `json:"source"` + DeclaredEventType string `json:"declared_event_type"` + Fields jsontext.Value `json:"fields"` + ReceivedAt time.Time `json:"received_at"` // TriggerID is the trigger that started the run, and Trigger its current // name. TriggerID is the nil UUID for a run a trigger proposal started, // whose trigger wasn't saved, and Trigger is then the proposed name. diff --git a/ui/src/captures/event-types.ts b/ui/src/captures/event-types.ts index 6e6a26b81..313da85b8 100644 --- a/ui/src/captures/event-types.ts +++ b/ui/src/captures/event-types.ts @@ -53,11 +53,11 @@ export function parseHeaderLines(text: string): Record { /** captureIdentity names what a capture was identified as when it arrived. */ export function captureIdentity( - capture: { id: unknown; event_type?: string }, + capture: { id: unknown; event_type_id?: string }, types: EventType[], ): { label: string; identified: boolean } { - if (!capture.event_type) return { label: "Unidentified", identified: false }; - const found = types.find((t) => t.id === capture.event_type); + if (!capture.event_type_id) return { label: "Unidentified", identified: false }; + const found = types.find((t) => t.id === capture.event_type_id); return { label: found ? found.name : "Deleted type", identified: true }; } diff --git a/ui/src/captures/state.ts b/ui/src/captures/state.ts index b5f193fe6..112f75fa1 100644 --- a/ui/src/captures/state.ts +++ b/ui/src/captures/state.ts @@ -30,7 +30,7 @@ export interface Capture { /** How the delivery was verified: signed, token or unsigned. */ verification?: string; /** The event type it was identified as on arrival; empty is unidentified. */ - event_type?: string; + event_type_id?: string; } interface CapturesResponse { diff --git a/ui/src/events/EventList.vue b/ui/src/events/EventList.vue index d868bd1d3..7616ca3a2 100644 --- a/ui/src/events/EventList.vue +++ b/ui/src/events/EventList.vue @@ -19,7 +19,7 @@ import EventDetail from "./EventDetail.vue"; const route = useRoute(); const ALL = "__all__"; const source = ref(ALL); -const type = ref(""); +const declaredEventType = ref(""); const matched = ref(ALL); const sources = useRead(() => api.eventSources()); @@ -27,7 +27,7 @@ const { data, error, reload } = useRead(() => api.events({ limit: 200, source_id: source.value === ALL ? undefined : source.value, - type: type.value.trim() || undefined, + declared_event_type: declaredEventType.value.trim() || undefined, matched: matched.value === ALL ? undefined : matched.value, }), ); @@ -44,7 +44,7 @@ const linked = computed(() => String(route.query.event ?? "")); const time = (at?: string) => (at ? Date.parse(at) : 0); const columns: DataTableColumn[] = [ - { id: "type", label: "Type", fixed: true, width: "auto", sort: (e) => e.type }, + { id: "type", label: "Type", fixed: true, width: "auto", sort: (e) => e.declared_event_type }, { id: "source", label: "Source", fixed: true, hide: "sm", width: "12rem", sort: (e) => e.source ?? "" }, { id: "matched", label: "Trigger", hide: "sm", width: "9rem", sort: (e) => (e.matched ? 1 : 0) }, { id: "received", label: "Received", fixed: true, width: "7.5rem", sort: (e) => time(e.received_at) }, @@ -73,7 +73,7 @@ const columns: DataTableColumn[] = [
- +
@@ -88,7 +88,7 @@ const columns: DataTableColumn[] = [ > - + diff --git a/ui/src/events/TriggerList.vue b/ui/src/events/TriggerList.vue index 2f52e8ed7..0a2d1a019 100644 --- a/ui/src/events/TriggerList.vue +++ b/ui/src/events/TriggerList.vue @@ -65,7 +65,7 @@ async function save(id: string, input: TriggerInput): Promise { const editing = ref(false); const isNew = ref(true); -const form = ref({ id: "", name: "", mode: "event", source_id: "", event_type: "", every: "", workflow: "", filter: "", disabled: false }); +const form = ref({ id: "", name: "", mode: "event", source_id: "", declared_event_type: "", every: "", workflow: "", filter: "", disabled: false }); function open(trigger?: Trigger): void { isNew.value = !trigger; actionError.value = ""; @@ -74,7 +74,7 @@ function open(trigger?: Trigger): void { name: trigger?.name ?? "", mode: trigger?.every ? "schedule" : "event", source_id: trigger?.every ? "" : (trigger?.source_id ?? ""), - event_type: trigger?.every ? "" : (trigger?.event_type ?? ""), + declared_event_type: trigger?.every ? "" : (trigger?.declared_event_type ?? ""), every: trigger?.every ?? "", workflow: trigger?.workflow_id ?? props.workflow ?? "", filter: trigger?.every ? "" : toLines(trigger?.filter ?? {}), @@ -88,7 +88,7 @@ async function submit(): Promise { const input: TriggerInput = f.mode === "schedule" ? { name: f.name.trim(), every: f.every.trim(), workflow_id: f.workflow, disabled: f.disabled } - : { name: f.name.trim(), source_id: f.source_id, event_type: f.event_type.trim(), filter, workflow_id: f.workflow, disabled: f.disabled }; + : { name: f.name.trim(), source_id: f.source_id, declared_event_type: f.declared_event_type.trim(), filter, workflow_id: f.workflow, disabled: f.disabled }; if (await save(f.id, input)) editing.value = false; } @@ -103,10 +103,10 @@ async function submit(): Promise { - +