Files

1208 lines
46 KiB
Go

//go:build integration
package integration_test
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log/slog"
"maps"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/internal/adapter/secondary/kafka"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/eventconsumer"
"lincodex/backend/internal/worker/retry"
)
const (
consumerTestTimeout = 5 * time.Minute
// consumerWaitTimeout bounds every wait for a consumer to reach a state;
// it covers the group join and the first fetch on a loaded machine.
consumerWaitTimeout = time.Minute
// consumerStopTimeout bounds Run's return after cancellation: the grace
// plus one commit and margin.
consumerStopTimeout = 15 * time.Second
consumerName = "integration_effects"
consumerEventType = "test.effect_requested"
consumerAggregate = "test_effect"
consumerMaxAttempts = 3
consumerShortBackoff = 10 * time.Millisecond
// consumerPoisonBackoff makes every retry wait between 100ms and 200ms,
// long enough to tell backoff from a hot loop.
consumerPoisonBackoff = 200 * time.Millisecond
consumerPoisonMinimumGap = consumerPoisonBackoff / 2
// consumerPoisonBudget bounds the whole retry sequence of one poison
// event: the attempts are fast, so it is the backoff plus a large margin.
consumerPoisonBudget = 5 * time.Second
// consumerHandlerTime outlasts lockWaitTimeout, so a race test on a slow
// machine fails on the lock wait it asserts, not on an attempt timeout.
consumerHandlerTime = 2 * lockWaitTimeout
consumerCommitTimeout = 5 * time.Second
consumerGrace = 2 * time.Second
// consumerShortGrace lets a stuck handler be canceled quickly.
consumerShortGrace = 300 * time.Millisecond
// consumerQuietPeriod is how long a test watches that a finished consumer
// does not touch a record again.
consumerQuietPeriod = 500 * time.Millisecond
effectsTable = "effects"
effectsSchema = "consumer_test"
racingApplication = "consumer_race_second"
)
var (
effectsIdentifier = pgx.Identifier{effectsSchema, effectsTable}
createEffectsTable = fmt.Sprintf(`
CREATE SCHEMA %[1]s;
-- No unique key: a second effect for an event must stay visible.
CREATE TABLE %[2]s (
event_id uuid NOT NULL,
consumer_name text NOT NULL
)`, pgx.Identifier{effectsSchema}.Sanitize(), effectsIdentifier.Sanitize())
errEffectFailed = errors.New("effect failed")
)
// effectHandler is the test-only consumer: it writes one row per applied
// event into a table that exists only in this test, then runs hook inside
// the same transaction.
type effectHandler struct {
hook func(ctx context.Context, tx pgx.Tx, event outbound.ConsumedEvent) error
mu sync.Mutex
calls map[uuid.UUID][]time.Time
}
func newEffectHandler(hook func(context.Context, pgx.Tx, outbound.ConsumedEvent) error) *effectHandler {
return &effectHandler{hook: hook, calls: make(map[uuid.UUID][]time.Time)}
}
func (*effectHandler) ConsumerName() string { return consumerName }
func (*effectHandler) Handles(eventType string) bool { return eventType == consumerEventType }
func (handler *effectHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
handler.mu.Lock()
handler.calls[event.EventID] = append(handler.calls[event.EventID], time.Now())
handler.mu.Unlock()
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
if !ok {
return errors.New("unit of work is not a PostgreSQL transaction")
}
if _, err := tx.Exec(ctx, "INSERT INTO "+effectsIdentifier.Sanitize()+" (event_id, consumer_name) VALUES ($1, $2)", event.EventID, consumerName); err != nil {
return err
}
if handler.hook == nil {
return nil
}
return handler.hook(ctx, tx, event)
}
func (handler *effectHandler) callTimes(eventID uuid.UUID) []time.Time {
handler.mu.Lock()
defer handler.mu.Unlock()
return append([]time.Time(nil), handler.calls[eventID]...)
}
func (handler *effectHandler) totalCalls() int {
handler.mu.Lock()
defer handler.mu.Unlock()
total := 0
for _, calls := range handler.calls {
total += len(calls)
}
return total
}
// consumerHarness owns the database side of consumer tests.
type consumerHarness struct {
env *testEnvironment
pool *pgxpool.Pool
store *postgresadapter.EventConsumerStore
}
func TestEventConsumer(t *testing.T) {
env := bootstrap(t, postgresService, kafkaService)
ctx, cancel := context.WithTimeout(t.Context(), consumerTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
for _, statement := range []string{createEffectsTable, createTestAccountsTable} {
if _, err := pool.Exec(ctx, statement); err != nil {
t.Fatalf("create test-only tables: %v", err)
}
}
harness := &consumerHarness{
env: env,
pool: pool,
store: postgresadapter.NewEventConsumerStore(pool, consumerHandlerTime),
}
// Subtests share tables and run sequentially; each starts from empty
// tables and uses its own topic and consumer group.
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool,
effectsIdentifier,
pgx.Identifier{"consumer_processed_events"},
pgx.Identifier{"consumer_dead_letters"},
outboxEventsTable,
testAccountsTable,
)
}
t.Run("an event delivered three times on two partitions is applied once", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 2)
repeated, other := newConsumerEnvelope(), newConsumerEnvelope()
producer := env.newKafkaClient(t, kgo.RecordPartitioner(kgo.ManualPartitioner()))
produceKafkaRecords(ctx, t, producer,
envelopeRecord(t, topic, 0, repeated),
envelopeRecord(t, topic, 1, repeated),
envelopeRecord(t, topic, 0, repeated),
envelopeRecord(t, topic, 1, other),
)
handler := newEffectHandler(nil)
metrics := prometheus.New()
group := newConsumerGroup()
harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2, 1: 2})
harness.assertEffects(ctx, t, repeated.EventID, 1)
harness.assertEffects(ctx, t, other.EventID, 1)
harness.assertMarkers(ctx, t, 2)
assertConsumerMetric(t, metrics, "records", "applied", 2)
assertConsumerMetric(t, metrics, "records", "duplicate", 2)
})
t.Run("two deliveries of one event racing on the marker apply it once", func(t *testing.T) {
reset(t)
record := consumedRecord(newConsumerEnvelope())
inEffect := make(chan struct{})
releaseFirst := make(chan struct{})
first := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error {
close(inEffect)
return awaitOrCancel(ctx, releaseFirst, nil)
})
second := newEffectHandler(nil)
firstSource, secondSource := newStaticSource(record), newStaticSource(record)
firstMetrics, secondMetrics := prometheus.New(), prometheus.New()
runWithSource(ctx, t, firstSource, first, harness.store, firstMetrics, consumerTestSettings(consumerGrace))
awaitSignal(ctx, t, inEffect, "the first delivery to hold its marker")
// The first transaction holds the uncommitted marker. The second
// delivery's marker insert must wait for it instead of running the
// effect in parallel.
racingPool := env.newPoolWithApplicationName(ctx, t, racingApplication)
runWithSource(ctx, t, secondSource, second, postgresadapter.NewEventConsumerStore(racingPool, consumerHandlerTime), secondMetrics, consumerTestSettings(consumerGrace))
if waitEvent, waiting := waitForLockWait(ctx, pool, racingApplication); !waiting {
t.Fatalf("the second delivery did not wait for the first marker; last wait event %q", waitEvent)
}
close(releaseFirst)
firstSource.waitForCommit(ctx, t)
secondSource.waitForCommit(ctx, t)
harness.assertEffects(ctx, t, record.EventID, 1)
if calls := len(second.callTimes(record.EventID)); calls != 0 {
t.Fatalf("the second delivery ran the handler %d times after the first committed", calls)
}
assertConsumerMetric(t, firstMetrics, "records", "applied", 1)
assertConsumerMetric(t, secondMetrics, "records", "duplicate", 1)
})
t.Run("when the first of two racing deliveries rolls back the second applies the event once", func(t *testing.T) {
reset(t)
record := consumedRecord(newConsumerEnvelope())
inEffect := make(chan struct{})
failFirst := make(chan struct{})
var firstCalls atomic.Int64
first := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error {
if firstCalls.Add(1) == 1 {
close(inEffect)
return awaitOrCancel(ctx, failFirst, errEffectFailed)
}
return nil
})
second := newEffectHandler(nil)
firstSource, secondSource := newStaticSource(record), newStaticSource(record)
firstMetrics, secondMetrics := prometheus.New(), prometheus.New()
// The first delivery retries only after the second one committed,
// with a margin of 100ms or more over a commit of one row.
firstSettings := consumerTestSettings(consumerGrace)
firstSettings.Backoff = retry.Backoff{Initial: consumerPoisonBackoff, Max: consumerPoisonBackoff}
runWithSource(ctx, t, firstSource, first, harness.store, firstMetrics, firstSettings)
awaitSignal(ctx, t, inEffect, "the first delivery to hold its marker")
racingPool := env.newPoolWithApplicationName(ctx, t, racingApplication)
runWithSource(ctx, t, secondSource, second, postgresadapter.NewEventConsumerStore(racingPool, consumerHandlerTime), secondMetrics, consumerTestSettings(consumerGrace))
if waitEvent, waiting := waitForLockWait(ctx, pool, racingApplication); !waiting {
t.Fatalf("the second delivery did not wait for the first marker; last wait event %q", waitEvent)
}
close(failFirst)
firstSource.waitForCommit(ctx, t)
secondSource.waitForCommit(ctx, t)
harness.assertEffects(ctx, t, record.EventID, 1)
// The second delivery applied the event after the rollback; the
// first one's retry then found the marker.
assertConsumerMetric(t, secondMetrics, "records", "applied", 1)
assertConsumerMetric(t, firstMetrics, "records", "duplicate", 1)
assertConsumerMetric(t, firstMetrics, "failures", "handler", 1)
})
t.Run("a consumer stopped before its commit leaves the record to its successor, which applies it once", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 1)
event := newConsumerEnvelope()
produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event))
group := newConsumerGroup()
effectWritten := make(chan struct{})
stuck := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error {
close(effectWritten)
// The effect row is written; the process now "dies" before the
// commit: the handler outlives the shutdown grace.
<-ctx.Done()
return ctx.Err()
})
stop := harness.startConsumer(ctx, t, topic, group, stuck, prometheus.New(), consumerShortGrace)
awaitSignal(ctx, t, effectWritten, "the first consumer to reach the handler")
stop()
harness.assertEffects(ctx, t, event.EventID, 0)
harness.assertMarkers(ctx, t, 0)
if offsets := env.committedOffsets(ctx, t, group, topic); len(offsets) != 0 {
t.Fatalf("the stopped consumer committed %v for unfinished work", offsets)
}
successor := newEffectHandler(nil)
metrics := prometheus.New()
harness.startConsumer(ctx, t, topic, group, successor, metrics, consumerGrace)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1})
harness.assertEffects(ctx, t, event.EventID, 1)
assertConsumerMetric(t, metrics, "records", "applied", 1)
})
t.Run("a record whose effect committed before a crash is a duplicate on redelivery", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 1)
event := newConsumerEnvelope()
// The earlier instance committed the effect and the marker, then
// crashed before it committed the offset.
applied, err := harness.store.ApplyOnce(ctx, consumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error {
return newEffectHandler(nil).Handle(ctx, unit, consumedRecord(event).Event)
})
if err != nil || !applied {
t.Fatalf("ApplyOnce() = %t, %v; want the first application", applied, err)
}
produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event))
handler := newEffectHandler(nil)
metrics := prometheus.New()
group := newConsumerGroup()
harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1})
harness.assertEffects(ctx, t, event.EventID, 1)
if calls := handler.totalCalls(); calls != 0 {
t.Fatalf("handler ran %d times for a redelivered event", calls)
}
assertConsumerMetric(t, metrics, "records", "duplicate", 1)
})
t.Run("an invalid record is dead-lettered once and later records on its partition are applied", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 1)
headerID := uuid.New()
invalidValue := []byte(`{"envelope_version":1,"payload":"secret-value"`)
valid := newConsumerEnvelope()
produceKafkaRecords(ctx, t, env.newKafkaClient(t),
&kgo.Record{Topic: topic, Value: invalidValue, Headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte(headerID.String())}}},
envelopeRecord(t, topic, -1, valid),
)
handler := newEffectHandler(nil)
metrics := prometheus.New()
group := newConsumerGroup()
harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2})
letters := harness.readDeadLetters(ctx, t)
if len(letters) != 1 {
t.Fatalf("dead letters = %d, want 1", len(letters))
}
assertDeadLetter(t, letters[0], deadLetterRow{
topic: topic, partition: 0, offset: 0, eventID: &headerID,
errorClass: string(outbound.DeadLetterInvalidRecord), attempts: 0,
valueSize: len(invalidValue), valueSHA256: sha256.Sum256(invalidValue),
})
if strings.Contains(letters[0].reason, "secret") {
t.Fatalf("dead letter reason quotes the value: %q", letters[0].reason)
}
harness.assertEffects(ctx, t, valid.EventID, 1)
if calls := handler.totalCalls(); calls != 1 {
t.Fatalf("handler ran %d times, want only for the valid record", calls)
}
assertConsumerMetric(t, metrics, "records", "dead_lettered", 1)
assertConsumerMetric(t, metrics, "records", "applied", 1)
// The dead letter is final: the consumer does not come back to it.
time.Sleep(consumerQuietPeriod)
if again := harness.readDeadLetters(ctx, t); len(again) != 1 {
t.Fatalf("dead letters = %d after the quiet period, want 1", len(again))
}
})
t.Run("a handler that keeps failing is retried with backoff a bounded number of times, then dead-lettered", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 1)
poison, next := newConsumerEnvelope(), newConsumerEnvelope()
produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, poison), envelopeRecord(t, topic, -1, next))
handler := newEffectHandler(func(_ context.Context, _ pgx.Tx, event outbound.ConsumedEvent) error {
if event.EventID == poison.EventID {
// The effect row was written; the failure must roll it back.
return errEffectFailed
}
return nil
})
metrics := prometheus.New()
group := newConsumerGroup()
settings := consumerTestSettings(consumerGrace)
settings.Backoff = retry.Backoff{Initial: consumerPoisonBackoff, Max: consumerPoisonBackoff}
harness.startConsumerWith(ctx, t, topic, group, handler, metrics, settings)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2})
calls := handler.callTimes(poison.EventID)
if len(calls) != consumerMaxAttempts {
t.Fatalf("poison event attempts = %d, want %d", len(calls), consumerMaxAttempts)
}
for index := 1; index < len(calls); index++ {
if gap := calls[index].Sub(calls[index-1]); gap < consumerPoisonMinimumGap {
t.Fatalf("attempt %d followed the previous one after %s, want at least %s", index+1, gap, consumerPoisonMinimumGap)
}
}
if spent := calls[len(calls)-1].Sub(calls[0]); spent > consumerPoisonBudget {
t.Fatalf("retries took %s, want at most %s", spent, consumerPoisonBudget)
}
letters := harness.readDeadLetters(ctx, t)
if len(letters) != 1 {
t.Fatalf("dead letters = %d, want 1", len(letters))
}
value := envelopeValue(t, poison)
eventType := consumerEventType
assertDeadLetter(t, letters[0], deadLetterRow{
topic: topic, partition: 0, offset: 0, eventID: &poison.EventID, eventType: &eventType,
errorClass: string(outbound.DeadLetterRetriesExhausted), attempts: consumerMaxAttempts,
valueSize: len(value), valueSHA256: sha256.Sum256(value),
})
if !strings.Contains(letters[0].reason, errEffectFailed.Error()) {
t.Fatalf("dead letter reason = %q, want the handler error", letters[0].reason)
}
harness.assertEffects(ctx, t, poison.EventID, 0)
harness.assertEffects(ctx, t, next.EventID, 1)
assertConsumerMetric(t, metrics, "failures", "handler", consumerMaxAttempts)
assertConsumerMetric(t, metrics, "records", "dead_lettered", 1)
// No hot loop: after the dead letter the handler is not called again.
time.Sleep(consumerQuietPeriod)
if again := len(handler.callTimes(poison.EventID)); again != consumerMaxAttempts {
t.Fatalf("poison event attempts grew to %d after the dead letter", again)
}
})
t.Run("a connection killed inside the handler rolls back on the server, and a new member applies the event once", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 1)
event := newConsumerEnvelope()
produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event))
group := newConsumerGroup()
killed := make(chan struct{})
var backendPID atomic.Int32
crashing := newEffectHandler(func(ctx context.Context, tx pgx.Tx, _ outbound.ConsumedEvent) error {
// The effect row and the marker are written but not committed.
// Ending the backend is what a crashed process or a dropped
// connection leaves behind: only the server can roll back.
var pid int32
if err := tx.QueryRow(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {
return err
}
backendPID.Store(pid)
var terminated bool
if err := pool.QueryRow(ctx, "SELECT pg_terminate_backend($1)", pid).Scan(&terminated); err != nil || !terminated {
return fmt.Errorf("terminate backend %d: %t, %w", pid, terminated, err)
}
close(killed)
<-ctx.Done()
return ctx.Err()
})
stop := harness.startConsumer(ctx, t, topic, group, crashing, prometheus.New(), consumerShortGrace)
awaitSignal(ctx, t, killed, "the handler to end its own backend")
stop()
waitFor(ctx, t, "the terminated backend to disappear", func() bool {
var alive bool
err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = $1)", backendPID.Load()).Scan(&alive)
return err == nil && !alive
})
harness.assertEffects(ctx, t, event.EventID, 0)
harness.assertMarkers(ctx, t, 0)
if offsets := env.committedOffsets(ctx, t, group, topic); len(offsets) != 0 {
t.Fatalf("the crashed member committed %v", offsets)
}
successor := newEffectHandler(nil)
metrics := prometheus.New()
harness.startConsumer(ctx, t, topic, group, successor, metrics, consumerGrace)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1})
harness.assertEffects(ctx, t, event.EventID, 1)
assertConsumerMetric(t, metrics, "records", "applied", 1)
})
t.Run("a handler that ignores a failed statement ends in a dead letter instead of retrying forever", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, 1)
event := newConsumerEnvelope()
produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event))
swallowing := newEffectHandler(func(ctx context.Context, tx pgx.Tx, _ outbound.ConsumedEvent) error {
// The failed statement aborts the transaction; the handler
// hides the error, so PostgreSQL refuses the commit.
_, _ = tx.Exec(ctx, "SELECT 1 / 0")
return nil
})
metrics := prometheus.New()
group := newConsumerGroup()
harness.startConsumer(ctx, t, topic, group, swallowing, metrics, consumerGrace)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1})
letters := harness.readDeadLetters(ctx, t)
if len(letters) != 1 || letters[0].errorClass != string(outbound.DeadLetterRetriesExhausted) || letters[0].attempts != consumerMaxAttempts {
t.Fatalf("dead letters = %+v, want one retries_exhausted after %d attempts", letters, consumerMaxAttempts)
}
if calls := len(swallowing.callTimes(event.EventID)); calls != consumerMaxAttempts {
t.Fatalf("handler ran %d times, want %d", calls, consumerMaxAttempts)
}
harness.assertEffects(ctx, t, event.EventID, 0)
harness.assertMarkers(ctx, t, 0)
assertConsumerMetric(t, metrics, "failures", "handler", consumerMaxAttempts)
assertConsumerMetric(t, metrics, "failures", "store", 0)
})
t.Run("a repeated dead letter updates its row, and another value at the same position gets its own", func(t *testing.T) {
reset(t)
letter := outbound.DeadLetter{
Consumer: consumerName, Topic: "integration-dead-letters", Partition: 1, Offset: 7,
EventID: uuid.New(), EventType: consumerEventType, ErrorClass: outbound.DeadLetterHandlerRejected,
Reason: "first failure", Attempts: 1, ValueSize: 3, ValueSHA256: sha256.Sum256([]byte("one")),
}
if err := harness.store.RecordDeadLetter(ctx, letter); err != nil {
t.Fatalf("RecordDeadLetter() error = %v", err)
}
// After a rewind the same record fails again, differently.
again := letter
again.ErrorClass, again.Reason, again.Attempts = outbound.DeadLetterRetriesExhausted, "second failure", consumerMaxAttempts
if err := harness.store.RecordDeadLetter(ctx, again); err != nil {
t.Fatalf("RecordDeadLetter() again error = %v", err)
}
// A recreated topic reuses the position for another record.
other := letter
other.EventID, other.ValueSHA256 = uuid.New(), sha256.Sum256([]byte("two"))
if err := harness.store.RecordDeadLetter(ctx, other); err != nil {
t.Fatalf("RecordDeadLetter() other error = %v", err)
}
letters := harness.readDeadLetters(ctx, t)
if len(letters) != 2 {
t.Fatalf("dead letters = %d, want 2", len(letters))
}
if letters[0].errorClass != string(outbound.DeadLetterRetriesExhausted) || letters[0].reason != "second failure" ||
letters[0].attempts != consumerMaxAttempts || letters[0].valueSHA256 != letter.ValueSHA256 {
t.Fatalf("repeated dead letter = %+v, want the second outcome", letters[0])
}
if letters[1].valueSHA256 != other.ValueSHA256 || *letters[1].eventID != other.EventID {
t.Fatalf("dead letter of the other value = %+v", letters[1])
}
})
t.Run("a member joining while another holds a record takes over without a lost or repeated effect", func(t *testing.T) {
reset(t)
harness.runRebalanceHandover(ctx, t)
})
t.Run("an event appended to the outbox reaches the consumer through the relay", func(t *testing.T) {
reset(t)
topic := env.createKafkaTopic(ctx, t, relayTopicPartitions)
relayHarness := &relayHarness{
env: env,
pool: pool,
transactor: postgresadapter.NewTransactor(pool),
store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts),
}
account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive}
event := newAccountEvent(t, account)
relayHarness.save(ctx, t, account, event)
relay := relayHarness.newRelay(relayHarness.newPublisher(t, topic))
if result, err := relay.PublishPending(ctx); err != nil || result.Published != 1 {
t.Fatalf("PublishPending() = %+v, %v; want one event published", result, err)
}
var received atomic.Pointer[outbound.ConsumedEvent]
handler := accountHandler{received: &received}
metrics := prometheus.New()
group := newConsumerGroup()
source, _ := harness.newSource(t, topic, group)
consumer, err := eventconsumer.New(handler, source, harness.store, metrics, slog.New(slog.DiscardHandler), consumerTestSettings(consumerGrace))
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
runConsumer(ctx, t, consumer)
waitFor(ctx, t, "the relayed event to be applied", func() bool { return received.Load() != nil })
got := received.Load()
if got.EventID != event.EventID() || got.AggregateID != account.id || got.AggregateVersion != account.version ||
got.EventType != testAccountEventType || got.AggregateType != testAggregateType {
t.Fatalf("consumed event %+v does not match the outbox event %s", got, event.EventID())
}
assertJSONEqual(t, got.Payload, accountPayload(account))
})
}
// accountHandler records the account event it consumed.
type accountHandler struct {
received *atomic.Pointer[outbound.ConsumedEvent]
}
func (accountHandler) ConsumerName() string { return "integration_relay_check" }
func (accountHandler) Handles(eventType string) bool { return eventType == testAccountEventType }
func (handler accountHandler) Handle(_ context.Context, _ outbound.UnitOfWork, event outbound.ConsumedEvent) error {
handler.received.Store(&event)
return nil
}
func consumerTestSettings(grace time.Duration) eventconsumer.Settings {
return eventconsumer.Settings{
MaxAttempts: consumerMaxAttempts,
Backoff: retry.Backoff{Initial: consumerShortBackoff, Max: consumerShortBackoff},
HandlerTimeout: consumerHandlerTime,
CommitTimeout: consumerCommitTimeout,
ShutdownGrace: grace,
}
}
func newConsumerGroup() string {
return "integration-consumer-" + strings.ToLower(rand.Text())
}
// newSource creates a group member for topic. close leaves the group; it
// also runs when t finishes, after the consumer stopped.
func (harness *consumerHarness) newSource(t *testing.T, topic, group string) (source *kafka.EventSource, closeOnce func()) {
t.Helper()
settings := harness.env.Config
settings.KafkaEventsTopic = topic
settings.ConsumerCommitTimeout = consumerCommitTimeout
source, closeSource, err := kafka.NewEventSource(settings, group, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewEventSource() error = %v", err)
}
var once sync.Once
closeOnce = func() { once.Do(closeSource) }
t.Cleanup(closeOnce)
return source, closeOnce
}
func (harness *consumerHarness) startConsumer(
ctx context.Context,
t *testing.T,
topic, group string,
handler *effectHandler,
metrics *prometheus.Metrics,
grace time.Duration,
) (stop func()) {
t.Helper()
return harness.startConsumerWith(ctx, t, topic, group, handler, metrics, consumerTestSettings(grace))
}
// startConsumerWith runs a consumer of topic in group. stop cancels it,
// waits until Run returned, and then leaves the group, as bootstrap does.
func (harness *consumerHarness) startConsumerWith(
ctx context.Context,
t *testing.T,
topic, group string,
handler *effectHandler,
metrics *prometheus.Metrics,
settings eventconsumer.Settings,
) (stop func()) {
t.Helper()
source, closeSource := harness.newSource(t, topic, group)
consumer, err := eventconsumer.New(handler, source, harness.store, metrics, slog.New(slog.DiscardHandler), settings)
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
stopRun := runConsumer(ctx, t, consumer)
return func() {
t.Helper()
stopRun()
closeSource()
}
}
// runWithSource runs a consumer of a static source with store.
func runWithSource(
ctx context.Context,
t *testing.T,
source *staticSource,
handler *effectHandler,
store outbound.EventConsumerStore,
metrics *prometheus.Metrics,
settings eventconsumer.Settings,
) {
t.Helper()
consumer, err := eventconsumer.New(handler, source, store, metrics, slog.New(slog.DiscardHandler), settings)
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
runConsumer(ctx, t, consumer)
}
// runConsumer runs consumer until the returned stop or the end of t.
func runConsumer(ctx context.Context, t *testing.T, consumer *eventconsumer.Consumer) (stop func()) {
t.Helper()
runCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() {
defer close(done)
consumer.Run(runCtx)
}()
var once sync.Once
stop = func() {
once.Do(func() {
cancel()
select {
case <-done:
case <-time.After(consumerStopTimeout):
t.Errorf("consumer %s did not stop within %s", consumer.Name(), consumerStopTimeout)
}
})
}
t.Cleanup(stop)
return stop
}
// staticSource delivers one batch, then waits for ctx, and records the
// committed offsets. It stands in for Kafka where a test needs two
// consumers to receive the same record at a moment it controls.
type staticSource struct {
mu sync.Mutex
batch []outbound.ConsumedRecord
committed []int64
commitSeen chan struct{}
}
func newStaticSource(records ...outbound.ConsumedRecord) *staticSource {
return &staticSource{batch: records, commitSeen: make(chan struct{})}
}
func (source *staticSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) {
source.mu.Lock()
batch := source.batch
source.batch = nil
source.mu.Unlock()
if len(batch) > 0 {
return batch, nil
}
<-ctx.Done()
return nil, ctx.Err()
}
func (source *staticSource) Commit(_ context.Context, finished []outbound.ConsumedRecord) error {
source.mu.Lock()
defer source.mu.Unlock()
for _, record := range finished {
source.committed = append(source.committed, record.Offset)
}
select {
case <-source.commitSeen:
default:
close(source.commitSeen)
}
return nil
}
func (*staticSource) Release() {}
func (source *staticSource) waitForCommit(ctx context.Context, t *testing.T) {
t.Helper()
select {
case <-source.commitSeen:
case <-ctx.Done():
t.Fatal("the consumer did not commit its record")
case <-time.After(consumerWaitTimeout):
t.Fatal("the consumer did not commit its record")
}
}
func newConsumerEnvelope() receivedEnvelope {
return receivedEnvelope{
EnvelopeVersion: kafka.EnvelopeVersion,
EventID: uuid.New(),
EventType: consumerEventType,
SchemaVersion: 1,
AggregateType: consumerAggregate,
AggregateID: uuid.New(),
AggregateVersion: 1,
OccurredAt: time.Now().UTC(),
Payload: json.RawMessage(`{"step":1}`),
}
}
func envelopeValue(t *testing.T, envelope receivedEnvelope) []byte {
t.Helper()
value, err := json.Marshal(envelope)
if err != nil {
t.Fatalf("encode envelope: %v", err)
}
return value
}
// envelopeRecord builds a record as the relay writes it. A negative
// partition leaves the choice to the producer's partitioner.
func envelopeRecord(t *testing.T, topic string, partition int32, envelope receivedEnvelope) *kgo.Record {
t.Helper()
record := &kgo.Record{
Topic: topic,
// A distinct key per record lets a duplicate land on another
// partition, as a manual partitioner sends it.
Key: []byte(envelope.AggregateType + ":" + envelope.AggregateID.String()),
Value: envelopeValue(t, envelope),
Headers: []kgo.RecordHeader{
{Key: "event_id", Value: []byte(envelope.EventID.String())},
{Key: "event_type", Value: []byte(envelope.EventType)},
{Key: "schema_version", Value: []byte(strconv.Itoa(int(envelope.SchemaVersion)))},
},
}
if partition >= 0 {
record.Partition = partition
}
return record
}
// consumedRecord is the decoded form of envelope at offset 0.
func consumedRecord(envelope receivedEnvelope) outbound.ConsumedRecord {
return outbound.ConsumedRecord{
Topic: "static",
EventID: envelope.EventID,
Event: outbound.ConsumedEvent{
EventID: envelope.EventID,
EventType: envelope.EventType,
SchemaVersion: envelope.SchemaVersion,
AggregateType: envelope.AggregateType,
AggregateID: envelope.AggregateID,
AggregateVersion: envelope.AggregateVersion,
OccurredAt: envelope.OccurredAt,
Payload: envelope.Payload,
},
}
}
// committedOffsets returns the committed offsets of group on topic. The
// coordinator of a new group can be unavailable for a moment while Kafka
// creates the offsets topic, so it retries retriable errors.
func (env *testEnvironment) committedOffsets(ctx context.Context, t *testing.T, group, topic string) map[int32]int64 {
t.Helper()
var offsets map[int32]int64
var lastErr error
waitFor(ctx, t, "the offsets of group "+group, func() bool {
offsets, lastErr = env.fetchCommittedOffsets(ctx, group, topic)
if lastErr != nil && !kerr.IsRetriable(lastErr) {
t.Fatalf("fetch offsets of group %s: %v", group, lastErr)
}
return lastErr == nil
})
return offsets
}
func (env *testEnvironment) fetchCommittedOffsets(ctx context.Context, group, topic string) (map[int32]int64, error) {
ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
offsets := make(map[int32]int64)
responses, err := env.KafkaAdmin.FetchOffsets(ctx, group)
if errors.Is(err, kerr.GroupIDNotFound) {
return offsets, nil
}
if err != nil {
return nil, err
}
responses.Each(func(response kadm.OffsetResponse) {
if response.Topic == topic && response.Err == nil && response.At >= 0 {
offsets[response.Partition] = response.At
}
})
return offsets, nil
}
func (env *testEnvironment) waitForCommittedOffsets(ctx context.Context, t *testing.T, group, topic string, want map[int32]int64) {
t.Helper()
waitFor(ctx, t, fmt.Sprintf("group %s to commit %v", group, want), func() bool {
got, err := env.fetchCommittedOffsets(ctx, group, topic)
if err != nil && !kerr.IsRetriable(err) {
t.Fatalf("fetch offsets of group %s: %v", group, err)
}
return err == nil && maps.Equal(got, want)
})
}
// waitFor polls condition until it holds or consumerWaitTimeout passes.
func waitFor(ctx context.Context, t *testing.T, what string, condition func() bool) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, consumerWaitTimeout)
defer cancel()
ticker := time.NewTicker(readinessInterval)
defer ticker.Stop()
for !condition() {
select {
case <-ctx.Done():
t.Fatalf("timed out waiting for %s", what)
case <-ticker.C:
}
}
}
func (env *testEnvironment) newPoolWithApplicationName(ctx context.Context, t *testing.T, name string) *pgxpool.Pool {
t.Helper()
poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL)
if err != nil {
t.Fatalf("parse bootstrap database URL: %v", err)
}
poolConfig.ConnConfig.RuntimeParams["application_name"] = name
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
t.Fatalf("create PostgreSQL pool %s: %v", name, err)
}
t.Cleanup(pool.Close)
return pool
}
func (harness *consumerHarness) assertEffects(ctx context.Context, t *testing.T, eventID uuid.UUID, want int) {
t.Helper()
var count int
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+effectsIdentifier.Sanitize()+" WHERE event_id = $1", eventID).Scan(&count); err != nil {
t.Fatalf("count effects: %v", err)
}
if count != want {
t.Fatalf("event %s has %d effect rows, want %d", eventID, count, want)
}
}
func (harness *consumerHarness) assertMarkers(ctx context.Context, t *testing.T, want int) {
t.Helper()
var count int
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consumer_processed_events WHERE consumer_name = $1", consumerName).Scan(&count); err != nil {
t.Fatalf("count processed event markers: %v", err)
}
if count != want {
t.Fatalf("processed event markers = %d, want %d", count, want)
}
}
type deadLetterRow struct {
consumer string
topic string
partition int32
offset int64
eventID *uuid.UUID
eventType *string
errorClass string
reason string
attempts int
valueSize int
valueSHA256 [32]byte
}
func (harness *consumerHarness) readDeadLetters(ctx context.Context, t *testing.T) []deadLetterRow {
t.Helper()
rows, err := harness.pool.Query(ctx, `
SELECT consumer_name, topic, kafka_partition, kafka_offset, event_id, event_type,
error_class, reason, attempts, value_size, value_sha256
FROM consumer_dead_letters ORDER BY id`)
if err != nil {
t.Fatalf("read dead letters: %v", err)
}
letters, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (deadLetterRow, error) {
var letter deadLetterRow
var digest []byte
err := row.Scan(&letter.consumer, &letter.topic, &letter.partition, &letter.offset, &letter.eventID, &letter.eventType,
&letter.errorClass, &letter.reason, &letter.attempts, &letter.valueSize, &digest)
copy(letter.valueSHA256[:], digest)
return letter, err
})
if err != nil {
t.Fatalf("scan dead letters: %v", err)
}
return letters
}
func assertDeadLetter(t *testing.T, got, want deadLetterRow) {
t.Helper()
sameID := (got.eventID == nil) == (want.eventID == nil) && (got.eventID == nil || *got.eventID == *want.eventID)
sameType := (got.eventType == nil) == (want.eventType == nil) && (got.eventType == nil || *got.eventType == *want.eventType)
if got.consumer != consumerName || got.topic != want.topic || got.partition != want.partition || got.offset != want.offset ||
!sameID || !sameType || got.errorClass != want.errorClass || got.attempts != want.attempts ||
got.valueSize != want.valueSize || got.valueSHA256 != want.valueSHA256 || got.reason == "" {
t.Fatalf("dead letter %+v, want %+v", got, want)
}
}
// assertConsumerMetric reads lincodex_event_consumer_<kind>_total for the
// test consumer and one outcome or stage label from the scrape output.
func assertConsumerMetric(t *testing.T, metrics *prometheus.Metrics, kind, label string, want int) {
t.Helper()
labelName := map[string]string{"records": "outcome", "failures": "stage"}[kind]
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
prefix := fmt.Sprintf(`lincodex_event_consumer_%s_total{consumer=%q,%s=%q} `, kind, consumerName, labelName, label)
for line := range strings.SplitSeq(response.Body.String(), "\n") {
if value, found := strings.CutPrefix(line, prefix); found {
if value != strconv.Itoa(want) {
t.Fatalf("%s%s, want %d", prefix, value, want)
}
return
}
}
t.Fatalf("metrics output has no series %s", prefix)
}
// awaitOrCancel waits for release inside a handler and returns result, or the
// context error when the attempt ends first, so a failed test never leaves a
// handler blocked.
func awaitOrCancel(ctx context.Context, release <-chan struct{}, result error) error {
select {
case <-release:
return result
case <-ctx.Done():
return ctx.Err()
}
}
// awaitSignal waits for signal within consumerWaitTimeout.
func awaitSignal(ctx context.Context, t *testing.T, signal <-chan struct{}, what string) {
t.Helper()
select {
case <-signal:
case <-ctx.Done():
t.Fatalf("test ended while waiting for %s", what)
case <-time.After(consumerWaitTimeout):
t.Fatalf("timed out waiting for %s", what)
}
}
// failingCommits makes every offset commit of one member fail, as a
// coordinator that keeps rejecting commits would. The member's finished
// positions then stay pending, and only the revocation of a partition can
// commit them. It records the offsets the member tried to commit.
type failingCommits struct {
*kafka.EventSource
succeeded atomic.Int64
mu sync.Mutex
attempted map[int32][]int64
}
func (source *failingCommits) Commit(ctx context.Context, finished []outbound.ConsumedRecord) error {
source.mu.Lock()
for _, record := range finished {
source.attempted[record.Partition] = append(source.attempted[record.Partition], record.Offset)
}
source.mu.Unlock()
canceled, cancel := context.WithCancel(ctx)
cancel()
err := source.EventSource.Commit(canceled, finished)
if err == nil {
source.succeeded.Add(1)
}
return err
}
func (source *failingCommits) attemptedOffsets(partition int32) []int64 {
source.mu.Lock()
defer source.mu.Unlock()
return append([]int64(nil), source.attempted[partition]...)
}
// runRebalanceHandover lets a second member join a group while the first one
// holds a record, so the rebalance has to wait for it. The first member's
// commits fail, so the position of the partition it gives up reaches Kafka
// only through the commit in its revocation.
func (harness *consumerHarness) runRebalanceHandover(ctx context.Context, t *testing.T) {
t.Helper()
env := harness.env
logger := slog.New(slog.DiscardHandler)
topic := env.createKafkaTopic(ctx, t, 2)
group := newConsumerGroup()
producer := env.newKafkaClient(t, kgo.RecordPartitioner(kgo.ManualPartitioner()))
first := [2]receivedEnvelope{newConsumerEnvelope(), newConsumerEnvelope()}
produceKafkaRecords(ctx, t, producer, envelopeRecord(t, topic, 0, first[0]), envelopeRecord(t, topic, 1, first[1]))
held, release := make(chan struct{}), make(chan struct{})
var holding sync.Once
holder := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error {
hold := false
holding.Do(func() { hold = true })
if !hold {
return nil
}
close(held)
return awaitOrCancel(ctx, release, nil)
})
holderSource, closeHolder := harness.newSource(t, topic, group)
failing := &failingCommits{EventSource: holderSource, attempted: make(map[int32][]int64)}
holderConsumer, err := eventconsumer.New(holder, failing, harness.store, prometheus.New(), logger, consumerTestSettings(consumerGrace))
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
stopHolder := runConsumer(ctx, t, holderConsumer)
awaitSignal(ctx, t, held, "the first member to hold a record")
joiner := newEffectHandler(nil)
joinerSource, _ := harness.newSource(t, topic, group)
joinerMetrics := prometheus.New()
joinerConsumer, err := eventconsumer.New(joiner, joinerSource, harness.store, joinerMetrics, logger, consumerTestSettings(consumerGrace))
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
runConsumer(ctx, t, joinerConsumer)
// The join starts a rebalance that cannot finish while the first member
// holds its polled records.
env.waitForGroupState(ctx, t, group, "PreparingRebalance")
close(release)
// Cooperative rebalancing first revokes the partition that moves, then
// assigns it to the joiner in a second round.
env.waitForBalancedGroup(ctx, t, group, 2)
// After the handover each member owns one partition. One new event per
// partition shows which partition moved.
second := [2]receivedEnvelope{newConsumerEnvelope(), newConsumerEnvelope()}
produceKafkaRecords(ctx, t, producer, envelopeRecord(t, topic, 0, second[0]), envelopeRecord(t, topic, 1, second[1]))
all := []receivedEnvelope{first[0], first[1], second[0], second[1]}
waitFor(ctx, t, "every event to be applied", func() bool {
for _, event := range all {
if harness.countEffects(ctx, t, event.EventID) == 0 {
return false
}
}
return true
})
moved := int32(-1)
for partition := range int32(2) {
if len(joiner.callTimes(second[partition].EventID)) > 0 {
moved = partition
}
}
if moved < 0 {
t.Fatal("the joining member applied no event, so no partition moved")
}
kept := 1 - moved
for _, event := range all {
harness.assertEffects(ctx, t, event.EventID, 1)
}
for partition := range int32(2) {
if calls := len(holder.callTimes(first[partition].EventID)); calls != 1 {
t.Fatalf("the first member handled the first event of partition %d %d times, want once before the rebalance", partition, calls)
}
}
if failing.succeeded.Load() != 0 {
t.Fatal("a commit of the first member succeeded, so the revocation path was not needed")
}
// The moved partition's position was committed in the revocation: the
// joiner started after the first event instead of receiving it again.
if calls := len(joiner.callTimes(first[moved].EventID)); calls != 0 {
t.Fatalf("the joiner applied the moved partition's first event %d times", calls)
}
assertConsumerMetric(t, joinerMetrics, "records", "duplicate", 0)
// No commit for the moved partition came from the first member after it
// lost the partition.
if offsets := failing.attemptedOffsets(moved); len(offsets) != 1 || offsets[0] != 0 {
t.Fatalf("the first member tried to commit offsets %v of the moved partition %d, want only 0", offsets, moved)
}
if calls := len(holder.callTimes(second[moved].EventID)); calls != 0 {
t.Fatalf("the first member handled the moved partition's second event %d times", calls)
}
waitFor(ctx, t, "the joiner to commit the moved partition", func() bool {
offsets, err := env.fetchCommittedOffsets(ctx, group, topic)
return err == nil && offsets[moved] == 2
})
// Leaving the group revokes the kept partition, and the revocation
// commits its pending position; the moved partition is not rewound.
stopHolder()
closeHolder()
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{moved: 2, kept: 2})
assertConsumerMetric(t, joinerMetrics, "records", "duplicate", 0)
}
func (env *testEnvironment) waitForGroupState(ctx context.Context, t *testing.T, group, state string) {
t.Helper()
last := ""
waitFor(ctx, t, "group "+group+" to reach state "+state, func() bool {
requestCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
described, err := env.KafkaAdmin.DescribeGroups(requestCtx, group)
if err != nil {
return false
}
if detail, ok := described[group]; ok && detail.Err == nil {
last = detail.State
}
return last == state
})
}
func (harness *consumerHarness) countEffects(ctx context.Context, t *testing.T, eventID uuid.UUID) int {
t.Helper()
var count int
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+effectsIdentifier.Sanitize()+" WHERE event_id = $1", eventID).Scan(&count); err != nil {
t.Fatalf("count effects: %v", err)
}
return count
}
// waitForBalancedGroup waits until group is stable with members members that
// each own at least one partition.
func (env *testEnvironment) waitForBalancedGroup(ctx context.Context, t *testing.T, group string, members int) {
t.Helper()
waitFor(ctx, t, fmt.Sprintf("group %s to give each of %d members a partition", group, members), func() bool {
requestCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout)
defer cancel()
described, err := env.KafkaAdmin.DescribeGroups(requestCtx, group)
if err != nil {
return false
}
detail, ok := described[group]
if !ok || detail.Err != nil || detail.State != "Stable" || len(detail.Members) != members {
return false
}
for _, member := range detail.Members {
assignment, ok := member.Assigned.AsConsumer()
if !ok || len(assignment.Topics) == 0 || len(assignment.Topics[0].Partitions) == 0 {
return false
}
}
return true
})
}