feat(outbox): relay committed outbox events to Kafka

This commit is contained in:
shira committed 2026-10-06 03:01:53 +03:00
1 parent 78f1651f6b
commit 6c3b34f73e
42 files changed
+3731 -45

No files matched your search

+39 -2
View File
@@ -17,6 +17,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/outboxrelay"
)
const (
@@ -32,6 +33,9 @@ type Application struct {
// mailSender is the transport selected by EMAIL_PROVIDER. No usecase
// sends mail yet; the delivery layer will take it from here.
mailSender outbound.MailSender
// 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
}
func NewApplication(
@@ -40,8 +44,16 @@ func NewApplication(
metrics *prometheus.Metrics,
logger *slog.Logger,
mailSender outbound.MailSender,
relay *outboxrelay.Relay,
) *Application {
return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger, mailSender: mailSender}
return &Application{
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
}
}
func Run() (runErr error) {
@@ -137,10 +149,16 @@ 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
// failure that leaves ctx running.
runCtx, stopRun := context.WithCancel(ctx)
defer stopRun()
relayStopped := application.startRelay(runCtx)
apiServer := newHTTPServer(application.apiHandler)
metricsServer := newHTTPServer(application.metrics.Handler())
err = serveServers(
ctx,
runCtx,
apiListener,
apiServer,
metricsListener,
@@ -148,9 +166,28 @@ func (application *Application) run(ctx context.Context) error {
application.config.ShutdownTimeout,
)
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
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
}
go func() {
defer close(stopped)
application.relay.Run(ctx)
}()
return stopped
}
func newHTTPServer(handler http.Handler) *http.Server {
return &http.Server{
Handler: handler,
+92
View File
@@ -0,0 +1,92 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/kafka"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/worker/outboxrelay"
)
const (
// relayPoolMaxConns covers the claim transaction and the backlog read,
// the only two statements the relay can have open at once.
relayPoolMaxConns = 2
// relayBacklogInterval matches the usual Prometheus scrape interval, so
// the backlog gauges stay current without a count on every busy pass.
relayBacklogInterval = 15 * time.Second
)
// newOutboxRelay builds the outbox relay and the resources it owns: a
// PostgreSQL pool and a Kafka producer. It returns a nil relay when
// RELAY_ENABLED is false or DATABASE_URL is unset; the service then starts
// without publishing events and the outbox keeps them. Neither the pool nor
// the producer connects here, so an unavailable Kafka never blocks startup:
// the relay retries in the background.
func newOutboxRelay(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
) (*outboxrelay.Relay, func(), error) {
if !settings.RelayEnabled {
logger.Info("outbox relay is disabled; events stay in the outbox")
return nil, func() {}, nil
}
if settings.DatabaseURL == "" {
logger.Warn("outbox relay skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, relayPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newOutboxRelay - create pool: %w", err)
}
relayLogger := logger.With(slog.String("component", "outbox_relay"), slog.String("topic", settings.KafkaEventsTopic))
publisher, closePublisher, err := kafka.NewPublisher(settings, relayLogger)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newOutboxRelay - create Kafka publisher: %w", err)
}
relay := outboxrelay.New(
postgres.NewOutboxRelayStore(pool, relayTransactionTimeouts(settings)),
publisher,
metrics,
relayLogger,
relaySettings(settings),
)
// The application stops the relay before this cleanup runs, so no pass
// uses the producer or the pool while they close.
return relay, func() {
closePublisher()
pool.Close()
}, nil
}
func relaySettings(settings config.Config) outboxrelay.Settings {
return outboxrelay.Settings{
BatchSize: settings.RelayBatchSize,
PollInterval: settings.RelayPollInterval,
Backoff: outboxrelay.Backoff{
Initial: settings.RelayBackoffInitial,
Max: settings.RelayBackoffMax,
},
ShutdownTimeout: settings.ShutdownTimeout,
BacklogInterval: relayBacklogInterval,
}
}
// relayTransactionTimeouts derives the server-side bounds of a claim. Between
// its statements the transaction waits only for the publish, which ends by
// RELAY_PRODUCE_TIMEOUT; one statement timeout on top covers the work around
// it, so only a client that stopped responding hits the idle limit.
func relayTransactionTimeouts(settings config.Config) postgres.OutboxRelayTimeouts {
return postgres.OutboxRelayTimeouts{
Statement: settings.RelayStatementTimeout,
IdleInTransaction: settings.RelayProduceTimeout + settings.RelayStatementTimeout,
}
}
+107
View File
@@ -0,0 +1,107 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/outboxrelay"
)
const relayLifecycleTimeout = 5 * time.Second
func TestNewOutboxRelaySkipsWithoutWork(t *testing.T) {
tests := []struct {
name string
settings config.Config
}{
{name: "disabled", settings: config.Config{RelayEnabled: false, DatabaseURL: "postgres://app@db/app"}},
{name: "database not configured", settings: config.Config{RelayEnabled: true}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
relay, cleanup, err := newOutboxRelay(t.Context(), test.settings, slog.New(slog.DiscardHandler), prometheus.New())
if err != nil {
t.Fatalf("newOutboxRelay() error = %v", err)
}
cleanup()
if relay != nil {
t.Fatal("newOutboxRelay() built a relay without work to do")
}
})
}
}
// claimCounter is an outbox store with no pending events that counts passes.
type claimCounter struct {
passes atomic.Int64
}
func (store *claimCounter) ClaimPending(context.Context, int, outbound.PublishOutboxBatch) error {
store.passes.Add(1)
return nil
}
func (*claimCounter) Backlog(context.Context) (outbound.OutboxBacklog, error) {
return outbound.OutboxBacklog{}, nil
}
type readyPublisher struct{}
func (readyPublisher) Prepare(context.Context) error { return nil }
func (readyPublisher) Publish(_ context.Context, events []outbound.OutboxEvent) []error {
return make([]error, len(events))
}
func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
store := &claimCounter{}
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
relay := outboxrelay.New(store, readyPublisher{}, metrics, logger, outboxrelay.Settings{
BatchSize: 1,
PollInterval: time.Millisecond,
Backoff: outboxrelay.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
ShutdownTimeout: time.Second,
BacklogInterval: time.Second,
})
application := NewApplication(config.Config{
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay)
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 store.passes.Load() < 2 {
if time.Now().After(deadline) {
t.Fatal("the relay did not poll the outbox 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 relay stopped, so no pass follows.
passes := store.passes.Load()
time.Sleep(10 * time.Millisecond)
if after := store.passes.Load(); after != passes {
t.Fatalf("the relay ran %d passes after run() returned", after-passes)
}
}
+1
View File
@@ -47,6 +47,7 @@ func initialize(
v1.NewHandler,
v1.NewDenyAllSecurity,
httpadapter.NewRouter,
newOutboxRelay,
NewApplication,
),
)
+9 -1
View File
@@ -55,8 +55,16 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender)
relay, cleanup4, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay)
return application, func() {
cleanup4()
cleanup3()
cleanup2()
cleanup()