Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions acceleration/internal/eventforward/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
Expand Down
108 changes: 86 additions & 22 deletions acceleration/internal/eventforward/forwarder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -267,8 +271,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()
Expand Down Expand Up @@ -504,26 +509,44 @@ 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()
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)
defer done()
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
Comment thread
getstream-metis[bot] marked this conversation as resolved.
Resolved
switch {
case errors.Is(err, auth.ErrKeyVersionUnavailable) && time.Since(delivery.CreatedAt) > f.unsignedWait():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should Fix] Give-up by row age drops a forward still on its retries
Issue: A forward still within its normal retries, or one that waited behind a slow destination's backlog, is dropped as not sent the first time a router without its key version claims it. A router that holds the key never gets to send it.
Cause: forwarder.go:532 compares time.Since(delivery.CreatedAt) with unsignedWait(), which is the lease plus the sum of the retries. That measures the row's age, not how long no router could sign it. Retries are scheduled from the end of each send (forwarder.go:549), so real retries pass the margin.
Fix: Time the give-up from the first release for ErrKeyVersionUnavailable. For example, store a marker that Release sets once and that a successful send or a retry leaves alone.
Side effect: This needs a new column or marker on the delivery row, so check the migration order.

Evidence
  • created_at comes from DEFAULT now() in Queue (store/event_delivery.go:87), so it is the queue time
  • unsignedWait = lease + sum(retries) (forwarder.go:562-568); defaultRetries sum is about 2h35m (line 90)
  • Retry at forwarder.go:549 schedules from time.Now() after each send, and attemptTimeout is 15s (line 50). Four timed-out sends add 60s, which is the whole lease margin.
  • Key rotation rollout: a v1-only router claims an old row, errors.Is(err, ErrKeyVersionUnavailable) holds and the row age is over the limit. Finish at line 536 deletes it without any v2 router trying.

// 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 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)
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))
Expand All @@ -534,6 +557,47 @@ 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.
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) {
Expand Down
96 changes: 96 additions & 0 deletions acceleration/internal/eventforward/forwarder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,102 @@ 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)
// 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}`)}))

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())
}

// 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() {
Expand Down
36 changes: 26 additions & 10 deletions acceleration/internal/store/event_delivery.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -189,11 +189,27 @@ 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 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 = ?", delivery.DestinationID).
Where("id = ?", delivery.ID).
Where("attempts = ?", delivery.Attempts).
Where("next_attempt_at = ?", delivery.NextAttemptAt).
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).
Expand Down
Loading
Loading