Files
lincodex/backend/internal/worker/outboxrelay/relay_test.go
T

433 lines
13 KiB
Go

package outboxrelay
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/retry"
)
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: retry.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: retry.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: retry.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: retry.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)
}
}