diff --git a/api/openapi.yaml b/api/openapi.yaml index e8b713e9f..6ca8a3136 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1307,7 +1307,9 @@ components: outcome: enum: - started - - skipped + - failed + - denied + - disabled type: string reason: {} run_id: @@ -1616,7 +1618,9 @@ components: outcome: enum: - started - - skipped + - failed + - denied + - disabled type: string reason: {} run_id: @@ -3035,6 +3039,7 @@ components: type: string reason: type: string + value: {} required: - field_name - path diff --git a/internal/platform/pg/migrations/00062_events_dispatch_no_run_outcomes.sql b/internal/platform/pg/migrations/00062_events_dispatch_no_run_outcomes.sql new file mode 100644 index 000000000..5f1167828 --- /dev/null +++ b/internal/platform/pg/migrations/00062_events_dispatch_no_run_outcomes.sql @@ -0,0 +1,14 @@ +-- +goose Up +-- A trigger that matched an event but started no run records why: failed (the +-- event doesn't match the trigger's mapping), denied (access policy refused the +-- start) or disabled (the workflow is disabled). +ALTER TABLE events.dispatches DROP CONSTRAINT dispatches_outcome_check; +UPDATE events.dispatches SET outcome = 'failed' WHERE outcome = 'skipped'; +ALTER TABLE events.dispatches + ADD CONSTRAINT dispatches_outcome_check CHECK (outcome IN ('started', 'failed', 'denied', 'disabled')); + +-- +goose Down +DELETE FROM events.dispatches WHERE outcome IN ('denied', 'disabled'); +ALTER TABLE events.dispatches DROP CONSTRAINT dispatches_outcome_check; +UPDATE events.dispatches SET outcome = 'skipped' WHERE outcome = 'failed'; +ALTER TABLE events.dispatches ADD CONSTRAINT dispatches_outcome_check CHECK (outcome IN ('started', 'skipped')); diff --git a/modules/events/access_test.go b/modules/events/access_test.go index e48ec71cd..25ea6ed98 100644 --- a/modules/events/access_test.go +++ b/modules/events/access_test.go @@ -131,18 +131,20 @@ func (s *startRecorder) Start(ctx context.Context, _ runs.StartRequest) (uuid.UU func (*startRecorder) CheckTrigger(context.Context, string, string) error { return nil } // TestTriggersStartRunsAsTheWorkload guards that dispatching an event never -// starts a run without a principal: the workload principal acts, a refusal -// skips the trigger for good, and a chain that can't decide fails the dispatch -// so the event stays queued instead of being dropped. +// starts a run without a principal: the workload principal acts, a policy +// refusal or a disabled workflow is final and names its own outcome, and a +// chain that can't decide fails the dispatch so the event stays queued instead +// of being dropped. func TestTriggersStartRunsAsTheWorkload(t *testing.T) { tests := []struct { name string err error - wantStarted bool + wantOutcome string wantErr error }{ - {name: "an allowed start", wantStarted: true}, - {name: "a refused start is final", err: governance.ErrDenied}, + {name: "an allowed start"}, + {name: "a refused start is final", err: governance.ErrDenied, wantOutcome: store.OutcomeDenied}, + {name: "a disabled workflow is final", err: runs.ErrDisabled, wantOutcome: store.OutcomeDisabled}, {name: "an undecidable start is retried", err: governance.ErrChainUnavailable, wantErr: governance.ErrChainUnavailable}, {name: "another failure is retried", err: errors.New("database down"), wantErr: errors.New("database down")}, } @@ -150,9 +152,13 @@ func TestTriggersStartRunsAsTheWorkload(t *testing.T) { t.Run(tt.name, func(t *testing.T) { starts := &startRecorder{err: tt.err} m := &Module{runs: starts, log: slog.New(slog.DiscardHandler)} - _, started, err := m.startRun(t.Context(), store.Event{ID: uuid.New(), OrgID: "default"}, store.Trigger{Name: "t", Workflow: "triage"}, nil) - if started != tt.wantStarted { - t.Fatalf("started = %v, want %v", started, tt.wantStarted) + _, why, err := m.startRun(t.Context(), store.Event{ID: uuid.New(), OrgID: "default"}, store.Trigger{Name: "t", Workflow: "triage"}, nil) + var outcome string + if why != nil { + outcome = why.outcome + } + if outcome != tt.wantOutcome { + t.Fatalf("no-run outcome = %q, want %q", outcome, tt.wantOutcome) } if (err == nil) != (tt.wantErr == nil) || (tt.wantErr != nil && !strings.Contains(err.Error(), tt.wantErr.Error())) { t.Fatalf("error = %v, want %v", err, tt.wantErr) diff --git a/modules/events/api.go b/modules/events/api.go index d092215e8..4860dc63f 100644 --- a/modules/events/api.go +++ b/modules/events/api.go @@ -598,7 +598,7 @@ type eventDetail struct { type triggerRun struct { Trigger string `json:"trigger"` RunID *uuid.UUID `json:"run_id,omitempty"` - Outcome string `json:"outcome" enum:"started,skipped"` + Outcome string `json:"outcome" enum:"started,failed,denied,disabled"` Reason jsontext.Value `json:"reason,omitempty"` } diff --git a/modules/events/api_capture.go b/modules/events/api_capture.go index 53da68da9..215257af5 100644 --- a/modules/events/api_capture.go +++ b/modules/events/api_capture.go @@ -108,7 +108,7 @@ func captureOf(e store.Event) captureView { type dispatchView struct { EventID uuid.UUID `json:"event_id"` RunID *uuid.UUID `json:"run_id,omitempty"` - Outcome string `json:"outcome" enum:"started,skipped"` + Outcome string `json:"outcome" enum:"started,failed,denied,disabled"` Reason jsontext.Value `json:"reason,omitempty"` Trigger string `json:"trigger,omitempty"` CreatedAt time.Time `json:"created_at,omitzero"` diff --git a/modules/events/events.go b/modules/events/events.go index 1e5b9913a..0bbc43578 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -617,7 +617,7 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { switch outcome { case fired: matched = true - case refusedRun: + case noRun: refused = true } } @@ -627,14 +627,14 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { return matched, nil } -// outcome is the result of evaluating a trigger against an event: skipped (its -// filter didn't match), refusedRun (the run was refused) or fired (a run -// started). +// outcome is the result of evaluating a trigger against an event: notMatched +// (its filter didn't match), noRun (it matched but started no run, and the +// dispatch records why) or fired (a run started). type outcome int const ( - skipped outcome = iota - refusedRun + notMatched outcome = iota + noRun fired ) @@ -643,42 +643,50 @@ const ( func (m *Module) fire(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger) (outcome, error) { var filter map[string]string if err := json.Unmarshal(t.Filter, &filter); err != nil { - return skipped, fmt.Errorf("trigger %q filter: %w", t.Name, err) + return notMatched, fmt.Errorf("trigger %q filter: %w", t.Name, err) } if !match.Fields(e.Fields, filter) { - return skipped, nil + return notMatched, nil } - input, mapped, skip, err := m.inputFor(ctx, tx, e, t) + input, mapped, why, err := m.inputFor(ctx, tx, e, t) if err != nil { - return refusedRun, err + return noRun, err } - if skip != nil { - m.log.WarnContext(ctx, "trigger skipped: the event does not match its mapping", "event", e.ID, "trigger", t.Name, "reason", skip) - return refusedRun, recordSkip(ctx, tx, e, t, skip) - } - runID, started, err := m.startRun(ctx, e, t, input) - if err != nil || !started { - return refusedRun, err + if why == nil { + var runID uuid.UUID + runID, why, err = m.startRun(ctx, e, t, input) + if err != nil { + return noRun, err + } + if why == nil { + return fired, m.recordStarted(ctx, tx, e, t, runID, mapped) + } } + return noRun, recordNoRun(ctx, tx, e, t, why) +} + +// recordStarted records the run trigger t started for e, and counts the match +// against the trigger's mapping when one was applied. +func (m *Module) recordStarted(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger, runID uuid.UUID, mapped bool) error { if mapped { if err := store.CountMatch(ctx, tx, t.MappingID.UUID); err != nil { - return skipped, err + return err } } if err := store.RecordDispatch(ctx, tx, e.ID, t.Name, runID); err != nil { - return skipped, err + return err } m.log.InfoContext(ctx, "trigger started run", "event", e.ID, "trigger", t.Name, "run", runID) - return fired, nil + return nil } -// recordSkip stores the reason trigger t started no run for e. -func recordSkip(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger, skip *skipReason) error { - reason, err := json.Marshal(skip) +// recordNoRun stores why trigger t matched e but started no run. +func recordNoRun(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger, why *noRunReason) error { + reason, err := json.Marshal(why) if err != nil { - return fmt.Errorf("encode skip reason: %w", err) + return fmt.Errorf("encode no-run reason: %w", err) } - return store.RecordSkip(ctx, tx, e.ID, t.Name, reason) + return store.RecordNoRun(ctx, tx, e.ID, t.Name, why.outcome, reason) } // noteUnmatched files an event no trigger took into a group for review. @@ -694,27 +702,28 @@ func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event) } // startRun starts the run trigger t asks for, as the workload principal, so -// the start is decided by the same policy chain as any other caller. A refusal -// is final: it reports no run and no error, and the trigger is skipped. A policy -// chain that can't decide returns an error instead, which rolls the dispatch -// back so the event stays queued and is dispatched again. -func (m *Module) startRun(ctx context.Context, e store.Event, t store.Trigger, input jsontext.Value) (runID uuid.UUID, started bool, err error) { +// the start is decided by the same policy chain as any other caller. A policy +// refusal or a disabled workflow is final: it returns the reason no run started +// and no error. A policy chain that can't decide returns an error instead, +// which rolls the dispatch back so the event stays queued and is dispatched +// again. +func (m *Module) startRun(ctx context.Context, e store.Event, t store.Trigger, input jsontext.Value) (uuid.UUID, *noRunReason, error) { ctx = governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID)) - runID, err = m.runs.Start(ctx, runs.StartRequest{ + runID, err := m.runs.Start(ctx, runs.StartRequest{ OrgID: e.OrgID, Workflow: t.Workflow, Key: e.ID.String() + ":" + t.Name, Input: input, }) if errors.Is(err, governance.ErrDenied) { m.log.WarnContext(ctx, "trigger not permitted to start its workflow", "event", e.ID, "trigger", t.Name, "error", err) - return uuid.Nil, false, nil + return uuid.Nil, &noRunReason{outcome: store.OutcomeDenied, Code: reasonAccessDenied, Workflow: t.Workflow, Detail: err.Error()}, nil } if errors.Is(err, runs.ErrDisabled) { - m.log.InfoContext(ctx, "trigger skipped: the workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.Workflow) - return uuid.Nil, false, nil + m.log.InfoContext(ctx, "trigger started no run: the workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.Workflow) + return uuid.Nil, &noRunReason{outcome: store.OutcomeDisabled, Code: reasonWorkflowDisabled, Workflow: t.Workflow}, nil } if err != nil { - return uuid.Nil, false, fmt.Errorf("start run for trigger %q: %w", t.Name, err) + return uuid.Nil, nil, fmt.Errorf("start run for trigger %q: %w", t.Name, err) } - return runID, true, nil + return runID, nil, nil } // Origin returns the event and trigger that started a run. @@ -749,22 +758,31 @@ func runInputWith(e store.Event, mapped map[string]any) jsontext.Value { return input } -// skipMappingMismatch is the reason code for a trigger skipped because the -// event does not match its mapping. -const skipMappingMismatch = "mapping_mismatch" +// Codes for why a trigger that matched an event started no run. +const ( + reasonMappingMismatch = "mapping_mismatch" + reasonAccessDenied = "access_denied" + reasonWorkflowDisabled = "workflow_disabled" +) + +// noRunReason explains why a trigger matched an event but started no run. It +// is stored as the dispatch's reason and shown on the capture and the trigger. +type noRunReason struct { + // outcome is the dispatch outcome the reason is recorded under. + outcome string -// skipReason explains why a trigger didn't start a run for an event. It is stored -// as the dispatch's reason and shown on the capture and the trigger. -type skipReason struct { Code string `json:"code"` Mapping string `json:"mapping,omitempty"` Failures []mapping.Failure `json:"failures,omitempty"` + Workflow string `json:"workflow,omitempty"` + Detail string `json:"detail,omitempty"` } // inputFor builds the run input for trigger t. For a trigger with a mapping, -// the mapping is applied to the event's payload. When a field the mapping requires is missing -// or has the wrong shape, no run starts and the skip is recorded on the event. -func (m *Module) inputFor(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger) (input jsontext.Value, mapped bool, skip *skipReason, err error) { +// the mapping is applied to the event's payload. When a field the mapping +// requires is missing or has the wrong shape, no run starts and the failure is +// recorded on the event. +func (m *Module) inputFor(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger) (input jsontext.Value, mapped bool, failure *noRunReason, err error) { if !t.MappingID.Valid { return runInput(e), false, nil, nil } @@ -776,14 +794,14 @@ func (m *Module) inputFor(ctx context.Context, tx *sqlx.Tx, e store.Event, t sto } // applyMapping applies the mapping row to the event's payload. -func applyMapping(e store.Event, row store.Mapping) (input jsontext.Value, mapped bool, skip *skipReason, err error) { +func applyMapping(e store.Event, row store.Mapping) (input jsontext.Value, mapped bool, failure *noRunReason, err error) { var fields []mapping.Field if err := json.Unmarshal(row.Fields, &fields); err != nil { return nil, false, nil, fmt.Errorf("mapping %q fields: %w", row.Name, err) } values, failures := mapping.Resolve(fields, e.Body) if len(failures) > 0 { - return nil, false, &skipReason{Code: skipMappingMismatch, Mapping: row.Name, Failures: failures}, nil + return nil, false, &noRunReason{outcome: store.OutcomeFailed, Code: reasonMappingMismatch, Mapping: row.Name, Failures: failures}, nil } return runInputWith(e, values), true, nil, nil } diff --git a/modules/events/internal/mapping/mapping.go b/modules/events/internal/mapping/mapping.go index 09a3c8304..fd2ae01eb 100644 --- a/modules/events/internal/mapping/mapping.go +++ b/modules/events/internal/mapping/mapping.go @@ -103,11 +103,14 @@ func (m Mapping) Validate() error { } // Failure describes one field that did not resolve cleanly against a payload -- -// named by field and path so the operator knows exactly what drifted. +// named by field and path so the operator knows exactly what drifted. Value is +// what the payload held at the path when the field was found with the wrong +// type; it is absent when the field is missing or null. type Failure struct { FieldName string `json:"field_name"` Path string `json:"path"` Reason string `json:"reason"` + Value any `json:"value,omitempty"` } // Resolve walks payload independently for each field, so one field's @@ -138,7 +141,7 @@ func Resolve(fields []Field, payload []byte) (values map[string]any, failures [] continue } if !typeMatches(v, f.Type) { - failures = append(failures, Failure{FieldName: f.Name, Path: f.Path, Reason: ReasonTypeMismatch}) + failures = append(failures, Failure{FieldName: f.Name, Path: f.Path, Reason: ReasonTypeMismatch, Value: v}) continue } values[f.Name] = v diff --git a/modules/events/internal/store/store.go b/modules/events/internal/store/store.go index e6af97ab8..5c3d73f42 100644 --- a/modules/events/internal/store/store.go +++ b/modules/events/internal/store/store.go @@ -288,33 +288,39 @@ func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string, return out, nil } -// Dispatch outcomes. +// Dispatch outcomes. A trigger that matched an event either started a run, or +// started none because the event failed its mapping, access policy denied the +// start, or the workflow is disabled. const ( - OutcomeStarted = "started" - OutcomeSkipped = "skipped" + OutcomeStarted = "started" + OutcomeFailed = "failed" + OutcomeDenied = "denied" + OutcomeDisabled = "disabled" ) // RecordDispatch records that trigger started run for an event. It replaces an -// earlier skip of the same event by the same trigger. +// earlier outcome of the same event by the same trigger that started no run. func RecordDispatch(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger string, runID uuid.UUID) error { if _, err := tx.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, outcome = 'started', reason = NULL, created_at = now() - WHERE events.dispatches.outcome = 'skipped'`, eventID, trigger, runID); err != nil { + WHERE events.dispatches.outcome <> 'started'`, eventID, trigger, runID); err != nil { return fmt.Errorf("record dispatch: %w", err) } return nil } -// RecordSkip records that trigger started no run for an event, with the reason -// as a JSON document. A dispatch already recorded for the pair is kept. -func RecordSkip(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger string, reason jsontext.Value) error { +// RecordNoRun records that trigger matched an event but started no run, with +// the outcome and the reason as a JSON document. A started run already +// recorded for the pair is kept. +func RecordNoRun(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger, outcome string, reason jsontext.Value) error { if _, err := tx.ExecContext(ctx, ` - INSERT INTO events.dispatches (event_id, trigger, outcome, reason) VALUES ($1, $2, 'skipped', $3) - ON CONFLICT (event_id, trigger) DO UPDATE SET reason = EXCLUDED.reason, created_at = now() - WHERE events.dispatches.outcome = 'skipped'`, eventID, trigger, []byte(reason)); err != nil { - return fmt.Errorf("record skip: %w", err) + INSERT INTO events.dispatches (event_id, trigger, outcome, reason) VALUES ($1, $2, $3, $4) + ON CONFLICT (event_id, trigger) DO UPDATE + SET outcome = EXCLUDED.outcome, reason = EXCLUDED.reason, created_at = now() + WHERE events.dispatches.outcome <> 'started'`, eventID, trigger, outcome, []byte(reason)); err != nil { + return fmt.Errorf("record dispatch outcome: %w", err) } return nil } diff --git a/modules/events/mapping_skip_test.go b/modules/events/mapping_failure_test.go similarity index 55% rename from modules/events/mapping_skip_test.go rename to modules/events/mapping_failure_test.go index 18f5ceb97..5a74ce920 100644 --- a/modules/events/mapping_skip_test.go +++ b/modules/events/mapping_failure_test.go @@ -1,17 +1,19 @@ package events import ( + "reflect" "testing" "github.com/samcharles93/archie-core/modules/events/internal/mapping" "github.com/samcharles93/archie-core/modules/events/internal/store" ) -// TestMappingMismatchIsASkipWithItsReason guards the dispatch contract: an -// event that does not match a trigger's mapping starts no run and yields a skip -// naming each failed field, so the operator can see why the workflow didn't -// start. An event that matches still produces its run input. -func TestMappingMismatchIsASkipWithItsReason(t *testing.T) { +// TestMappingMismatchIsAFailureWithItsReason guards the dispatch contract: an +// event that does not match a trigger's mapping starts no run and records a +// failure naming each failed field and the value found there, so the operator +// can see why the workflow didn't start. An event that matches still produces +// its run input. +func TestMappingMismatchIsAFailureWithItsReason(t *testing.T) { row := store.Mapping{ Name: "incident", Fields: []byte(`[ @@ -26,7 +28,7 @@ func TestMappingMismatchIsASkipWithItsReason(t *testing.T) { }{ {name: "a matching event dispatches", body: `{"incident":{"id":"a1","severity":3}}`}, { - name: "a missing field is skipped", + name: "a missing field fails", body: `{"incident":{"id":"a1"}}`, wantFailures: []mapping.Failure{ {FieldName: "severity", Path: "incident.severity", Reason: mapping.ReasonMissing}, @@ -37,38 +39,33 @@ func TestMappingMismatchIsASkipWithItsReason(t *testing.T) { body: `{"incident":{"id":null,"severity":"high"}}`, wantFailures: []mapping.Failure{ {FieldName: "id", Path: "incident.id", Reason: mapping.ReasonNull}, - {FieldName: "severity", Path: "incident.severity", Reason: mapping.ReasonTypeMismatch}, + {FieldName: "severity", Path: "incident.severity", Reason: mapping.ReasonTypeMismatch, Value: "high"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - input, mapped, skip, err := applyMapping(store.Event{Body: []byte(tt.body)}, row) + input, mapped, failure, err := applyMapping(store.Event{Body: []byte(tt.body)}, row) if err != nil { t.Fatalf("applyMapping: %v", err) } if tt.wantFailures == nil { - if skip != nil || !mapped || len(input) == 0 { - t.Fatalf("applyMapping = (%s, %v, %+v), want a run input", input, mapped, skip) + if failure != nil || !mapped || len(input) == 0 { + t.Fatalf("applyMapping = (%s, %v, %+v), want a run input", input, mapped, failure) } return } - if skip == nil { - t.Fatalf("applyMapping recorded no skip, want %v", tt.wantFailures) + if failure == nil { + t.Fatalf("applyMapping recorded no failure, want %v", tt.wantFailures) } - if skip.Code != skipMappingMismatch || skip.Mapping != "incident" { - t.Errorf("skip = %+v, want code %q for mapping incident", skip, skipMappingMismatch) + if failure.outcome != store.OutcomeFailed || failure.Code != reasonMappingMismatch || failure.Mapping != "incident" { + t.Errorf("failure = %+v, want outcome %q, code %q for mapping incident", failure, store.OutcomeFailed, reasonMappingMismatch) } - if len(skip.Failures) != len(tt.wantFailures) { - t.Fatalf("failures = %+v, want %+v", skip.Failures, tt.wantFailures) - } - for i, f := range skip.Failures { - if f != tt.wantFailures[i] { - t.Errorf("failure %d = %+v, want %+v", i, f, tt.wantFailures[i]) - } + if !reflect.DeepEqual(failure.Failures, tt.wantFailures) { + t.Fatalf("failures = %+v, want %+v", failure.Failures, tt.wantFailures) } if mapped || input != nil { - t.Errorf("a skip must carry no run input, got %s", input) + t.Errorf("a failure must carry no run input, got %s", input) } }) } diff --git a/ui/src/bindings/TriggerRuns.vue b/ui/src/bindings/TriggerRuns.vue index 88fbc19a5..2c241ace5 100644 --- a/ui/src/bindings/TriggerRuns.vue +++ b/ui/src/bindings/TriggerRuns.vue @@ -1,7 +1,7 @@