feat(events,proposals,ui): identify triggers by immutable UUID (#2126)

This commit is contained in:
sam committed 2026-11-24 05:36:52 +11:00
1 parent 67ce2901a5
commit efe7069bc1
24 files changed
+473 -299

No files matched your search

+102 -65
View File
@@ -1523,9 +1523,13 @@ components:
type: string
trigger:
type: string
trigger_id:
type: string
required:
- event_id
- outcome
- trigger_id
- trigger
type: object
EventsEventDetail:
additionalProperties: false
@@ -1864,6 +1868,50 @@ components:
- signing
- capture
type: object
EventsTriggerBody:
additionalProperties: false
properties:
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
type: string
every:
description: Fire on an interval instead of on events, such as 1h
examples:
- 1h
type: string
filter:
additionalProperties:
type: string
description: Event fields that must match exactly
type: object
mapping_id:
description: A mapping of the event type that reads the payload into the run's input under mapped
format: uuid
type: string
name:
description: Lowercase letters, digits and hyphens, unique among the triggers
type: string
pending:
description: Save the trigger waiting for approval; it fires once a person approves it
type: boolean
source_id:
description: The source whose events fire it; none when every is set
format: uuid
type: string
workflow_id:
description: The workflow each match runs
format: uuid
type: string
required:
- name
- workflow_id
type: object
EventsTriggerRun:
additionalProperties: false
properties:
@@ -1879,17 +1927,12 @@ components:
type: string
trigger:
type: string
required:
- trigger
- outcome
type: object
EventsTriggerSaved:
additionalProperties: false
properties:
trigger:
trigger_id:
type: string
required:
- trigger_id
- trigger
- outcome
type: object
EventsTriggerView:
additionalProperties: false
@@ -1906,6 +1949,8 @@ components:
additionalProperties:
type: string
type: object
id:
type: string
mapping_id:
type: string
name:
@@ -1927,6 +1972,7 @@ components:
workflow_id:
type: string
required:
- id
- name
- event_type
- filter
@@ -3705,46 +3751,6 @@ components:
- array
- "null"
type: object
PutTriggerInputBody:
additionalProperties: false
properties:
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
type: string
every:
description: Fire on an interval instead of on events, such as 1h
examples:
- 1h
type: string
filter:
additionalProperties:
type: string
description: Event fields that must match exactly
type: object
mapping_id:
description: A mapping of the event type that reads the payload into the run's input under mapped
format: uuid
type: string
pending:
description: Save the trigger waiting for approval; it fires once a person approves it
type: boolean
source_id:
description: The source whose events fire it; none when every is set
format: uuid
type: string
workflow_id:
description: The workflow each match runs
format: uuid
type: string
required:
- workflow_id
type: object
PutWorkflowInputBody:
additionalProperties: false
properties:
@@ -4029,6 +4035,8 @@ components:
type: string
trigger:
type: string
trigger_id:
type: string
type:
type: string
required:
@@ -4038,6 +4046,7 @@ components:
- type
- fields
- received_at
- trigger_id
- trigger
- filter
type: object
@@ -9424,14 +9433,39 @@ paths:
summary: List triggers
tags:
- Events
/api/triggers/{name}:
post:
operationId: create-trigger
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/EventsTriggerBody"
required: true
responses:
"201":
content:
application/json:
schema:
$ref: "#/components/schemas/EventsTriggerView"
description: Created
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Add a trigger
tags:
- Events
/api/triggers/{id}:
delete:
operationId: delete-trigger
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"204":
@@ -9448,25 +9482,24 @@ paths:
put:
operationId: put-trigger
parameters:
- description: Lowercase letters, digits and hyphens
in: path
name: name
- in: path
name: id
required: true
schema:
description: Lowercase letters, digits and hyphens
format: uuid
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/PutTriggerInputBody"
$ref: "#/components/schemas/EventsTriggerBody"
required: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/EventsTriggerSaved"
$ref: "#/components/schemas/EventsTriggerView"
description: OK
default:
content:
@@ -9474,17 +9507,18 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Add or change a trigger
summary: Change a trigger, including its name; its dispatches refer to it by id and are unchanged
tags:
- Events
/api/triggers/{name}/approve:
/api/triggers/{id}/approve:
post:
operationId: approve-trigger
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"200":
@@ -9502,14 +9536,15 @@ paths:
summary: Arm a trigger that waits for approval
tags:
- Events
/api/triggers/{name}/dispatches:
/api/triggers/{id}/dispatches:
get:
operationId: list-trigger-dispatches
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
- explode: false
in: query
@@ -9540,14 +9575,15 @@ paths:
summary: List the dispatches of a trigger
tags:
- Events
/api/triggers/{name}/pause:
/api/triggers/{id}/pause:
post:
operationId: pause-trigger
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"200":
@@ -9565,14 +9601,15 @@ paths:
summary: Stop a trigger firing
tags:
- Events
/api/triggers/{name}/resume:
/api/triggers/{id}/resume:
post:
operationId: resume-trigger
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"200":
+9 -8
View File
@@ -32,25 +32,26 @@ async function main() {
await request("/api/workflows", { authenticated: false, status: 401 });
const name = `smoke-${randomUUID()}`;
const saved = await request(`/api/workflows/${name}`, {
method: "PUT",
body: { body: `repository: none\nsteps:\n - id: notify\n type: run.notify\n settings: {title: ${name}}\n` },
const saved = await request("/api/workflows", {
method: "POST",
status: 201,
body: { name, body: `repository: none\nsteps:\n - id: notify\n type: run.notify\n settings: {title: ${name}}\n` },
});
const trigger = { workflow: name, every: "1m" };
const trigger = { name, workflow_id: saved.id, every: "1m" };
const created = await request("/api/triggers", { method: "POST", body: trigger, status: 201 });
try {
await request(`/api/triggers/${name}`, { method: "PUT", body: trigger });
const deadline = Date.now() + 90_000;
let last = "no scheduled run";
while (Date.now() < deadline) {
const recent = await request("/api/runs");
const run = recent.find((row) => row.workflow === name);
const run = recent.find((row) => row.workflow_id === saved.id);
if (run) {
last = `run ${run.id}: ${run.state}`;
assert.ok(!["failed", "cancelled"].includes(run.state), `${last}: ${run.error || "no error returned"}`);
if (run.state === "succeeded") {
const trail = await request(`/api/runs/${run.id}`);
assert.equal(trail.run.workflow_version, saved.version, "Run used the wrong workflow version");
assert.equal(trail.origin?.trigger, name, "Run trail is missing the schedule trigger");
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");
const messages = await request("/api/composer/messages");
@@ -64,7 +65,7 @@ async function main() {
}
throw new Error(`Timed out waiting for ${name}: ${last}`);
} finally {
await request(`/api/triggers/${name}`, { method: "PUT", body: { ...trigger, disabled: true } });
await request(`/api/triggers/${created.id}`, { method: "PUT", body: { ...trigger, disabled: true } });
}
}
@@ -92,7 +92,13 @@ CREATE TABLE events.mappings (
updated_at timestamptz NOT NULL DEFAULT now()
);
-- A trigger is identified by its id, fixed when it is created; its name is a
-- 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.
CREATE TABLE events.triggers (
id uuid PRIMARY KEY,
org_id text NOT NULL,
name text NOT NULL,
source_id uuid REFERENCES events.sources (id),
@@ -106,21 +112,32 @@ CREATE TABLE events.triggers (
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,
PRIMARY KEY (org_id, name),
CHECK ((source_id IS NULL) = (schedule_every_s IS NOT NULL))
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);
CREATE TABLE events.dispatches (
event_id uuid NOT NULL REFERENCES events.events (id),
trigger text NOT NULL,
trigger_id uuid NOT NULL REFERENCES events.triggers (id),
run_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
outcome text NOT NULL DEFAULT 'started' CHECK (outcome IN ('started', 'failed', 'denied', 'disabled')),
reason jsonb,
PRIMARY KEY (event_id, trigger),
PRIMARY KEY (event_id, trigger_id),
CHECK ((outcome = 'started') = (run_id IS NOT NULL))
);
-- A replay is a run started for a stored event outside dispatch: a test run of
-- a trigger proposal, or a run an approved proposal starts for the events that
-- prompted it. label is the proposed trigger's name when the run started.
CREATE TABLE events.replays (
run_id uuid PRIMARY KEY,
event_id uuid NOT NULL REFERENCES events.events (id),
label text NOT NULL,
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.
CREATE TABLE events.groups (
+84 -63
View File
@@ -49,9 +49,13 @@ func (m *Module) Register(api huma.API) {
OperationID: "list-triggers", Method: http.MethodGet, Path: "/api/triggers",
Summary: "List triggers", Tags: tags,
}, m.triggers)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindTrigger), huma.Operation{
OperationID: "create-trigger", Method: http.MethodPost, Path: "/api/triggers",
Summary: "Add a trigger", Tags: tags, DefaultStatus: http.StatusCreated,
}, m.createTrigger)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindTrigger), huma.Operation{
OperationID: "put-trigger", Method: http.MethodPut, Path: "/api/triggers/{name}",
Summary: "Add or change a trigger", Tags: tags,
OperationID: "put-trigger", Method: http.MethodPut, Path: "/api/triggers/{id}",
Summary: "Change a trigger, including its name; its dispatches refer to it by id and are unchanged", Tags: tags,
}, m.putTrigger)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
OperationID: "list-groups", Method: http.MethodGet, Path: "/api/groups",
@@ -238,25 +242,29 @@ func (m *Module) setHMAC(src *store.Source, set SourceSettings, stored *store.So
return generated, nil
}
type putTriggerInput struct {
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
Body struct {
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"`
// 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"`
MappingID string `json:"mapping_id,omitzero" format:"uuid" doc:"A mapping of the event type that reads the payload into the run's input under mapped"`
Pending bool `json:"pending,omitzero" doc:"Save the trigger waiting for approval; it fires once a person approves it"`
}
// 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"`
// 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"`
MappingID string `json:"mapping_id,omitzero" format:"uuid" doc:"A mapping of the event type that reads the payload into the run's input under mapped"`
Pending bool `json:"pending,omitzero" doc:"Save the trigger waiting for approval; it fires once a person approves it"`
}
type triggerSaved struct {
Trigger string `json:"trigger"`
type createTriggerInput struct {
Body triggerBody
}
type putTriggerInput struct {
ID string `path:"id" format:"uuid"`
Body triggerBody
}
// parseEvery reads a schedule interval; an empty one is no schedule.
@@ -271,49 +279,76 @@ func parseEvery(raw string) (sql.NullInt64, error) {
return sql.NullInt64{Int64: int64(d / time.Second), Valid: true}, nil
}
func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.Reply[triggerSaved], error) {
req := in.Body
every, err := parseEvery(req.Every)
func (m *Module) createTrigger(ctx context.Context, in *createTriggerInput) (*httpapi.Reply[triggerView], error) {
return m.saveTrigger(ctx, store.Trigger{ID: uuid.New(), Approved: true}, in.Body)
}
// putTrigger changes a trigger, including its name.
func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.Reply[triggerView], error) {
t, err := m.visibleTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
return m.saveTrigger(ctx, t, in.Body)
}
// saveTrigger writes req over the trigger current describes; a new trigger's
// current has only its id and approval set.
func (m *Module) saveTrigger(ctx context.Context, current store.Trigger, req triggerBody) (*httpapi.Reply[triggerView], error) {
t, err := m.triggerOf(ctx, current, req)
if err != nil {
return nil, err
}
switch err := m.store.UpsertTrigger(ctx, t); {
case errors.Is(err, store.ErrExists):
return nil, huma.Error409Conflict("a trigger named " + req.Name + " already exists")
case errors.Is(err, store.ErrNotFound):
return nil, huma.Error404NotFound("no such trigger")
case err != nil:
return nil, huma.Error500InternalServerError("couldn't save the trigger", err)
}
view, err := m.viewOfTrigger(ctx, t)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the trigger", err)
}
return httpapi.OK(view), nil
}
// triggerOf checks req and returns the trigger it describes. A change keeps
// the trigger's approval unless it asks to wait for a new one.
func (m *Module) triggerOf(ctx context.Context, current store.Trigger, req triggerBody) (store.Trigger, error) {
every, err := parseEvery(req.Every)
if err != nil {
return store.Trigger{}, err
}
if every.Valid {
req.SourceID, req.EventType = "", scheduleType
// Every schedule's ticks share a source and type, so the filter keeps
// this trigger to its own.
req.Filter = map[string]string{"trigger": in.Name}
req.Filter = scheduleFilter(current.ID)
}
if !validName.MatchString(in.Name) || (req.SourceID == "" && !every.Valid) || (req.EventType == "" && req.EventTypeID == "") || req.WorkflowID == "" {
return nil, huma.Error400BadRequest("a trigger needs a lowercase name, a workflow, and either a source and event type or an every interval")
if !validName.MatchString(req.Name) || (req.SourceID == "" && !every.Valid) || (req.EventType == "" && 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)
if err != nil {
return nil, err
return store.Trigger{}, err
}
workflow, err := uuid.Parse(req.WorkflowID)
if err != nil {
return nil, huma.Error400BadRequest("a workflow id is a UUID", &huma.ErrorDetail{Location: "body.workflow_id", Message: "a workflow id is a UUID"})
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)
if err != nil {
return nil, err
return store.Trigger{}, err
}
filter, err := json.Marshal(req.Filter)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
return store.Trigger{}, huma.Error400BadRequest(err.Error())
}
approved, err := m.approvedOnSave(ctx, in.Name, req.Pending)
if err != nil {
return nil, err
}
if err := m.store.UpsertTrigger(ctx, store.Trigger{
OrgID: m.orgID, Name: in.Name, SourceID: sourceID, EventType: req.EventType,
Filter: filter, WorkflowID: workflow, Enabled: !req.Disabled, Approved: approved,
return store.Trigger{
ID: current.ID, OrgID: m.orgID, Name: req.Name, SourceID: sourceID, EventType: req.EventType,
Filter: filter, WorkflowID: workflow, Enabled: !req.Disabled, Approved: current.Approved && !req.Pending,
EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every,
}); err != nil {
return nil, huma.Error500InternalServerError("couldn't save the trigger", err)
}
return httpapi.OK(triggerSaved{Trigger: in.Name}), nil
}, nil
}
// triggerSource parses the source a trigger names, if any, and refuses one the
@@ -357,23 +392,6 @@ func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, event
return typeID, mapID, err
}
// approvedOnSave decides whether a saved trigger is approved. A new trigger is
// unless it asks to wait; a saved one keeps its approval unless the change asks
// to wait for a new approval.
func (m *Module) approvedOnSave(ctx context.Context, name string, pending bool) (bool, error) {
if pending {
return false, nil
}
t, err := m.store.Trigger(ctx, m.orgID, name)
if errors.Is(err, store.ErrNotFound) {
return true, nil
}
if err != nil {
return false, huma.Error500InternalServerError("couldn't read the trigger", err)
}
return t.Approved, nil
}
// checkBinding resolves the event type and mapping a trigger binds to. The
// event type must be the source's, and the mapping the event type's.
func (m *Module) checkBinding(ctx context.Context, sourceID uuid.NullUUID, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
@@ -580,7 +598,8 @@ func viewOfSource(src store.Source) (sourceView, error) {
// triggerView is a trigger as the API returns it.
type triggerView struct {
Name string `json:"name"`
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"`
@@ -613,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{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, EventType: t.EventType, 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)
@@ -672,7 +691,7 @@ func (m *Module) triggers(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]tr
}
view, err := viewOfTrigger(t)
if err != nil {
m.log.ErrorContext(ctx, "read trigger", "trigger", t.Name, "error", err)
m.log.ErrorContext(ctx, "read trigger", "trigger", t.ID, "error", err)
return nil, huma.Error500InternalServerError("couldn't read the filter of " + t.Name)
}
view.Source, view.Unsigned = src.Label, src.Verification == store.None
@@ -731,6 +750,8 @@ type eventDetail struct {
// triggerRun is the outcome of a trigger for an event: the run it started,
// or the reason no run started.
type triggerRun struct {
TriggerID uuid.UUID `json:"trigger_id"`
// Trigger is the trigger's current name.
Trigger string `json:"trigger"`
RunID *uuid.UUID `json:"run_id,omitempty"`
Outcome string `json:"outcome" enum:"started,failed,denied,disabled"`
@@ -775,7 +796,7 @@ func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[even
view.Body = jsontext.Value("null")
}
for _, run := range runs {
view.Runs = append(view.Runs, triggerRun{Trigger: run.Trigger, RunID: runIDOf(run.RunID), Outcome: run.Outcome, Reason: run.Reason})
view.Runs = append(view.Runs, triggerRun{TriggerID: run.TriggerID, Trigger: run.Trigger, RunID: runIDOf(run.RunID), Outcome: run.Outcome, Reason: run.Reason})
}
return httpapi.OK(view), nil
}
+5 -3
View File
@@ -118,8 +118,10 @@ type dispatchView struct {
RunID *uuid.UUID `json:"run_id,omitempty"`
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"`
TriggerID uuid.UUID `json:"trigger_id"`
// Trigger is the trigger's current name.
Trigger string `json:"trigger"`
CreatedAt time.Time `json:"created_at,omitzero"`
}
type idInput struct {
@@ -142,7 +144,7 @@ func (m *Module) captureDispatches(ctx context.Context, in *idInput) (*httpapi.R
}
out := make([]dispatchView, 0, len(runs))
for _, r := range runs {
out = append(out, dispatchView{EventID: id, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, Trigger: r.Trigger})
out = append(out, dispatchView{EventID: id, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, TriggerID: r.TriggerID, Trigger: r.Trigger})
}
return httpapi.OK(out), nil
}
+22 -20
View File
@@ -37,11 +37,11 @@ func (m *Module) registerSourceSettings(api huma.API) {
httpapi.Register(api, admin(governance.ActionReadSecret, governance.KindSecret), op("rotate-source-secret", http.MethodPost, "/api/sources/{id}/secret", "Replace a signed source's secret and return it once"), m.rotateSecret)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindSource), op("delete-source", http.MethodDelete, "/api/sources/{id}", "Delete a source"), m.deleteSource)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindTrigger), op("approve-trigger", http.MethodPost, "/api/triggers/{name}/approve", "Arm a trigger that waits for approval"), m.approveTrigger)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindTrigger), op("pause-trigger", http.MethodPost, "/api/triggers/{name}/pause", "Stop a trigger firing"), m.pauseTrigger)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindTrigger), op("resume-trigger", http.MethodPost, "/api/triggers/{name}/resume", "Return a paused trigger to waiting for approval"), m.resumeTrigger)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindTrigger), op("delete-trigger", http.MethodDelete, "/api/triggers/{name}", "Delete a trigger"), m.deleteTrigger)
httpapi.Register(api, admin(governance.ActionRead, governance.KindTrigger), op("list-trigger-dispatches", http.MethodGet, "/api/triggers/{name}/dispatches", "List the dispatches of a trigger"), m.triggerDispatches)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindTrigger), op("approve-trigger", http.MethodPost, "/api/triggers/{id}/approve", "Arm a trigger that waits for approval"), m.approveTrigger)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindTrigger), op("pause-trigger", http.MethodPost, "/api/triggers/{id}/pause", "Stop a trigger firing"), m.pauseTrigger)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindTrigger), op("resume-trigger", http.MethodPost, "/api/triggers/{id}/resume", "Return a paused trigger to waiting for approval"), m.resumeTrigger)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindTrigger), op("delete-trigger", http.MethodDelete, "/api/triggers/{id}", "Delete a trigger"), m.deleteTrigger)
httpapi.Register(api, admin(governance.ActionRead, governance.KindTrigger), op("list-trigger-dispatches", http.MethodGet, "/api/triggers/{id}/dispatches", "List the dispatches of a trigger"), m.triggerDispatches)
}
type sourceInput struct {
@@ -325,20 +325,20 @@ func (m *Module) deleteSource(ctx context.Context, in *sourceInput) (*struct{},
}
type triggerInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
}
// moveTrigger changes a trigger's state when it is in one of from, and refuses
// otherwise.
func (m *Module) moveTrigger(ctx context.Context, name string, allowed func(store.Trigger) bool, refusal string, approved, enabled bool) (*httpapi.Reply[triggerView], error) {
t, err := m.visibleTrigger(ctx, name)
func (m *Module) moveTrigger(ctx context.Context, id string, allowed func(store.Trigger) bool, refusal string, approved, enabled bool) (*httpapi.Reply[triggerView], error) {
t, err := m.visibleTrigger(ctx, id)
if err != nil {
return nil, err
}
if !allowed(t) {
return nil, huma.Error409Conflict(refusal)
}
if _, err := m.store.SetTriggerState(ctx, m.orgID, name, approved, enabled); err != nil {
if _, err := m.store.SetTriggerState(ctx, m.orgID, t.ID, approved, enabled); err != nil {
return nil, huma.Error500InternalServerError("couldn't save the trigger", err)
}
t.Approved, t.Enabled = approved, enabled
@@ -350,27 +350,28 @@ func (m *Module) moveTrigger(ctx context.Context, name string, allowed func(stor
}
func (m *Module) approveTrigger(ctx context.Context, in *triggerInput) (*httpapi.Reply[triggerView], error) {
return m.moveTrigger(ctx, in.Name, func(t store.Trigger) bool { return !t.Approved }, "the trigger isn't waiting for approval", true, true)
return m.moveTrigger(ctx, in.ID, func(t store.Trigger) bool { return !t.Approved }, "the trigger isn't waiting for approval", true, true)
}
func (m *Module) pauseTrigger(ctx context.Context, in *triggerInput) (*httpapi.Reply[triggerView], error) {
return m.moveTrigger(ctx, in.Name, func(t store.Trigger) bool { return t.Approved && t.Enabled }, "only an armed trigger can be paused", true, false)
return m.moveTrigger(ctx, in.ID, func(t store.Trigger) bool { return t.Approved && t.Enabled }, "only an armed trigger can be paused", true, false)
}
// resumeTrigger returns a paused trigger to waiting for approval, so a person
// approves it again before it fires.
func (m *Module) resumeTrigger(ctx context.Context, in *triggerInput) (*httpapi.Reply[triggerView], error) {
return m.moveTrigger(ctx, in.Name, func(t store.Trigger) bool { return t.Approved && !t.Enabled }, "only a paused trigger can be resumed", false, true)
return m.moveTrigger(ctx, in.ID, func(t store.Trigger) bool { return t.Approved && !t.Enabled }, "only a paused trigger can be resumed", false, true)
}
// deleteTrigger removes a trigger. It cascades to nothing: the runs it already
// started continue, and the dispatch records that link them to their events stay
// under the trigger's name.
// started continue, and the dispatch records that link them to their events
// still name the trigger. Its name is free for a new trigger.
func (m *Module) deleteTrigger(ctx context.Context, in *triggerInput) (*struct{}, error) {
if _, err := m.visibleTrigger(ctx, in.Name); err != nil {
t, err := m.visibleTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
err := m.store.DeleteTrigger(ctx, m.orgID, in.Name)
err = m.store.DeleteTrigger(ctx, m.orgID, t.ID)
switch {
case errors.Is(err, store.ErrNotFound):
return nil, huma.Error404NotFound("no such trigger")
@@ -381,21 +382,22 @@ func (m *Module) deleteTrigger(ctx context.Context, in *triggerInput) (*struct{}
}
type triggerDispatchesInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
Limit int `query:"limit" minimum:"1" maximum:"200" default:"50"`
}
func (m *Module) triggerDispatches(ctx context.Context, in *triggerDispatchesInput) (*httpapi.Reply[[]dispatchView], error) {
if _, err := m.visibleTrigger(ctx, in.Name); err != nil {
t, err := m.visibleTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
rows, err := m.store.DispatchesOf(ctx, m.orgID, in.Name, in.Limit)
rows, err := m.store.DispatchesOf(ctx, m.orgID, t.ID, in.Limit)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list the runs of the trigger", err)
}
out := make([]dispatchView, 0, len(rows))
for _, r := range rows {
out = append(out, dispatchView{EventID: r.EventID, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, Trigger: in.Name, CreatedAt: r.CreatedAt})
out = append(out, dispatchView{EventID: r.EventID, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, TriggerID: t.ID, Trigger: t.Name, CreatedAt: r.CreatedAt})
}
return httpapi.OK(out), nil
}
+21 -8
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"time"
@@ -68,14 +69,26 @@ func (m *Module) GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]St
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)
// Replayed records that a run for a proposed trigger replayed an event, so the
// run's trail names that event as its origin. label is the trigger's name.
func (m *Module) Replayed(ctx context.Context, eventID uuid.UUID, label string, runID uuid.UUID) error {
return m.store.RecordReplay(ctx, eventID, label, runID)
}
// TriggerSpec is an event trigger to save.
// TriggerNamed returns the id of the live trigger with the name, if there is
// one.
func (m *Module) TriggerNamed(ctx context.Context, name string) (uuid.UUID, bool, error) {
id, err := m.store.TriggerNamed(ctx, m.orgID, name)
if errors.Is(err, store.ErrNotFound) {
return uuid.Nil, false, nil
}
return id, err == nil, err
}
// 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
@@ -86,8 +99,8 @@ type TriggerSpec struct {
// SaveTrigger creates or replaces an event trigger.
func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error {
if !validName.MatchString(t.Name) || t.SourceID == uuid.Nil || t.EventType == "" || t.WorkflowID == uuid.Nil {
return fmt.Errorf("a trigger needs 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.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 err := m.runs.CheckTrigger(ctx, m.orgID, t.WorkflowID); err != nil {
return err
@@ -97,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{
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}, EventType: t.EventType,
Filter: filter, WorkflowID: t.WorkflowID, Enabled: true, Approved: true,
})
}
+9 -9
View File
@@ -650,7 +650,7 @@ 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 notMatched, fmt.Errorf("trigger %q filter: %w", t.Name, err)
return notMatched, fmt.Errorf("trigger %s filter: %w", t.ID, err)
}
if !match.Fields(e.Fields, filter) {
return notMatched, nil
@@ -680,10 +680,10 @@ func (m *Module) recordStarted(ctx context.Context, tx *sqlx.Tx, e store.Event,
return err
}
}
if err := store.RecordDispatch(ctx, tx, e.ID, t.Name, runID); err != nil {
if err := store.RecordDispatch(ctx, tx, e.ID, t.ID, runID); err != nil {
return err
}
m.log.InfoContext(ctx, "trigger started run", "event", e.ID, "trigger", t.Name, "run", runID)
m.log.InfoContext(ctx, "trigger started run", "event", e.ID, "trigger", t.ID, "run", runID)
return nil
}
@@ -693,7 +693,7 @@ func recordNoRun(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigge
if err != nil {
return fmt.Errorf("encode no-run reason: %w", err)
}
return store.RecordNoRun(ctx, tx, e.ID, t.Name, why.outcome, reason)
return store.RecordNoRun(ctx, tx, e.ID, t.ID, why.outcome, reason)
}
// noteUnmatched files an event no trigger took into a group for review.
@@ -717,18 +717,18 @@ func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event)
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{
OrgID: e.OrgID, WorkflowID: t.WorkflowID, Key: e.ID.String() + ":" + t.Name, Input: input,
OrgID: e.OrgID, WorkflowID: t.WorkflowID, Key: e.ID.String() + ":" + t.ID.String(), 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)
m.log.WarnContext(ctx, "trigger not permitted to start its workflow", "event", e.ID, "trigger", t.ID, "error", err)
return uuid.Nil, &noRunReason{outcome: store.OutcomeDenied, Code: reasonAccessDenied, WorkflowID: t.WorkflowID, Workflow: m.workflowName(ctx, t.WorkflowID), Detail: err.Error()}, nil
}
if errors.Is(err, runs.ErrDisabled) {
m.log.InfoContext(ctx, "trigger started no run: the workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.WorkflowID)
m.log.InfoContext(ctx, "trigger started no run: the workflow is disabled", "event", e.ID, "trigger", t.ID, "workflow", t.WorkflowID)
return uuid.Nil, &noRunReason{outcome: store.OutcomeDisabled, Code: reasonWorkflowDisabled, WorkflowID: t.WorkflowID, Workflow: m.workflowName(ctx, t.WorkflowID)}, nil
}
if err != nil {
return uuid.Nil, nil, fmt.Errorf("start run for trigger %q: %w", t.Name, err)
return uuid.Nil, nil, fmt.Errorf("start run for trigger %s: %w", t.ID, err)
}
return runID, nil, nil
}
@@ -741,7 +741,7 @@ func (m *Module) Origin(ctx context.Context, runID uuid.UUID) (runs.Origin, bool
}
return runs.Origin{
EventID: o.EventID, SourceID: o.SourceID.UUID, Source: o.Source, Type: o.Type, Fields: o.Fields,
ReceivedAt: o.ReceivedAt, Trigger: o.Trigger, Filter: o.Filter,
ReceivedAt: o.ReceivedAt, TriggerID: o.TriggerID.UUID, Trigger: o.Trigger, Filter: o.Filter,
}, true, nil
}
+33 -16
View File
@@ -350,7 +350,7 @@ func (s *Store) DeleteSource(ctx context.Context, orgID string, id uuid.UUID) er
}
defer func() { _ = tx.Rollback() }()
var triggers int
if err := tx.GetContext(ctx, &triggers, `SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2`, orgID, id); err != nil {
if err := tx.GetContext(ctx, &triggers, `SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2 AND deleted_at IS NULL`, orgID, id); err != nil {
return fmt.Errorf("check triggers of source: %w", err)
}
if triggers > 0 {
@@ -377,18 +377,19 @@ func (s *Store) DeleteSource(ctx context.Context, orgID string, id uuid.UUID) er
func (s *Store) MappedTriggers(ctx context.Context, orgID string, sourceID uuid.UUID) (int, error) {
var n int
if err := s.db.GetContext(ctx, &n, `
SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2 AND mapping_id IS NOT NULL`, orgID, sourceID); err != nil {
SELECT count(*) FROM events.triggers
WHERE org_id = $1 AND source_id = $2 AND mapping_id IS NOT NULL AND deleted_at IS NULL`, orgID, sourceID); err != nil {
return 0, fmt.Errorf("count mapped triggers: %w", err)
}
return n, nil
}
// SetTriggerState changes whether a trigger is approved and enabled, and
// SetTriggerState changes whether a live trigger is approved and enabled, and
// reports whether it exists.
func (s *Store) SetTriggerState(ctx context.Context, orgID, name string, approved, enabled bool) (bool, error) {
func (s *Store) SetTriggerState(ctx context.Context, orgID string, id uuid.UUID, approved, enabled bool) (bool, error) {
res, err := s.db.ExecContext(ctx, `
UPDATE events.triggers SET approved = $3, enabled = $4, updated_at = now()
WHERE org_id = $1 AND name = $2`, orgID, name, approved, enabled)
WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, orgID, id, approved, enabled)
if err != nil {
return false, fmt.Errorf("save trigger: %w", err)
}
@@ -396,13 +397,12 @@ func (s *Store) SetTriggerState(ctx context.Context, orgID, name string, approve
return n == 1, err
}
// Trigger returns one trigger.
func (s *Store) Trigger(ctx context.Context, orgID, name string) (Trigger, error) {
// Trigger returns one live trigger.
func (s *Store) Trigger(ctx context.Context, orgID string, id uuid.UUID) (Trigger, error) {
var t Trigger
err := s.db.GetContext(ctx, &t, `
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id,
schedule_every_s, schedule_since
FROM events.triggers WHERE org_id = $1 AND name = $2`, orgID, name)
SELECT `+triggerColumns+`
FROM events.triggers WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Trigger{}, ErrNotFound
}
@@ -412,10 +412,27 @@ func (s *Store) Trigger(ctx context.Context, orgID, name string) (Trigger, error
return t, nil
}
// DeleteTrigger removes a trigger. Runs it already started and their dispatch
// records stay.
func (s *Store) DeleteTrigger(ctx context.Context, orgID, name string) error {
res, err := s.db.ExecContext(ctx, `DELETE FROM events.triggers WHERE org_id = $1 AND name = $2`, orgID, name)
// TriggerNamed returns the id of the live trigger with the name.
func (s *Store) TriggerNamed(ctx context.Context, orgID, name string) (uuid.UUID, error) {
var id uuid.UUID
err := s.db.GetContext(ctx, &id, `
SELECT id FROM events.triggers WHERE org_id = $1 AND name = $2 AND deleted_at IS NULL`, orgID, name)
if errors.Is(err, sql.ErrNoRows) {
return uuid.Nil, ErrNotFound
}
if err != nil {
return uuid.Nil, fmt.Errorf("read trigger: %w", err)
}
return id, nil
}
// DeleteTrigger marks a trigger deleted and clears its source, event type and
// mapping. Runs it already started and their dispatch records stay.
func (s *Store) DeleteTrigger(ctx context.Context, orgID string, id uuid.UUID) error {
res, err := s.db.ExecContext(ctx, `
UPDATE events.triggers
SET deleted_at = now(), enabled = false, source_id = NULL, event_type_id = NULL, mapping_id = NULL, updated_at = now()
WHERE org_id = $1 AND id = $2 AND deleted_at IS NULL`, orgID, id)
if err != nil {
return fmt.Errorf("delete trigger: %w", err)
}
@@ -436,12 +453,12 @@ type Dispatch struct {
}
// DispatchesOf returns a trigger's dispatches, newest first.
func (s *Store) DispatchesOf(ctx context.Context, orgID, trigger string, limit int) ([]Dispatch, error) {
func (s *Store) DispatchesOf(ctx context.Context, orgID string, triggerID uuid.UUID, limit int) ([]Dispatch, error) {
var out []Dispatch
if err := s.db.SelectContext(ctx, &out, `
SELECT d.event_id, d.run_id, d.outcome, d.reason, d.created_at FROM events.dispatches d
JOIN events.events e ON e.id = d.event_id
WHERE e.org_id = $1 AND d.trigger = $2 ORDER BY d.created_at DESC LIMIT $3`, orgID, trigger, limit); err != nil {
WHERE e.org_id = $1 AND d.trigger_id = $2 ORDER BY d.created_at DESC LIMIT $3`, orgID, triggerID, limit); err != nil {
return nil, fmt.Errorf("list dispatches: %w", err)
}
return out, nil
+6 -7
View File
@@ -38,14 +38,13 @@ func (s *Store) GroupEvents(ctx context.Context, orgID string, id uuid.UUID, lim
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 {
// RecordReplay notes that run replayed an event outside dispatch, so the run's
// origin reads as that event. label names the trigger the run was for.
func (s *Store) RecordReplay(ctx context.Context, eventID uuid.UUID, label 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, outcome = 'started', reason = NULL, created_at = now()`,
eventID, trigger, runID); err != nil {
INSERT INTO events.replays (run_id, event_id, label) VALUES ($1, $2, $3)
ON CONFLICT (run_id) DO NOTHING`,
runID, eventID, label); err != nil {
return fmt.Errorf("record replay: %w", err)
}
return nil
+2 -2
View File
@@ -69,8 +69,8 @@ func (s *Store) Groups(ctx context.Context, orgID, person string, limit int) ([]
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.source_id = g.source_id AND t.event_type = g.event_type
AND t.filter = g.filter)
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)
ORDER BY g.last_seen DESC LIMIT $3`, orgID, person, limit); err != nil {
return nil, fmt.Errorf("list groups: %w", err)
}
+67 -44
View File
@@ -124,8 +124,11 @@ const (
// Trigger starts a workflow for events of one type from one source whose
// fields match its filter.
type Trigger struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
// Name is the trigger's label, unique among the organisation's live
// 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"`
@@ -145,6 +148,9 @@ 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`
// Store is the events module's Postgres store.
type Store struct {
db *sqlx.DB
@@ -344,10 +350,10 @@ func SetEventPayload(ctx context.Context, tx *sqlx.Tx, e Event) error {
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID string, sourceID uuid.NullUUID, eventType string, typeID uuid.NullUUID) ([]Trigger, error) {
var out []Trigger
if err := tx.SelectContext(ctx, &out, `
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id
SELECT `+triggerColumns+`
FROM events.triggers
WHERE org_id = $1 AND source_id IS NOT DISTINCT FROM $2 AND (event_type = $3 OR event_type = '') AND enabled AND approved
AND (event_type_id IS NULL OR event_type_id = $4)
WHERE org_id = $1 AND deleted_at IS NULL AND source_id IS NOT DISTINCT FROM $2 AND (event_type = $3 OR 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 {
return nil, fmt.Errorf("read triggers: %w", err)
@@ -365,43 +371,45 @@ const (
OutcomeDisabled = "disabled"
)
// RecordDispatch records that trigger started run for an event. It replaces an
// 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 {
// RecordDispatch records that a trigger started run for an event. It replaces
// an earlier outcome of the same event by the same trigger that started no run.
func RecordDispatch(ctx context.Context, tx *sqlx.Tx, eventID, triggerID, 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
INSERT INTO events.dispatches (event_id, trigger_id, run_id) VALUES ($1, $2, $3)
ON CONFLICT (event_id, trigger_id) DO UPDATE
SET run_id = EXCLUDED.run_id, outcome = 'started', reason = NULL, created_at = now()
WHERE events.dispatches.outcome <> 'started'`, eventID, trigger, runID); err != nil {
WHERE events.dispatches.outcome <> 'started'`, eventID, triggerID, runID); err != nil {
return fmt.Errorf("record dispatch: %w", err)
}
return nil
}
// 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
// RecordNoRun records that a 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 {
func RecordNoRun(ctx context.Context, tx *sqlx.Tx, eventID, triggerID uuid.UUID, outcome string, reason jsontext.Value) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO events.dispatches (event_id, trigger, outcome, reason) VALUES ($1, $2, $3, $4)
ON CONFLICT (event_id, trigger) DO UPDATE
INSERT INTO events.dispatches (event_id, trigger_id, outcome, reason) VALUES ($1, $2, $3, $4)
ON CONFLICT (event_id, trigger_id) DO UPDATE
SET outcome = EXCLUDED.outcome, reason = EXCLUDED.reason, created_at = now()
WHERE events.dispatches.outcome <> 'started'`, eventID, trigger, outcome, []byte(reason)); err != nil {
WHERE events.dispatches.outcome <> 'started'`, eventID, triggerID, outcome, []byte(reason)); err != nil {
return fmt.Errorf("record dispatch outcome: %w", err)
}
return nil
}
// UpsertTrigger creates or replaces a trigger.
// UpsertTrigger creates the trigger t.ID names, or replaces it. It returns
// ErrExists when a live trigger already has the name, and ErrNotFound when the
// trigger was deleted.
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.triggers (org_id, name, source_id, event_type, filter, workflow_id, enabled, approved,
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 (:org_id, :name, :source_id, :event_type, :filter, :workflow_id, :enabled, :approved,
VALUES (:id, :org_id, :name, :source_id, :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 (org_id, name) DO UPDATE
SET source_id = EXCLUDED.source_id, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter,
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,
schedule_since = CASE
@@ -409,8 +417,13 @@ func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
WHEN events.triggers.schedule_every_s IS NOT DISTINCT FROM EXCLUDED.schedule_every_s
THEN events.triggers.schedule_since
ELSE now() END,
schedule_every_s = EXCLUDED.schedule_every_s, updated_at = now()`, t); err != nil {
return fmt.Errorf("save trigger: %w", err)
schedule_every_s = EXCLUDED.schedule_every_s, updated_at = now()
WHERE events.triggers.org_id = EXCLUDED.org_id AND events.triggers.deleted_at IS NULL`, t)
if err != nil {
return fmt.Errorf("save trigger: %w", classify(err))
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return ErrNotFound
}
return nil
}
@@ -419,10 +432,10 @@ func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
var out []Trigger
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id,
schedule_every_s, schedule_since
SELECT `+triggerColumns+`
FROM events.triggers
WHERE org_id = $1 AND enabled AND approved AND schedule_every_s IS NOT NULL ORDER BY name`, orgID); err != nil {
WHERE org_id = $1 AND deleted_at IS NULL AND enabled AND approved AND schedule_every_s IS NOT NULL
ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("read schedules: %w", err)
}
return out, nil
@@ -481,37 +494,39 @@ func (s *Store) Event(ctx context.Context, orgID, person string, id uuid.UUID) (
// TriggerRun is the outcome of a trigger for an event: the run it started, or
// the reason no run started.
type TriggerRun struct {
Trigger string `db:"trigger"`
RunID uuid.NullUUID `db:"run_id"`
Outcome string `db:"outcome"`
Reason jsontext.Value `db:"reason"`
TriggerID uuid.UUID `db:"trigger_id"`
Trigger string `db:"trigger"`
RunID uuid.NullUUID `db:"run_id"`
Outcome string `db:"outcome"`
Reason jsontext.Value `db:"reason"`
}
// RunsForEvent returns the dispatches of every trigger for an event.
func (s *Store) RunsForEvent(ctx context.Context, orgID string, id uuid.UUID) ([]TriggerRun, error) {
var out []TriggerRun
if err := s.db.SelectContext(ctx, &out, `
SELECT d.trigger, d.run_id, d.outcome, d.reason FROM events.dispatches d
SELECT d.trigger_id, t.name AS trigger, d.run_id, d.outcome, d.reason FROM events.dispatches d
JOIN events.events e ON e.id = d.event_id
WHERE e.org_id = $1 AND d.event_id = $2 ORDER BY d.trigger`, orgID, id); err != nil {
JOIN events.triggers t ON t.id = d.trigger_id
WHERE e.org_id = $1 AND d.event_id = $2 ORDER BY t.name, d.trigger_id`, orgID, id); err != nil {
return nil, fmt.Errorf("read event runs: %w", err)
}
return out, nil
}
// AllTriggers returns every trigger of the organisation, enabled or not.
// AllTriggers returns every live trigger of the organisation, enabled or not.
func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
var out []Trigger
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, source_id, event_type, filter, workflow_id, enabled, approved, event_type_id, mapping_id,
schedule_every_s, schedule_since
FROM events.triggers WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
SELECT `+triggerColumns+`
FROM events.triggers WHERE org_id = $1 AND deleted_at IS NULL ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("list triggers: %w", err)
}
return out, nil
}
// Origin is the event and trigger that started a run.
// 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"`
@@ -519,6 +534,7 @@ type Origin struct {
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"`
}
@@ -527,13 +543,20 @@ type Origin struct {
func (s *Store) OriginOf(ctx context.Context, orgID string, runID uuid.UUID) (Origin, bool, error) {
var o Origin
err := s.db.GetContext(ctx, &o, `
WITH o AS (
SELECT d.event_id, t.id AS trigger_id, t.name AS trigger, t.filter
FROM events.dispatches d JOIN events.triggers t ON t.id = d.trigger_id
WHERE d.run_id = $2
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, d.trigger, COALESCE(t.filter, '{}') AS filter
FROM events.dispatches d
JOIN events.events e ON e.id = d.event_id
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
LEFT JOIN events.triggers t ON t.org_id = e.org_id AND t.name = d.trigger
WHERE e.org_id = $1 AND d.run_id = $2`, orgID, runID)
WHERE e.org_id = $1
LIMIT 1`, orgID, runID)
if errors.Is(err, sql.ErrNoRows) {
return Origin{}, false, nil
}
+19 -5
View File
@@ -44,25 +44,39 @@ func (m *Module) tick(ctx context.Context, now time.Time) error {
if !due {
continue
}
fields, err := json.Marshal(map[string]string{"trigger": t.Name, "slot": slot.UTC().Format(time.RFC3339)})
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.Name, slot, fields))
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.Name, "slot", slot)
m.log.InfoContext(ctx, "schedule fired", "trigger", t.ID, "slot", slot)
}
}
return nil
}
func tickEvent(orgID, trigger string, slot time.Time, fields jsontext.Value) store.Event {
// 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, Type: scheduleType,
SourceEventID: trigger + "@" + slot.UTC().Format(time.RFC3339), Fields: fields,
SourceEventID: trigger.String() + "@" + slot.UTC().Format(time.RFC3339), Fields: fields,
}
e.OccurredAt.Time, e.OccurredAt.Valid = slot, true
return e
+6 -2
View File
@@ -44,8 +44,12 @@ func (m *Module) canUse(ctx context.Context, id uuid.UUID) (bool, error) {
// visibleTrigger reads a trigger the caller may see. A trigger on someone
// else's person source reads as missing.
func (m *Module) visibleTrigger(ctx context.Context, name string) (store.Trigger, error) {
t, err := m.store.Trigger(ctx, m.orgID, name)
func (m *Module) visibleTrigger(ctx context.Context, rawID string) (store.Trigger, error) {
id, err := uuid.Parse(rawID)
if err != nil {
return store.Trigger{}, huma.Error400BadRequest("a trigger id is a UUID")
}
t, err := m.store.Trigger(ctx, m.orgID, id)
if errors.Is(err, store.ErrNotFound) {
return t, huma.Error404NotFound("no such trigger")
}
+11 -3
View File
@@ -84,8 +84,10 @@ const workInterval = 5 * time.Second
type Groups interface {
Group(ctx context.Context, id uuid.UUID) (events.Group, bool, error)
GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]events.Stored, error)
Replayed(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error
Replayed(ctx context.Context, eventID uuid.UUID, label string, runID uuid.UUID) error
SaveTrigger(ctx context.Context, t events.TriggerSpec) error
// TriggerNamed returns the live trigger with the name, if there is one.
TriggerNamed(ctx context.Context, name string) (uuid.UUID, bool, error)
}
// Workflows installs workflow documents, starts runs and manages dry runs.
@@ -394,8 +396,8 @@ func (m *Module) Approve(ctx context.Context, id uuid.UUID, assertion *approvals
}
// readyToApprove refuses an approval that could not be applied: a trigger
// whose workflow name is taken or whose parts are invalid, or an action that
// would not be bound to the approval.
// whose name or workflow name is taken or whose parts are invalid, or an
// action that would not be bound to the approval.
func (m *Module) readyToApprove(ctx context.Context, p store.Proposal, actions []store.Action, decisions []judgement.Decision, who string) error {
if p.Kind == KindTrigger {
c, err := readTrigger(p)
@@ -412,6 +414,12 @@ func (m *Module) readyToApprove(ctx context.Context, p store.Proposal, actions [
default:
return fmt.Errorf("%w: a workflow named %s already exists; rename the proposal", ErrTaken, c.Name)
}
switch id, found, err := m.groups.TriggerNamed(ctx, c.Name); {
case err != nil:
return fmt.Errorf("check the trigger name: %w", err)
case found && id != c.TriggerID:
return fmt.Errorf("%w: a trigger named %s already exists; rename the proposal", ErrTaken, c.Name)
}
}
trial := p
trial.State = StateApproved
+8 -5
View File
@@ -26,9 +26,12 @@ const replayable = 50
// it starts and the policy added with them, for the group of unmatched events
// that prompted it.
type triggerChange struct {
GroupID uuid.UUID `json:"group_id"`
Name string `json:"name"`
SourceID uuid.UUID `json:"source_id"`
GroupID uuid.UUID `json:"group_id"`
// TriggerID is the id the trigger is saved under, chosen when the proposal
// is made so that publishing it again replaces the same trigger.
TriggerID uuid.UUID `json:"trigger_id"`
Name string `json:"name"`
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"`
@@ -162,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, 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, EventType: g.EventType, Filter: g.Filter,
Workflow: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules,
}
raw, err := json.Marshal(change)
@@ -288,7 +291,7 @@ func (m *Module) publishTrigger(ctx context.Context, p store.Proposal) error {
return err
}
if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{
Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: c.Filter, WorkflowID: workflow,
ID: c.TriggerID, Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: c.Filter, WorkflowID: workflow,
}); err != nil {
return fmt.Errorf("save the trigger: %w", err)
}
+6 -2
View File
@@ -32,8 +32,12 @@ type Origin struct {
Type string `json:"type"`
Fields jsontext.Value `json:"fields"`
ReceivedAt time.Time `json:"received_at"`
Trigger string `json:"trigger"`
Filter jsontext.Value `json:"filter"`
// 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.
TriggerID uuid.UUID `json:"trigger_id"`
Trigger string `json:"trigger"`
Filter jsontext.Value `json:"filter"`
}
// Origins finds the event and trigger that started a run. A run started any
-1
View File
@@ -106,7 +106,6 @@ const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
<Input
id="binding-name"
v-model="draft.name"
:disabled="!!props.binding"
pattern="[a-z][a-z0-9\-]*"
required
/>
+1 -1
View File
@@ -61,7 +61,7 @@ const noRunText = (reason?: NoRunReason) => {
<ul v-else-if="runs.length" class="flex flex-col gap-1 text-caption">
<li
v-for="r in runs"
:key="r.event_id + (r.trigger ?? '')"
:key="r.event_id + r.trigger_id"
class="flex flex-wrap items-center gap-x-2 font-mono text-fg-muted"
>
<RouterLink
+6 -5
View File
@@ -7,7 +7,7 @@
import type { EventType } from "../captures/event-types";
import type { Trigger, TriggerInput } from "../lib/api";
/** A trigger bound to an event type, named by the trigger's name. */
/** A trigger bound to an event type. id is the trigger's id. */
export interface Binding {
id: string;
name: string;
@@ -24,7 +24,7 @@ export interface Binding {
export function bindingOfTrigger(trigger: Trigger): Binding {
return {
id: trigger.name,
id: trigger.id,
name: trigger.name,
source: trigger.source ?? "",
event_type_id: trigger.event_type_id,
@@ -61,7 +61,7 @@ export interface WorkflowOption {
/** The editor's field state. */
export interface BindingDraft {
/** The trigger's name when editing; null for a new binding. */
/** The trigger's id when editing; null for a new binding. */
id: string | null;
name: string;
/** The event type the binding applies to; its source is the binding's. */
@@ -85,14 +85,15 @@ export function draftFromBinding(binding: Binding): BindingDraft {
};
}
/** The body PUT /api/triggers/{name} takes. A saved binding waits for
* approval again. */
/** The body that saving a trigger takes. A saved binding waits for approval
* again. */
export function bindingPayload(
draft: BindingDraft,
eventTypes: EventType[],
): TriggerInput {
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
return {
name: draft.name,
source_id: eventType?.source_id ?? "",
event_type_id: draft.eventTypeId,
mapping_id: draft.mappingId || undefined,
+2 -1
View File
@@ -79,7 +79,8 @@ export function useBindings() {
saving.value = true;
saveFailure.value = null;
try {
await api.putTrigger(draft.id ?? draft.name, bindingPayload(draft, eventTypes.value));
const payload = bindingPayload(draft, eventTypes.value);
await (draft.id ? api.putTrigger(draft.id, payload) : api.createTrigger(payload));
await load();
return true;
} catch (err) {
+11 -9
View File
@@ -47,11 +47,12 @@ const columns = computed<DataTableColumn<Trigger>[]>(() => [
const busy = ref(false);
const actionError = ref("");
async function save(name: string, input: TriggerInput): Promise<boolean> {
/** save changes the trigger id names, or adds one when id is empty. */
async function save(id: string, input: TriggerInput): Promise<boolean> {
busy.value = true;
actionError.value = "";
try {
await api.putTrigger(name, input);
await (id ? api.putTrigger(id, input) : api.createTrigger(input));
await reload();
return true;
} catch (cause) {
@@ -64,11 +65,12 @@ async function save(name: string, input: TriggerInput): Promise<boolean> {
const editing = ref(false);
const isNew = ref(true);
const form = ref({ name: "", mode: "event", source_id: "", event_type: "", every: "", workflow: "", filter: "", disabled: false });
const form = ref({ id: "", name: "", mode: "event", source_id: "", event_type: "", every: "", workflow: "", filter: "", disabled: false });
function open(trigger?: Trigger): void {
isNew.value = !trigger;
actionError.value = "";
form.value = {
id: trigger?.id ?? "",
name: trigger?.name ?? "",
mode: trigger?.every ? "schedule" : "event",
source_id: trigger?.every ? "" : (trigger?.source_id ?? ""),
@@ -85,9 +87,9 @@ async function submit(): Promise<void> {
const filter = fromLines(f.filter);
const input: TriggerInput =
f.mode === "schedule"
? { every: f.every.trim(), workflow_id: f.workflow, disabled: f.disabled }
: { source_id: f.source_id, event_type: f.event_type.trim(), filter, workflow_id: f.workflow, disabled: f.disabled };
if (await save(f.name.trim(), input)) editing.value = false;
? { 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 };
if (await save(f.id, input)) editing.value = false;
}
</script>
@@ -100,7 +102,7 @@ async function submit(): Promise<void> {
<div class="mb-2 flex justify-end">
<Button size="icon-sm" variant="ghost" aria-label="Add trigger" title="Add trigger" @click="open()"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="rows" :row-key="(t) => t.name" :storage-key="workflow ? 'workflow-triggers' : 'triggers'">
<DataTable :columns="columns" :rows="rows" :row-key="(t) => t.id" :storage-key="workflow ? 'workflow-triggers' : 'triggers'">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.every ? `Every ${interval(row.every)}` : `${row.source} ${row.event_type}` }}</span></template>
<template #cell-fires="{ row }">
<template v-if="row.every">Every {{ interval(row.every) }}</template>
@@ -111,7 +113,7 @@ async function submit(): Promise<void> {
<span v-if="!row.every" class="font-mono text-caption">{{ Object.entries(row.filter ?? {}).map(([k, v]) => `${k}=${v}`).join(", ") }}</span>
</template>
<template #cell-enabled="{ row }">
<Switch size="sm" :model-value="row.enabled" :disabled="busy" :aria-label="`${row.name} on`" @click.stop @update:model-value="save(row.name, { ...triggerInput(row), disabled: !$event })" />
<Switch size="sm" :model-value="row.enabled" :disabled="busy" :aria-label="`${row.name} on`" @click.stop @update:model-value="save(row.id, { ...triggerInput(row), disabled: !$event })" />
</template>
<template #actions="{ row }">
<MoreMenu :label="`${row.name} actions`"><DropdownMenuItem @select="open(row)">Edit</DropdownMenuItem></MoreMenu>
@@ -124,7 +126,7 @@ async function submit(): Promise<void> {
<DialogContent>
<DialogHeader><DialogTitle>{{ isNew ? "Add trigger" : `Edit ${form.name}` }}</DialogTitle></DialogHeader>
<form id="trigger-form" class="space-y-3" @submit.prevent="submit">
<Input v-if="isNew" v-model="form.name" aria-label="Name" placeholder="Name" pattern="[a-z0-9][a-z0-9-]*" required />
<Input v-model="form.name" aria-label="Name" placeholder="Name" pattern="[a-z0-9][a-z0-9-]*" required />
<ToggleGroup v-model="form.mode" type="single" variant="outline" size="sm" aria-label="Fires on">
<ToggleGroupItem value="event">Events</ToggleGroupItem>
<ToggleGroupItem value="schedule">Schedule</ToggleGroupItem>
+2 -1
View File
@@ -3,8 +3,9 @@ import type { Trigger, TriggerInput } from "@/lib/api";
/** triggerInput is the put that keeps a listed trigger as it is. A schedule
* sends only its interval: the server fixes its source, type and filter. */
export function triggerInput(trigger: Trigger): TriggerInput {
if (trigger.every) return { every: trigger.every, workflow_id: trigger.workflow_id, disabled: !trigger.enabled };
if (trigger.every) return { name: trigger.name, every: trigger.every, workflow_id: trigger.workflow_id, disabled: !trigger.enabled };
return {
name: trigger.name,
source_id: trigger.source_id,
event_type: trigger.event_type,
filter: trigger.filter,
+20 -15
View File
@@ -225,25 +225,26 @@ export const api = {
sourceCapture: (id: string, capture: boolean) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/capture`, { method: "PUT", body: { capture } }),
/** The runs a trigger started, newest first. */
triggerDispatches: (name: string) =>
request<TriggerRun[]>(`/api/triggers/${encodeURIComponent(name)}/dispatches`),
approveTrigger: (name: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(name)}/approve`, { method: "POST" }),
pauseTrigger: (name: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(name)}/pause`, { method: "POST" }),
triggerDispatches: (id: string) =>
request<TriggerRun[]>(`/api/triggers/${encodeURIComponent(id)}/dispatches`),
approveTrigger: (id: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(id)}/approve`, { method: "POST" }),
pauseTrigger: (id: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(id)}/pause`, { method: "POST" }),
/** A resumed trigger waits for approval again. */
resumeTrigger: (name: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(name)}/resume`, { method: "POST" }),
deleteTrigger: (name: string) =>
request<void>(`/api/triggers/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
resumeTrigger: (id: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(id)}/resume`, { method: "POST" }),
deleteTrigger: (id: string) =>
request<void>(`/api/triggers/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
/** The runs a stored delivery started. */
captureDispatches: (id: string) =>
request<TriggerRun[]>(`/api/captures/${encodeURIComponent(id)}/dispatches`),
putSourceKeyFields: (id: string, paths: string[]) =>
request<{ key_fields: string[] }>(`/api/sources/${encodeURIComponent(id)}/key-fields`, { method: "PUT", body: { paths } }),
triggers: () => request<Trigger[]>("/api/triggers"),
putTrigger: (name: string, trigger: TriggerInput) =>
request<{ trigger: string }>(`/api/triggers/${encodeURIComponent(name)}`, { method: "PUT", body: trigger }),
createTrigger: (trigger: TriggerInput) => request<Trigger>("/api/triggers", { method: "POST", body: trigger }),
putTrigger: (id: string, trigger: TriggerInput) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(id)}`, { method: "PUT", body: trigger }),
workflowList: () => request<WorkflowVersion[]>("/api/workflows"),
/** Creates a workflow, publishing body as its first version when given. */
createWorkflow: (name: string, body?: string) =>
@@ -1016,7 +1017,7 @@ export interface RunStage {
export interface RunTrail {
run: Run;
origin?: { event_id?: string; source_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
origin?: { event_id?: string; source_id?: string; source?: string; type?: string; trigger_id?: string; trigger?: string; received_at?: string };
actions?: RunAction[];
entries?: RunEntry[];
/** The document the run executes: its version, or the draft a test run tested. */
@@ -1067,13 +1068,15 @@ export interface TriggerRun {
run_id?: string;
outcome: "started" | "failed" | "denied" | "disabled";
reason?: NoRunReason;
trigger?: string;
trigger_id: string;
/** The trigger's current name. */
trigger: string;
created_at?: string;
}
export interface EventDetail {
body: unknown;
runs?: { run_id?: string; trigger: string; outcome: string }[];
runs?: { run_id?: string; trigger_id: string; trigger: string; outcome: string }[];
}
// Named with a trailing underscore: EventSource is the browser's SSE class.
@@ -1120,6 +1123,7 @@ export interface EventSource_ {
}
export interface Trigger {
id: string;
name: string;
/** Empty for a scheduled trigger. */
source_id?: string;
@@ -1140,6 +1144,7 @@ export interface Trigger {
}
export interface TriggerInput {
name: string;
source_id?: string;
event_type?: string;
every?: string;