feat(outbox): relay committed outbox events to Kafka
This commit is contained in:
1 parent
78f1651f6b
commit
6c3b34f73e
42 files changed
+3731
-45
No files matched your search
@@ -0,0 +1,40 @@
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Backoff is a capped exponential delay with equal jitter: the ceiling starts
|
||||
// at Initial, doubles with every consecutive failure, and stops at Max; the
|
||||
// delay is half the ceiling plus a random share of the other half. The fixed
|
||||
// half keeps retries from hammering a recovering broker, and the random half
|
||||
// spreads several relays apart.
|
||||
type Backoff struct {
|
||||
Initial time.Duration
|
||||
Max time.Duration
|
||||
// jitter returns a value in [0, limit]. Tests replace it.
|
||||
jitter func(limit time.Duration) time.Duration
|
||||
}
|
||||
|
||||
// Delay returns the wait before the next attempt after failures consecutive
|
||||
// failures. failures below 1 count as 1.
|
||||
func (backoff Backoff) Delay(failures int) time.Duration {
|
||||
ceiling := min(backoff.Initial, backoff.Max)
|
||||
for attempt := 1; attempt < failures && ceiling < backoff.Max; attempt++ {
|
||||
ceiling = min(ceiling*2, backoff.Max)
|
||||
}
|
||||
half := ceiling / 2
|
||||
jitter := backoff.jitter
|
||||
if jitter == nil {
|
||||
jitter = randomJitter
|
||||
}
|
||||
return half + jitter(ceiling-half)
|
||||
}
|
||||
|
||||
func randomJitter(limit time.Duration) time.Duration {
|
||||
if limit <= 0 {
|
||||
return 0
|
||||
}
|
||||
return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness.
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBackoffDoublesFromInitialToTheCap(t *testing.T) {
|
||||
noJitter := func(time.Duration) time.Duration { return 0 }
|
||||
fullJitter := func(limit time.Duration) time.Duration { return limit }
|
||||
backoff := Backoff{Initial: 500 * time.Millisecond, Max: 5 * time.Second}
|
||||
|
||||
ceilings := []time.Duration{
|
||||
500 * time.Millisecond, // failure 1
|
||||
time.Second,
|
||||
2 * time.Second,
|
||||
4 * time.Second,
|
||||
5 * time.Second, // capped
|
||||
5 * time.Second,
|
||||
}
|
||||
for index, ceiling := range ceilings {
|
||||
failures := index + 1
|
||||
backoff.jitter = noJitter
|
||||
if got := backoff.Delay(failures); got != ceiling/2 {
|
||||
t.Fatalf("Delay(%d) without jitter = %s, want %s", failures, got, ceiling/2)
|
||||
}
|
||||
backoff.jitter = fullJitter
|
||||
if got := backoff.Delay(failures); got != ceiling {
|
||||
t.Fatalf("Delay(%d) with full jitter = %s, want %s", failures, got, ceiling)
|
||||
}
|
||||
}
|
||||
backoff.jitter = fullJitter
|
||||
if got := backoff.Delay(0); got != 500*time.Millisecond {
|
||||
t.Fatalf("Delay(0) = %s, want the first delay", got)
|
||||
}
|
||||
if got := backoff.Delay(1 << 20); got != 5*time.Second {
|
||||
t.Fatalf("Delay(many) = %s, want the cap", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackoffRandomJitterStaysWithinTheCeiling(t *testing.T) {
|
||||
backoff := Backoff{Initial: 100 * time.Millisecond, Max: time.Second}
|
||||
for failures := 1; failures <= 8; failures++ {
|
||||
ceiling := min(100*time.Millisecond<<(failures-1), time.Second)
|
||||
for range 50 {
|
||||
delay := backoff.Delay(failures)
|
||||
if delay < ceiling/2 || delay > ceiling {
|
||||
t.Fatalf("Delay(%d) = %s, want between %s and %s", failures, delay, ceiling/2, ceiling)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// Package outboxrelay publishes committed transactional outbox events to the
|
||||
// event bus with at-least-once delivery.
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Metrics records relay outcomes and the backlog without per-event labels.
|
||||
type Metrics interface {
|
||||
ObserveOutboxRelayPass(published, failed int)
|
||||
ObserveOutboxBacklog(backlog outbound.OutboxBacklog)
|
||||
}
|
||||
|
||||
// Settings are the named relay limits; config validates their ranges.
|
||||
type Settings struct {
|
||||
// BatchSize bounds the events one pass locks and publishes.
|
||||
BatchSize int
|
||||
// PollInterval is the wait after a pass that found no pending event.
|
||||
PollInterval time.Duration
|
||||
// Backoff is the wait after a failed pass or a failed Prepare.
|
||||
Backoff Backoff
|
||||
// ShutdownTimeout bounds how long a pass in progress may continue after
|
||||
// Run's context ends. When it expires the pass is canceled and its
|
||||
// transaction rolls back, so nothing it published is marked.
|
||||
ShutdownTimeout time.Duration
|
||||
// BacklogInterval is the least time between two backlog reads for the
|
||||
// metrics, so a busy relay does not count the outbox on every pass. It
|
||||
// also bounds one read.
|
||||
BacklogInterval time.Duration
|
||||
}
|
||||
|
||||
// Relay moves pending outbox events to the event bus. Several relays may run
|
||||
// against one database: each pass locks its rows with SKIP LOCKED, and only
|
||||
// the earliest unpublished event of an aggregate can be claimed, so one
|
||||
// aggregate's events are published in order. A pass marks only events the
|
||||
// broker acknowledged. An event acknowledged in a pass that does not commit
|
||||
// is published again later with the same event ID; consumers deduplicate.
|
||||
type Relay struct {
|
||||
store outbound.OutboxRelayStore
|
||||
publisher outbound.EventPublisher
|
||||
metrics Metrics
|
||||
logger *slog.Logger
|
||||
settings Settings
|
||||
}
|
||||
|
||||
func New(
|
||||
store outbound.OutboxRelayStore,
|
||||
publisher outbound.EventPublisher,
|
||||
metrics Metrics,
|
||||
logger *slog.Logger,
|
||||
settings Settings,
|
||||
) *Relay {
|
||||
return &Relay{store: store, publisher: publisher, metrics: metrics, logger: logger, settings: settings}
|
||||
}
|
||||
|
||||
// PassResult counts the events of one pass.
|
||||
type PassResult struct {
|
||||
// Claimed events were locked and handed to the publisher.
|
||||
Claimed int
|
||||
// Published events were acknowledged and marked in a committed
|
||||
// transaction.
|
||||
Published int
|
||||
}
|
||||
|
||||
// PublishPending runs one pass: it locks a batch, publishes it, and marks the
|
||||
// acknowledged events in the same transaction. A nil error means every
|
||||
// claimed event was published. On an error Published counts only events whose
|
||||
// mark committed.
|
||||
func (relay *Relay) PublishPending(ctx context.Context) (PassResult, error) {
|
||||
var (
|
||||
result PassResult
|
||||
acknowledged int
|
||||
publishErr error
|
||||
)
|
||||
claimErr := relay.store.ClaimPending(ctx, relay.settings.BatchSize, func(ctx context.Context, events []outbound.OutboxEvent) []uuid.UUID {
|
||||
result.Claimed = len(events)
|
||||
ids, err := relay.publish(ctx, events)
|
||||
acknowledged, publishErr = len(ids), err
|
||||
return ids
|
||||
})
|
||||
if claimErr != nil {
|
||||
return result, fmt.Errorf("Relay.PublishPending - claim pending events: %w", errors.Join(claimErr, publishErr))
|
||||
}
|
||||
result.Published = acknowledged
|
||||
if publishErr != nil {
|
||||
return result, fmt.Errorf("Relay.PublishPending - publish events: %w", publishErr)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// publish returns the acknowledged event IDs and, when some events were not
|
||||
// acknowledged, an error with their count and the first cause. The other
|
||||
// causes are dropped to keep one log line per pass.
|
||||
func (relay *Relay) publish(ctx context.Context, events []outbound.OutboxEvent) ([]uuid.UUID, error) {
|
||||
outcomes := relay.publisher.Publish(ctx, events)
|
||||
if len(outcomes) != len(events) {
|
||||
return nil, fmt.Errorf("Relay.publish - publisher returned %d results for %d events", len(outcomes), len(events))
|
||||
}
|
||||
acknowledged := make([]uuid.UUID, 0, len(events))
|
||||
var firstErr error
|
||||
for index, err := range outcomes {
|
||||
if err == nil {
|
||||
acknowledged = append(acknowledged, events[index].EventID)
|
||||
continue
|
||||
}
|
||||
// A missing destination wins, so Run sees it and prepares again.
|
||||
if firstErr == nil || (errors.Is(err, outbound.ErrEventDestinationMissing) && !errors.Is(firstErr, outbound.ErrEventDestinationMissing)) {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
if firstErr != nil {
|
||||
return acknowledged, fmt.Errorf("Relay.publish - %d of %d events not acknowledged: %w", len(events)-len(acknowledged), len(events), firstErr)
|
||||
}
|
||||
return acknowledged, nil
|
||||
}
|
||||
|
||||
// Run prepares the event bus and then publishes pending events until ctx
|
||||
// ends. A pass that published events is followed immediately by the next one,
|
||||
// even when some of its events failed; an empty pass waits PollInterval; a
|
||||
// pass that published nothing and failed waits Backoff, which grows only
|
||||
// across such passes. A pass that reports a missing destination makes Run
|
||||
// call Prepare again first. Failures are logged and retried indefinitely, so
|
||||
// Run returns only after ctx ends and the pass in progress finishes or
|
||||
// ShutdownTimeout cancels it.
|
||||
func (relay *Relay) Run(ctx context.Context) {
|
||||
passCtx, stopPasses := relay.passContext(ctx)
|
||||
defer stopPasses()
|
||||
relay.logger.Info("outbox relay started",
|
||||
slog.Int("batch_size", relay.settings.BatchSize),
|
||||
slog.Duration("poll_interval", relay.settings.PollInterval),
|
||||
)
|
||||
defer relay.logger.Info("outbox relay stopped")
|
||||
|
||||
backlog := backlogRefresher{relay: relay}
|
||||
failures := 0
|
||||
needsPrepare := true
|
||||
for {
|
||||
if needsPrepare {
|
||||
if !relay.prepare(ctx, &backlog) {
|
||||
return
|
||||
}
|
||||
}
|
||||
result, err := relay.PublishPending(passCtx)
|
||||
relay.metrics.ObserveOutboxRelayPass(result.Published, result.Claimed-result.Published)
|
||||
backlog.refresh(ctx)
|
||||
needsPrepare = errors.Is(err, outbound.ErrEventDestinationMissing)
|
||||
var delay time.Duration
|
||||
delay, failures = relay.nextDelay(result, err, failures)
|
||||
if !wait(ctx, delay) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nextDelay returns the wait before the next pass and the new count of
|
||||
// consecutive failed passes that published nothing.
|
||||
func (relay *Relay) nextDelay(result PassResult, err error, failures int) (time.Duration, int) {
|
||||
switch {
|
||||
case err != nil && result.Published > 0:
|
||||
// The pass made progress, so the event bus works; the failed events
|
||||
// are retried at once instead of slowing the others down.
|
||||
relay.logger.Warn("outbox relay pass published part of its batch; the rest stay pending",
|
||||
slog.Int("claimed", result.Claimed),
|
||||
slog.Int("published", result.Published),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
return 0, 0
|
||||
case err != nil:
|
||||
failures++
|
||||
delay := relay.settings.Backoff.Delay(failures)
|
||||
relay.logger.Warn("outbox relay pass failed; unacknowledged events stay pending",
|
||||
slog.Int("claimed", result.Claimed),
|
||||
slog.Int("published", result.Published),
|
||||
slog.Int("consecutive_failures", failures),
|
||||
slog.Duration("retry_in", delay),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
return delay, failures
|
||||
case result.Claimed > 0:
|
||||
return 0, 0
|
||||
default:
|
||||
return relay.settings.PollInterval, 0
|
||||
}
|
||||
}
|
||||
|
||||
// prepare repeats Prepare with backoff until it succeeds or ctx ends. The
|
||||
// backlog metrics keep refreshing meanwhile, so a growing outbox stays visible.
|
||||
func (relay *Relay) prepare(ctx context.Context, backlog *backlogRefresher) bool {
|
||||
for failures := 1; ; failures++ {
|
||||
err := relay.publisher.Prepare(ctx)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
backlog.refresh(ctx)
|
||||
delay := relay.settings.Backoff.Delay(failures)
|
||||
relay.logger.Warn("outbox relay could not prepare the event bus; events stay pending",
|
||||
slog.Int("consecutive_failures", failures),
|
||||
slog.Duration("retry_in", delay),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
if !wait(ctx, delay) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// backlogRefresher reads the outbox backlog for the metrics at most once per
|
||||
// BacklogInterval.
|
||||
type backlogRefresher struct {
|
||||
relay *Relay
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func (refresher *backlogRefresher) refresh(ctx context.Context) {
|
||||
interval := refresher.relay.settings.BacklogInterval
|
||||
if !refresher.last.IsZero() && time.Since(refresher.last) < interval {
|
||||
return
|
||||
}
|
||||
refresher.last = time.Now()
|
||||
readCtx, cancel := context.WithTimeout(ctx, interval)
|
||||
defer cancel()
|
||||
backlog, err := refresher.relay.store.Backlog(readCtx)
|
||||
if err != nil {
|
||||
// A read interrupted by shutdown is not worth a warning.
|
||||
if ctx.Err() == nil {
|
||||
refresher.relay.logger.Warn("outbox relay could not read the backlog; its metrics are stale", slog.Any("error", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
refresher.relay.metrics.ObserveOutboxBacklog(backlog)
|
||||
}
|
||||
|
||||
// passContext returns a context for passes that outlives ctx by at most
|
||||
// ShutdownTimeout, so a pass in progress at shutdown can finish and mark what
|
||||
// the broker acknowledged. stop releases the watcher goroutine.
|
||||
func (relay *Relay) passContext(ctx context.Context) (context.Context, func()) {
|
||||
passCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
||||
stopWatching := context.AfterFunc(ctx, func() {
|
||||
timer := time.NewTimer(relay.settings.ShutdownTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
cancel()
|
||||
case <-passCtx.Done():
|
||||
}
|
||||
})
|
||||
return passCtx, func() {
|
||||
stopWatching()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// wait sleeps for delay and reports false when ctx ends first. A zero delay
|
||||
// still reports a canceled context.
|
||||
func wait(ctx context.Context, delay time.Duration) bool {
|
||||
if delay <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package outboxrelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
testTimeout = 5 * time.Second
|
||||
testInterval = time.Millisecond
|
||||
)
|
||||
|
||||
var errBrokerDown = errors.New("broker down")
|
||||
|
||||
// fakeStore models the claim transaction: events acknowledged by publish are
|
||||
// marked only when ctx is still live afterwards, as a commit would require.
|
||||
type fakeStore struct {
|
||||
mu sync.Mutex
|
||||
pending []outbound.OutboxEvent
|
||||
marked []uuid.UUID
|
||||
passes int
|
||||
backlogReads int
|
||||
}
|
||||
|
||||
func newFakeStore(count int) *fakeStore {
|
||||
store := &fakeStore{}
|
||||
for version := range count {
|
||||
store.pending = append(store.pending, outbound.OutboxEvent{
|
||||
EventID: uuid.New(),
|
||||
EventType: "test.changed",
|
||||
SchemaVersion: 1,
|
||||
AggregateType: "test",
|
||||
AggregateID: uuid.New(),
|
||||
AggregateVersion: int64(version + 1),
|
||||
})
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
func (store *fakeStore) ClaimPending(ctx context.Context, limit int, publish outbound.PublishOutboxBatch) error {
|
||||
store.mu.Lock()
|
||||
store.passes++
|
||||
batch := slices.Clone(store.pending[:min(limit, len(store.pending))])
|
||||
store.mu.Unlock()
|
||||
if len(batch) == 0 {
|
||||
return nil
|
||||
}
|
||||
acknowledged := publish(ctx, batch)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
for _, eventID := range acknowledged {
|
||||
store.marked = append(store.marked, eventID)
|
||||
store.pending = slices.DeleteFunc(store.pending, func(event outbound.OutboxEvent) bool { return event.EventID == eventID })
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) Backlog(context.Context) (outbound.OutboxBacklog, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
store.backlogReads++
|
||||
return outbound.OutboxBacklog{Pending: int64(len(store.pending))}, nil
|
||||
}
|
||||
|
||||
func (store *fakeStore) reads() int {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return store.backlogReads
|
||||
}
|
||||
|
||||
func (store *fakeStore) state() (pending int, marked []uuid.UUID, passes int) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
return len(store.pending), slices.Clone(store.marked), store.passes
|
||||
}
|
||||
|
||||
type fakePublisher struct {
|
||||
prepare func(ctx context.Context) error
|
||||
publish func(ctx context.Context, events []outbound.OutboxEvent) []error
|
||||
}
|
||||
|
||||
func (publisher fakePublisher) Prepare(ctx context.Context) error {
|
||||
if publisher.prepare == nil {
|
||||
return nil
|
||||
}
|
||||
return publisher.prepare(ctx)
|
||||
}
|
||||
|
||||
func (publisher fakePublisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
return publisher.publish(ctx, events)
|
||||
}
|
||||
|
||||
func acknowledgeAll(_ context.Context, events []outbound.OutboxEvent) []error {
|
||||
return make([]error, len(events))
|
||||
}
|
||||
|
||||
type countingMetrics struct {
|
||||
mu sync.Mutex
|
||||
published, failed int
|
||||
backlogs []int64
|
||||
}
|
||||
|
||||
func (metrics *countingMetrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.backlogs = append(metrics.backlogs, backlog.Pending)
|
||||
}
|
||||
|
||||
func (metrics *countingMetrics) ObserveOutboxRelayPass(published, failed int) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
metrics.published += published
|
||||
metrics.failed += failed
|
||||
}
|
||||
|
||||
func (metrics *countingMetrics) totals() (published, failed int) {
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
return metrics.published, metrics.failed
|
||||
}
|
||||
|
||||
func newTestRelay(store outbound.OutboxRelayStore, publisher outbound.EventPublisher, metrics Metrics, shutdownTimeout time.Duration) *Relay {
|
||||
return New(store, publisher, metrics, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 2,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: testInterval, Max: 4 * testInterval},
|
||||
ShutdownTimeout: shutdownTimeout,
|
||||
BacklogInterval: testInterval,
|
||||
})
|
||||
}
|
||||
|
||||
// runRelay starts Run and returns a function that cancels it and waits for
|
||||
// it to return.
|
||||
func runRelay(t *testing.T, relay *Relay) (stop func() time.Duration) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
relay.Run(ctx)
|
||||
}()
|
||||
return func() time.Duration {
|
||||
started := time.Now()
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(testTimeout):
|
||||
t.Fatal("Run did not return after cancellation")
|
||||
}
|
||||
return time.Since(started)
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, condition func() bool, description string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(testTimeout)
|
||||
for !condition() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting for %s", description)
|
||||
}
|
||||
time.Sleep(testInterval)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPendingMarksOnlyAcknowledgedEvents(t *testing.T) {
|
||||
store := newFakeStore(2)
|
||||
relay := newTestRelay(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
|
||||
return []error{nil, errBrokerDown}
|
||||
}}, &countingMetrics{}, time.Second)
|
||||
|
||||
result, err := relay.PublishPending(t.Context())
|
||||
if !errors.Is(err, errBrokerDown) {
|
||||
t.Fatalf("PublishPending() error = %v, want the publish failure", err)
|
||||
}
|
||||
if result != (PassResult{Claimed: 2, Published: 1}) {
|
||||
t.Fatalf("PublishPending() result = %+v, want 2 claimed and 1 published", result)
|
||||
}
|
||||
pending, marked, _ := store.state()
|
||||
if pending != 1 || len(marked) != 1 {
|
||||
t.Fatalf("pending %d, marked %v; want the failed event pending and one marked", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPendingMarksNothingWhenResultsDoNotMatchTheBatch(t *testing.T) {
|
||||
store := newFakeStore(2)
|
||||
relay := newTestRelay(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
|
||||
return []error{nil}
|
||||
}}, &countingMetrics{}, time.Second)
|
||||
|
||||
result, err := relay.PublishPending(t.Context())
|
||||
if err == nil || result.Published != 0 {
|
||||
t.Fatalf("PublishPending() = %+v, %v; want an error and nothing published", result, err)
|
||||
}
|
||||
if pending, marked, _ := store.state(); pending != 2 || len(marked) != 0 {
|
||||
t.Fatalf("pending %d, marked %v; want every event pending", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRetriesPrepareAndFailedPassesUntilEventsArePublished(t *testing.T) {
|
||||
store := newFakeStore(5)
|
||||
var mu sync.Mutex
|
||||
prepareFailures, publishFailures := 2, 3
|
||||
publisher := fakePublisher{
|
||||
prepare: func(context.Context) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if prepareFailures > 0 {
|
||||
prepareFailures--
|
||||
return errBrokerDown
|
||||
}
|
||||
return nil
|
||||
},
|
||||
publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if publishFailures > 0 {
|
||||
publishFailures--
|
||||
results := make([]error, len(events))
|
||||
for index := range results {
|
||||
results[index] = errBrokerDown
|
||||
}
|
||||
return results
|
||||
}
|
||||
return acknowledgeAll(ctx, events)
|
||||
},
|
||||
}
|
||||
metrics := &countingMetrics{}
|
||||
stop := runRelay(t, newTestRelay(store, publisher, metrics, time.Second))
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 0
|
||||
}, "every event to be published")
|
||||
stop()
|
||||
|
||||
_, marked, _ := store.state()
|
||||
if len(marked) != 5 {
|
||||
t.Fatalf("marked %d events, want 5", len(marked))
|
||||
}
|
||||
if published, failed := metrics.totals(); published != 5 || failed != 6 {
|
||||
t.Fatalf("metrics published=%d failed=%d, want 5 and 6 (three failed passes of two)", published, failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunLetsThePassInProgressFinishAfterCancellation(t *testing.T) {
|
||||
store := newFakeStore(1)
|
||||
publishing, release := make(chan struct{}), make(chan struct{})
|
||||
publisher := fakePublisher{publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
close(publishing)
|
||||
<-release
|
||||
return acknowledgeAll(ctx, events)
|
||||
}}
|
||||
stop := runRelay(t, newTestRelay(store, publisher, &countingMetrics{}, testTimeout))
|
||||
<-publishing
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stopped)
|
||||
stop()
|
||||
}()
|
||||
// Run must still be waiting for the pass after cancellation.
|
||||
select {
|
||||
case <-stopped:
|
||||
t.Fatal("Run returned before the pass in progress finished")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
close(release)
|
||||
<-stopped
|
||||
if pending, marked, _ := store.state(); pending != 0 || len(marked) != 1 {
|
||||
t.Fatalf("pending %d, marked %v; want the acknowledged event marked", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunCancelsAPassThatOutlivesTheShutdownTimeout(t *testing.T) {
|
||||
const shutdownTimeout = 50 * time.Millisecond
|
||||
store := newFakeStore(1)
|
||||
publishing := make(chan struct{})
|
||||
var once sync.Once
|
||||
publisher := fakePublisher{publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
once.Do(func() { close(publishing) })
|
||||
// A hung broker: the publish ends only with its context.
|
||||
<-ctx.Done()
|
||||
results := make([]error, len(events))
|
||||
for index := range results {
|
||||
results[index] = ctx.Err()
|
||||
}
|
||||
return results
|
||||
}}
|
||||
stop := runRelay(t, newTestRelay(store, publisher, &countingMetrics{}, shutdownTimeout))
|
||||
<-publishing
|
||||
if elapsed := stop(); elapsed < shutdownTimeout {
|
||||
t.Fatalf("Run returned after %s, before the %s shutdown timeout", elapsed, shutdownTimeout)
|
||||
}
|
||||
if pending, marked, _ := store.state(); pending != 1 || len(marked) != 0 {
|
||||
t.Fatalf("pending %d, marked %v; want the unacknowledged event pending", pending, marked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStopsDuringBackoffWithoutAnotherPass(t *testing.T) {
|
||||
store := newFakeStore(1)
|
||||
relay := New(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
|
||||
return []error{errBrokerDown}
|
||||
}}, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 1,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: time.Hour,
|
||||
})
|
||||
stop := runRelay(t, relay)
|
||||
waitFor(t, func() bool {
|
||||
_, _, passes := store.state()
|
||||
return passes == 1
|
||||
}, "the first pass")
|
||||
if elapsed := stop(); elapsed > time.Second {
|
||||
t.Fatalf("Run took %s to stop during backoff", elapsed)
|
||||
}
|
||||
if _, _, passes := store.state(); passes != 1 {
|
||||
t.Fatalf("store saw %d passes, want 1", passes)
|
||||
}
|
||||
}
|
||||
|
||||
// hourBackoffRelay never retries a failed pass that published nothing within
|
||||
// a test, so a test that finishes proves the relay did not back off.
|
||||
func hourBackoffRelay(store outbound.OutboxRelayStore, publisher outbound.EventPublisher, backlogInterval time.Duration) *Relay {
|
||||
return New(store, publisher, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 2,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: backlogInterval,
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunDoesNotBackOffAfterAPassThatMadeProgress(t *testing.T) {
|
||||
store := newFakeStore(5)
|
||||
poison := store.pending[0].EventID
|
||||
publisher := fakePublisher{publish: func(_ context.Context, events []outbound.OutboxEvent) []error {
|
||||
results := make([]error, len(events))
|
||||
for index, event := range events {
|
||||
if event.EventID == poison {
|
||||
results[index] = errBrokerDown
|
||||
}
|
||||
}
|
||||
return results
|
||||
}}
|
||||
stop := runRelay(t, hourBackoffRelay(store, publisher, time.Hour))
|
||||
// The poison event leads every batch; the others drain only if a pass
|
||||
// that published something is followed at once by the next one.
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 1
|
||||
}, "every event except the poison event to be published")
|
||||
stop()
|
||||
if _, marked, _ := store.state(); slices.Contains(marked, poison) {
|
||||
t.Fatal("the failed event was marked as published")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPreparesAgainAfterAMissingDestination(t *testing.T) {
|
||||
store := newFakeStore(1)
|
||||
var mu sync.Mutex
|
||||
prepares, missing := 0, true
|
||||
publisher := fakePublisher{
|
||||
prepare: func(context.Context) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
prepares++
|
||||
return nil
|
||||
},
|
||||
publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if missing {
|
||||
missing = false
|
||||
return []error{fmt.Errorf("produce: %w", outbound.ErrEventDestinationMissing)}
|
||||
}
|
||||
return acknowledgeAll(ctx, events)
|
||||
},
|
||||
}
|
||||
relay := newTestRelay(store, publisher, &countingMetrics{}, time.Second)
|
||||
stop := runRelay(t, relay)
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 0
|
||||
}, "the event to be published after the topic was prepared again")
|
||||
stop()
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if prepares != 2 {
|
||||
t.Fatalf("Prepare ran %d times, want 2 (start and after the missing destination)", prepares)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRefreshesTheBacklogAtMostOncePerInterval(t *testing.T) {
|
||||
store := newFakeStore(6)
|
||||
metrics := &countingMetrics{}
|
||||
relay := New(store, fakePublisher{publish: acknowledgeAll}, metrics, slog.New(slog.DiscardHandler), Settings{
|
||||
BatchSize: 1,
|
||||
PollInterval: testInterval,
|
||||
Backoff: Backoff{Initial: testInterval, Max: testInterval},
|
||||
ShutdownTimeout: time.Second,
|
||||
BacklogInterval: time.Hour,
|
||||
})
|
||||
stop := runRelay(t, relay)
|
||||
waitFor(t, func() bool {
|
||||
pending, _, _ := store.state()
|
||||
return pending == 0
|
||||
}, "every event to be published")
|
||||
stop()
|
||||
_, _, passes := store.state()
|
||||
if reads := store.reads(); reads != 1 || passes < 6 {
|
||||
t.Fatalf("%d backlog reads over %d passes, want 1 read per interval", reads, passes)
|
||||
}
|
||||
metrics.mu.Lock()
|
||||
defer metrics.mu.Unlock()
|
||||
if len(metrics.backlogs) != 1 || metrics.backlogs[0] != 5 {
|
||||
t.Fatalf("backlog observations %v, want one with the 5 events left after the first pass", metrics.backlogs)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user