feat: record skipped dispatches and approver ids

- store trigger dispatches as started or skipped, with a JSON reason surfaced in the API and UI
- persist the answering account's identity id beside its display name for approvals and judgements
- save connector acceptances and their declarations in one transaction so a refused change stores nothing
This commit is contained in:
sam committed 2026-11-22 23:24:30 +11:00
1 parent 33f7ebdff4
commit 8c267b6edd
29 files changed
+517 -158

No files matched your search

+18 -4
View File
@@ -61,6 +61,8 @@ components:
type: string
answered_by:
type: string
answered_by_id:
type: string
answered_via:
type: string
deadline:
@@ -1302,13 +1304,19 @@ components:
type: string
event_id:
type: string
outcome:
enum:
- started
- skipped
type: string
reason: {}
run_id:
type: string
trigger:
type: string
required:
- event_id
- run_id
- outcome
type: object
EventsEventDetail:
additionalProperties: false
@@ -1605,13 +1613,19 @@ components:
EventsTriggerRun:
additionalProperties: false
properties:
outcome:
enum:
- started
- skipped
type: string
reason: {}
run_id:
type: string
trigger:
type: string
required:
- trigger
- run_id
- outcome
type: object
EventsTriggerSaved:
additionalProperties: false
@@ -5057,7 +5071,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List the runs a capture started
summary: List trigger dispatches for a capture
tags:
- Events
/api/chat/sessions:
@@ -8644,7 +8658,7 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: List the runs a trigger started
summary: List the dispatches of a trigger
tags:
- Events
/api/triggers/{name}/pause:
@@ -0,0 +1,7 @@
-- +goose Up
-- The identity ID of the account that answered a request. answered_by holds
-- that account's display name, which is not unique.
ALTER TABLE approvals.requests ADD COLUMN answered_by_id text;
-- +goose Down
ALTER TABLE approvals.requests DROP COLUMN answered_by_id;
@@ -0,0 +1,17 @@
-- +goose Up
-- A dispatch records the outcome of a trigger for an event: a started run or a
-- skip. A skip's reason is a JSON document with a code and display details,
-- such as the mapping fields that failed.
ALTER TABLE events.dispatches
ALTER COLUMN run_id DROP NOT NULL,
ADD COLUMN outcome text NOT NULL DEFAULT 'started' CHECK (outcome IN ('started', 'skipped')),
ADD COLUMN reason jsonb,
ADD CONSTRAINT dispatches_run_matches_outcome CHECK ((outcome = 'started') = (run_id IS NOT NULL));
-- +goose Down
DELETE FROM events.dispatches WHERE outcome = 'skipped';
ALTER TABLE events.dispatches
DROP CONSTRAINT dispatches_run_matches_outcome,
DROP COLUMN reason,
DROP COLUMN outcome,
ALTER COLUMN run_id SET NOT NULL;
+41 -23
View File
@@ -94,7 +94,17 @@ type Request struct {
ChangeRequest bool
AnsweredAt time.Time
AnsweredBy string
AnsweredVia string
// AnsweredByID is the answering account's identity ID. It is empty when
// the request expired without an answer.
AnsweredByID string
AnsweredVia string
}
// Answerer is the account that answered. Display names are not unique, so
// the ID distinguishes accounts with the same name.
type Answerer struct {
ID string
Name string
}
// Answer records the decision and who made it.
@@ -102,14 +112,16 @@ type Answer struct {
RequestID uuid.UUID `json:"request_id"`
Approved bool `json:"approved"`
By string `json:"by"`
Via string `json:"via"`
At time.Time `json:"at"`
// ByID is the identity ID of the account named by By.
ByID string `json:"by_id,omitzero"`
Via string `json:"via"`
At time.Time `json:"at"`
}
// Approval binds the approver's identity and response time to the decision ID
// and action digest.
func (a Answer) Approval(d judgement.Decision) judgement.Approval {
return judgement.Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: a.By, At: a.At}
return judgement.Approval{DecisionID: d.ID, Digest: d.Action.Digest, By: a.By, ByID: a.ByID, At: a.At}
}
// View is the API representation of an approval request.
@@ -129,9 +141,12 @@ type View struct {
// DecisionID identifies the judgement decision or, for a raise request, the proposed raise.
DecisionID uuid.UUID `json:"decision_id"`
RequestedAt time.Time `json:"requested_at"`
AnsweredBy string `json:"answered_by,omitzero"`
AnsweredVia string `json:"answered_via,omitzero"`
AnsweredAt time.Time `json:"answered_at,omitzero"`
// AnsweredBy is the answering account's display name.
AnsweredBy string `json:"answered_by,omitzero"`
// AnsweredByID is the answering account's identity ID.
AnsweredByID string `json:"answered_by_id,omitzero"`
AnsweredVia string `json:"answered_via,omitzero"`
AnsweredAt time.Time `json:"answered_at,omitzero"`
}
// View converts a request to its API representation.
@@ -141,7 +156,7 @@ func (r Request) View() View {
Target: r.TargetKind + ":" + r.TargetID, Level: r.Level,
Summary: r.Summary, State: r.State, Deadline: r.Deadline, Step: r.Step, StepDeadline: r.StepDeadline,
DecisionID: r.DecisionID, RequestedAt: r.RequestedAt,
AnsweredBy: r.AnsweredBy, AnsweredVia: r.AnsweredVia, AnsweredAt: r.AnsweredAt,
AnsweredBy: r.AnsweredBy, AnsweredByID: r.AnsweredByID, AnsweredVia: r.AnsweredVia, AnsweredAt: r.AnsweredAt,
}
}
@@ -250,7 +265,7 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
return r, nil
}
func (m *Module) answerAs(ctx context.Context, id uuid.UUID, by, via string, approved bool) (Request, error) {
func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via string, approved bool) (Request, error) {
now := m.now().UTC()
if _, err := m.pending(ctx, id, now); err != nil {
return Request{}, err
@@ -259,14 +274,14 @@ func (m *Module) answerAs(ctx context.Context, id uuid.UUID, by, via string, app
if approved {
state = StateApproved
}
row, err := m.store.Answer(ctx, m.orgID, id, state, by, via, now)
row, err := m.store.Answer(ctx, m.orgID, id, state, who.Name, who.ID, via, now)
if err != nil {
return Request{}, err
}
if row.State != state {
return Request{}, fmt.Errorf("%w: %s", ErrAnswered, row.State)
}
answer := Answer{RequestID: row.ID, Approved: approved, By: by, Via: via, At: now}
answer := Answer{RequestID: row.ID, Approved: approved, By: who.Name, ByID: who.ID, Via: via, At: now}
if row.Kind == KindRaise {
if err := m.answerRaise(ctx, row, answer); err != nil {
return Request{}, err
@@ -367,7 +382,7 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec
if err != nil {
return false, err
}
name, err := m.channelAnswerer(ctx, who, row)
answerer, err := m.channelAnswerer(ctx, who, row)
if refusal(err) {
identity := who.Issuer + ":" + who.Subject
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
@@ -384,7 +399,7 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec
if err != nil {
return false, err
}
_, err = m.answerAs(ctx, id, name, via, approved)
_, err = m.answerAs(ctx, id, answerer, via, approved)
switch {
case err == nil:
return true, nil
@@ -394,28 +409,28 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec
return false, err
}
// channelAnswerer returns the name of the account who holds the channel
// credential when that account may answer row.
func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (string, error) {
// channelAnswerer returns the account that holds the channel credential when
// that account may answer row.
func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (Answerer, error) {
account, err := m.accounts.ResolveSubject(ctx, who)
if errors.Is(err, governance.ErrIdentityNotFound) {
return "", ErrUnlinked
return Answerer{}, ErrUnlinked
}
if err != nil {
return "", fmt.Errorf("resolve %s:%s: %w", who.Issuer, who.Subject, err)
return Answerer{}, fmt.Errorf("resolve %s:%s: %w", who.Issuer, who.Subject, err)
}
if account.Kind != governance.KindUser || !account.CanAct() {
return "", ErrNotApprover
return Answerer{}, ErrNotApprover
}
p, err := m.accounts.PrincipalFor(ctx, account.ID)
if err != nil {
return "", fmt.Errorf("read access of %s: %w", account.ID, err)
return Answerer{}, fmt.Errorf("read access of %s: %w", account.ID, err)
}
p.Kind = account.Kind
if err := m.mayAnswer(ctx, p, row); err != nil {
return "", err
return Answerer{}, err
}
return account.DisplayName, nil
return Answerer{ID: string(account.ID), Name: account.DisplayName}, nil
}
// mayAnswer applies the access policies to an answer, as to any other
@@ -452,7 +467,7 @@ func refusal(err error) bool {
// Expire records a timeout without reducing the action class's autonomy:
// receiving no response is not a denial.
func (m *Module) Expire(ctx context.Context, id uuid.UUID) error {
row, err := m.store.Answer(ctx, m.orgID, id, StateExpired, "deadline", "clock", m.now().UTC())
row, err := m.store.Answer(ctx, m.orgID, id, StateExpired, "deadline", "", "clock", m.now().UTC())
if err != nil {
if errors.Is(err, ErrNotFound) {
return nil
@@ -637,6 +652,9 @@ func requestOf(row store.Request, d judgement.Decision) Request {
if row.AnsweredBy.Valid {
r.AnsweredBy = row.AnsweredBy.String
}
if row.AnsweredByID.Valid {
r.AnsweredByID = row.AnsweredByID.String
}
if row.AnsweredVia.Valid {
r.AnsweredVia = row.AnsweredVia.String
}
+40 -3
View File
@@ -119,12 +119,12 @@ func TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := &Module{accounts: tt.accounts, authz: tt.authz}
name, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, tt.row)
who, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, tt.row)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
if name != tt.wantName {
t.Fatalf("name = %q, want %q", name, tt.wantName)
if who.Name != tt.wantName {
t.Fatalf("name = %q, want %q", who.Name, tt.wantName)
}
if tt.wantErr != nil && !refusal(err) {
t.Fatalf("%v isn't recorded as a refusal", err)
@@ -160,3 +160,40 @@ func TestSettleableRefusesASecondAnswerOrALateOne(t *testing.T) {
})
}
}
// TestAnswerersWithTheSameNameRecordDifferentIDs guards the approver record:
// display names are not unique, so an answer must carry the account's
// identity ID for the trail and audit record to distinguish two accounts.
func TestAnswerersWithTheSameNameRecordDifferentIDs(t *testing.T) {
accounts := newAccounts()
for _, id := range []governance.IdentityID{"admin", "owner"} {
a := accounts.accounts[id]
a.DisplayName = "Alex"
accounts.accounts[id] = a
}
m := &Module{accounts: accounts, authz: shipped()}
row := store.Request{ID: uuid.New(), Kind: KindAction, Level: judgement.ProposeAndWait.String()}
tests := []struct {
name string
who string
wantID string
}{
{name: "the first account records its own id", who: "tg-admin", wantID: "admin"},
{name: "the second account with the same name records its own id", who: "tg-owner", wantID: "owner"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
who, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, row)
if err != nil {
t.Fatal(err)
}
if who.Name != "Alex" || who.ID != tt.wantID {
t.Fatalf("answerer = %+v, want name Alex and id %q", who, tt.wantID)
}
answer := Answer{By: who.Name, ByID: who.ID}
if got := answer.Approval(judgement.Decision{}).ByID; got != tt.wantID {
t.Fatalf("approval records id %q, want %q", got, tt.wantID)
}
})
}
}
+12 -12
View File
@@ -68,36 +68,36 @@ func (m *Module) UseAuthorizer(a governance.Authorizer) { m.authz = a }
// caller returns the signed-in person, checked as a channel account is: their
// role must let them answer. The bootstrap token is no person, so it can't
// answer.
func (m *Module) caller(ctx context.Context, row store.Request) (name, identity string, err error) {
func (m *Module) caller(ctx context.Context, row store.Request) (who Answerer, identity string, err error) {
p, ok := governance.PrincipalFromContext(ctx)
if !ok || p.IdentityID == governance.SystemID || p.Kind != governance.KindUser {
return "", "", ErrNotSignedIn
return Answerer{}, "", ErrNotSignedIn
}
identity = string(p.IdentityID)
if err := m.mayAnswer(ctx, p, row); err != nil {
return "", identity, err
return Answerer{}, identity, err
}
account, err := m.accounts.Get(ctx, p.IdentityID)
if err != nil {
return "", identity, fmt.Errorf("read account %s: %w", identity, err)
return Answerer{}, identity, fmt.Errorf("read account %s: %w", identity, err)
}
return account.DisplayName, identity, nil
return Answerer{ID: identity, Name: account.DisplayName}, identity, nil
}
// authorise accepts an answer from the dashboard only from a person who may
// give it. Approving an action that can't be undone also needs a passkey
// assertion made for this request.
func (m *Module) authorise(ctx context.Context, row store.Request, approved bool, assertion *Assertion) (by, identity string, err error) {
by, identity, err = m.caller(ctx, row)
func (m *Module) authorise(ctx context.Context, row store.Request, approved bool, assertion *Assertion) (who Answerer, identity string, err error) {
who, identity, err = m.caller(ctx, row)
if err != nil {
return "", identity, err
return Answerer{}, identity, err
}
if approved && row.Irreversible {
if err := m.confirmed(ctx, row, assertion); err != nil {
return "", identity, err
return Answerer{}, identity, err
}
}
return by, identity, nil
return who, identity, nil
}
func (m *Module) confirmed(ctx context.Context, row store.Request, a *Assertion) error {
@@ -164,14 +164,14 @@ func (m *Module) answer(ctx context.Context, in *answerInput) (*httpapi.Reply[Vi
return nil, m.answerError(ctx, id, err)
}
req := in.Body
by, identity, err := m.authorise(ctx, row, req.Approved, req.Assertion)
who, identity, err := m.authorise(ctx, row, req.Approved, req.Assertion)
if err != nil {
if refusal(err) || errors.Is(err, ErrFreshAuthenticationFailed) {
m.refuse(ctx, id, identity, err)
}
return nil, m.answerError(ctx, id, err)
}
out, err := m.answerAs(ctx, id, by, viaDashboard, req.Approved)
out, err := m.answerAs(ctx, id, who, viaDashboard, req.Approved)
if err != nil {
return nil, m.answerError(ctx, id, err)
}
+3 -3
View File
@@ -82,12 +82,12 @@ func TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove(t *testing.T) {
if tt.as != nil {
ctx = governance.WithPrincipal(ctx, *tt.as)
}
by, _, err := m.authorise(ctx, tt.row, tt.approved, tt.assertion)
who, _, err := m.authorise(ctx, tt.row, tt.approved, tt.assertion)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
if err == nil && by != string(tt.as.IdentityID) {
t.Fatalf("answered by %q, want the account's name recorded", by)
if err == nil && who != (Answerer{ID: string(tt.as.IdentityID), Name: string(tt.as.IdentityID)}) {
t.Fatalf("answered by %+v, want the account's id and name recorded", who)
}
if tt.confirmer != nil && len(tt.confirmer.subjects) == 1 && tt.confirmer.subjects[0] != confirmationSubject(request) {
t.Fatalf("confirmed %q, want the assertion confirmed for this request", tt.confirmer.subjects[0])
+1 -1
View File
@@ -63,7 +63,7 @@ func (m *Module) Accept(ctx context.Context, id uuid.UUID) error {
return err
}
return m.learn(ctx, row, Answer{
RequestID: row.ID, Approved: true, By: row.AnsweredBy.String, Via: row.AnsweredVia.String, At: row.AnsweredAt.Time,
RequestID: row.ID, Approved: true, By: row.AnsweredBy.String, ByID: row.AnsweredByID.String, Via: row.AnsweredVia.String, At: row.AnsweredAt.Time,
})
}
+6 -4
View File
@@ -36,6 +36,8 @@ type Request struct {
CreatedAt time.Time `db:"created_at"`
AnsweredAt sql.NullTime `db:"answered_at"`
AnsweredBy sql.NullString `db:"answered_by"`
// AnsweredByID is the answering account's identity ID.
AnsweredByID sql.NullString `db:"answered_by_id"`
AnsweredVia sql.NullString `db:"answered_via"`
Step int `db:"step"`
StepDeadline sql.NullTime `db:"step_deadline"`
@@ -56,7 +58,7 @@ type Store struct {
func New(db *sqlx.DB) *Store { return &Store{db: db} }
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, action, target_kind,
target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_via,
target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_by_id, answered_via,
step, step_deadline, change_request, counted, discarded_because`
// Put inserts r or returns the existing request for the same organisation,
@@ -96,13 +98,13 @@ func (s *Store) Get(ctx context.Context, orgID string, runID uuid.UUID, key stri
// Answer updates only pending requests. If another response already settled
// the request, it returns the stored record unchanged.
func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, by, via string, at time.Time) (Request, error) {
func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, by, byID, via string, at time.Time) (Request, error) {
var out Request
err := s.db.GetContext(ctx, &out, `
UPDATE approvals.requests
SET state = $3, answered_at = $4, answered_by = $5, answered_via = $6
SET state = $3, answered_at = $4, answered_by = $5, answered_by_id = nullif($6, ''), answered_via = $7
WHERE org_id = $1 AND id = $2 AND state = 'pending'
RETURNING `+requestColumns, orgID, id, state, at, by, via)
RETURNING `+requestColumns, orgID, id, state, at, by, byID, via)
if errors.Is(err, sql.ErrNoRows) {
return s.ByID(ctx, orgID, id)
}
+35 -4
View File
@@ -184,10 +184,42 @@ func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) {
// Upsert records an accepted connector, replacing an earlier acceptance.
func (s *Store) Upsert(ctx context.Context, a Accepted) error {
return upsert(ctx, s.db, a)
}
// SetCapabilities records what an accepted connector declared when it loaded.
func (s *Store) SetCapabilities(ctx context.Context, orgID, name string, capabilities jsontext.Value) error {
return setCapabilities(ctx, s.db, orgID, name, capabilities)
}
// Save records an acceptance together with what the connector declared, in one
// transaction, so a failure leaves the acceptance and its declarations as they
// were. Nil capabilities leave the stored declarations unchanged.
func (s *Store) Save(ctx context.Context, a Accepted, capabilities jsontext.Value) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("save %q: %w", a.Name, err)
}
defer func() { _ = tx.Rollback() }()
if err := upsert(ctx, tx, a); err != nil {
return err
}
if capabilities != nil {
if err := setCapabilities(ctx, tx, a.OrgID, a.Name, capabilities); err != nil {
return err
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("save %q: %w", a.Name, err)
}
return nil
}
func upsert(ctx context.Context, db sqlx.ExtContext, a Accepted) error {
if GroupOf(a.Contract) == "" {
return fmt.Errorf("accept %q: unknown contract %q", a.Name, a.Contract)
}
if _, err := s.db.NamedExecContext(ctx, `
if _, err := sqlx.NamedExecContext(ctx, db, `
INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings, contract, credentials, args, url, tools, effects, enabled, package)
VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings, :contract, :credentials, :args, :url, :tools, :effects, :enabled, :package)
ON CONFLICT (org_id, name) DO UPDATE
@@ -201,9 +233,8 @@ func (s *Store) Upsert(ctx context.Context, a Accepted) error {
return nil
}
// SetCapabilities records what an accepted connector declared when it loaded.
func (s *Store) SetCapabilities(ctx context.Context, orgID, name string, capabilities jsontext.Value) error {
if _, err := s.db.ExecContext(ctx, `
func setCapabilities(ctx context.Context, db sqlx.ExtContext, orgID, name string, capabilities jsontext.Value) error {
if _, err := db.ExecContext(ctx, `
UPDATE connectors.accepted SET capabilities = $3 WHERE org_id = $1 AND name = $2`, orgID, name, []byte(capabilities)); err != nil {
return fmt.Errorf("store capabilities of %q: %w", name, err)
}
+7 -2
View File
@@ -178,9 +178,14 @@ func (m *Module) checkAccepted(a store.Accepted) error {
if !ok || len(schema) == 0 {
return nil
}
return checkSettingValues(schema, a.Settings)
}
// checkSettingValues checks stored settings against a declared schema.
func checkSettingValues(schema []Setting, stored []byte) error {
var values map[string]string
if len(a.Settings) > 0 {
if err := json.Unmarshal(a.Settings, &values); err != nil {
if len(stored) > 0 {
if err := json.Unmarshal(stored, &values); err != nil {
return fmt.Errorf("settings: %w", err)
}
}
+1 -1
View File
@@ -168,7 +168,7 @@ func (m *Module) acceptServer(ctx context.Context, in *mcpInput) (*httpapi.Reply
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if err := m.store.Upsert(ctx, a); err != nil {
if err := m.store.Save(ctx, a, nil); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
if err := m.launch(context.WithoutCancel(ctx), a); err != nil {
+78 -21
View File
@@ -78,7 +78,7 @@ func (m *Module) Use(recheck Recheck) {
// registry is the module's persistence, so removal can be tested with a fake.
type registry interface {
List(ctx context.Context, orgID string) ([]store.Accepted, error)
Upsert(ctx context.Context, a store.Accepted) error
Save(ctx context.Context, a store.Accepted, capabilities jsontext.Value) error
Delete(ctx context.Context, orgID, name string) (bool, error)
Credential(ctx context.Context, orgID, name string) (store.Credential, bool, error)
Credentials(ctx context.Context, orgID string) ([]store.Credential, error)
@@ -446,35 +446,83 @@ func (m *Module) acceptAs(ctx context.Context, in *packageInput, contract string
// holds a list either way.
Tools: jsontext.Value(`[]`), Enabled: true,
}
if managed, err := m.managedBy(ctx, name); err != nil {
previous, found, err := m.acceptedRow(ctx, name)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the accepted packages")
} else if managed {
}
if found && len(previous.Package) > 0 {
return nil, huma.NewError(http.StatusConflict, name+" is installed from the catalogue; change it through its extension page")
}
if err := m.store.Upsert(ctx, a); err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
if err := m.launch(context.WithoutCancel(ctx), a); err != nil {
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
// The extension declares its settings when it starts. A value it doesn't
// declare, or a required one that is missing, is refused now rather than
// left for the extension to misread.
if err := m.checkAccepted(a); err != nil {
_, _ = m.store.Delete(context.WithoutCancel(ctx), m.orgID, name)
m.release(name)
m.mu.Lock()
delete(m.failed, name)
m.mu.Unlock()
return nil, huma.NewError(http.StatusUnprocessableEntity, err.Error())
if err := m.commit(context.WithoutCancel(ctx), a, found, previous); err != nil {
return nil, acceptError(err)
}
return httpapi.OK(packageState{Name: name, State: "running"}), nil
}
// persistError marks a failure to store an acceptance, as distinct from a
// refusal.
type persistError struct{ err error }
func (e persistError) Error() string { return e.err.Error() }
func (e persistError) Unwrap() error { return e.err }
// acceptError maps an error returned by commit to an HTTP error.
func acceptError(err error) error {
if errors.As(err, new(persistError)) {
return huma.NewError(http.StatusInternalServerError, err.Error())
}
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
// commit starts next and stores it only once it has started and its
// declarations and settings are accepted. The acceptance and the connector's
// declarations are written in one transaction, after every check, so a
// refusal changes nothing that is stored. The extension that previously ran
// under the name is restarted from its stored row.
func (m *Module) commit(ctx context.Context, next store.Accepted, hadPrevious bool, previous store.Accepted) error {
saved := false
save := func(ctx context.Context, caps jsontext.Value) error {
if err := m.store.Save(ctx, next, caps); err != nil {
return persistError{err}
}
saved = true
return nil
}
err := m.launchWith(ctx, next, save)
// A connector validates its settings against its declared schema before
// saving. Other contracts are checked after they start.
if err == nil && !saved && next.Enabled && next.Contract != store.ContractConnector {
err = m.checkAccepted(next)
}
if err == nil && !saved {
err = save(ctx, nil)
}
if err == nil {
return nil
}
m.release(next.Name)
m.mu.Lock()
delete(m.failed, next.Name)
m.mu.Unlock()
if hadPrevious {
_ = m.launch(ctx, previous)
}
return err
}
// launch starts or restarts one accepted package and records the outcome. A
// name runs one package: whatever ran under it before is stopped first, so a
// connector, a secret engine and an MCP server never share a name.
func (m *Module) launch(ctx context.Context, a store.Accepted) error {
return m.launchWith(ctx, a, nil)
}
// launchWith launches an acceptance that is not stored yet. When save is
// set, a connector calls it with its declarations once they and its settings
// are accepted, and is registered only if it succeeds; the other contracts
// leave saving to the caller. Without save, the row is already stored and only
// the declarations are recorded.
func (m *Module) launchWith(ctx context.Context, a store.Accepted, save func(context.Context, jsontext.Value) error) error {
m.releaseAs(a.Name, a.Contract)
if !a.Enabled {
m.markStopped(a.Name)
@@ -525,7 +573,13 @@ func (m *Module) launch(ctx context.Context, a store.Accepted) error {
m.host.Stop(a.Name)
return m.fail(ctx, a.Name, err)
}
if err := m.storeCapabilities(ctx, c); err != nil {
if save != nil {
if err := checkSettingValues(c.SettingsSchema(), a.Settings); err != nil {
m.host.Stop(a.Name)
return m.fail(ctx, a.Name, err)
}
}
if err := m.storeCapabilities(ctx, c, save); err != nil {
m.host.Stop(a.Name)
return m.fail(ctx, a.Name, err)
}
@@ -572,11 +626,14 @@ func (m *Module) checkDeclarations(ctx context.Context, name string, caps Capabi
// storeCapabilities records what a connector declared, so workflows and
// triggers can be checked against it while the connector is stopped.
func (m *Module) storeCapabilities(ctx context.Context, c *Connector) error {
func (m *Module) storeCapabilities(ctx context.Context, c *Connector, save func(context.Context, jsontext.Value) error) error {
raw, err := json.Marshal(c.Capabilities())
if err != nil {
return fmt.Errorf("encode capabilities: %w", err)
}
if save != nil {
return save(ctx, raw)
}
return m.store.SetCapabilities(ctx, m.orgID, c.Name(), raw)
}
+19 -24
View File
@@ -73,14 +73,18 @@ func restarts(old, next store.Accepted) bool {
!bytes.Equal(old.Credentials, next.Credentials) || !bytes.Equal(old.Settings, next.Settings)
}
// managedBy reports whether name is installed from the catalogue.
func (m *Module) managedBy(ctx context.Context, name string) (bool, error) {
// acceptedRow returns the stored acceptance of name; ok is false when there is
// none.
func (m *Module) acceptedRow(ctx context.Context, name string) (a store.Accepted, ok bool, err error) {
accepted, err := m.store.List(ctx, m.orgID)
if err != nil {
return false, err
return store.Accepted{}, false, err
}
i := slices.IndexFunc(accepted, func(a store.Accepted) bool { return a.Name == name })
return i >= 0 && len(accepted[i].Package) > 0, nil
if i < 0 {
return store.Accepted{}, false, nil
}
return accepted[i], true, nil
}
var errNotManaged = errors.New("not installed from the catalogue")
@@ -126,29 +130,20 @@ func (m *Module) lifecycleError(ctx context.Context, err error) error {
return huma.NewError(http.StatusInternalServerError, "couldn't change the extension")
}
// replace stores next and restarts what changed. When the new row won't start
// or its settings are refused, the old row is put back and restarted, so a
// failed change leaves the extension as it was.
// replace stores next and restarts what changed. next is stored only once it
// has started and its settings are accepted, so a refused change leaves the
// extension, its stored settings and its declarations as they were.
func (m *Module) replace(ctx context.Context, old, next store.Accepted) error {
if err := m.store.Upsert(ctx, next); err != nil {
return err
}
if !restarts(old, next) {
return nil
return m.store.Save(ctx, next, nil)
}
bg := context.WithoutCancel(ctx)
err := m.launch(bg, next)
if err == nil && next.Enabled {
err = m.checkAccepted(next)
if err := m.commit(context.WithoutCancel(ctx), next, true, old); err != nil {
if errors.As(err, new(persistError)) {
return err
}
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
}
if err == nil {
return nil
}
if restoreErr := m.store.Upsert(bg, old); restoreErr != nil {
return errors.Join(err, restoreErr)
}
_ = m.launch(bg, old)
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
return nil
}
// extensionName is the path of an operation on one installed extension.
@@ -227,7 +222,7 @@ func (m *Module) install(ctx context.Context, in *extensionName) (*httpapi.Reply
if err != nil {
return nil, m.lifecycleError(ctx, err)
}
if err := m.store.Upsert(ctx, row); err != nil {
if err := m.store.Save(ctx, row, nil); err != nil {
return nil, m.lifecycleError(ctx, err)
}
m.log.InfoContext(ctx, "extension installed", "audit", true, "action", "extension.install", "package", entry.Name, "digest", pin.Digest)
+2 -2
View File
@@ -31,8 +31,6 @@ func (f *fakeRegistry) List(context.Context, string) ([]store.Accepted, error) {
return out, nil
}
func (f *fakeRegistry) Upsert(context.Context, store.Accepted) error { return nil }
func (f *fakeRegistry) Delete(_ context.Context, _, name string) (bool, error) {
_, ok := f.accepted[name]
delete(f.accepted, name)
@@ -146,3 +144,5 @@ func statusOf(err error) (int, string) {
}
return http.StatusInternalServerError, err.Error()
}
func (f *fakeRegistry) Save(context.Context, store.Accepted, jsontext.Value) error { return nil }
+14 -3
View File
@@ -593,9 +593,20 @@ type eventDetail struct {
Runs []triggerRun `json:"runs"`
}
// 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 `json:"trigger"`
RunID uuid.UUID `json:"run_id"`
Trigger string `json:"trigger"`
RunID *uuid.UUID `json:"run_id,omitempty"`
Outcome string `json:"outcome" enum:"started,skipped"`
Reason jsontext.Value `json:"reason,omitempty"`
}
func runIDOf(id uuid.NullUUID) *uuid.UUID {
if !id.Valid {
return nil
}
return &id.UUID
}
type eventInput struct {
@@ -625,7 +636,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: run.RunID})
view.Runs = append(view.Runs, triggerRun{Trigger: run.Trigger, RunID: runIDOf(run.RunID), Outcome: run.Outcome, Reason: run.Reason})
}
return httpapi.OK(view), nil
}
+9 -6
View File
@@ -2,6 +2,7 @@ package events
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"net/http"
@@ -29,7 +30,7 @@ func (m *Module) registerCapture(api huma.API) {
return httpapi.AdminAuthorized(action, governance.KindCapture)
}
httpapi.Register(api, capture(governance.ActionRead), op("list-captures", http.MethodGet, "/api/captures", "List recent deliveries a source kept"), m.captures)
httpapi.Register(api, capture(governance.ActionRead), op("list-capture-dispatches", http.MethodGet, "/api/captures/{id}/dispatches", "List the runs a capture started"), m.captureDispatches)
httpapi.Register(api, capture(governance.ActionRead), op("list-capture-dispatches", http.MethodGet, "/api/captures/{id}/dispatches", "List trigger dispatches for a capture"), m.captureDispatches)
eventType := func(action governance.Action) httpapi.Access {
return httpapi.AdminAuthorized(action, governance.KindEventType)
@@ -105,10 +106,12 @@ func captureOf(e store.Event) captureView {
}
type dispatchView struct {
EventID uuid.UUID `json:"event_id"`
RunID uuid.UUID `json:"run_id"`
Trigger string `json:"trigger,omitempty"`
CreatedAt time.Time `json:"created_at,omitzero"`
EventID uuid.UUID `json:"event_id"`
RunID *uuid.UUID `json:"run_id,omitempty"`
Outcome string `json:"outcome" enum:"started,skipped"`
Reason jsontext.Value `json:"reason,omitempty"`
Trigger string `json:"trigger,omitempty"`
CreatedAt time.Time `json:"created_at,omitzero"`
}
type idInput struct {
@@ -126,7 +129,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: r.RunID, Trigger: r.Trigger})
out = append(out, dispatchView{EventID: id, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, Trigger: r.Trigger})
}
return httpapi.OK(out), nil
}
+2 -2
View File
@@ -39,7 +39,7 @@ func (m *Module) registerSourceSettings(api huma.API) {
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 runs a trigger started"), m.triggerDispatches)
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)
}
type sourceInput struct {
@@ -335,7 +335,7 @@ func (m *Module) triggerDispatches(ctx context.Context, in *triggerDispatchesInp
}
out := make([]dispatchView, 0, len(rows))
for _, r := range rows {
out = append(out, dispatchView{EventID: r.EventID, RunID: r.RunID, Trigger: in.Name, CreatedAt: r.CreatedAt})
out = append(out, dispatchView{EventID: r.EventID, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, Trigger: in.Name, CreatedAt: r.CreatedAt})
}
return httpapi.OK(out), nil
}
+45 -15
View File
@@ -624,8 +624,9 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
return matched, nil
}
// What a trigger did with an event: left it (its filter didn't match), had its
// run refused, or started a run.
// 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).
type outcome int
const (
@@ -644,10 +645,14 @@ func (m *Module) fire(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.T
if !match.Fields(e.Fields, filter) {
return skipped, nil
}
input, mapped, ok, err := m.inputFor(ctx, tx, e, t)
if err != nil || !ok {
input, mapped, skip, err := m.inputFor(ctx, tx, e, t)
if err != nil {
return refusedRun, 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
@@ -664,6 +669,15 @@ func (m *Module) fire(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.T
return fired, 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)
if err != nil {
return fmt.Errorf("encode skip reason: %w", err)
}
return store.RecordSkip(ctx, tx, e.ID, t.Name, reason)
}
// noteUnmatched files an event no trigger took into a group for review.
func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event) error {
created, err := store.NoteUnmatched(ctx, tx, e)
@@ -691,7 +705,7 @@ func (m *Module) startRun(ctx context.Context, e store.Event, t store.Trigger, i
return uuid.Nil, false, nil
}
if errors.Is(err, runs.ErrDisabled) {
m.log.InfoContext(ctx, "trigger skipped: its workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.Workflow)
m.log.InfoContext(ctx, "trigger skipped: the workflow is disabled", "event", e.ID, "trigger", t.Name, "workflow", t.Workflow)
return uuid.Nil, false, nil
}
if err != nil {
@@ -732,27 +746,43 @@ func runInputWith(e store.Event, mapped map[string]any) jsontext.Value {
return input
}
// inputFor builds the run input for trigger t. A trigger with a mapping reads
// the event's payload through it; when a field the mapping requires is missing
// or has the wrong shape no run starts, and the reason is logged.
func (m *Module) inputFor(ctx context.Context, tx *sqlx.Tx, e store.Event, t store.Trigger) (input jsontext.Value, mapped, ok bool, err error) {
// skipMappingMismatch is the reason code for a trigger skipped because the
// event does not match its mapping.
const skipMappingMismatch = "mapping_mismatch"
// 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"`
}
// 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) {
if !t.MappingID.Valid {
return runInput(e), false, true, nil
return runInput(e), false, nil, nil
}
row, err := store.MappingIn(ctx, tx, e.OrgID, t.MappingID.UUID)
if err != nil {
return nil, false, false, err
return nil, false, nil, err
}
return applyMapping(e, row)
}
// 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) {
var fields []mapping.Field
if err := json.Unmarshal(row.Fields, &fields); err != nil {
return nil, false, false, fmt.Errorf("mapping %q fields: %w", row.Name, err)
return nil, false, nil, fmt.Errorf("mapping %q fields: %w", row.Name, err)
}
values, failures := mapping.Resolve(fields, e.Body)
if len(failures) > 0 {
m.log.WarnContext(ctx, "mapping didn't fit the event; trigger skipped", "event", e.ID, "trigger", t.Name, "mapping", row.Name, "failures", failures)
return nil, false, false, nil
return nil, false, &skipReason{Code: skipMappingMismatch, Mapping: row.Name, Failures: failures}, nil
}
return runInputWith(e, values), true, true, nil
return runInputWith(e, values), true, nil, nil
}
func newToken() (string, error) {
+9 -6
View File
@@ -399,18 +399,21 @@ func (s *Store) DeleteTrigger(ctx context.Context, orgID, name string) error {
return nil
}
// Dispatch is one run a trigger started for an event.
// Dispatch is the outcome of a trigger for an event: the run it started, or
// the reason no run started.
type Dispatch struct {
EventID uuid.UUID `db:"event_id"`
RunID uuid.UUID `db:"run_id"`
CreatedAt time.Time `db:"created_at"`
EventID uuid.UUID `db:"event_id"`
RunID uuid.NullUUID `db:"run_id"`
Outcome string `db:"outcome"`
Reason jsontext.Value `db:"reason"`
CreatedAt time.Time `db:"created_at"`
}
// DispatchesOf returns the runs a trigger started, newest first.
// DispatchesOf returns a trigger's dispatches, newest first.
func (s *Store) DispatchesOf(ctx context.Context, orgID, trigger string, limit int) ([]Dispatch, error) {
var out []Dispatch
if err := s.db.SelectContext(ctx, &out, `
SELECT d.event_id, d.run_id, d.created_at FROM events.dispatches d
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 {
return nil, fmt.Errorf("list dispatches: %w", err)
+2 -1
View File
@@ -43,7 +43,8 @@ func (s *Store) GroupEvents(ctx context.Context, orgID string, id uuid.UUID, lim
func (s *Store) RecordReplay(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO events.dispatches (event_id, trigger, run_id) VALUES ($1, $2, $3)
ON CONFLICT (event_id, trigger) DO UPDATE SET run_id = EXCLUDED.run_id, created_at = now()`,
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 {
return fmt.Errorf("record replay: %w", err)
}
+31 -7
View File
@@ -279,16 +279,37 @@ func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string,
return out, nil
}
// RecordDispatch notes that trigger started run for an event.
// Dispatch outcomes.
const (
OutcomeStarted = "started"
OutcomeSkipped = "skipped"
)
// RecordDispatch records that trigger started run for an event. It replaces an
// earlier skip of the same event by the same trigger.
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 NOTHING`, eventID, trigger, runID); err != nil {
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 {
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 {
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)
}
return nil
}
// UpsertTrigger creates or replaces a trigger.
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
if _, err := s.db.NamedExecContext(ctx, `
@@ -368,17 +389,20 @@ func (s *Store) Event(ctx context.Context, orgID string, id uuid.UUID) (Event, e
return e, nil
}
// TriggerRun is a run a trigger started for an event.
// 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.UUID `db:"run_id"`
Trigger string `db:"trigger"`
RunID uuid.NullUUID `db:"run_id"`
Outcome string `db:"outcome"`
Reason jsontext.Value `db:"reason"`
}
// RunsForEvent returns the runs triggers started for an event.
// 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 FROM events.dispatches d
SELECT d.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 {
return nil, fmt.Errorf("read event runs: %w", err)
+75
View File
@@ -0,0 +1,75 @@
package events
import (
"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) {
row := store.Mapping{
Name: "incident",
Fields: []byte(`[
{"name":"id","path":"incident.id","type":"string","required":true},
{"name":"severity","path":"incident.severity","type":"number","required":true}
]`),
}
tests := []struct {
name string
body string
wantFailures []mapping.Failure
}{
{name: "a matching event dispatches", body: `{"incident":{"id":"a1","severity":3}}`},
{
name: "a missing field is skipped",
body: `{"incident":{"id":"a1"}}`,
wantFailures: []mapping.Failure{
{FieldName: "severity", Path: "incident.severity", Reason: mapping.ReasonMissing},
},
},
{
name: "every failed field is listed",
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},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
input, mapped, skip, 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)
}
return
}
if skip == nil {
t.Fatalf("applyMapping recorded no skip, want %v", tt.wantFailures)
}
if skip.Code != skipMappingMismatch || skip.Mapping != "incident" {
t.Errorf("skip = %+v, want code %q for mapping incident", skip, skipMappingMismatch)
}
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 mapped || input != nil {
t.Errorf("a skip must carry no run input, got %s", input)
}
})
}
}
+3 -1
View File
@@ -445,7 +445,9 @@ type Approval struct {
DecisionID uuid.UUID `json:"decision_id"`
Digest string `json:"digest"`
By string `json:"by"`
At time.Time `json:"at"`
// ByID is the identity ID of the account named by By.
ByID string `json:"by_id,omitzero"`
At time.Time `json:"at"`
}
// Covers reports whether the approval was given for d's action.
+3 -4
View File
@@ -7,10 +7,9 @@ import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Timestamp } from "@/components/ui/timestamp";
/**
* The dispatch ledger rows for one binding, capture or task, each linking the
* other two ends: which binding evaluated which capture, and the task it
* started or the reason it started none. `omit` drops the column the page
* already is.
* Dispatch ledger rows for one binding, capture or task. Each row links the
* binding, the capture it evaluated, and the task it started or the reason no
* task started. `omit` hides the column for the page's own entity.
*/
interface Dispatch {
binding_id: string;
+12 -2
View File
@@ -1,8 +1,9 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import { api, type TriggerRun } from "@/lib/api";
import { api, type SkipReason, type TriggerRun } from "@/lib/api";
import { errors } from "@/copy/errors";
import { Badge } from "@/components/ui/badge";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Timestamp } from "@/components/ui/timestamp";
@@ -39,6 +40,11 @@ watch(
},
{ immediate: true },
);
const skipText = (reason?: SkipReason) =>
reason?.failures?.length
? `${reason.mapping}: ${reason.failures.map((f) => `${f.path} ${f.reason.replace("_", " ")}`).join(", ")}`
: errors.bindings.dispatchLinks.skipUnknown;
</script>
<template>
@@ -61,9 +67,13 @@ watch(
class="hover:text-foreground"
>{{ r.trigger }}</RouterLink
>
<RouterLink :to="`/runs/${r.run_id}`" class="text-foreground hover:underline"
<RouterLink v-if="r.run_id" :to="`/runs/${r.run_id}`" class="text-foreground hover:underline"
>run {{ r.run_id.slice(0, 8) }}</RouterLink
>
<template v-else>
<Badge variant="outline">skipped</Badge>
<span class="break-all">{{ skipText(r.reason) }}</span>
</template>
<Timestamp v-if="r.created_at" :at="r.created_at" />
</li>
</ul>
+1
View File
@@ -12,5 +12,6 @@ export const bindings = {
dispatchLinks: {
unavailable: "Dispatches unavailable.",
noTask: "claimed, no task recorded",
skipUnknown: "no reason recorded",
},
} as const;
+19 -2
View File
@@ -865,6 +865,7 @@ export interface Approval {
deadline?: string;
answered_at?: string;
answered_by?: string;
answered_by_id?: string;
answered_via?: string;
}
@@ -945,10 +946,26 @@ export interface EventRecord {
verification?: "signed" | "token" | "unsigned" | "";
}
/** A run a trigger started for a stored event. */
/** One mapping field that did not resolve against an event's payload. */
export interface MappingFailure {
field_name: string;
path: string;
reason: "missing" | "null" | "type_mismatch";
}
/** The reason a trigger did not start a run for an event. */
export interface SkipReason {
code: string;
mapping?: string;
failures?: MappingFailure[];
}
/** The outcome of a trigger for a stored event: the run it started, or the reason no run started. */
export interface TriggerRun {
event_id: string;
run_id: string;
run_id?: string;
outcome: "started" | "skipped";
reason?: SkipReason;
trigger?: string;
created_at?: string;
}
+5 -5
View File
@@ -431,11 +431,11 @@ export const useSettingsStore = defineStore("settings", () => {
stopStatus();
});
/** Re-read on every load and after each save, so the page reflects what the
* processes did with the edit rather than what was stored. A failure leaves
* the previous rows: apply status is a diagnostic, and losing it must not
* take the settings page with it. It is an instance-only read, so another
* org's page does not issue it at all (the answer there is a 404). */
/** Re-read on every load and after each save, so the page shows whether each
* process applied the edit, not only what was stored. A failed read keeps the
* previous rows: apply status is diagnostic, and a failure must not break the
* settings page. The read is instance-only, so pages for other orgs skip it
* (it would return 404). */
async function loadApplyStatus(): Promise<void> {
await live.loadCapabilities();
if (!live.systemOrg) return;