Files
lincodex/backend/integration_test/outbox_relay_test.go
T

769 lines
28 KiB
Go

//go:build integration
package integration_test
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"slices"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/kafka"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/outboxrelay"
"lincodex/backend/internal/worker/retry"
)
const (
relayTestTimeout = 5 * time.Minute
// relayProduceTimeout keeps outage passes short; it is the smallest
// value franz-go accepts plus a margin for a loaded test machine.
relayProduceTimeout = 2 * time.Second
// relayLongProduceTimeout outlasts the shutdown timeout many times, so a
// relay that stops in time proves the shutdown timeout canceled its pass.
relayLongProduceTimeout = 30 * time.Second
// relayShutdownMargin covers the rollback and scheduling after the
// shutdown timeout, far below relayLongProduceTimeout.
relayShutdownMargin = 5 * time.Second
// relayStatementTimeout and relayIdleTimeout are the server-side bounds
// of the shared store; the idle bound outlasts the longest publish.
relayStatementTimeout = 5 * time.Second
relayIdleTimeout = relayLongProduceTimeout + relayStatementTimeout
// shortIdleTimeout is the idle bound of the case that lets the server
// end a silent claim; shortIdleSilence outlasts it.
shortIdleTimeout = 300 * time.Millisecond
shortIdleSilence = 2 * time.Second
// idleInTransactionTimeoutCode is the SQLSTATE of a session that the
// server ended for idle_in_transaction_session_timeout.
idleInTransactionTimeoutCode = "25P03"
// relayBacklogInterval refreshes the backlog metrics often in tests.
relayBacklogInterval = 50 * time.Millisecond
relayTopicPartitions = 3
relayBatchSize = 5
relayPollInterval = 20 * time.Millisecond
relayBackoffInitial = 50 * time.Millisecond
relayBackoffMax = 500 * time.Millisecond
relayShutdownTimeout = time.Second
// relayRecoveryTimeout bounds reconnection after the broker resumes.
relayRecoveryTimeout = time.Minute
relayDrainTimeout = time.Minute
competingRelays = 2
// More aggregates than one batch holds, so a second relay finds
// unlocked aggregate heads while the first relay's pass is in progress.
competingAggregates = 12
competingVersions = 8
// competingPublishDelay stretches each pass, as a remote broker would,
// so the relays' passes overlap.
competingPublishDelay = 10 * time.Millisecond
// relayLockTimeout makes a claim fail instead of waiting if SKIP LOCKED
// ever waited for a row lock.
relayLockTimeout = 500 * time.Millisecond
)
// relayHarness owns the database side of relay tests: the pool, the
// business-transaction writer, and the relay store.
type relayHarness struct {
env *testEnvironment
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
store *postgresadapter.OutboxRelayStore
}
func TestOutboxRelay(t *testing.T) {
env := bootstrap(t, postgresService, kafkaService)
ctx, cancel := context.WithTimeout(t.Context(), relayTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
if _, err := pool.Exec(ctx, createTestAccountsTable); err != nil {
t.Fatalf("create test aggregate table: %v", err)
}
harness := &relayHarness{
env: env,
pool: pool,
transactor: postgresadapter.NewTransactor(pool),
store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts),
}
// Subtests share tables and run sequentially; each starts from empty
// tables and uses its own topic.
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool, outboxEventsTable, testAccountsTable)
}
t.Run("publishes a committed event as an envelope and marks it", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, relayTopicPartitions)
account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
event := newAccountEvent(t, account)
harness.save(ctx, t, account, event)
relay := harness.newRelay(harness.newPublisher(t, topic))
result, err := relay.PublishPending(ctx)
if err != nil || result != (outboxrelay.PassResult{Claimed: 1, Published: 1}) {
t.Fatalf("PublishPending() = %+v, %v; want one event published", result, err)
}
records := env.consumeKafkaRecords(ctx, t, topic, 1)
stored := readOutboxEvents(ctx, t, pool)
assertEnvelope(t, records[0], stored[0])
if stored[0].publishedAt == nil {
t.Fatal("published event is not marked")
}
result, err = relay.PublishPending(ctx)
if err != nil || result.Claimed != 0 {
t.Fatalf("second PublishPending() = %+v, %v; want nothing to claim", result, err)
}
})
t.Run("a Kafka outage keeps events pending without affecting business writes, and recovery publishes them", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, relayTopicPartitions)
relay := harness.newRelay(harness.newPublisher(t, topic))
before := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
harness.save(ctx, t, before, newAccountEvent(t, before))
resume := env.pauseKafka(ctx, t)
// A business transaction only writes the outbox, so it commits while
// the broker is unavailable.
during := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
harness.save(ctx, t, during, newAccountEvent(t, during))
result, err := relay.PublishPending(ctx)
if err == nil || result.Published != 0 || result.Claimed != 2 {
t.Fatalf("PublishPending() during the outage = %+v, %v; want two claimed, none published, and an error", result, err)
}
t.Logf("pass during the outage failed as expected: %v", err)
assertUnpublished(ctx, t, pool, 2)
assertAccount(ctx, t, pool, before)
assertAccount(ctx, t, pool, during)
resume()
published := harness.publishUntilDrained(ctx, t, relay)
if published != 2 {
t.Fatalf("published %d events after recovery, want 2", published)
}
assertUnpublished(ctx, t, pool, 0)
stored := readOutboxEvents(ctx, t, pool)
// The broker may also store a record from the request that was in
// flight when it froze; consumers deduplicate it by event_id.
received := consumeUntilEventIDs(ctx, t, env, topic, eventIDs(stored))
for _, event := range stored {
assertEnvelope(t, received[event.eventID][0], event)
}
})
t.Run("a relay that dies between publish and mark republishes the same event_id", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, relayTopicPartitions)
account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
event := newAccountEvent(t, account)
harness.save(ctx, t, account, event)
// The publisher really produces and then ends the pass context, as a
// killed process would, so the mark never commits.
passCtx, killPass := context.WithCancel(ctx)
defer killPass()
dying := harness.newRelay(crashAfterPublish{EventPublisher: harness.newPublisher(t, topic), crash: killPass})
result, err := dying.PublishPending(passCtx)
if !errors.Is(err, context.Canceled) || result.Published != 0 {
t.Fatalf("PublishPending() of the dying relay = %+v, %v; want context.Canceled and nothing marked", result, err)
}
assertUnpublished(ctx, t, pool, 1)
first := env.consumeKafkaRecords(ctx, t, topic, 1)
assertEnvelope(t, first[0], readOutboxEvents(ctx, t, pool)[0])
restarted := harness.newRelay(harness.newPublisher(t, topic))
result, err = restarted.PublishPending(ctx)
if err != nil || result != (outboxrelay.PassResult{Claimed: 1, Published: 1}) {
t.Fatalf("PublishPending() after restart = %+v, %v; want the event published", result, err)
}
assertUnpublished(ctx, t, pool, 0)
both := env.consumeKafkaRecords(ctx, t, topic, 2)
for _, record := range both {
if got := headerValue(record, "event_id"); got != event.EventID().String() {
t.Fatalf("record event_id = %s, want the original %s", got, event.EventID())
}
}
})
t.Run("a competing claim skips locked rows without waiting and never overtakes an aggregate", func(t *testing.T) {
reset(t)
first := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
firstNext := testAccount{id: first.id, version: 2, status: accountStatusArchived}
second := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
third := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
for _, account := range []testAccount{first, firstNext, second, third} {
harness.save(ctx, t, account, newAccountEvent(t, account))
}
competitor := postgresadapter.NewOutboxRelayStore(env.newPoolWithLockTimeout(ctx, t, relayLockTimeout), relayStoreTimeouts)
var held, competing []outbound.OutboxEvent
err := harness.store.ClaimPending(ctx, 2, func(ctx context.Context, events []outbound.OutboxEvent) []uuid.UUID {
held = events
// While this batch holds its row locks, another relay claims.
if err := competitor.ClaimPending(ctx, relayBatchSize, func(_ context.Context, events []outbound.OutboxEvent) []uuid.UUID {
competing = events
return ids(events)
}); err != nil {
t.Errorf("competing ClaimPending() error = %v", err)
}
return ids(events)
})
if err != nil {
t.Fatalf("ClaimPending() error = %v", err)
}
assertClaimed(t, "first relay", held, first, second)
// The first aggregate's version 2 waits for version 1, which the
// first relay holds; the third aggregate is free.
assertClaimed(t, "competing relay", competing, third)
var next []outbound.OutboxEvent
if err := harness.store.ClaimPending(ctx, relayBatchSize, func(_ context.Context, events []outbound.OutboxEvent) []uuid.UUID {
next = events
return ids(events)
}); err != nil {
t.Fatalf("next ClaimPending() error = %v", err)
}
assertClaimed(t, "next pass", next, firstNext)
assertUnpublished(ctx, t, pool, 0)
assertNoBusyConnections(t, pool)
})
t.Run("competing relays publish every event and keep each aggregate in version order", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, relayTopicPartitions)
runCtx, stopRelays := context.WithCancel(ctx)
defer stopRelays()
var relays sync.WaitGroup
counters := make([]*publishedCounter, competingRelays)
for index := range competingRelays {
counters[index] = &publishedCounter{}
publisher := slowPublisher{EventPublisher: harness.newPublisher(t, topic), delay: competingPublishDelay}
relay := harness.newRelayWithMetrics(publisher, counters[index])
relays.Go(func() { relay.Run(runCtx) })
}
// Writers append versions while the relays run, so claims race with
// commits as well as with each other.
var writers sync.WaitGroup
writeErrs := make([]error, competingAggregates)
for index := range competingAggregates {
writers.Go(func() {
id := uuid.New()
for version := int64(1); version <= competingVersions; version++ {
account := testAccount{id: id, version: version, status: fmt.Sprintf("v%d", version)}
event, err := newAccountEventE(account)
if err == nil {
err = harness.transactor.WithinTransaction(ctx, saveAccountWith(account, event))
}
if err != nil {
writeErrs[index] = err
return
}
}
})
}
writers.Wait()
for index, err := range writeErrs {
if err != nil {
t.Fatalf("writer %d error = %v", index, err)
}
}
waitForUnpublished(ctx, t, pool, 0)
stopRelays()
relays.Wait()
stored := readOutboxEvents(ctx, t, pool)
if want := competingAggregates * competingVersions; len(stored) != want {
t.Fatalf("outbox has %d events, want %d", len(stored), want)
}
received := consumeUntilEventIDs(ctx, t, env, topic, eventIDs(stored))
assertAggregateOrder(t, received)
for index, counter := range counters {
t.Logf("relay %d published %d events", index+1, counter.published.Load())
}
})
t.Run("shutdown during a batch leaves unacknowledged events unpublished", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, relayTopicPartitions)
account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
harness.save(ctx, t, account, newAccountEvent(t, account))
// The broker stays frozen and the produce timeout is far longer than
// the shutdown timeout, so only the shutdown timeout can end the pass
// in time; its transaction then rolls back.
resume := env.pauseKafka(ctx, t)
defer resume()
settings := harness.relayConfig(topic)
settings.RelayProduceTimeout = relayLongProduceTimeout
relay := harness.newRelay(harness.newPublisherWith(t, settings))
runCtx, stopRelay := context.WithCancel(ctx)
stopped := make(chan struct{})
go func() {
defer close(stopped)
relay.Run(runCtx)
}()
waitForLockedOutboxRow(ctx, t, pool)
stopRelay()
stopStarted := time.Now()
select {
case <-stopped:
case <-time.After(relayShutdownTimeout + relayShutdownMargin):
t.Fatalf("relay did not stop within the %s shutdown timeout plus %s", relayShutdownTimeout, relayShutdownMargin)
}
if elapsed := time.Since(stopStarted); elapsed < relayShutdownTimeout {
t.Fatalf("relay stopped after %s, before the %s shutdown timeout could cancel the pass", elapsed, relayShutdownTimeout)
}
assertUnpublished(ctx, t, pool, 1)
assertNoBusyConnections(t, pool)
})
t.Run("the server ends a claim whose client stays silent past the idle timeout", func(t *testing.T) {
reset(t)
account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
harness.save(ctx, t, account, newAccountEvent(t, account))
store := postgresadapter.NewOutboxRelayStore(pool, postgresadapter.OutboxRelayTimeouts{
Statement: relayStatementTimeout,
IdleInTransaction: shortIdleTimeout,
})
// The callback ignores its context, like a frozen process, and then
// reports the event as acknowledged.
err := store.ClaimPending(ctx, relayBatchSize, func(_ context.Context, events []outbound.OutboxEvent) []uuid.UUID {
time.Sleep(shortIdleSilence)
return ids(events)
})
var stateError interface{ SQLState() string }
if !errors.As(err, &stateError) || stateError.SQLState() != idleInTransactionTimeoutCode {
t.Fatalf("ClaimPending() error = %v, want SQLSTATE %s from the idle timeout", err, idleInTransactionTimeoutCode)
}
assertUnpublished(ctx, t, pool, 1)
assertNoBusyConnections(t, pool)
})
t.Run("the backlog reports pending events and the age of the earliest one", func(t *testing.T) {
reset(t)
if backlog, err := harness.store.Backlog(ctx); err != nil || backlog != (outbound.OutboxBacklog{}) {
t.Fatalf("Backlog() of an empty outbox = %+v, %v; want zero values", backlog, err)
}
for range 2 {
account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
harness.save(ctx, t, account, newAccountEvent(t, account))
}
backlog, err := harness.store.Backlog(ctx)
if err != nil || backlog.Pending != 2 || backlog.OldestAge <= 0 {
t.Fatalf("Backlog() = %+v, %v; want 2 pending events with a positive age", backlog, err)
}
})
t.Run("prepare creates the events topic once and accepts an existing topic", func(t *testing.T) {
topic := newKafkaTopicName()
cleanupCtx := context.WithoutCancel(ctx)
t.Cleanup(func() { env.deleteKafkaTopic(cleanupCtx, t, topic) })
settings := harness.relayConfig(topic)
settings.KafkaProvisionTopics = true
// The broker default replication factor and an explicit
// min.insync.replicas, as a production cluster would be configured.
settings.KafkaEventsTopicReplicationFactor = config.KafkaBrokerDefaultReplicationFactor
settings.KafkaEventsTopicMinInsyncReplicas = kafkaReplicationFactor
publisher, cleanup, err := kafka.NewPublisher(settings, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewPublisher() error = %v", err)
}
t.Cleanup(cleanup)
for attempt := range 2 {
if err := publisher.Prepare(ctx); err != nil {
t.Fatalf("Prepare() attempt %d error = %v", attempt+1, err)
}
}
topics, err := env.KafkaAdmin.ListTopics(ctx, topic)
if err != nil {
t.Fatalf("list topic: %v", err)
}
detail, ok := topics[topic]
if !ok || detail.Err != nil || len(detail.Partitions) != relayTopicPartitions || detail.Partitions.NumReplicas() != kafkaReplicationFactor {
t.Fatalf("topic %s: present %t, error %v, partitions %d, replicas %d; want %d partitions with the broker default replication",
topic, ok, detail.Err, len(detail.Partitions), detail.Partitions.NumReplicas(), relayTopicPartitions)
}
configs, err := env.KafkaAdmin.DescribeTopicConfigs(ctx, topic)
if err != nil {
t.Fatalf("describe topic configs: %v", err)
}
resource, err := configs.On(topic, nil)
if err != nil || resource.Err != nil {
t.Fatalf("topic %s configs: %v, %v", topic, err, resource.Err)
}
minInsync := ""
for _, entry := range resource.Configs {
// Only a topic-level value proves the relay set it; the broker
// default has the same number.
if entry.Key == "min.insync.replicas" && entry.Value != nil && entry.Source.String() == "DYNAMIC_TOPIC_CONFIG" {
minInsync = *entry.Value
}
}
if minInsync != fmt.Sprint(kafkaReplicationFactor) {
t.Fatalf("topic min.insync.replicas = %q, want a topic-level %d", minInsync, kafkaReplicationFactor)
}
})
}
// crashAfterPublish produces for real and then ends the pass, like a process
// killed between the broker acknowledgement and the mark.
type crashAfterPublish struct {
outbound.EventPublisher
crash context.CancelFunc
}
func (publisher crashAfterPublish) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
results := publisher.EventPublisher.Publish(ctx, events)
publisher.crash()
return results
}
// slowPublisher delays every publish while the pass holds its row locks.
type slowPublisher struct {
outbound.EventPublisher
delay time.Duration
}
func (publisher slowPublisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
select {
case <-time.After(publisher.delay):
case <-ctx.Done():
}
return publisher.EventPublisher.Publish(ctx, events)
}
func (harness *relayHarness) relayConfig(topic string) config.Config {
settings := harness.env.Config
settings.KafkaEventsTopic = topic
settings.KafkaEventsTopicPartitions = relayTopicPartitions
settings.KafkaEventsTopicReplicationFactor = kafkaReplicationFactor
// Test topics are created by the test helpers.
settings.KafkaProvisionTopics = false
settings.RelayProduceTimeout = relayProduceTimeout
return settings
}
func (harness *relayHarness) newPublisher(t *testing.T, topic string) *kafka.Publisher {
t.Helper()
return harness.newPublisherWith(t, harness.relayConfig(topic))
}
func (harness *relayHarness) newPublisherWith(t *testing.T, settings config.Config) *kafka.Publisher {
t.Helper()
publisher, cleanup, err := kafka.NewPublisher(settings, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewPublisher() error = %v", err)
}
t.Cleanup(cleanup)
return publisher
}
// publishedCounter records how many events one relay published.
type publishedCounter struct {
published atomic.Int64
}
func (counter *publishedCounter) ObserveOutboxRelayPass(published, _ int) {
counter.published.Add(int64(published))
}
func (*publishedCounter) ObserveOutboxBacklog(outbound.OutboxBacklog) {}
var relayStoreTimeouts = postgresadapter.OutboxRelayTimeouts{
Statement: relayStatementTimeout,
IdleInTransaction: relayIdleTimeout,
}
func (harness *relayHarness) newRelay(publisher outbound.EventPublisher) *outboxrelay.Relay {
return harness.newRelayWithMetrics(publisher, &publishedCounter{})
}
func (harness *relayHarness) newRelayWithMetrics(publisher outbound.EventPublisher, metrics outboxrelay.Metrics) *outboxrelay.Relay {
return outboxrelay.New(harness.store, publisher, metrics, slog.New(slog.DiscardHandler), outboxrelay.Settings{
BatchSize: relayBatchSize,
PollInterval: relayPollInterval,
Backoff: retry.Backoff{Initial: relayBackoffInitial, Max: relayBackoffMax},
ShutdownTimeout: relayShutdownTimeout,
BacklogInterval: relayBacklogInterval,
})
}
func (harness *relayHarness) save(ctx context.Context, t *testing.T, account testAccount, event domain.DomainEvent) {
t.Helper()
if err := harness.transactor.WithinTransaction(ctx, saveAccountWith(account, event)); err != nil {
t.Fatalf("save account %s v%d: %v", account.id, account.version, err)
}
}
// publishUntilDrained runs passes until one claims nothing, tolerating the
// failures of a client that is still reconnecting, and returns the number of
// events published.
func (harness *relayHarness) publishUntilDrained(ctx context.Context, t *testing.T, relay *outboxrelay.Relay) int {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, relayRecoveryTimeout)
defer cancel()
published := 0
var lastErr error
for {
result, err := relay.PublishPending(ctx)
published += result.Published
if err == nil && result.Claimed == 0 {
return published
}
if err != nil {
lastErr = err
}
select {
case <-ctx.Done():
t.Fatalf("events still pending after recovery: published %d, last error %v", published, lastErr)
case <-time.After(relayBackoffInitial):
}
}
}
func ids(events []outbound.OutboxEvent) []uuid.UUID {
result := make([]uuid.UUID, 0, len(events))
for _, event := range events {
result = append(result, event.EventID)
}
return result
}
func eventIDs(events []storedEvent) []uuid.UUID {
result := make([]uuid.UUID, 0, len(events))
for _, event := range events {
result = append(result, event.eventID)
}
return result
}
func assertClaimed(t *testing.T, name string, claimed []outbound.OutboxEvent, want ...testAccount) {
t.Helper()
if len(claimed) != len(want) {
t.Fatalf("%s claimed %d events, want %d", name, len(claimed), len(want))
}
for index, account := range want {
if claimed[index].AggregateID != account.id || claimed[index].AggregateVersion != account.version {
t.Fatalf("%s claim %d = %s v%d, want %s v%d", name, index,
claimed[index].AggregateID, claimed[index].AggregateVersion, account.id, account.version)
}
}
}
func countUnpublished(ctx context.Context, t *testing.T, pool *pgxpool.Pool) int {
t.Helper()
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE published_at IS NULL`).Scan(&count); err != nil {
t.Fatalf("count unpublished events: %v", err)
}
return count
}
func assertUnpublished(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want int) {
t.Helper()
if got := countUnpublished(ctx, t, pool); got != want {
t.Fatalf("outbox has %d unpublished events, want %d", got, want)
}
}
func waitForUnpublished(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want int) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, relayDrainTimeout)
defer cancel()
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
for {
got := countUnpublished(ctx, t, pool)
if got == want {
return
}
select {
case <-ctx.Done():
t.Fatalf("outbox still has %d unpublished events, want %d", got, want)
case <-ticker.C:
}
}
}
// waitForLockedOutboxRow waits until a relay pass holds the row lock of an
// outbox event, which proves the pass is in progress.
func waitForLockedOutboxRow(ctx context.Context, t *testing.T, pool *pgxpool.Pool) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, lockWaitTimeout)
defer cancel()
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
for {
var unlocked int
err := pool.QueryRow(ctx, `
SELECT count(*) FROM (
SELECT 1 FROM outbox_events WHERE published_at IS NULL
FOR UPDATE SKIP LOCKED
) AS free`).Scan(&unlocked)
if err == nil && unlocked == 0 {
return
}
select {
case <-ctx.Done():
t.Fatalf("no relay pass locked the outbox row: %v", err)
case <-ticker.C:
}
}
}
// consumeUntilEventIDs reads the topic from the start until every wanted
// event ID has arrived and returns the records grouped by event ID in
// consumption order. Duplicates are kept.
func consumeUntilEventIDs(ctx context.Context, t *testing.T, env *testEnvironment, topic string, want []uuid.UUID) map[uuid.UUID][]*kgo.Record {
t.Helper()
consumer := env.newKafkaClient(t,
kgo.ConsumeTopics(topic),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
)
ctx, cancel := context.WithTimeout(ctx, relayRecoveryTimeout)
defer cancel()
received := make(map[uuid.UUID][]*kgo.Record, len(want))
missing := func() int {
count := 0
for _, eventID := range want {
if len(received[eventID]) == 0 {
count++
}
}
return count
}
for missing() > 0 {
fetches := consumer.PollFetches(ctx)
if err := ctx.Err(); err != nil {
t.Fatalf("consume topic %s: %d of %d events missing: %v", topic, missing(), len(want), err)
}
if err := fetches.Err(); err != nil {
t.Fatalf("consume topic %s: %v", topic, err)
}
for _, record := range fetches.Records() {
eventID, err := uuid.Parse(headerValue(record, "event_id"))
if err != nil {
t.Fatalf("record without a valid event_id header: %v", err)
}
received[eventID] = append(received[eventID], record)
}
}
return received
}
// assertAggregateOrder checks that every aggregate's events share one
// partition and that, ignoring duplicates, their first appearances follow
// aggregate_version without gaps.
func assertAggregateOrder(t *testing.T, received map[uuid.UUID][]*kgo.Record) {
t.Helper()
type position struct {
partition int32
offset int64
}
type delivery struct {
version int64
first position
}
byAggregate := make(map[string][]delivery)
partitions := make(map[string]int32)
duplicates := 0
for _, records := range received {
duplicates += len(records) - 1
envelope := decodeEnvelope(t, records[0])
key := string(records[0].Key)
for _, record := range records {
if partition, ok := partitions[key]; ok && partition != record.Partition {
t.Fatalf("aggregate %s has records in partitions %d and %d", key, partition, record.Partition)
}
partitions[key] = record.Partition
}
byAggregate[key] = append(byAggregate[key], delivery{
version: envelope.AggregateVersion,
first: position{partition: records[0].Partition, offset: records[0].Offset},
})
}
if len(byAggregate) != competingAggregates {
t.Fatalf("received %d aggregates, want %d", len(byAggregate), competingAggregates)
}
for key, deliveries := range byAggregate {
slices.SortFunc(deliveries, func(a, b delivery) int { return cmp.Compare(a.first.offset, b.first.offset) })
for index, delivery := range deliveries {
if want := int64(index + 1); delivery.version != want {
t.Fatalf("aggregate %s: delivery %d has version %d, want %d", key, index, delivery.version, want)
}
}
}
t.Logf("received %d events with %d duplicate deliveries", len(received), duplicates)
}
type receivedEnvelope struct {
EnvelopeVersion int `json:"envelope_version"`
EventID uuid.UUID `json:"event_id"`
EventType string `json:"event_type"`
SchemaVersion int32 `json:"schema_version"`
AggregateType string `json:"aggregate_type"`
AggregateID uuid.UUID `json:"aggregate_id"`
AggregateVersion int64 `json:"aggregate_version"`
OccurredAt time.Time `json:"occurred_at"`
Payload json.RawMessage `json:"payload"`
}
func decodeEnvelope(t *testing.T, record *kgo.Record) receivedEnvelope {
t.Helper()
var envelope receivedEnvelope
if err := json.Unmarshal(record.Value, &envelope); err != nil {
t.Fatalf("decode envelope: %v", err)
}
return envelope
}
func headerValue(record *kgo.Record, key string) string {
for _, header := range record.Headers {
if header.Key == key {
return string(header.Value)
}
}
return ""
}
// assertEnvelope checks the record against the stored outbox row.
func assertEnvelope(t *testing.T, record *kgo.Record, stored storedEvent) {
t.Helper()
envelope := decodeEnvelope(t, record)
if envelope.EnvelopeVersion != kafka.EnvelopeVersion || envelope.EventID != stored.eventID ||
envelope.EventType != stored.eventType || envelope.SchemaVersion != stored.schemaVersion ||
envelope.AggregateType != stored.aggregateType || envelope.AggregateID != stored.aggregateID ||
envelope.AggregateVersion != stored.aggregateVersion || envelope.OccurredAt.IsZero() {
t.Fatalf("envelope %+v does not match stored event %s", envelope, stored.eventID)
}
assertJSONEqual(t, envelope.Payload, stored.payload)
if want := stored.aggregateType + ":" + stored.aggregateID.String(); string(record.Key) != want {
t.Fatalf("record key = %q, want %q", record.Key, want)
}
for key, want := range map[string]string{
"event_id": stored.eventID.String(),
"event_type": stored.eventType,
"schema_version": fmt.Sprint(stored.schemaVersion),
} {
if got := headerValue(record, key); got != want {
t.Fatalf("header %s = %q, want %q", key, got, want)
}
}
}