From f0d75f14b36c2e729b6274c2373672ec7f7f63fa Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 6 Oct 2026 00:51:45 +1100 Subject: [PATCH] fix(eda): dispatch each webhook delivery once, however often the sender retries it --- internal/contracts/state/v1/state.pb.go | 17 ++++-- .../domain/storecontract/storecontract.go | 4 ++ .../infrastructure/captureintake/receiver.go | 21 ++++++++ .../postgres/binding_dispatch_test.go | 54 +++++++++++++++++++ internal/infrastructure/postgres/edastore.go | 18 +++++-- .../migrations/0036_capture_delivery.sql | 21 ++++++++ .../postgres/postgresdb/edastore.sql.go | 34 +++++++----- .../postgres/postgresdb/models.go | 2 + .../postgres/queries/edastore.sql | 17 +++--- internal/infrastructure/staterpc/values.go | 4 +- proto/state/v1/state.proto | 3 ++ 11 files changed, 165 insertions(+), 30 deletions(-) create mode 100644 internal/infrastructure/postgres/migrations/0036_capture_delivery.sql diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 2c197f67a..1bb88a201 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -2261,7 +2261,10 @@ type CapturedEvent struct { // arrival; empty is unidentified. EventType string `protobuf:"bytes,9,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // unsigned marks an event taken on an approved unsigned source. - Unsigned bool `protobuf:"varint,10,opt,name=unsigned,proto3" json:"unsigned,omitempty"` + Unsigned bool `protobuf:"varint,10,opt,name=unsigned,proto3" json:"unsigned,omitempty"` + // delivery names the sender's delivery; a retry of one delivery shares it. + // Intake sets the sender's delivery ID; empty takes the capture ID. + Delivery string `protobuf:"bytes,11,opt,name=delivery,proto3" json:"delivery,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2366,6 +2369,13 @@ func (x *CapturedEvent) GetUnsigned() bool { return false } +func (x *CapturedEvent) GetDelivery() string { + if x != nil { + return x.Delivery + } + return "" +} + // EventTypeHeaderCondition mirrors internal/domain/eventtype.HeaderCondition. type EventTypeHeaderCondition struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -14888,7 +14898,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\bactor_id\x18\f \x01(\tR\aactorId\x12\x1d\n" + "\n" + "actor_kind\x18\r \x01(\tR\tactorKind\x12!\n" + - "\fprincipal_id\x18\x0e \x01(\tR\vprincipalId\"\xc7\x02\n" + + "\fprincipal_id\x18\x0e \x01(\tR\vprincipalId\"\xe3\x02\n" + "\rCapturedEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12;\n" + "\vreceived_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" + @@ -14903,7 +14913,8 @@ const file_state_v1_state_proto_rawDesc = "" + "\n" + "event_type\x18\t \x01(\tR\teventType\x12\x1a\n" + "\bunsigned\x18\n" + - " \x01(\bR\bunsigned\"D\n" + + " \x01(\bR\bunsigned\x12\x1a\n" + + "\bdelivery\x18\v \x01(\tR\bdelivery\"D\n" + "\x18EventTypeHeaderCondition\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value\"U\n" + diff --git a/internal/domain/storecontract/storecontract.go b/internal/domain/storecontract/storecontract.go index 39e92ed23..6c903c264 100644 --- a/internal/domain/storecontract/storecontract.go +++ b/internal/domain/storecontract/storecontract.go @@ -366,6 +366,10 @@ type CapturedEvent struct { // Unsigned marks an event that arrived on an approved unsigned source. // It dispatches without Authenticated and is flagged wherever it shows. Unsigned bool `json:"unsigned"` + // Delivery names the sender's delivery; a retry of one delivery shares + // it, so a binding dispatches each delivery once. Intake sets the + // sender's delivery ID; the store fills the capture ID when it is empty. + Delivery string `json:"delivery"` } // Dispatchable reports whether a binding may start a task from this event: diff --git a/internal/infrastructure/captureintake/receiver.go b/internal/infrastructure/captureintake/receiver.go index 357335193..1f8d95e09 100644 --- a/internal/infrastructure/captureintake/receiver.go +++ b/internal/infrastructure/captureintake/receiver.go @@ -11,6 +11,7 @@ import ( "net" "net/http" "net/url" + "strings" "time" "github.com/samcharles93/archie-core/internal/domain/access" @@ -132,6 +133,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) { Body: string(redactedBody), Authenticated: authenticated, Unsigned: unsigned, + Delivery: deliveryID(r.Header), } id, err := rc.Captures.InsertCapture(r.Context(), c, rc.Retention, rc.MaxEvents) if err != nil { @@ -206,6 +208,25 @@ func verify(src *source.Source, h http.Header, body []byte) (authenticated, unsi return webhookguard.VerifyHMAC(body, sig, src.Secret), false } +// deliveryHeaders carry a sender's ID for one delivery, repeated unchanged on +// every retry of it: GitHub, Gitea, Gogs, GitLab, Standard Webhooks, and the +// generic idempotency key. +var deliveryHeaders = []string{ + "X-GitHub-Delivery", "X-Gitea-Delivery", "X-Gogs-Delivery", + "X-Gitlab-Event-UUID", "Webhook-Id", "Idempotency-Key", +} + +// deliveryID is the sender's delivery ID, or empty when it sends none and +// each arrival counts as its own delivery. +func deliveryID(h http.Header) string { + for _, name := range deliveryHeaders { + if id := strings.TrimSpace(h.Get(name)); id != "" { + return name + ":" + id + } + } + return "" +} + // formPayload turns a form-encoded delivery into JSON so it types and maps // like a JSON one. A payload field holding JSON (GitHub's and Slack's form // shape) is the event itself; any other form becomes an object of its fields, diff --git a/internal/infrastructure/postgres/binding_dispatch_test.go b/internal/infrastructure/postgres/binding_dispatch_test.go index 8d76965f5..d817ad24d 100644 --- a/internal/infrastructure/postgres/binding_dispatch_test.go +++ b/internal/infrastructure/postgres/binding_dispatch_test.go @@ -84,6 +84,60 @@ func TestEvaluatedCaptureIsNotReoffered(t *testing.T) { } } +// A sender's retry of one delivery is captured again but dispatches once, +// even when both copies are offered before either is claimed. +func TestRedeliveryDispatchesOnce(t *testing.T) { + ctx := t.Context() + eda := pgstore.EDA(t, nil) + eventTypeID, err := eda.InsertEventType(ctx, eventtype.EventType{Source: "forge", Name: "push"}) + if err != nil { + t.Fatal(err) + } + mappingID, err := eda.InsertMapping(ctx, mapping.Mapping{Name: "push", EventTypeID: eventTypeID}) + if err != nil { + t.Fatal(err) + } + bindingID, err := eda.InsertBinding(ctx, binding.Binding{ + Name: "on-push", Matcher: binding.Matcher{Source: "forge"}, MappingID: mappingID, Workflow: "tdd", + }) + if err != nil { + t.Fatal(err) + } + if err := eda.ApproveBinding(ctx, bindingID); err != nil { + t.Fatal(err) + } + capture := func(delivery string) string { + id, err := eda.InsertCapture(ctx, storecontract.CapturedEvent{ + Source: "forge", Body: "{}", Authenticated: true, ReceivedAt: time.Now(), Delivery: delivery, + }, time.Hour, 100) + if err != nil { + t.Fatal(err) + } + return id + } + + original, retry := capture("X-GitHub-Delivery:abc"), capture("X-GitHub-Delivery:abc") + assertUndispatched(t, eda, 2) + if err := eda.RecordDispatch(ctx, bindingID, 1, original, 0, ""); err != nil { + t.Fatal(err) + } + if err := eda.RecordDispatch(ctx, bindingID, 1, retry, 0, ""); !errors.Is(err, storecontract.ErrAlreadyDispatched) { + t.Fatalf("dispatch of the retry = %v, want ErrAlreadyDispatched", err) + } + assertUndispatched(t, eda, 0) + + capture("X-GitHub-Delivery:def") + capture("") + assertUndispatched(t, eda, 2) + captures, err := eda.ListCaptures(ctx, 10) + if err != nil { + t.Fatal(err) + } + if len(captures) != 4 { + t.Fatalf("captures = %d, want 4: a retry is still recorded", len(captures)) + } +} + func assertUndispatched(t *testing.T, eda *postgres.EDA, want int) { t.Helper() got, err := eda.ListUndispatchedCaptures(t.Context(), []string{"forge"}, 10) diff --git a/internal/infrastructure/postgres/edastore.go b/internal/infrastructure/postgres/edastore.go index d0473be12..59903045f 100644 --- a/internal/infrastructure/postgres/edastore.go +++ b/internal/infrastructure/postgres/edastore.go @@ -86,6 +86,10 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, return "", err } id := newRecordID() + delivery := c.Delivery + if delivery == "" { + delivery = id + } if err := s.q.InsertCapture(ctx, postgresdb.InsertCaptureParams{ ID: id, Source: c.Source, @@ -97,6 +101,7 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, Unsigned: c.Unsigned, ReceivedAt: received.UTC(), EventType: eventType, + Delivery: delivery, }); err != nil { return "", fmt.Errorf("edastore: insert capture: %w", err) } @@ -132,6 +137,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent { Authenticated: r.Authenticated, EventType: r.EventType, Unsigned: r.Unsigned, + Delivery: r.Delivery, } } @@ -512,18 +518,22 @@ func (s *EDA) transitionBinding(ctx context.Context, id string, from, to binding // --- dispatch ledgers --- -// RecordDispatch writes one at-most-once binding dispatch. binding_version is -// stored but is not part of the unique key, so a version bump does not permit -// re-dispatching the same (binding, capture). A non-empty reason records an +// RecordDispatch writes one at-most-once binding dispatch, keyed on the +// capture's delivery so a retried delivery is refused like the original. +// binding_version is stored but is not part of the key, so a version bump does +// not permit re-dispatching the same delivery. A non-empty reason records an // evaluation that ended without a task. func (s *EDA) RecordDispatch(ctx context.Context, bindingID string, bindingVersion int64, captureID string, taskID int64, reason string) error { - err := s.q.InsertBindingDispatch(ctx, postgresdb.InsertBindingDispatchParams{ + n, err := s.q.InsertBindingDispatch(ctx, postgresdb.InsertBindingDispatchParams{ Binding: bindingID, BindingVersion: bindingVersion, Capture: captureID, TaskID: taskID, Reason: reason, }) + if err == nil && n == 0 { + return fmt.Errorf("edastore: record dispatch: capture %q not found", captureID) + } return ledgerWrite(err, "edastore: record dispatch") } diff --git a/internal/infrastructure/postgres/migrations/0036_capture_delivery.sql b/internal/infrastructure/postgres/migrations/0036_capture_delivery.sql new file mode 100644 index 000000000..869c75f61 --- /dev/null +++ b/internal/infrastructure/postgres/migrations/0036_capture_delivery.sql @@ -0,0 +1,21 @@ +-- captures.delivery names the sender's delivery: its delivery ID header when +-- it sends one, else the capture itself. A retry of one delivery shares it, so +-- binding_dispatches keyed on it dispatches each delivery once however many +-- times it arrives. + +-- +goose Up + +ALTER TABLE captures ADD COLUMN delivery text NOT NULL DEFAULT ''; +UPDATE captures SET delivery = id; + +ALTER TABLE binding_dispatches ADD COLUMN delivery text NOT NULL DEFAULT ''; +UPDATE binding_dispatches SET delivery = capture; +DROP INDEX idx_binding_dispatch_once; +CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, delivery); + +-- +goose Down + +DROP INDEX idx_binding_dispatch_once; +CREATE UNIQUE INDEX idx_binding_dispatch_once ON binding_dispatches (binding, capture); +ALTER TABLE binding_dispatches DROP COLUMN delivery; +ALTER TABLE captures DROP COLUMN delivery; diff --git a/internal/infrastructure/postgres/postgresdb/edastore.sql.go b/internal/infrastructure/postgres/postgresdb/edastore.sql.go index 81fd92854..a93f1a65f 100644 --- a/internal/infrastructure/postgres/postgresdb/edastore.sql.go +++ b/internal/infrastructure/postgres/postgresdb/edastore.sql.go @@ -412,34 +412,38 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er return err } -const insertBindingDispatch = `-- name: InsertBindingDispatch :exec -INSERT INTO binding_dispatches (binding, binding_version, capture, task_id, reason) -VALUES ($1, $2, $3, $4, $5) +const insertBindingDispatch = `-- name: InsertBindingDispatch :execrows +INSERT INTO binding_dispatches (binding, binding_version, capture, task_id, reason, delivery) +SELECT $1, $2, c.id, $3, $4, c.delivery +FROM captures c WHERE c.id = $5 ` type InsertBindingDispatchParams struct { Binding string BindingVersion int64 - Capture string TaskID int64 Reason string + Capture string } -func (q *Queries) InsertBindingDispatch(ctx context.Context, arg InsertBindingDispatchParams) error { - _, err := q.db.Exec(ctx, insertBindingDispatch, +func (q *Queries) InsertBindingDispatch(ctx context.Context, arg InsertBindingDispatchParams) (int64, error) { + result, err := q.db.Exec(ctx, insertBindingDispatch, arg.Binding, arg.BindingVersion, - arg.Capture, arg.TaskID, arg.Reason, + arg.Capture, ) - return err + if err != nil { + return 0, err + } + return result.RowsAffected(), nil } const insertCapture = `-- name: InsertCapture :exec -INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) +INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type, delivery) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) ` type InsertCaptureParams struct { @@ -453,6 +457,7 @@ type InsertCaptureParams struct { ReceivedAt time.Time Unsigned bool EventType string + Delivery string } // EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls. @@ -468,6 +473,7 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er arg.ReceivedAt, arg.Unsigned, arg.EventType, + arg.Delivery, ) return err } @@ -733,7 +739,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) { } const listCaptures = `-- name: ListCaptures :many -SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type, org_id, workspace_id +SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type, org_id, workspace_id, delivery FROM captures ORDER BY received_at DESC LIMIT $1 @@ -761,6 +767,7 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err &i.EventType, &i.OrgID, &i.WorkspaceID, + &i.Delivery, ); err != nil { return nil, err } @@ -886,14 +893,14 @@ func (q *Queries) ListSources(ctx context.Context) ([]Source, error) { } const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many -SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type, c.org_id, c.workspace_id +SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type, c.org_id, c.workspace_id, c.delivery FROM captures c WHERE c.source = ANY($1::text[]) AND c.event_type <> '' AND EXISTS ( SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type - AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id) + AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.delivery = c.delivery) ) ORDER BY c.received_at DESC LIMIT $2 @@ -926,6 +933,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat &i.EventType, &i.OrgID, &i.WorkspaceID, + &i.Delivery, ); err != nil { return nil, err } diff --git a/internal/infrastructure/postgres/postgresdb/models.go b/internal/infrastructure/postgres/postgresdb/models.go index e381f55bb..b3c744e43 100644 --- a/internal/infrastructure/postgres/postgresdb/models.go +++ b/internal/infrastructure/postgres/postgresdb/models.go @@ -79,6 +79,7 @@ type BindingDispatch struct { TaskID int64 DispatchedAt time.Time Reason string + Delivery string } type Capture struct { @@ -94,6 +95,7 @@ type Capture struct { EventType string OrgID string WorkspaceID string + Delivery string } type CaptureRefusal struct { diff --git a/internal/infrastructure/postgres/queries/edastore.sql b/internal/infrastructure/postgres/queries/edastore.sql index dee2416fa..beec2ce31 100644 --- a/internal/infrastructure/postgres/queries/edastore.sql +++ b/internal/infrastructure/postgres/queries/edastore.sql @@ -1,24 +1,24 @@ -- EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls. -- name: InsertCapture :exec -INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10); +INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type, delivery) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11); -- name: ListCaptures :many -SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type, org_id, workspace_id +SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type, org_id, workspace_id, delivery FROM captures ORDER BY received_at DESC LIMIT $1; -- name: ListUndispatchedCaptures :many -SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type, c.org_id, c.workspace_id +SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type, c.org_id, c.workspace_id, c.delivery FROM captures c WHERE c.source = ANY(@sources::text[]) AND c.event_type <> '' AND EXISTS ( SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type - AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id) + AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.delivery = c.delivery) ) ORDER BY c.received_at DESC LIMIT @entry_limit; @@ -91,9 +91,10 @@ WHERE id = @id AND status = @from_status; -- name: DeleteBinding :execrows DELETE FROM bindings WHERE id = $1; --- name: InsertBindingDispatch :exec -INSERT INTO binding_dispatches (binding, binding_version, capture, task_id, reason) -VALUES ($1, $2, $3, $4, $5); +-- name: InsertBindingDispatch :execrows +INSERT INTO binding_dispatches (binding, binding_version, capture, task_id, reason, delivery) +SELECT @binding, @binding_version, c.id, @task_id, @reason, c.delivery +FROM captures c WHERE c.id = @capture; -- name: SetBindingDispatchTask :exec UPDATE binding_dispatches SET task_id = $3 WHERE binding = $1 AND capture = $2; diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 571420c36..e964e0a81 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -193,7 +193,7 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent { Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source, RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers, Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType, - Unsigned: c.Unsigned, + Unsigned: c.Unsigned, Delivery: c.Delivery, } } @@ -205,7 +205,7 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent { ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source, RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers, Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType, - Unsigned: c.Unsigned, + Unsigned: c.Unsigned, Delivery: c.Delivery, } } diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index c4630d062..8926e7f99 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -472,6 +472,9 @@ message CapturedEvent { string event_type = 9; // unsigned marks an event taken on an approved unsigned source. bool unsigned = 10; + // delivery names the sender's delivery; a retry of one delivery shares it. + // Intake sets the sender's delivery ID; empty takes the capture ID. + string delivery = 11; } // EventTypeHeaderCondition mirrors internal/domain/eventtype.HeaderCondition.