feat(events): add idempotent Kafka event consumer runtime

This commit is contained in:
shira committed 2026-10-06 03:59:57 +03:00
1 parent 565ef8d4f5
commit 3adb0ef9e4
47 files changed
+5018 -105

No files matched your search

+26 -13
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
@@ -36,6 +37,9 @@ type Application struct {
// relay publishes outbox events while the servers run. It is nil when
// the relay is disabled or the database is not configured.
relay *outboxrelay.Relay
// consumers apply events from the event bus while the servers run. The
// list is empty until a handler is registered in eventHandlers.
consumers eventConsumers
}
func NewApplication(
@@ -45,6 +49,7 @@ func NewApplication(
logger *slog.Logger,
mailSender outbound.MailSender,
relay *outboxrelay.Relay,
consumers eventConsumers,
) *Application {
return &Application{
config: config,
@@ -53,6 +58,7 @@ func NewApplication(
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
}
}
@@ -149,11 +155,11 @@ func (application *Application) run(ctx context.Context) error {
slog.String("metrics_addr", application.config.MetricsAddr),
)
// The relay stops when the servers stop, including after a server
// The workers stop when the servers stop, including after a server
// failure that leaves ctx running.
runCtx, stopRun := context.WithCancel(ctx)
defer stopRun()
relayStopped := application.startRelay(runCtx)
workersStopped := application.startWorkers(runCtx)
apiServer := newHTTPServer(application.apiHandler)
metricsServer := newHTTPServer(application.metrics.Handler())
@@ -167,23 +173,30 @@ func (application *Application) run(ctx context.Context) error {
)
application.logger.Info("servers stopped")
stopRun()
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, so
// the cleanup that closes its pool and producer runs after it.
<-relayStopped
// The relay finishes its pass in progress within SHUTDOWN_TIMEOUT and
// each consumer its record in progress within CONSUMER_SHUTDOWN_GRACE
// plus one offset commit, so the cleanup that closes their pools,
// producer, and group members runs after all of them stopped.
<-workersStopped
application.logger.Info("workers stopped")
return err
}
// startRelay runs the relay until ctx ends and returns a channel that closes
// when it has stopped.
func (application *Application) startRelay(ctx context.Context) <-chan struct{} {
stopped := make(chan struct{})
if application.relay == nil {
close(stopped)
return stopped
// startWorkers runs the relay and every consumer until ctx ends and returns
// a channel that closes when all of them have stopped. The workers stop
// together with the servers; none of them depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
var workers sync.WaitGroup
if application.relay != nil {
workers.Go(func() { application.relay.Run(ctx) })
}
for _, consumer := range application.consumers {
workers.Go(func() { consumer.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
application.relay.Run(ctx)
workers.Wait()
}()
return stopped
}
+133
View File
@@ -0,0 +1,133 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"math"
"sync"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/kafka"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/worker/eventconsumer"
"lincodex/backend/internal/worker/retry"
)
// consumerGroupSeparator joins CONSUMER_GROUP_PREFIX and a consumer name.
const consumerGroupSeparator = "."
// eventConsumers are the consumers that run next to the HTTP servers.
type eventConsumers []*eventconsumer.Consumer
var _ eventconsumer.Metrics = (*prometheus.Metrics)(nil)
// eventHandlers lists the handlers that get a consumer. It is empty because
// no product module consumes domain events yet; a module adds its handler
// here, and its consumer then starts with the next deployment.
func eventHandlers() []inbound.EventHandler {
return nil
}
func newEventConsumers(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
) (eventConsumers, func(), error) {
return buildEventConsumers(ctx, settings, logger, metrics, eventHandlers())
}
// buildEventConsumers builds one consumer per handler and the resources they
// own: one PostgreSQL pool shared by all of them and one Kafka group member
// each. Nothing connects here, so an unavailable Kafka or database never
// blocks startup; the consumers retry in the background. It returns no
// consumer when CONSUMER_ENABLED is false, when no handler is registered, or
// when DATABASE_URL is unset.
func buildEventConsumers(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics eventconsumer.Metrics,
handlers []inbound.EventHandler,
) (eventConsumers, func(), error) {
switch {
case !settings.ConsumerEnabled:
logger.Info("event consumers are disabled")
return nil, func() {}, nil
case len(handlers) == 0:
logger.Info("no event consumer is registered")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("event consumers skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
// A consumer processes one record at a time and writes a dead letter
// only after its transaction ended, so it needs one connection.
poolSize := len(handlers)
if poolSize > math.MaxInt32 {
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - %d handlers exceed the pool size limit", poolSize)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, int32(poolSize))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create pool: %w", err)
}
store := postgres.NewEventConsumerStore(pool, settings.ConsumerHandlerTimeout)
consumers := make(eventConsumers, 0, len(handlers))
closers := make([]func(), 0, len(handlers))
cleanup := func() {
// The application stops every consumer before this runs, so no
// record is in progress while the members leave their groups. They
// leave in parallel, so shutdown waits for the slowest leave rather
// than for the sum of them.
var leaving sync.WaitGroup
for _, closeSource := range closers {
leaving.Go(closeSource)
}
leaving.Wait()
pool.Close()
}
names := make(map[string]bool, len(handlers))
for _, handler := range handlers {
name := handler.ConsumerName()
if names[name] {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - consumer %s is registered twice", name)
}
names[name] = true
group := settings.ConsumerGroupPrefix + consumerGroupSeparator + name
consumerLogger := logger.With(
slog.String("component", "event_consumer"),
slog.String("topic", settings.KafkaEventsTopic),
slog.String("group", group),
)
source, closeSource, err := kafka.NewEventSource(settings, group, consumerLogger)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create Kafka group member for %s: %w", name, err)
}
closers = append(closers, closeSource)
consumer, err := eventconsumer.New(handler, source, store, metrics, consumerLogger, consumerSettings(settings))
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create consumer: %w", err)
}
consumers = append(consumers, consumer)
}
return consumers, cleanup, nil
}
func consumerSettings(settings config.Config) eventconsumer.Settings {
return eventconsumer.Settings{
MaxAttempts: settings.ConsumerMaxAttempts,
Backoff: retry.Backoff{
Initial: settings.ConsumerBackoffInitial,
Max: settings.ConsumerBackoffMax,
},
HandlerTimeout: settings.ConsumerHandlerTimeout,
CommitTimeout: settings.ConsumerCommitTimeout,
ShutdownGrace: settings.ConsumerShutdownGrace,
}
}
@@ -0,0 +1,206 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/eventconsumer"
)
type namedHandler string
func (handler namedHandler) ConsumerName() string { return string(handler) }
func (namedHandler) Handles(string) bool { return true }
func (namedHandler) Handle(context.Context, outbound.UnitOfWork, outbound.ConsumedEvent) error {
return nil
}
func consumerTestConfig(t *testing.T) config.Config {
t.Helper()
settings, err := config.LoadFromEnv(func(key string) (string, bool) {
value, ok := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_PROVIDER": "disabled",
"EMAIL_FROM": "no-reply@example.com",
"APP_PUBLIC_URL": "http://localhost:8080",
"DATABASE_URL": "postgres://app@127.0.0.1:1/app",
}[key]
return value, ok
})
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
return settings
}
func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
disabled := consumerTestConfig(t)
disabled.ConsumerEnabled = false
noDatabase := consumerTestConfig(t)
noDatabase.DatabaseURL = ""
tests := []struct {
name string
settings config.Config
handlers []inbound.EventHandler
}{
{name: "disabled", settings: disabled, handlers: []inbound.EventHandler{namedHandler("audit")}},
{name: "no handler registered", settings: consumerTestConfig(t)},
{name: "database not configured", settings: noDatabase, handlers: []inbound.EventHandler{namedHandler("audit")}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
consumers, cleanup, err := buildEventConsumers(t.Context(), test.settings, logger, prometheus.New(), test.handlers)
if err != nil {
t.Fatalf("buildEventConsumers() error = %v", err)
}
cleanup()
if len(consumers) != 0 {
t.Fatalf("buildEventConsumers() built %d consumers without work to do", len(consumers))
}
})
}
}
func TestBootstrapRegistersNoEventHandlerYet(t *testing.T) {
if handlers := eventHandlers(); len(handlers) != 0 {
t.Fatalf("eventHandlers() = %d handlers; update the documentation when the first consumer is registered", len(handlers))
}
}
func TestBuildEventConsumersBuildsOneConsumerPerHandler(t *testing.T) {
settings := consumerTestConfig(t)
consumers, cleanup, err := buildEventConsumers(t.Context(), settings, slog.New(slog.DiscardHandler), prometheus.New(),
[]inbound.EventHandler{namedHandler("audit"), namedHandler("search_index")})
if err != nil {
t.Fatalf("buildEventConsumers() error = %v", err)
}
// Nothing connected, so closing the group members returns at once.
closed := make(chan struct{})
go func() {
defer close(closed)
cleanup()
}()
select {
case <-closed:
case <-time.After(relayLifecycleTimeout):
t.Fatal("cleanup did not return")
}
if len(consumers) != 2 || consumers[0].Name() != "audit" || consumers[1].Name() != "search_index" {
t.Fatalf("buildEventConsumers() = %v, want audit and search_index", consumers)
}
}
func TestBuildEventConsumersRejectsInvalidRegistrations(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
tests := map[string][]inbound.EventHandler{
"duplicate name": {namedHandler("audit"), namedHandler("audit")},
"invalid name": {namedHandler("Audit-Log")},
}
for name, handlers := range tests {
t.Run(name, func(t *testing.T) {
_, _, err := buildEventConsumers(t.Context(), consumerTestConfig(t), logger, prometheus.New(), handlers)
if err == nil {
t.Fatal("buildEventConsumers() accepted an invalid registration")
}
})
}
}
func TestEventConsumerLabelsMatchThePreparedMetrics(t *testing.T) {
metrics := prometheus.New()
metrics.PrepareEventConsumer("audit")
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
body := response.Body.String()
for _, outcome := range []string{eventconsumer.OutcomeApplied, eventconsumer.OutcomeDuplicate, eventconsumer.OutcomeIgnored, eventconsumer.OutcomeDeadLettered} {
if want := `lincodex_event_consumer_records_total{consumer="audit",outcome="` + outcome + `"} 0`; !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s", want)
}
}
for _, stage := range []string{eventconsumer.StageHandler, eventconsumer.StageStore, eventconsumer.StagePoll, eventconsumer.StageCommit} {
if want := `lincodex_event_consumer_failures_total{consumer="audit",stage="` + stage + `"} 0`; !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s", want)
}
}
}
// blockingSource returns nothing and counts polls until ctx ends.
type blockingSource struct {
polls atomic.Int64
running atomic.Bool
}
func (source *blockingSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) {
source.polls.Add(1)
source.running.Store(true)
<-ctx.Done()
source.running.Store(false)
return nil, ctx.Err()
}
func (*blockingSource) Commit(context.Context, []outbound.ConsumedRecord) error { return nil }
func (*blockingSource) Release() {}
type unusedStore struct{}
func (unusedStore) ApplyOnce(context.Context, string, uuid.UUID, outbound.ApplyEvent) (bool, error) {
return false, nil
}
func (unusedStore) RecordDeadLetter(context.Context, outbound.DeadLetter) error { return nil }
func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
source := &blockingSource{}
settings := consumerSettings(consumerTestConfig(t))
consumer, err := eventconsumer.New(namedHandler("audit"), source, unusedStore{}, metrics, logger, settings)
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
application := NewApplication(config.Config{
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer})
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
deadline := time.Now().Add(relayLifecycleTimeout)
for source.polls.Load() < 1 {
if time.Now().After(deadline) {
t.Fatal("the consumer did not poll while the servers ran")
}
time.Sleep(time.Millisecond)
}
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
// run returns only after the consumer stopped polling, so the cleanup
// that closes its group member never races a poll.
if source.running.Load() {
t.Fatal("the consumer was still polling after run() returned")
}
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/worker/outboxrelay"
"lincodex/backend/internal/worker/retry"
)
const (
@@ -71,7 +72,7 @@ func relaySettings(settings config.Config) outboxrelay.Settings {
return outboxrelay.Settings{
BatchSize: settings.RelayBatchSize,
PollInterval: settings.RelayPollInterval,
Backoff: outboxrelay.Backoff{
Backoff: retry.Backoff{
Initial: settings.RelayBackoffInitial,
Max: settings.RelayBackoffMax,
},
+3 -2
View File
@@ -12,6 +12,7 @@ import (
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/outboxrelay"
"lincodex/backend/internal/worker/retry"
)
const relayLifecycleTimeout = 5 * time.Second
@@ -67,7 +68,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
relay := outboxrelay.New(store, readyPublisher{}, metrics, logger, outboxrelay.Settings{
BatchSize: 1,
PollInterval: time.Millisecond,
Backoff: outboxrelay.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
ShutdownTimeout: time.Second,
BacklogInterval: time.Second,
})
@@ -75,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -48,6 +48,7 @@ func initialize(
v1.NewDenyAllSecurity,
httpadapter.NewRouter,
newOutboxRelay,
newEventConsumers,
NewApplication,
),
)
+10 -1
View File
@@ -62,8 +62,17 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay)
bootstrapEventConsumers, cleanup5, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers)
return application, func() {
cleanup5()
cleanup4()
cleanup3()
cleanup2()