fix(eda): dispatch each webhook delivery once, however often the sender retries it

This commit is contained in:
sam committed 2026-10-06 00:51:45 +11:00
1 parent 328d1847ff
commit f0d75f14b3
11 files changed
+165 -30

No files matched your search

+14 -3
View File
@@ -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" +
@@ -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:
@@ -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,
@@ -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)
+14 -4
View File
@@ -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")
}
@@ -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;
@@ -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
}
@@ -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 {
@@ -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;
+2 -2
View File
@@ -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,
}
}
+3
View File
@@ -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.