From 98735f3f73a4f235f7ef27324376c1e9a67dc9d3 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:46:42 +0100 Subject: [PATCH 1/3] fix(eventforward): count a forward's attempt at its claim, and leave an unopenable secret to another router The claim of event deliveries now counts the attempt, as queue.go's claim does, and Retry no longer writes it. A delivery whose forwarder dies between claim and send every time is given up once it was claimed more often than it may be tried, instead of coming back with the same count for ever. A router that does not hold the key version a destination's secret was sealed with sends nothing: it gives the counted attempt back and leaves the delivery due a poll later, rather than deleting it as refused. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/eventforward/AGENTS.md | 1 + .../internal/eventforward/forwarder.go | 31 +++++++++++- .../internal/eventforward/forwarder_test.go | 49 +++++++++++++++++++ acceleration/internal/store/event_delivery.go | 31 ++++++++---- .../internal/store/event_destination_test.go | 29 +++++++++-- 5 files changed, 126 insertions(+), 15 deletions(-) diff --git a/acceleration/internal/eventforward/AGENTS.md b/acceleration/internal/eventforward/AGENTS.md index 2ebfcba766..de6641847b 100644 --- a/acceleration/internal/eventforward/AGENTS.md +++ b/acceleration/internal/eventforward/AGENTS.md @@ -53,6 +53,7 @@ worker (every router) off the request - **A message the bridge could not write is unhandled after all.** `Bridge.Deliver` counts a message as answered before it writes it into its thread channel, after the ack. The route hands `Deliver` the delivery (`unanswered`: its event id, provider headers and when they stop verifying) when it forwards and nothing else handled the delivery, and the bridge stores it with each queued message (`channel_thread_inbound.forward`). When the bridge's worker gives a message up, on whichever router, it queues that delivery for the `unhandled` destinations alone (`ForwardUnanswered`); the `all` destinations already have it. Only the first given-up message of a delivery whose forward was queued forwards it (`store.FailChannelInbound`): a sent forward's row is deleted, so the destinations' key alone would not stop a second one; a forward that failed leaves it to the next message given up. A Slack reply that waited for its thread's link is the exception (AI-1001): it is queued with no forward, since its own delivery went to the `unhandled` destinations when it arrived; a failed write of it later forwards nothing, and never the delivery of the mention that took it. - **An idle router looks once a lease, not once a second.** The worker looks at start, on `Forward`, on a finished send, at the first queued row due, and at least once a lease (1 min) whatever is queued. Example: a router with connectors on and no destination sends Postgres two queries at start and two a minute after (`TestAForwarderWithNothingQueuedSendsNoQuery`); router A queues a forward and is scaled down before it sends it, and idle router B sends it within about two minutes, its next look plus A's lease (`TestAnIdleRouterSendsAForwardAnotherRouterLeftQueued`, `TestARouterWaitingOnALaterRetryStillSendsAForwardAnotherRouterLeft`). - **A claimed row is one router's.** The claim ranks due rows from the statement's start, then locks them and checks `next_attempt_at` again on the locked row: a row another router leased in between is skipped (`TestTwoRoutersClaimingAtOnceTakeEachDeliveryOnce`). +- **The claim counts the attempt.** A forwarder that dies between its claim and its send records nothing, so a row claimed more often than it may be tried is dropped unsent (`TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAttempts`). A router without the key version a destination's secret was sealed with sends nothing: it gives the attempt back and leaves the row due a poll later, for a router that holds the key (`TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneThatCan`). A secret that opens under no key is still given up. - **Every destination URL goes through egress.** `CheckURL` at create (`egress.ValidatePublicHTTPSURL`), and the worker's client is `egress.NewClient`. Redirects are never followed. - **Only a provider app's route forwards.** A connector's own route is the operator's app, whose events are no one customer's. - **The router's own events come from the built-in source `stream`.** A destination whose connector id is `stream` (`store.StreamSource`) needs no provider app, and is created, listed, rotated and deleted with the same operations. The policies' notices loop, which runs off the money pass so a slow Postgres never stales the balances, queues `account.balance_low` and `account.balance_exhausted` for every `stream` destination of every app of the organization, whatever its forward, in the transaction that writes the warning's `notices` row (`store.Notices.InsertQueued`), so one warning is queued once however many routers saw it. It wakes the worker (`Forwarder.Wake`); the send is this package's, signing included. diff --git a/acceleration/internal/eventforward/forwarder.go b/acceleration/internal/eventforward/forwarder.go index 5aa51d6887..a739d02238 100644 --- a/acceleration/internal/eventforward/forwarder.go +++ b/acceleration/internal/eventforward/forwarder.go @@ -504,6 +504,10 @@ func (f *Forwarder) sendDue() (wait time.Duration, again bool) { // it or refused it for good, else due again after the next wait, or gone when the waits ran // out. func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { + if delivery.Attempts > len(f.retries)+1 { + f.giveUpUnsent(delivery) + return + } ctx, cancel := context.WithTimeout(f.ctx, attemptTimeout) err := f.send(ctx, delivery) cancel() @@ -516,14 +520,22 @@ func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { log := f.logger.With("connector", delivery.ConnectorID, "customer", delivery.CustomerID, "destination", delivery.DestinationID, "webhook_id", delivery.ID) var again retryable - attempts := delivery.Attempts + 1 + // The claim counted this attempt. + attempts := delivery.Attempts switch { + case errors.Is(err, auth.ErrKeyVersionUnavailable): + // Another router may hold the key version the secret was sealed with: this one sent + // nothing, so the delivery goes back to the queue with no attempt counted. It is due + // again a poll later, not at once, or this router, woken by its own finished send, + // would take it straight back each time and starve the router that can send it. + log.Error("this router cannot open an event destination's signing secret; the forward is left to another", "error", err) + err = f.store.EventDeliveries.Release(writing, delivery.DestinationID, delivery.ID, f.poll) case err == nil: f.count(delivery, "") err = f.store.EventDeliveries.Finish(writing, delivery.DestinationID, delivery.ID) case errors.As(err, &again) && attempts <= len(f.retries): log.Info("an event forward failed and is sent again", "attempts", attempts, "error", err) - err = f.store.EventDeliveries.Retry(writing, delivery.DestinationID, delivery.ID, attempts, time.Now().Add(f.retries[attempts-1])) + err = f.store.EventDeliveries.Retry(writing, delivery.DestinationID, delivery.ID, time.Now().Add(f.retries[attempts-1])) default: log.Warn("gave up an event forward", "attempts", attempts, "error", err) f.count(delivery, givenUpCode(err)) @@ -534,6 +546,21 @@ func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { } } +// giveUpUnsent drops a delivery claimed more times than it may be tried: each claim before +// this one counted its attempt, and a forwarder that died between its claim and its send, every +// time, recorded nothing else. +func (f *Forwarder) giveUpUnsent(delivery store.ClaimedEventDelivery) { + writing, done := context.WithTimeout(context.WithoutCancel(f.ctx), attemptTimeout) + defer done() + log := f.logger.With("connector", delivery.ConnectorID, "customer", delivery.CustomerID, + "destination", delivery.DestinationID, "webhook_id", delivery.ID) + log.Warn("gave up an event forward its earlier claims never finished", "attempts", delivery.Attempts) + f.count(delivery, codeNotSent) + if err := f.store.EventDeliveries.Finish(writing, delivery.DestinationID, delivery.ID); err != nil { + log.Error("could not record an event forward's attempt", "error", err) + } +} + // count counts a forward that ended in the activity record, once and not per attempt: sent, or // refused with code when it was given up. func (f *Forwarder) count(delivery store.ClaimedEventDelivery, code string) { diff --git a/acceleration/internal/eventforward/forwarder_test.go b/acceleration/internal/eventforward/forwarder_test.go index 5e3d4ab3c0..05e72066f3 100644 --- a/acceleration/internal/eventforward/forwarder_test.go +++ b/acceleration/internal/eventforward/forwarder_test.go @@ -97,6 +97,55 @@ func (s *ForwarderSuite) TestAForwardThatKeepsFailingIsGivenUpAfterItsRetries() s.Equal(int32(3), hits.Load(), "the first attempt and the two waits") } +// A forwarder that dies between its claim and its send, every time, records no attempt; the +// claims count them, so the delivery is given up once it was claimed as often as it may be +// tried, and not claimed for ever. +func (s *ForwarderSuite) TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAttempts() { + var hits atomic.Int32 + target := s.destination(func(w http.ResponseWriter, _ *http.Request) { hits.Add(1) }) + stopped, err := New(Options{Store: s.store, Secrets: s.sealer, HTTP: target.Client()}) + s.Require().NoError(err) + customer := s.destinationOf(stopped, target.URL) + s.Require().NoError(stopped.Forward(s.ctx, Event{CustomerID: customer, ConnectorID: "slack_bot", Body: []byte(`{"dies":1}`)})) + // The first attempt and the two waits of s.forwarder's, each claimed by a router that + // stopped before it sent, its lease over at once. + for range 3 { + now := time.Now() + claimed, err := s.store.EventDeliveries.Claim(s.ctx, now, 10, 10, nil, now) + s.Require().NoError(err) + s.Require().NotEmpty(claimed) + } + s.Equal(1, s.pending(customer)) + + s.forwarder(target.Client()) + + s.Require().Eventually(func() bool { return s.pending(customer) == 0 }, 5*time.Second, 10*time.Millisecond) + s.Zero(hits.Load(), "given up, not tried a fourth time") +} + +// A router that does not hold the key version a destination's secret was sealed with sends +// nothing and leaves the forward queued, with no attempt counted, for a router that holds it. +func (s *ForwarderSuite) TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneThatCan() { + var hits atomic.Int32 + target := s.destination(func(w http.ResponseWriter, _ *http.Request) { hits.Add(1) }) + rotated, err := auth.NewSealerWithKeyring(2, map[int]string{1: "test key one", 2: "test key two"}) + s.Require().NoError(err) + holder, err := New(Options{Store: s.store, Secrets: rotated, HTTP: target.Client(), + Retries: []time.Duration{time.Millisecond, time.Millisecond}, Poll: 10 * time.Millisecond}) + s.Require().NoError(err) + customer := s.destinationOf(holder, target.URL) + s.forwarder(target.Client()) + + s.Require().NoError(holder.Forward(s.ctx, Event{CustomerID: customer, ConnectorID: "slack_bot", Body: []byte(`{"sealed":2}`)})) + + s.Never(func() bool { return s.pending(customer) == 0 || hits.Load() > 0 }, 500*time.Millisecond, 10*time.Millisecond, + "a router on key version 1 alone neither sends it nor drops it") + holder.Start() + s.T().Cleanup(holder.Close) + s.Require().Eventually(func() bool { return s.pending(customer) == 0 }, 5*time.Second, 10*time.Millisecond) + s.Equal(int32(1), hits.Load()) +} + // The spec: «3xx: Failure. Following redirects causes unnecessary load on both the sender and // the receiver» (https://www.standardwebhooks.com/). func (s *ForwarderSuite) TestARedirectIsNotFollowedNorSentAgain() { diff --git a/acceleration/internal/store/event_delivery.go b/acceleration/internal/store/event_delivery.go index 0a557175ab..3e1f19796b 100644 --- a/acceleration/internal/store/event_delivery.go +++ b/acceleration/internal/store/event_delivery.go @@ -97,9 +97,9 @@ ON CONFLICT (destination_id, id) DO NOTHING`, return int(queued), nil } -// Claim takes at most limit deliveries due at now, oldest due first, and moves -// each one's next attempt to leaseUntil, so no other worker takes it while this one sends it. -// Rows another worker is claiming at the same moment are skipped, not waited for. +// Claim takes at most limit deliveries due at now, oldest due first, moves each one's next +// attempt to leaseUntil, so no other worker takes it while this one sends it, and counts the +// attempt. Rows another worker is claiming at the same moment are skipped, not waited for. // // It takes at most perDestination deliveries of one destination, less the ones of it the // caller is still sending (sending, by destination id). So one destination that never answers @@ -122,8 +122,8 @@ func (r *EventDeliveries) Claim(ctx context.Context, now time.Time, limit, perDe // // It is not queue.go's claim: a delivery is known by two columns, the cap needs ranked's // window, and the destination's secrets come back in the same statement through a join the -// claim's UPDATE has no place for. A claim does not count attempts either: Retry writes the -// count the forwarder makes. +// claim's UPDATE has no place for. Like queue.go's claim it counts the attempt, so a delivery +// whose forwarder dies between the claim and the send still runs out of attempts. const claimEventDeliveriesQuery = ` WITH sending AS ( SELECT * FROM unnest(?::text[], ?::int[]) AS s (destination_id, count) @@ -143,7 +143,7 @@ WITH sending AS ( FOR UPDATE OF cedl SKIP LOCKED ) UPDATE connector_event_deliveries AS cedl -SET next_attempt_at = ? +SET next_attempt_at = ?, attempts = cedl.attempts + 1 FROM due, connector_event_destinations AS ced WHERE cedl.destination_id = due.destination_id AND cedl.id = due.id AND ced.id = cedl.destination_id RETURNING cedl.destination_id, cedl.id, cedl.headers, cedl.body, cedl.attempts, cedl.next_attempt_at, cedl.created_at, @@ -189,11 +189,22 @@ func (r *EventDeliveries) Finish(ctx context.Context, destinationID, id string) return stack.Wrap(err) } -// Retry records a failed attempt of a delivery, the attempts it has now, and when -// the next one is due. -func (r *EventDeliveries) Retry(ctx context.Context, destinationID, id string, attempts int, at time.Time) error { +// Release gives back a claim that made no attempt: the attempt its claim counted is taken back, +// and the delivery is due again after, on Postgres's clock, for a router that can send it. +func (r *EventDeliveries) Release(ctx context.Context, destinationID, id string, after time.Duration) error { + _, err := r.store.global.NewUpdate().Model((*EventDelivery)(nil)). + Set("attempts = greatest(attempts - 1, 0)"). + Set("next_attempt_at = now() + make_interval(secs => ?)", after.Seconds()). + Where("destination_id = ?", destinationID). + Where("id = ?", id). + Exec(ctx) + return stack.Wrap(err) +} + +// Retry records when the next attempt of a delivery is due. The attempt that failed was +// counted by its claim. +func (r *EventDeliveries) Retry(ctx context.Context, destinationID, id string, at time.Time) error { _, err := r.store.global.NewUpdate().Model((*EventDelivery)(nil)). - Set("attempts = ?", attempts). Set("next_attempt_at = ?", at.UTC()). Where("destination_id = ?", destinationID). Where("id = ?", id). diff --git a/acceleration/internal/store/event_destination_test.go b/acceleration/internal/store/event_destination_test.go index 619af863e1..eb5ed11d81 100644 --- a/acceleration/internal/store/event_destination_test.go +++ b/acceleration/internal/store/event_destination_test.go @@ -217,7 +217,7 @@ func (s *StoreSuite) TestARetriedDeliveryIsDueAtItsNextAttempt() { _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll, ForwardUnhandled}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) s.Require().NoError(err) - s.Require().NoError(s.store.EventDeliveries.Retry(s.ctx, "every", "msg_one", 1, s.base.Add(5*time.Second))) + s.Require().NoError(s.store.EventDeliveries.Retry(s.ctx, "every", "msg_one", s.base.Add(5*time.Second))) early, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(4*time.Second), 10, 10, nil, s.base.Add(time.Minute)) s.Require().NoError(err) @@ -225,7 +225,30 @@ func (s *StoreSuite) TestARetriedDeliveryIsDueAtItsNextAttempt() { due, err := s.store.EventDeliveries.Claim(s.ctx, s.base.Add(5*time.Second), 10, 10, nil, s.base.Add(time.Minute)) s.Require().NoError(err) s.Require().Len(due, 1) - s.Equal(1, due[0].Attempts) + s.Equal(1, due[0].Attempts, "the claim that took it, as Retry counts none") +} + +// A forwarder that dies between its claim and its send records nothing else, so the claim is +// what counts the attempt; a release, of a claim that sent nothing, takes it back. +func (s *StoreSuite) TestAClaimCountsItsAttemptAndAReleaseTakesItBack() { + s.eventDestination("acme-app", "slack_bot", "every", ForwardAll) + _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) + s.Require().NoError(err) + + first, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base) + s.Require().NoError(err) + s.Require().Len(first, 1) + second, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base.Add(time.Hour)) + s.Require().NoError(err) + s.Require().Len(second, 1) + s.Equal([]int{1, 2}, []int{first[0].Attempts, second[0].Attempts}) + + s.Require().NoError(s.store.EventDeliveries.Release(s.ctx, "every", "msg_one", 0)) + + again, err := s.store.EventDeliveries.Claim(s.ctx, time.Now(), 10, 10, nil, time.Now().Add(time.Hour)) + s.Require().NoError(err) + s.Require().Len(again, 1, "due again after the release's wait, though the last claim's lease runs an hour") + s.Equal(2, again[0].Attempts, "the released claim is not counted") } func (s *StoreSuite) TestDeletingADestinationDropsItsPendingDeliveries() { @@ -313,7 +336,7 @@ func (s *StoreSuite) TestEventDeliveryQueryBudgets() { s.Require().NoError(err) }), "NextDue") s.Equal(1, s.countQueries(func() { - s.Require().NoError(s.store.EventDeliveries.Retry(s.ctx, claimed[0].DestinationID, claimed[0].ID, 1, s.base.Add(time.Hour))) + s.Require().NoError(s.store.EventDeliveries.Retry(s.ctx, claimed[0].DestinationID, claimed[0].ID, s.base.Add(time.Hour))) }), "Retry") s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.EventDeliveries.Finish(s.ctx, claimed[1].DestinationID, claimed[1].ID)) From d6d8aeb4732f73c610f59710d3494dc234f32342 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:36:21 +0100 Subject: [PATCH 2/3] docs(eventforward): a send Close cuts short keeps the attempt its claim counted Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/eventforward/forwarder.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/eventforward/forwarder.go b/acceleration/internal/eventforward/forwarder.go index a739d02238..cdd399c64d 100644 --- a/acceleration/internal/eventforward/forwarder.go +++ b/acceleration/internal/eventforward/forwarder.go @@ -267,8 +267,9 @@ func (f *Forwarder) Start() { }() } -// Close stops the worker and cancels the sends in flight. A send cut short is not counted as -// an attempt: its lease runs out and a router sends it again. +// Close stops the worker and cancels the sends in flight. A send cut short keeps the attempt +// its claim counted, as a router that died mid-send does, since the destination may have had +// it: its lease runs out and a router sends it again while attempts remain. func (f *Forwarder) Close() { f.cancel() f.working.Wait() @@ -512,7 +513,8 @@ func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { err := f.send(ctx, delivery) cancel() if f.ctx.Err() != nil { - // Close cut it short: the lease runs out and a router sends it again. + // Close cut it short: the attempt its claim counted stays, the lease runs out and a + // router sends it again. return } writing, done := context.WithTimeout(context.WithoutCancel(f.ctx), attemptTimeout) From d9038120f7da1feb51881e5bb0ad11647fb6412c Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 09:54:24 +0100 Subject: [PATCH 3/3] fix(eventforward): bound a forward no router can sign, and fence its release A release is due a lease later rather than a poll, so a router without the key no longer cycles the destination's backlog every second, and logs once a lease per destination. A forward no router has signed for longer than its retries and a lease is given up as forward_failed. Release names the claim it gives back by its attempts and lease, so it cannot undo a newer claim. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/eventforward/AGENTS.md | 2 +- .../internal/eventforward/forwarder.go | 77 ++++++++++++++----- .../internal/eventforward/forwarder_test.go | 49 +++++++++++- acceleration/internal/store/event_delivery.go | 15 ++-- .../internal/store/event_destination_test.go | 31 +++++++- 5 files changed, 144 insertions(+), 30 deletions(-) diff --git a/acceleration/internal/eventforward/AGENTS.md b/acceleration/internal/eventforward/AGENTS.md index de6641847b..9d55e70482 100644 --- a/acceleration/internal/eventforward/AGENTS.md +++ b/acceleration/internal/eventforward/AGENTS.md @@ -53,7 +53,7 @@ worker (every router) off the request - **A message the bridge could not write is unhandled after all.** `Bridge.Deliver` counts a message as answered before it writes it into its thread channel, after the ack. The route hands `Deliver` the delivery (`unanswered`: its event id, provider headers and when they stop verifying) when it forwards and nothing else handled the delivery, and the bridge stores it with each queued message (`channel_thread_inbound.forward`). When the bridge's worker gives a message up, on whichever router, it queues that delivery for the `unhandled` destinations alone (`ForwardUnanswered`); the `all` destinations already have it. Only the first given-up message of a delivery whose forward was queued forwards it (`store.FailChannelInbound`): a sent forward's row is deleted, so the destinations' key alone would not stop a second one; a forward that failed leaves it to the next message given up. A Slack reply that waited for its thread's link is the exception (AI-1001): it is queued with no forward, since its own delivery went to the `unhandled` destinations when it arrived; a failed write of it later forwards nothing, and never the delivery of the mention that took it. - **An idle router looks once a lease, not once a second.** The worker looks at start, on `Forward`, on a finished send, at the first queued row due, and at least once a lease (1 min) whatever is queued. Example: a router with connectors on and no destination sends Postgres two queries at start and two a minute after (`TestAForwarderWithNothingQueuedSendsNoQuery`); router A queues a forward and is scaled down before it sends it, and idle router B sends it within about two minutes, its next look plus A's lease (`TestAnIdleRouterSendsAForwardAnotherRouterLeftQueued`, `TestARouterWaitingOnALaterRetryStillSendsAForwardAnotherRouterLeft`). - **A claimed row is one router's.** The claim ranks due rows from the statement's start, then locks them and checks `next_attempt_at` again on the locked row: a row another router leased in between is skipped (`TestTwoRoutersClaimingAtOnceTakeEachDeliveryOnce`). -- **The claim counts the attempt.** A forwarder that dies between its claim and its send records nothing, so a row claimed more often than it may be tried is dropped unsent (`TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAttempts`). A router without the key version a destination's secret was sealed with sends nothing: it gives the attempt back and leaves the row due a poll later, for a router that holds the key (`TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneThatCan`). A secret that opens under no key is still given up. +- **The claim counts the attempt.** A forwarder that dies between its claim and its send records nothing, so a row claimed more often than it may be tried is dropped unsent (`TestAForwardWhoseSenderDiesEveryTimeIsGivenUpAfterItsAttempts`). A router without the key version a destination's secret was sealed with sends nothing: it gives the attempt back and leaves the row due a lease later, for a router that holds the key (`TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneThatCan`), and logs it once a lease per destination. A forward no router has signed for longer than its retries and a lease is given up as `forward_failed` (`TestAForwardNoRouterCanSignIsGivenUpAndNotClaimedEveryPoll`). A secret that opens under no key is still given up. - **Every destination URL goes through egress.** `CheckURL` at create (`egress.ValidatePublicHTTPSURL`), and the worker's client is `egress.NewClient`. Redirects are never followed. - **Only a provider app's route forwards.** A connector's own route is the operator's app, whose events are no one customer's. - **The router's own events come from the built-in source `stream`.** A destination whose connector id is `stream` (`store.StreamSource`) needs no provider app, and is created, listed, rotated and deleted with the same operations. The policies' notices loop, which runs off the money pass so a slow Postgres never stales the balances, queues `account.balance_low` and `account.balance_exhausted` for every `stream` destination of every app of the organization, whatever its forward, in the transaction that writes the warning's `notices` row (`store.Notices.InsertQueued`), so one warning is queued once however many routers saw it. It wakes the worker (`Forwarder.Wake`); the send is this package's, signing included. diff --git a/acceleration/internal/eventforward/forwarder.go b/acceleration/internal/eventforward/forwarder.go index cdd399c64d..23288a4513 100644 --- a/acceleration/internal/eventforward/forwarder.go +++ b/acceleration/internal/eventforward/forwarder.go @@ -157,9 +157,12 @@ type Forwarder struct { // sending is how many sends to each destination are running, by destination id. mu sync.Mutex sending map[string]int - ctx context.Context - cancel context.CancelFunc - working sync.WaitGroup + // unopenedAt is when this router last logged that it cannot open a destination's signing + // secret, by destination id (unopened). + unopenedAt map[string]time.Time + ctx context.Context + cancel context.CancelFunc + working sync.WaitGroup } // Event is one verified provider delivery of one customer's provider app. @@ -224,20 +227,21 @@ func New(options Options) (*Forwarder, error) { } ctx, cancel := context.WithCancel(context.Background()) return &Forwarder{ - store: options.Store, - secrets: options.Secrets, - http: &unredirected, - publicURL: publicURL, - retries: retries, - poll: poll, - lease: leaseFor, - activity: options.Activity, - logger: logger, - kick: make(chan struct{}, 1), - slots: make(chan struct{}, inFlight), - sending: map[string]int{}, - ctx: ctx, - cancel: cancel, + store: options.Store, + secrets: options.Secrets, + http: &unredirected, + publicURL: publicURL, + retries: retries, + poll: poll, + lease: leaseFor, + activity: options.Activity, + logger: logger, + kick: make(chan struct{}, 1), + slots: make(chan struct{}, inFlight), + sending: map[string]int{}, + unopenedAt: map[string]time.Time{}, + ctx: ctx, + cancel: cancel, }, nil } @@ -525,13 +529,18 @@ func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { // The claim counted this attempt. attempts := delivery.Attempts switch { + case errors.Is(err, auth.ErrKeyVersionUnavailable) && time.Since(delivery.CreatedAt) > f.unsignedWait(): + // No router opened it for longer than its retries would have run: none holds the key. + log.Warn("gave up an event forward no router could sign", "error", err) + f.count(delivery, codeNotSent) + err = f.store.EventDeliveries.Finish(writing, delivery.DestinationID, delivery.ID) case errors.Is(err, auth.ErrKeyVersionUnavailable): // Another router may hold the key version the secret was sealed with: this one sent // nothing, so the delivery goes back to the queue with no attempt counted. It is due - // again a poll later, not at once, or this router, woken by its own finished send, - // would take it straight back each time and starve the router that can send it. - log.Error("this router cannot open an event destination's signing secret; the forward is left to another", "error", err) - err = f.store.EventDeliveries.Release(writing, delivery.DestinationID, delivery.ID, f.poll) + // again a lease later, as if its claim had run out, not at once: this router, woken by + // its own finished send, would take the destination's backlog straight back every poll. + f.unopened(log, delivery.DestinationID, err) + err = f.store.EventDeliveries.Release(writing, delivery, f.lease) case err == nil: f.count(delivery, "") err = f.store.EventDeliveries.Finish(writing, delivery.DestinationID, delivery.ID) @@ -548,6 +557,32 @@ func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { } } +// unsignedWait is how long a forward no router can sign is left for one that can: its whole +// retry schedule, and a lease for the release that ends it. +func (f *Forwarder) unsignedWait() time.Duration { + wait := f.lease + for _, retry := range f.retries { + wait += retry + } + return wait +} + +// unopened logs that this router cannot open a destination's signing secret, once a lease for +// each destination: a destination's whole backlog fails alike, and one line says it. +func (f *Forwarder) unopened(log *slog.Logger, destinationID string, err error) { + f.mu.Lock() + last, seen := f.unopenedAt[destinationID] + due := !seen || time.Since(last) >= f.lease + if due { + f.unopenedAt[destinationID] = time.Now() + } + f.mu.Unlock() + if !due { + return + } + log.Error("this router cannot open an event destination's signing secret; its forwards are left to another", "error", err) +} + // giveUpUnsent drops a delivery claimed more times than it may be tried: each claim before // this one counted its attempt, and a forwarder that died between its claim and its send, every // time, recorded nothing else. diff --git a/acceleration/internal/eventforward/forwarder_test.go b/acceleration/internal/eventforward/forwarder_test.go index 05e72066f3..8633062172 100644 --- a/acceleration/internal/eventforward/forwarder_test.go +++ b/acceleration/internal/eventforward/forwarder_test.go @@ -134,7 +134,13 @@ func (s *ForwarderSuite) TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneT Retries: []time.Duration{time.Millisecond, time.Millisecond}, Poll: 10 * time.Millisecond}) s.Require().NoError(err) customer := s.destinationOf(holder, target.URL) - s.forwarder(target.Client()) + // Its releases are due a 200 ms lease later, and its retries are long, so it leaves the + // forward for the holder well before it would give it up. + keyOne, err := New(Options{Store: s.store, Secrets: s.sealer, HTTP: target.Client(), + Retries: []time.Duration{time.Minute}, Poll: 10 * time.Millisecond, Lease: 200 * time.Millisecond}) + s.Require().NoError(err) + keyOne.Start() + s.T().Cleanup(keyOne.Close) s.Require().NoError(holder.Forward(s.ctx, Event{CustomerID: customer, ConnectorID: "slack_bot", Body: []byte(`{"sealed":2}`)})) @@ -146,6 +152,47 @@ func (s *ForwarderSuite) TestAForwardWhoseSecretThisRouterCannotOpenIsLeftToOneT s.Equal(int32(1), hits.Load()) } +// A forward sealed under a key version no router holds is released a lease at a time, not +// claimed again every poll, and given up once it has waited out its retries, rather than +// cycled for ever. +func (s *ForwarderSuite) TestAForwardNoRouterCanSignIsGivenUpAndNotClaimedEveryPoll() { + var hits atomic.Int32 + target := s.destination(func(w http.ResponseWriter, _ *http.Request) { hits.Add(1) }) + rotated, err := auth.NewSealerWithKeyring(2, map[int]string{1: "test key one", 2: "test key two"}) + s.Require().NoError(err) + sealer, err := New(Options{Store: s.store, Secrets: rotated, HTTP: target.Client()}) + s.Require().NoError(err) + customer := s.destinationOf(sealer, target.URL) + own, err := store.Open(s.dsn) + s.Require().NoError(err) + s.T().Cleanup(func() { s.Require().NoError(own.Close()) }) + releases := &releaseCount{} + own.GlobalDB().AddQueryHook(releases) + keyOne, err := New(Options{Store: own, Secrets: s.sealer, HTTP: target.Client(), + Retries: []time.Duration{time.Millisecond}, Poll: 10 * time.Millisecond, Lease: 500 * time.Millisecond}) + s.Require().NoError(err) + keyOne.Start() + s.T().Cleanup(keyOne.Close) + + s.Require().NoError(sealer.Forward(s.ctx, Event{CustomerID: customer, ConnectorID: "slack_bot", Body: []byte(`{"sealed":2}`)})) + + s.Require().Eventually(func() bool { return s.pending(customer) == 0 }, 5*time.Second, 10*time.Millisecond) + s.Zero(hits.Load()) + s.GreaterOrEqual(releases.Load(), int32(1), "left for another router before it was given up") + s.LessOrEqual(releases.Load(), int32(2), "released a lease at a time, over about a second, not every 10 ms poll") +} + +// releaseCount counts the releases a store sent Postgres. +type releaseCount struct{ atomic.Int32 } + +func (*releaseCount) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context { return ctx } + +func (r *releaseCount) AfterQuery(_ context.Context, event *bun.QueryEvent) { + if strings.Contains(event.Query, "greatest(attempts - 1") { + r.Add(1) + } +} + // The spec: «3xx: Failure. Following redirects causes unnecessary load on both the sender and // the receiver» (https://www.standardwebhooks.com/). func (s *ForwarderSuite) TestARedirectIsNotFollowedNorSentAgain() { diff --git a/acceleration/internal/store/event_delivery.go b/acceleration/internal/store/event_delivery.go index 3e1f19796b..6aaf3ad415 100644 --- a/acceleration/internal/store/event_delivery.go +++ b/acceleration/internal/store/event_delivery.go @@ -189,14 +189,19 @@ func (r *EventDeliveries) Finish(ctx context.Context, destinationID, id string) return stack.Wrap(err) } -// Release gives back a claim that made no attempt: the attempt its claim counted is taken back, -// and the delivery is due again after, on Postgres's clock, for a router that can send it. -func (r *EventDeliveries) Release(ctx context.Context, destinationID, id string, after time.Duration) error { +// Release gives back the claim of delivery that made no attempt: the attempt its claim counted +// is taken back, and the delivery is due again after, on Postgres's clock, for a router that can +// send it. It changes the row only while that claim still holds it, by the attempts and the +// lease the claim wrote: a release whose lease ran out, and whose row another router claimed +// since, would otherwise undo the newer claim. +func (r *EventDeliveries) Release(ctx context.Context, delivery ClaimedEventDelivery, after time.Duration) error { _, err := r.store.global.NewUpdate().Model((*EventDelivery)(nil)). Set("attempts = greatest(attempts - 1, 0)"). Set("next_attempt_at = now() + make_interval(secs => ?)", after.Seconds()). - Where("destination_id = ?", destinationID). - Where("id = ?", id). + Where("destination_id = ?", delivery.DestinationID). + Where("id = ?", delivery.ID). + Where("attempts = ?", delivery.Attempts). + Where("next_attempt_at = ?", delivery.NextAttemptAt). Exec(ctx) return stack.Wrap(err) } diff --git a/acceleration/internal/store/event_destination_test.go b/acceleration/internal/store/event_destination_test.go index eb5ed11d81..3755b6cdbe 100644 --- a/acceleration/internal/store/event_destination_test.go +++ b/acceleration/internal/store/event_destination_test.go @@ -243,14 +243,38 @@ func (s *StoreSuite) TestAClaimCountsItsAttemptAndAReleaseTakesItBack() { s.Require().Len(second, 1) s.Equal([]int{1, 2}, []int{first[0].Attempts, second[0].Attempts}) - s.Require().NoError(s.store.EventDeliveries.Release(s.ctx, "every", "msg_one", 0)) + s.Require().NoError(s.store.EventDeliveries.Release(s.ctx, second[0], 0)) - again, err := s.store.EventDeliveries.Claim(s.ctx, time.Now(), 10, 10, nil, time.Now().Add(time.Hour)) + // A minute on, past the release's now() on Postgres's clock, which may run ahead of this + // process's. + later := time.Now().Add(time.Minute) + again, err := s.store.EventDeliveries.Claim(s.ctx, later, 10, 10, nil, later.Add(time.Hour)) s.Require().NoError(err) s.Require().Len(again, 1, "due again after the release's wait, though the last claim's lease runs an hour") s.Equal(2, again[0].Attempts, "the released claim is not counted") } +// A release names the claim it gives back: one whose lease ran out, and whose row another +// router claimed since, leaves the newer claim alone. +func (s *StoreSuite) TestAReleaseOfAClaimTakenOverChangesNothing() { + s.eventDestination("acme-app", "slack_bot", "every", ForwardAll) + _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) + s.Require().NoError(err) + stale, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base) + s.Require().NoError(err) + s.Require().Len(stale, 1) + current, err := s.store.EventDeliveries.Claim(s.ctx, s.base, 10, 10, nil, s.base.Add(time.Hour)) + s.Require().NoError(err) + s.Require().Len(current, 1) + + s.Require().NoError(s.store.EventDeliveries.Release(s.ctx, stale[0], 0)) + + var held EventDelivery + s.Require().NoError(s.store.GlobalDB().NewSelect().Model(&held).Where("id = ?", "msg_one").Scan(s.ctx)) + s.Equal(2, held.Attempts, "the current claim's count") + s.True(held.NextAttemptAt.Equal(s.base.Add(time.Hour)), "the current claim's lease: %s", held.NextAttemptAt) +} + func (s *StoreSuite) TestDeletingADestinationDropsItsPendingDeliveries() { s.eventDestination("acme-app", "slack_bot", "every", ForwardAll) _, err := s.store.EventDeliveries.Queue(s.ctx, "acme-app", "slack_bot", []string{ForwardAll, ForwardUnhandled}, EventDelivery{ID: "msg_one", Body: []byte("{}"), NextAttemptAt: s.base}) @@ -341,4 +365,7 @@ func (s *StoreSuite) TestEventDeliveryQueryBudgets() { s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.EventDeliveries.Finish(s.ctx, claimed[1].DestinationID, claimed[1].ID)) }), "Finish") + s.Equal(1, s.countQueries(func() { + s.Require().NoError(s.store.EventDeliveries.Release(s.ctx, claimed[2], time.Minute)) + }), "Release") }