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

+41
View File
@@ -41,6 +41,24 @@ type Config struct {
SeaweedFSRegion string
SeaweedFSTimeout time.Duration
KafkaBrokers []string
// KafkaEventsTopic receives every published domain event.
KafkaEventsTopic string
KafkaEventsTopicPartitions int32
// KafkaEventsTopicReplicationFactor is -1 for the broker default.
KafkaEventsTopicReplicationFactor int16
// KafkaEventsTopicMinInsyncReplicas is 0 for the broker default.
KafkaEventsTopicMinInsyncReplicas int16
// KafkaProvisionTopics lets the relay create a missing events topic.
KafkaProvisionTopics bool
// RelayEnabled runs the outbox relay next to the HTTP servers.
RelayEnabled bool
RelayBatchSize int
RelayPollInterval time.Duration
RelayProduceTimeout time.Duration
// RelayStatementTimeout bounds each SQL statement of a relay pass.
RelayStatementTimeout time.Duration
RelayBackoffInitial time.Duration
RelayBackoffMax time.Duration
// EmailProvider selects the only active mail transport. Settings of the
// other transports are not loaded.
EmailProvider EmailProvider
@@ -94,6 +112,12 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadRedis(lookup); err != nil {
return Config{}, err
}
if err := config.loadKafkaTopics(lookup); err != nil {
return Config{}, err
}
if err := config.loadRelay(lookup); err != nil {
return Config{}, err
}
if err := config.loadMail(lookup); err != nil {
return Config{}, err
}
@@ -138,6 +162,9 @@ func (config Config) Validate() error {
if err := config.ValidateKafka(); err != nil {
return err
}
if err := config.ValidateRelay(); err != nil {
return err
}
if err := config.ValidateMail(); err != nil {
return err
}
@@ -195,6 +222,20 @@ func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) {
}
}
// intOrDefault parses a decimal integer, ignoring surrounding spaces. An empty
// value is an error rather than the default.
func intOrDefault(lookup LookupEnv, key string, fallback int) (int, error) {
value, ok := lookup(key)
if !ok {
return fallback, nil
}
number, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil {
return 0, fmt.Errorf("config.intOrDefault - %s must be an integer", key)
}
return number, nil
}
func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) {
value, ok := lookup(key)
if !ok {
+53
View File
@@ -251,3 +251,56 @@ func TestLoadFromEnvRejectsKafkaBrokers(t *testing.T) {
})
}
}
func TestLoadFromEnvKafkaTopicReplication(t *testing.T) {
tests := []struct {
name string
values map[string]string
replication, minInsync int16
}{
{name: "broker defaults", values: nil, replication: -1, minInsync: 0},
{name: "explicit broker default", values: map[string]string{"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "-1"}, replication: -1, minInsync: 0},
{name: "production cluster", values: map[string]string{
"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "3",
"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": " 2 ",
}, replication: 3, minInsync: 2},
{name: "min ISR with broker default replication", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "2"}, replication: -1, minInsync: 2},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(test.values))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.KafkaEventsTopicReplicationFactor != test.replication || settings.KafkaEventsTopicMinInsyncReplicas != test.minInsync {
t.Fatalf("replication = %d, min ISR = %d; want %d and %d", settings.KafkaEventsTopicReplicationFactor,
settings.KafkaEventsTopicMinInsyncReplicas, test.replication, test.minInsync)
}
})
}
}
func TestLoadFromEnvRejectsKafkaTopicReplication(t *testing.T) {
tests := []struct {
name string
values map[string]string
want string
}{
{name: "negative replication other than -1", values: map[string]string{"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "-2"}, want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR"},
{name: "empty min ISR", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": ""}, want: "config.intOrDefault - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS"},
{name: "zero min ISR", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "0"}, want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS"},
{name: "min ISR too large", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "32768"}, want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS"},
{name: "min ISR above replication", values: map[string]string{
"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "2",
"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "3",
}, want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must not exceed"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(test.values))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want)
}
})
}
}
+86
View File
@@ -3,7 +3,9 @@ package config
import (
"errors"
"fmt"
"math"
"net"
"regexp"
"strconv"
"strings"
)
@@ -11,8 +13,35 @@ import (
const (
defaultKafkaBrokers = "localhost:9092"
kafkaBrokersSeparator = ","
// defaultKafkaEventsTopic receives every domain event. One topic keeps
// the setup small; the record key keeps each aggregate's events ordered
// within one partition.
defaultKafkaEventsTopic = "lincodex.domain.events"
// defaultKafkaEventsTopicPartitions lets up to three consumers of one
// group share the topic. Partitions can be added later but not removed,
// and adding them moves keys to other partitions.
defaultKafkaEventsTopicPartitions = 3
// maxKafkaEventsTopicPartitions bounds a mistyped value; one node does
// not benefit from more partitions.
maxKafkaEventsTopicPartitions = 1000
// KafkaBrokerDefaultReplicationFactor asks the broker to apply its own
// default.replication.factor when it creates the topic, so one setting on
// the broker covers both the single-node stand and a replicated cluster.
KafkaBrokerDefaultReplicationFactor = -1
// KafkaBrokerDefaultMinInsyncReplicas leaves min.insync.replicas of a
// created topic to the broker default.
KafkaBrokerDefaultMinInsyncReplicas = 0
// Topic provisioning is on by default because the broker never creates
// topics on demand.
defaultKafkaProvisionTopics = true
// maxKafkaTopicNameLength is the Kafka limit for topic names.
maxKafkaTopicNameLength = 249
)
// kafkaTopicNamePattern holds the characters Kafka accepts in a topic name.
var kafkaTopicNamePattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
// parseKafkaBrokers splits a comma-separated broker list. Empty entries are
// kept so that validation can reject values such as "a:9092,,b:9092".
func parseKafkaBrokers(raw string) []string {
@@ -27,6 +56,41 @@ func parseKafkaBrokers(raw string) []string {
return brokers
}
// loadKafkaTopics reads the events topic settings. An unset value takes its
// default; an empty or malformed value is an error.
func (config *Config) loadKafkaTopics(lookup LookupEnv) error {
config.KafkaEventsTopic = strings.TrimSpace(valueOrDefault(lookup, "KAFKA_EVENTS_TOPIC", defaultKafkaEventsTopic))
partitions, err := intOrDefault(lookup, "KAFKA_EVENTS_TOPIC_PARTITIONS", defaultKafkaEventsTopicPartitions)
if err != nil {
return err
}
if partitions < 1 || partitions > maxKafkaEventsTopicPartitions {
return fmt.Errorf("Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_PARTITIONS must be between 1 and %d", maxKafkaEventsTopicPartitions)
}
config.KafkaEventsTopicPartitions = int32(partitions)
replicationFactor, err := intOrDefault(lookup, "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR", KafkaBrokerDefaultReplicationFactor)
if err != nil {
return err
}
if replicationFactor < KafkaBrokerDefaultReplicationFactor || replicationFactor == 0 || replicationFactor > math.MaxInt16 {
return fmt.Errorf("Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR must be -1 for the broker default or between 1 and %d", math.MaxInt16)
}
config.KafkaEventsTopicReplicationFactor = int16(replicationFactor)
minInsyncReplicas, err := intOrDefault(lookup, "KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS", KafkaBrokerDefaultMinInsyncReplicas)
if err != nil {
return err
}
// An explicit 0 would read as the broker default, so only an unset
// variable selects it.
_, set := lookup("KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS")
if minInsyncReplicas < KafkaBrokerDefaultMinInsyncReplicas || minInsyncReplicas > math.MaxInt16 || (set && minInsyncReplicas == KafkaBrokerDefaultMinInsyncReplicas) {
return fmt.Errorf("Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must be between 1 and %d, or unset for the broker default", math.MaxInt16)
}
config.KafkaEventsTopicMinInsyncReplicas = int16(minInsyncReplicas)
config.KafkaProvisionTopics, err = boolOrDefault(lookup, "KAFKA_PROVISION_TOPICS", defaultKafkaProvisionTopics)
return err
}
func (config Config) ValidateKafka() error {
if len(config.KafkaBrokers) == 0 {
return errors.New("Config.ValidateKafka - KAFKA_BROKERS must not be empty")
@@ -38,9 +102,31 @@ func (config Config) ValidateKafka() error {
return fmt.Errorf("Config.ValidateKafka - KAFKA_BROKERS entry %d must be a host:port address with a nonzero port", index+1)
}
}
if !validKafkaTopicName(config.KafkaEventsTopic) {
return fmt.Errorf("Config.ValidateKafka - KAFKA_EVENTS_TOPIC must be 1 to %d letters, digits, dots, underscores, or hyphens other than a single or double dot", maxKafkaTopicNameLength)
}
if config.KafkaEventsTopicPartitions < 1 || config.KafkaEventsTopicPartitions > maxKafkaEventsTopicPartitions {
return fmt.Errorf("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_PARTITIONS must be between 1 and %d", maxKafkaEventsTopicPartitions)
}
if config.KafkaEventsTopicReplicationFactor != KafkaBrokerDefaultReplicationFactor && config.KafkaEventsTopicReplicationFactor < 1 {
return errors.New("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR must be -1 for the broker default or positive")
}
if config.KafkaEventsTopicMinInsyncReplicas < KafkaBrokerDefaultMinInsyncReplicas {
return errors.New("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must be positive or unset for the broker default")
}
// With an explicit replication factor, a larger min.insync.replicas would
// make every acks=all write fail.
if config.KafkaEventsTopicReplicationFactor > 0 && config.KafkaEventsTopicMinInsyncReplicas > config.KafkaEventsTopicReplicationFactor {
return errors.New("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must not exceed KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR")
}
return nil
}
// validKafkaTopicName applies the broker's topic name rules.
func validKafkaTopicName(topic string) bool {
return len(topic) <= maxKafkaTopicNameLength && topic != "." && topic != ".." && kafkaTopicNamePattern.MatchString(topic)
}
// validKafkaBroker accepts a hostname or IP address with a port in 1-65535.
// URL schemes, user info, and paths are rejected because Kafka clients expect
// plain bootstrap addresses.
+90
View File
@@ -0,0 +1,90 @@
package config
import (
"errors"
"fmt"
"time"
)
const (
// The relay runs by default so committed events reach Kafka without an
// extra switch. It still needs DATABASE_URL; without it bootstrap skips
// the relay with a warning.
defaultRelayEnabled = true
// defaultRelayBatchSize bounds the events one pass locks and publishes in
// one transaction.
defaultRelayBatchSize = 100
// maxRelayBatchSize keeps a pass, and the time its transaction holds row
// locks, short.
maxRelayBatchSize = 1000
// defaultRelayPollInterval is the wait after a pass that found nothing.
defaultRelayPollInterval = time.Second
minRelayPollInterval = 10 * time.Millisecond
maxRelayPollInterval = 5 * time.Minute
// defaultRelayProduceTimeout bounds one publish, during which the pass
// holds its transaction open.
defaultRelayProduceTimeout = 10 * time.Second
// minRelayProduceTimeout is the smallest record delivery timeout that
// franz-go accepts.
minRelayProduceTimeout = time.Second
maxRelayProduceTimeout = 2 * time.Minute
// defaultRelayStatementTimeout bounds each SQL statement of a pass. The
// claim reads one batch through the partial indexes and the mark updates
// at most one batch, so a healthy database answers well below it.
defaultRelayStatementTimeout = 5 * time.Second
minRelayStatementTimeout = 100 * time.Millisecond
maxRelayStatementTimeout = time.Minute
// The backoff after a failed pass starts at the initial delay, doubles
// per consecutive failure, and stops growing at the maximum.
defaultRelayBackoffInitial = 500 * time.Millisecond
defaultRelayBackoffMax = 30 * time.Second
maxRelayBackoff = 10 * time.Minute
)
func (config *Config) loadRelay(lookup LookupEnv) error {
var err error
if config.RelayEnabled, err = boolOrDefault(lookup, "RELAY_ENABLED", defaultRelayEnabled); err != nil {
return err
}
if config.RelayBatchSize, err = intOrDefault(lookup, "RELAY_BATCH_SIZE", defaultRelayBatchSize); err != nil {
return err
}
if config.RelayPollInterval, err = durationOrDefault(lookup, "RELAY_POLL_INTERVAL", defaultRelayPollInterval); err != nil {
return err
}
if config.RelayProduceTimeout, err = durationOrDefault(lookup, "RELAY_PRODUCE_TIMEOUT", defaultRelayProduceTimeout); err != nil {
return err
}
if config.RelayStatementTimeout, err = durationOrDefault(lookup, "RELAY_STATEMENT_TIMEOUT", defaultRelayStatementTimeout); err != nil {
return err
}
if config.RelayBackoffInitial, err = durationOrDefault(lookup, "RELAY_BACKOFF_INITIAL", defaultRelayBackoffInitial); err != nil {
return err
}
config.RelayBackoffMax, err = durationOrDefault(lookup, "RELAY_BACKOFF_MAX", defaultRelayBackoffMax)
return err
}
// ValidateRelay checks the relay settings even when the relay is disabled, so
// enabling it later cannot surface an old mistake.
func (config Config) ValidateRelay() error {
if config.RelayBatchSize < 1 || config.RelayBatchSize > maxRelayBatchSize {
return fmt.Errorf("Config.ValidateRelay - RELAY_BATCH_SIZE must be between 1 and %d", maxRelayBatchSize)
}
if config.RelayPollInterval < minRelayPollInterval || config.RelayPollInterval > maxRelayPollInterval {
return fmt.Errorf("Config.ValidateRelay - RELAY_POLL_INTERVAL must be between %s and %s", minRelayPollInterval, maxRelayPollInterval)
}
if config.RelayProduceTimeout < minRelayProduceTimeout || config.RelayProduceTimeout > maxRelayProduceTimeout {
return fmt.Errorf("Config.ValidateRelay - RELAY_PRODUCE_TIMEOUT must be between %s and %s", minRelayProduceTimeout, maxRelayProduceTimeout)
}
if config.RelayStatementTimeout < minRelayStatementTimeout || config.RelayStatementTimeout > maxRelayStatementTimeout {
return fmt.Errorf("Config.ValidateRelay - RELAY_STATEMENT_TIMEOUT must be between %s and %s", minRelayStatementTimeout, maxRelayStatementTimeout)
}
if config.RelayBackoffInitial <= 0 {
return errors.New("Config.ValidateRelay - RELAY_BACKOFF_INITIAL must be positive")
}
if config.RelayBackoffMax < config.RelayBackoffInitial || config.RelayBackoffMax > maxRelayBackoff {
return fmt.Errorf("Config.ValidateRelay - RELAY_BACKOFF_MAX must be between RELAY_BACKOFF_INITIAL and %s", maxRelayBackoff)
}
return nil
}
+112
View File
@@ -0,0 +1,112 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvRelayAndTopicDefaults(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(nil))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if !settings.RelayEnabled || settings.RelayBatchSize != 100 || settings.RelayPollInterval != time.Second ||
settings.RelayProduceTimeout != 10*time.Second || settings.RelayStatementTimeout != 5*time.Second || settings.RelayBackoffInitial != 500*time.Millisecond ||
settings.RelayBackoffMax != 30*time.Second {
t.Fatalf("unexpected relay defaults: enabled=%t batch=%d poll=%s produce=%s backoff=%s..%s",
settings.RelayEnabled, settings.RelayBatchSize, settings.RelayPollInterval,
settings.RelayProduceTimeout, settings.RelayBackoffInitial, settings.RelayBackoffMax)
}
if settings.KafkaEventsTopic != "lincodex.domain.events" || settings.KafkaEventsTopicPartitions != 3 ||
settings.KafkaEventsTopicReplicationFactor != -1 || settings.KafkaEventsTopicMinInsyncReplicas != 0 ||
!settings.KafkaProvisionTopics {
t.Fatalf("unexpected topic defaults: topic=%q partitions=%d replication=%d provision=%t",
settings.KafkaEventsTopic, settings.KafkaEventsTopicPartitions,
settings.KafkaEventsTopicReplicationFactor, settings.KafkaProvisionTopics)
}
}
func TestLoadFromEnvReadsRelayAndTopicSettings(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"RELAY_ENABLED": " FALSE ",
"RELAY_BATCH_SIZE": " 1000 ",
"RELAY_POLL_INTERVAL": "10ms",
"RELAY_PRODUCE_TIMEOUT": "2m",
"RELAY_STATEMENT_TIMEOUT": "1m",
"RELAY_BACKOFF_INITIAL": "1s",
"RELAY_BACKOFF_MAX": "1s",
"KAFKA_EVENTS_TOPIC": " Team_1.events-v2 ",
"KAFKA_EVENTS_TOPIC_PARTITIONS": "1000",
"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "3",
"KAFKA_PROVISION_TOPICS": "false",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.RelayEnabled || settings.RelayBatchSize != 1000 || settings.RelayPollInterval != 10*time.Millisecond ||
settings.RelayProduceTimeout != 2*time.Minute || settings.RelayStatementTimeout != time.Minute || settings.RelayBackoffInitial != time.Second ||
settings.RelayBackoffMax != time.Second {
t.Fatal("relay settings were not loaded")
}
if settings.KafkaEventsTopic != "Team_1.events-v2" || settings.KafkaEventsTopicPartitions != 1000 ||
settings.KafkaEventsTopicReplicationFactor != 3 || settings.KafkaProvisionTopics {
t.Fatal("topic settings were not loaded")
}
}
func TestLoadFromEnvRejectsRelayAndTopicSettings(t *testing.T) {
tests := []struct {
key, value, want string
}{
{key: "RELAY_ENABLED", value: "yes", want: "config.boolOrDefault - RELAY_ENABLED"},
{key: "RELAY_BATCH_SIZE", value: "", want: "config.intOrDefault - RELAY_BATCH_SIZE"},
{key: "RELAY_BATCH_SIZE", value: "ten", want: "config.intOrDefault - RELAY_BATCH_SIZE"},
{key: "RELAY_BATCH_SIZE", value: "0", want: "Config.ValidateRelay - RELAY_BATCH_SIZE"},
{key: "RELAY_BATCH_SIZE", value: "1001", want: "Config.ValidateRelay - RELAY_BATCH_SIZE"},
{key: "RELAY_POLL_INTERVAL", value: "soon", want: "config.durationOrDefault - parse RELAY_POLL_INTERVAL"},
{key: "RELAY_POLL_INTERVAL", value: "9ms", want: "Config.ValidateRelay - RELAY_POLL_INTERVAL"},
{key: "RELAY_POLL_INTERVAL", value: "6m", want: "Config.ValidateRelay - RELAY_POLL_INTERVAL"},
{key: "RELAY_PRODUCE_TIMEOUT", value: "999ms", want: "Config.ValidateRelay - RELAY_PRODUCE_TIMEOUT"},
{key: "RELAY_PRODUCE_TIMEOUT", value: "3m", want: "Config.ValidateRelay - RELAY_PRODUCE_TIMEOUT"},
{key: "RELAY_STATEMENT_TIMEOUT", value: "99ms", want: "Config.ValidateRelay - RELAY_STATEMENT_TIMEOUT"},
{key: "RELAY_STATEMENT_TIMEOUT", value: "61s", want: "Config.ValidateRelay - RELAY_STATEMENT_TIMEOUT"},
{key: "RELAY_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateRelay - RELAY_BACKOFF_INITIAL"},
{key: "RELAY_BACKOFF_MAX", value: "100ms", want: "Config.ValidateRelay - RELAY_BACKOFF_MAX"},
{key: "RELAY_BACKOFF_MAX", value: "11m", want: "Config.ValidateRelay - RELAY_BACKOFF_MAX"},
{key: "RELAY_BACKOFF_INITIAL", value: "40s", want: "Config.ValidateRelay - RELAY_BACKOFF_MAX"},
{key: "KAFKA_EVENTS_TOPIC", value: "", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"},
{key: "KAFKA_EVENTS_TOPIC", value: "..", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"},
{key: "KAFKA_EVENTS_TOPIC", value: "domain events", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"},
{key: "KAFKA_EVENTS_TOPIC", value: "events/secret", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"},
{key: "KAFKA_EVENTS_TOPIC", value: strings.Repeat("a", 250), want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"},
{key: "KAFKA_EVENTS_TOPIC_PARTITIONS", value: "0", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_PARTITIONS"},
{key: "KAFKA_EVENTS_TOPIC_PARTITIONS", value: "1001", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_PARTITIONS"},
{key: "KAFKA_EVENTS_TOPIC_PARTITIONS", value: "many", want: "config.intOrDefault - KAFKA_EVENTS_TOPIC_PARTITIONS"},
{key: "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR", value: "0", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR"},
{key: "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR", value: "32768", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR"},
{key: "KAFKA_PROVISION_TOPICS", value: "1", want: "config.boolOrDefault - KAFKA_PROVISION_TOPICS"},
}
for _, test := range tests {
t.Run(test.key+"/"+test.value, func(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want)
}
if strings.Contains(err.Error(), "secret") {
t.Fatal("configuration error disclosed the value")
}
})
}
}
func TestValidateRelayChecksSettingsEvenWhenDisabled(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"RELAY_ENABLED": "false"}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
settings.RelayBatchSize = 0
if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateRelay - RELAY_BATCH_SIZE") {
t.Fatalf("Validate() error = %v, want the relay batch size error", err)
}
}
@@ -0,0 +1,13 @@
-- +goose Up
-- Supports the relay check that an outbox row is the earliest unpublished
-- event of its aggregate. The relay publishes only that row for each
-- aggregate per pass, so the check runs once for every candidate row. Without
-- this index the lookup reads every published event of the aggregate through
-- the unique key. The index covers only unpublished rows and shrinks as
-- events are published.
CREATE INDEX outbox_events_unpublished_aggregate_idx
ON outbox_events (aggregate_type, aggregate_id, aggregate_version, position)
WHERE published_at IS NULL;
-- +goose Down
DROP INDEX outbox_events_unpublished_aggregate_idx;
+79
View File
@@ -16,3 +16,82 @@ INSERT INTO outbox_events (
sqlc.arg(aggregate_version),
sqlc.arg(payload)
);
-- Locks the next relay batch. For each aggregate only its earliest unpublished
-- event (lowest aggregate_version, then position) qualifies, so a relay never
-- holds a later version while an earlier one is still pending, whether that
-- earlier row is locked by another relay or was just rolled back. Rows locked
-- by another relay are skipped without waiting. The statement snapshot can
-- only see a later version after the earlier version's transaction committed,
-- because aggregate writers check the expected version, so scanning without a
-- position watermark cannot overtake an earlier version.
-- name: LockPendingOutboxEvents :many
SELECT
pending.event_id,
pending.event_type,
pending.schema_version,
pending.aggregate_type,
pending.aggregate_id,
pending.aggregate_version,
pending.payload,
pending.occurred_at
FROM outbox_events AS pending
WHERE
pending.published_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM outbox_events AS earlier
WHERE
earlier.aggregate_type = pending.aggregate_type
AND earlier.aggregate_id = pending.aggregate_id
AND earlier.published_at IS NULL
AND (earlier.aggregate_version, earlier.position)
< (pending.aggregate_version, pending.position)
)
ORDER BY pending.position
LIMIT sqlc.arg(batch_limit)
FOR UPDATE OF pending SKIP LOCKED;
-- Marks the events that the broker acknowledged. The relay passes only IDs
-- whose rows its own transaction locked, so the statement never waits and the
-- count equals the number of distinct IDs.
-- name: MarkOutboxEventsPublished :execrows
UPDATE outbox_events
SET published_at = clock_timestamp()
WHERE
event_id = ANY(sqlc.arg(event_ids)::uuid [])
AND published_at IS NULL;
-- Reads the relay backlog for metrics without locking. Both subqueries use
-- the partial index on unpublished positions, so the cost follows the backlog
-- size, not the table size. The age comes from the database clock, the same
-- clock that set occurred_at.
-- name: GetOutboxBacklog :one
SELECT
(
SELECT count(*)
FROM outbox_events AS pending
WHERE pending.published_at IS NULL
)::bigint AS pending_events,
coalesce((
SELECT extract(EPOCH FROM clock_timestamp() - oldest.occurred_at)
FROM outbox_events AS oldest
WHERE oldest.published_at IS NULL
ORDER BY oldest.position
LIMIT 1
), 0)::float8 AS oldest_pending_age_seconds;
-- Bounds the claim transaction on the server. statement_timeout stops a
-- statement that runs too long; idle_in_transaction_session_timeout ends the
-- session, and with it the transaction and its row locks, when the client
-- stays silent longer than a publish may take, for example after the process
-- froze or lost the network without closing the connection. Both settings
-- are local to the transaction.
-- name: SetRelayTransactionTimeouts :exec
SELECT
set_config('statement_timeout', sqlc.arg(statement_timeout_ms)::text, true),
set_config(
'idle_in_transaction_session_timeout',
sqlc.arg(idle_timeout_ms)::text,
true
);
+1 -1
View File
@@ -14,6 +14,7 @@ require (
github.com/goforj/wire v1.2.0
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/moby/moby/client v0.5.1
github.com/ogen-go/ogen v1.24.0
github.com/pressly/goose/v3 v3.28.0
github.com/prometheus/client_golang v1.24.1
@@ -255,7 +256,6 @@ require (
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.3.0 // indirect
github.com/moby/moby/api v1.55.0 // indirect
github.com/moby/moby/client v0.5.1 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.1 // indirect
@@ -10,6 +10,8 @@ import (
"testing"
"time"
"github.com/moby/moby/client"
"github.com/testcontainers/testcontainers-go"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
@@ -150,3 +152,42 @@ func waitForKafkaTopicDeletion(ctx context.Context, t *testing.T, admin *kadm.Cl
}
}
}
// pauseKafka freezes the broker without closing its port, so clients see a
// broker that accepts connections and never answers. A stopped container
// would come back on a different host port, which the advertised listener
// and the clients' seed brokers do not follow. The returned function resumes
// the broker; cleanup also resumes it so the container can be terminated.
func (env *testEnvironment) pauseKafka(ctx context.Context, t *testing.T) (resume func()) {
t.Helper()
if env.kafkaContainer == nil {
t.Fatal("Kafka was not selected in bootstrap")
}
docker, err := testcontainers.NewDockerClientWithOpts(ctx)
if err != nil {
t.Fatalf("create Docker client: %v", err)
}
t.Cleanup(func() { _ = docker.Close() })
containerID := env.kafkaContainer.GetContainerID()
pauseCtx, cancel := context.WithTimeout(ctx, stopTimeout)
defer cancel()
if _, err := docker.ContainerPause(pauseCtx, containerID, client.ContainerPauseOptions{}); err != nil {
t.Fatalf("pause Kafka: %v", err)
}
paused := true
resume = func() {
t.Helper()
if !paused {
return
}
resumeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), stopTimeout)
defer cancel()
if _, err := docker.ContainerUnpause(resumeCtx, containerID, client.ContainerUnpauseOptions{}); err != nil {
t.Errorf("resume Kafka: %v", err)
return
}
paused = false
}
t.Cleanup(resume)
return resume
}
@@ -0,0 +1,767 @@
//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"
)
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: outboxrelay.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)
}
}
}
+11 -5
View File
@@ -543,7 +543,17 @@ func accountPayload(account testAccount) []byte {
func newAccountEvent(t *testing.T, account testAccount) domain.DomainEvent {
t.Helper()
event, err := domain.NewDomainEvent(domain.DomainEventInput{
event, err := newAccountEventE(account)
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
return event
}
// newAccountEventE is newAccountEvent for goroutines, which must not call
// t.Fatal.
func newAccountEventE(account testAccount) (domain.DomainEvent, error) {
return domain.NewDomainEvent(domain.DomainEventInput{
EventType: testAccountEventType,
SchemaVersion: testEventSchema,
AggregateType: testAggregateType,
@@ -551,10 +561,6 @@ func newAccountEvent(t *testing.T, account testAccount) domain.DomainEvent {
AggregateVersion: account.version,
Payload: accountPayload(account),
})
if err != nil {
t.Fatalf("NewDomainEvent() error = %v", err)
}
return event
}
func readOutboxEvents(ctx context.Context, t *testing.T, pool *pgxpool.Pool) []storedEvent {
@@ -0,0 +1,76 @@
package kafka
import (
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/google/uuid"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/internal/port/outbound"
)
// EnvelopeVersion identifies the layout of the record value. It changes only
// when envelope fields change; the payload layout of each event type is
// versioned separately by schema_version.
const EnvelopeVersion = 1
// Record header names. Consumers can route and deduplicate on headers without
// decoding the value.
const (
headerEventID = "event_id"
headerEventType = "event_type"
headerSchemaVersion = "schema_version"
)
// recordKeySeparator joins the aggregate type and ID in the record key.
// Aggregate types are snake_case, so the separator cannot occur in them.
const recordKeySeparator = ":"
// envelope is the JSON record value. Field names are part of the published
// contract; see the transactional outbox section of ARCHITECTURE.md.
type envelope 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"`
}
// newRecord builds the Kafka record for event. The key is the aggregate type
// and ID, so the default partitioner keeps all events of one aggregate in one
// partition and their relative order.
func newRecord(topic string, event outbound.OutboxEvent) (*kgo.Record, error) {
value, err := json.Marshal(envelope{
EnvelopeVersion: EnvelopeVersion,
EventID: event.EventID,
EventType: event.EventType,
SchemaVersion: event.SchemaVersion,
AggregateType: event.AggregateType,
AggregateID: event.AggregateID,
AggregateVersion: event.AggregateVersion,
OccurredAt: event.OccurredAt.UTC(),
Payload: event.Payload,
})
if err != nil {
// json.Marshal reports only the invalid payload position, not its
// content, but the cause is dropped to keep payload text out of logs.
return nil, fmt.Errorf("kafka.newRecord - encode envelope of event %s: payload is not valid JSON", event.EventID)
}
return &kgo.Record{
Topic: topic,
Key: []byte(event.AggregateType + recordKeySeparator + event.AggregateID.String()),
Value: value,
Headers: []kgo.RecordHeader{
{Key: headerEventID, Value: []byte(event.EventID.String())},
{Key: headerEventType, Value: []byte(event.EventType)},
{Key: headerSchemaVersion, Value: []byte(strconv.FormatInt(int64(event.SchemaVersion), 10))},
},
}, nil
}
@@ -0,0 +1,105 @@
package kafka
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
const testTopic = "lincodex.domain.events"
func testEvent() outbound.OutboxEvent {
return outbound.OutboxEvent{
EventID: uuid.MustParse("01920000-0000-7000-8000-000000000001"),
EventType: "identity.user_registered",
SchemaVersion: 2,
AggregateType: "user",
AggregateID: uuid.MustParse("6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a"),
AggregateVersion: 7,
// jsonb text output, as PostgreSQL returns it.
Payload: json.RawMessage(`{"user_id": "6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a", "nested": {"n": 1}}`),
OccurredAt: time.Date(2026, 10, 6, 12, 30, 0, 123456000, time.FixedZone("UTC+3", 3*60*60)),
}
}
func TestNewRecordEncodesTheEnvelope(t *testing.T) {
record, err := newRecord(testTopic, testEvent())
if err != nil {
t.Fatalf("newRecord() error = %v", err)
}
if record.Topic != testTopic {
t.Fatalf("topic = %q, want %q", record.Topic, testTopic)
}
if got, want := string(record.Key), "user:6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a"; got != want {
t.Fatalf("key = %q, want %q", got, want)
}
want := `{"envelope_version":1,"event_id":"01920000-0000-7000-8000-000000000001",` +
`"event_type":"identity.user_registered","schema_version":2,"aggregate_type":"user",` +
`"aggregate_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","aggregate_version":7,` +
`"occurred_at":"2026-10-06T09:30:00.123456Z",` +
`"payload":{"user_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","nested":{"n":1}}}`
if string(record.Value) != want {
t.Fatalf("value =\n%s\nwant\n%s", record.Value, want)
}
headers := make(map[string]string, len(record.Headers))
for _, header := range record.Headers {
headers[header.Key] = string(header.Value)
}
wantHeaders := map[string]string{
"event_id": "01920000-0000-7000-8000-000000000001",
"event_type": "identity.user_registered",
"schema_version": "2",
}
if len(headers) != len(wantHeaders) || len(record.Headers) != len(wantHeaders) {
t.Fatalf("headers = %v, want %v", headers, wantHeaders)
}
for key, value := range wantHeaders {
if headers[key] != value {
t.Fatalf("header %s = %q, want %q", key, headers[key], value)
}
}
}
func TestNewRecordKeepsAggregatesOnSeparateKeys(t *testing.T) {
first := testEvent()
sameAggregate := testEvent()
sameAggregate.EventID = uuid.New()
sameAggregate.AggregateVersion++
otherType := testEvent()
otherType.AggregateType = "company"
keys := make([]string, 0, 3)
for _, event := range []outbound.OutboxEvent{first, sameAggregate, otherType} {
record, err := newRecord(testTopic, event)
if err != nil {
t.Fatalf("newRecord() error = %v", err)
}
keys = append(keys, string(record.Key))
}
if keys[0] != keys[1] {
t.Fatalf("versions of one aggregate have keys %q and %q, want one key", keys[0], keys[1])
}
if keys[0] == keys[2] {
t.Fatalf("aggregates of different types share key %q", keys[0])
}
}
func TestNewRecordRejectsAnInvalidPayloadWithoutQuotingIt(t *testing.T) {
event := testEvent()
event.Payload = json.RawMessage(`{"token": "secret-value"`)
_, err := newRecord(testTopic, event)
if err == nil {
t.Fatal("newRecord() accepted an invalid payload")
}
if strings.Contains(err.Error(), "secret-value") {
t.Fatalf("newRecord() error quotes the payload: %v", err)
}
if !strings.Contains(err.Error(), event.EventID.String()) {
t.Fatalf("newRecord() error = %v, want the event ID", err)
}
}
@@ -0,0 +1,219 @@
package kafka
import (
"context"
"errors"
"fmt"
"log/slog"
"strconv"
"sync/atomic"
"time"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kgo"
"lincodex/backend/config"
"lincodex/backend/internal/port/outbound"
)
// maxRecordRetries bounds the client's own retries of one record within a
// publish call. The relay retries unacknowledged events on later passes, so
// the client does not need to retry indefinitely.
const maxRecordRetries = 5
// errNotAcknowledged reports an event whose broker acknowledgement did not
// arrive before the publish deadline. The broker may still have stored it.
var errNotAcknowledged = errors.New("event not acknowledged before the publish deadline")
// minInsyncReplicasConfig is the topic setting that acks=all writes need from
// the in-sync replicas.
const minInsyncReplicasConfig = "min.insync.replicas"
// Publisher implements outbound.EventPublisher with a franz-go producer. All
// events go to one topic; the record key keeps each aggregate's events in one
// partition.
type Publisher struct {
client *kgo.Client
admin *kadm.Client
logger *slog.Logger
topic string
partitions int32
replicationFactor int16
minInsyncReplicas int16
provisionTopics bool
produceTimeout time.Duration
// layoutReported keeps the warning about an existing topic with another
// layout to one log line per process.
layoutReported atomic.Bool
}
var _ outbound.EventPublisher = (*Publisher)(nil)
// NewPublisher creates the producer without connecting; franz-go dials brokers
// on first use, so an unavailable broker does not block startup. The returned
// cleanup closes the client and fails records that are still buffered.
func NewPublisher(settings config.Config, logger *slog.Logger) (*Publisher, func(), error) {
client, err := kgo.NewClient(
kgo.SeedBrokers(settings.KafkaBrokers...),
// Idempotent writes stay enabled (the franz-go default), which needs
// acks from all in-sync replicas.
kgo.RequiredAcks(kgo.AllISRAcks()),
// Without this option an idempotent record that is already in flight
// cannot be failed until the broker answers, so a hung broker would
// hold the relay transaction open indefinitely. Failing it keeps the
// publish deadline; a retried event may then be stored twice, which
// the at-least-once contract already allows.
kgo.AllowIdempotentProduceCancellation(),
kgo.RecordDeliveryTimeout(settings.RelayProduceTimeout),
kgo.RecordRetries(maxRecordRetries),
// Linger would delay every pass by its full value, because a pass
// produces its whole batch at once and then only waits. Without it the
// first record leaves at once and franz-go batches the records produced
// while that request is in flight (up to five idempotent requests per
// broker), so a pass needs a few requests at most.
kgo.ProducerLinger(0),
)
if err != nil {
return nil, nil, fmt.Errorf("kafka.NewPublisher - create Kafka client: %w", err)
}
publisher := &Publisher{
client: client,
admin: kadm.NewClient(client),
logger: logger,
topic: settings.KafkaEventsTopic,
partitions: settings.KafkaEventsTopicPartitions,
replicationFactor: settings.KafkaEventsTopicReplicationFactor,
minInsyncReplicas: settings.KafkaEventsTopicMinInsyncReplicas,
provisionTopics: settings.KafkaProvisionTopics,
produceTimeout: settings.RelayProduceTimeout,
}
return publisher, client.Close, nil
}
// Prepare creates the events topic with the configured partitions,
// replication factor, and min.insync.replicas unless it already exists; -1
// and 0 leave the last two to the broker defaults. It does not change an
// existing topic and warns once when that topic has another partition count
// or replication factor. With topic provisioning disabled it does nothing,
// and a missing topic makes every publish fail.
func (publisher *Publisher) Prepare(ctx context.Context) error {
if !publisher.provisionTopics {
return nil
}
ctx, cancel := context.WithTimeout(ctx, publisher.produceTimeout)
defer cancel()
var topicConfigs map[string]*string
if publisher.minInsyncReplicas > 0 {
value := strconv.Itoa(int(publisher.minInsyncReplicas))
topicConfigs = map[string]*string{minInsyncReplicasConfig: &value}
}
responses, err := publisher.admin.CreateTopics(ctx, publisher.partitions, publisher.replicationFactor, topicConfigs, publisher.topic)
if err != nil {
return fmt.Errorf("Publisher.Prepare - create topic %s: %w", publisher.topic, err)
}
response, err := responses.On(publisher.topic, nil)
if err != nil {
return fmt.Errorf("Publisher.Prepare - read create topic response for %s: %w", publisher.topic, err)
}
if response.Err != nil && !errors.Is(response.Err, kerr.TopicAlreadyExists) {
return fmt.Errorf("Publisher.Prepare - create topic %s: %w", publisher.topic, response.Err)
}
if response.Err != nil {
publisher.reportExistingLayout(ctx)
}
return nil
}
// reportExistingLayout warns once when the existing topic differs from the
// configured layout. The check is advisory: a failed metadata read leaves the
// topic as it is and logs nothing.
func (publisher *Publisher) reportExistingLayout(ctx context.Context) {
if publisher.layoutReported.Load() {
return
}
topics, err := publisher.admin.ListTopics(ctx, publisher.topic)
if err != nil {
return
}
detail, ok := topics[publisher.topic]
if !ok || detail.Err != nil {
return
}
partitions, replicas, differs := layoutDiffers(detail, publisher.partitions, publisher.replicationFactor)
if differs && publisher.layoutReported.CompareAndSwap(false, true) {
publisher.logger.Warn("existing events topic differs from the configured layout; the relay does not change it",
slog.Int("partitions", partitions),
slog.Int("configured_partitions", int(publisher.partitions)),
slog.Int("replication_factor", replicas),
slog.Int("configured_replication_factor", int(publisher.replicationFactor)),
)
}
}
// layoutDiffers compares an existing topic with the configured partition
// count and replication factor. A replication factor of -1 accepts any
// broker default.
func layoutDiffers(detail kadm.TopicDetail, partitions int32, replicationFactor int16) (actualPartitions, actualReplicas int, differs bool) {
actualPartitions = len(detail.Partitions)
actualReplicas = detail.Partitions.NumReplicas()
differs = actualPartitions != int(partitions) ||
(replicationFactor > 0 && actualReplicas != int(replicationFactor))
return actualPartitions, actualReplicas, differs
}
// Publish produces every event and waits at most the produce timeout for the
// acknowledgements. Results that do not arrive in time stay errors; the
// promises of abandoned records write to a buffered channel and never block.
func (publisher *Publisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
results := make([]error, len(events))
if len(events) == 0 {
return results
}
ctx, cancel := context.WithTimeout(ctx, publisher.produceTimeout)
defer cancel()
type outcome struct {
index int
err error
}
outcomes := make(chan outcome, len(events))
for index, event := range events {
results[index] = errNotAcknowledged
record, err := newRecord(publisher.topic, event)
if err != nil {
outcomes <- outcome{index: index, err: err}
continue
}
publisher.client.Produce(ctx, record, func(_ *kgo.Record, err error) {
outcomes <- outcome{index: index, err: err}
})
}
for range events {
select {
case result := <-outcomes:
results[result.index] = nil
if result.err != nil {
results[result.index] = produceError(events[result.index], result.err)
}
case <-ctx.Done():
for index, err := range results {
if errors.Is(err, errNotAcknowledged) {
results[index] = fmt.Errorf("Publisher.Publish - produce event %s: %w: %w", events[index].EventID, errNotAcknowledged, ctx.Err())
}
}
return results
}
}
return results
}
// produceError wraps a failed record. A missing topic also matches
// outbound.ErrEventDestinationMissing, so the relay provisions it again.
func produceError(event outbound.OutboxEvent, err error) error {
if errors.Is(err, kerr.UnknownTopicOrPartition) || errors.Is(err, kerr.UnknownTopicID) {
return fmt.Errorf("Publisher.Publish - produce event %s: %w: %w", event.EventID, outbound.ErrEventDestinationMissing, err)
}
return fmt.Errorf("Publisher.Publish - produce event %s: %w", event.EventID, err)
}
@@ -0,0 +1,151 @@
package kafka
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"testing"
"time"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kerr"
"lincodex/backend/config"
"lincodex/backend/internal/port/outbound"
)
const (
unitProduceTimeout = time.Second
// publishBoundSlack covers scheduling around the produce timeout.
publishBoundSlack = 2 * time.Second
)
// unreachableBroker returns the address of a closed local port, so every
// connection attempt is refused.
func unreachableBroker(t *testing.T) string {
t.Helper()
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
address := listener.Addr().String()
if err := listener.Close(); err != nil {
t.Fatalf("close listener: %v", err)
}
return address
}
func newUnitPublisher(t *testing.T, provision bool) *Publisher {
t.Helper()
publisher, cleanup, err := NewPublisher(config.Config{
KafkaBrokers: []string{unreachableBroker(t)},
KafkaEventsTopic: testTopic,
KafkaEventsTopicPartitions: 1,
KafkaEventsTopicReplicationFactor: 1,
KafkaProvisionTopics: provision,
RelayProduceTimeout: unitProduceTimeout,
}, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewPublisher() error = %v", err)
}
t.Cleanup(cleanup)
return publisher
}
func TestPublishFailsEveryEventWithinTheProduceTimeoutWhenBrokersAreDown(t *testing.T) {
publisher := newUnitPublisher(t, true)
events := []outbound.OutboxEvent{testEvent(), testEvent()}
events[1].AggregateVersion++
started := time.Now()
results := publisher.Publish(context.Background(), events)
if elapsed := time.Since(started); elapsed > unitProduceTimeout+publishBoundSlack {
t.Fatalf("Publish() took %s, want about the %s produce timeout", elapsed, unitProduceTimeout)
}
if len(results) != len(events) {
t.Fatalf("Publish() returned %d results for %d events", len(results), len(events))
}
for index, err := range results {
if err == nil {
t.Fatalf("event %d acknowledged without a broker", index)
}
}
}
func TestPublishReportsAnUnencodableEventWithoutDroppingOthers(t *testing.T) {
publisher := newUnitPublisher(t, true)
invalid := testEvent()
invalid.Payload = []byte(`{`)
results := publisher.Publish(context.Background(), []outbound.OutboxEvent{invalid, testEvent()})
if len(results) != 2 || results[0] == nil || results[1] == nil {
t.Fatalf("Publish() results = %v, want two errors", results)
}
if errors.Is(results[0], errNotAcknowledged) {
t.Fatalf("encoding failure reported as a timeout: %v", results[0])
}
}
func TestPublishWithoutEventsDoesNothing(t *testing.T) {
publisher := newUnitPublisher(t, true)
if results := publisher.Publish(context.Background(), nil); len(results) != 0 {
t.Fatalf("Publish(nil) = %v, want no results", results)
}
}
func TestPrepareSkipsProvisioningWhenDisabled(t *testing.T) {
publisher := newUnitPublisher(t, false)
if err := publisher.Prepare(context.Background()); err != nil {
t.Fatalf("Prepare() error = %v, want nil without contacting the broker", err)
}
}
func TestPrepareFailsWithinTheTimeoutWhenBrokersAreDown(t *testing.T) {
publisher := newUnitPublisher(t, true)
started := time.Now()
if err := publisher.Prepare(context.Background()); err == nil {
t.Fatal("Prepare() created a topic without a broker")
}
if elapsed := time.Since(started); elapsed > unitProduceTimeout+publishBoundSlack {
t.Fatalf("Prepare() took %s, want about the %s timeout", elapsed, unitProduceTimeout)
}
}
func TestProduceErrorMarksAMissingTopic(t *testing.T) {
event := testEvent()
for _, cause := range []error{kerr.UnknownTopicOrPartition, fmt.Errorf("load metadata: %w", kerr.UnknownTopicID)} {
if err := produceError(event, cause); !errors.Is(err, outbound.ErrEventDestinationMissing) || !errors.Is(err, cause) {
t.Fatalf("produceError(%v) = %v, want ErrEventDestinationMissing and the cause", cause, err)
}
}
if err := produceError(event, kerr.NotEnoughReplicas); errors.Is(err, outbound.ErrEventDestinationMissing) {
t.Fatalf("produceError(NotEnoughReplicas) = %v, want no missing destination", err)
}
}
func TestLayoutDiffersComparesPartitionsAndExplicitReplication(t *testing.T) {
detail := kadm.TopicDetail{Partitions: kadm.PartitionDetails{
0: {Partition: 0, Replicas: []int32{1, 2, 3}},
1: {Partition: 1, Replicas: []int32{2, 3, 1}},
}}
tests := []struct {
name string
partitions int32
replicationFactor int16
want bool
}{
{name: "same layout", partitions: 2, replicationFactor: 3, want: false},
{name: "broker default replication", partitions: 2, replicationFactor: -1, want: false},
{name: "other partition count", partitions: 3, replicationFactor: -1, want: true},
{name: "other replication factor", partitions: 2, replicationFactor: 1, want: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
partitions, replicas, differs := layoutDiffers(detail, test.partitions, test.replicationFactor)
if differs != test.want || partitions != 2 || replicas != 3 {
t.Fatalf("layoutDiffers() = %d, %d, %t; want 2, 3, %t", partitions, replicas, differs, test.want)
}
})
}
}
@@ -0,0 +1,181 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/port/outbound"
)
// OutboxRelayStore implements outbound.OutboxRelayStore with a pgx pool owned
// by the caller. Each claim holds one connection and one transaction for the
// duration of the publish callback.
type OutboxRelayStore struct {
pool *pgxpool.Pool
timeouts OutboxRelayTimeouts
}
// OutboxRelayTimeouts bound the claim transaction on the PostgreSQL server.
//
// The relay context already cancels a pass whose client is alive. These
// limits are set with SET LOCAL at the start of the transaction because they
// also hold when the client cannot act: a frozen process, or a network path
// that drops without closing the connection, would otherwise keep the row
// locks and an open transaction until TCP keepalive notices, which delays
// other relays and vacuum.
type OutboxRelayTimeouts struct {
// Statement bounds every statement of the claim (statement_timeout).
Statement time.Duration
// IdleInTransaction bounds the gap between statements, which is the
// publish call (idle_in_transaction_session_timeout). It must exceed the
// publish deadline, or a slow but successful publish loses its mark.
IdleInTransaction time.Duration
}
func NewOutboxRelayStore(pool *pgxpool.Pool, timeouts OutboxRelayTimeouts) *OutboxRelayStore {
return &OutboxRelayStore{pool: pool, timeouts: timeouts}
}
var _ outbound.OutboxRelayStore = (*OutboxRelayStore)(nil)
func (store *OutboxRelayStore) ClaimPending(ctx context.Context, limit int, publish outbound.PublishOutboxBatch) error {
if limit <= 0 || limit > math.MaxInt32 {
return fmt.Errorf("OutboxRelayStore.ClaimPending - limit must be between 1 and %d", math.MaxInt32)
}
// PostgreSQL reads 0 as no limit, so a value below one millisecond would
// silently remove the bound.
if store.timeouts.Statement < time.Millisecond || store.timeouts.IdleInTransaction < time.Millisecond {
return errors.New("OutboxRelayStore.ClaimPending - statement and idle timeouts must be at least 1ms")
}
tx, err := store.pool.BeginTx(ctx, transactionOptions)
if err != nil {
return fmt.Errorf("OutboxRelayStore.ClaimPending - begin transaction: %w", sanitizeConnectError(err))
}
finished := false
defer func() {
// Runs only when publish panics; the panic keeps its stack and the
// rollback error cannot change that outcome.
if !finished {
_ = rollback(ctx, tx)
}
}()
claimErr := claimPending(ctx, tx, int32(limit), store.timeouts, publish)
finished = true
if claimErr != nil {
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
return errors.Join(claimErr, fmt.Errorf("OutboxRelayStore.ClaimPending - roll back transaction: %w", rollbackErr))
}
return claimErr
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", relayDatabaseError(err))
}
return nil
}
func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRelayTimeouts, publish outbound.PublishOutboxBatch) error {
queries := sqlc.New(tx)
err := queries.SetRelayTransactionTimeouts(ctx, sqlc.SetRelayTransactionTimeoutsParams{
StatementTimeoutMs: milliseconds(timeouts.Statement),
IdleTimeoutMs: milliseconds(timeouts.IdleInTransaction),
})
if err != nil {
return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", relayDatabaseError(err))
}
rows, err := queries.LockPendingOutboxEvents(ctx, limit)
if err != nil {
return fmt.Errorf("postgres.claimPending - lock pending events: %w", relayDatabaseError(err))
}
if len(rows) == 0 {
return nil
}
events := make([]outbound.OutboxEvent, 0, len(rows))
claimed := make(map[uuid.UUID]bool, len(rows))
for _, row := range rows {
event := outboxEventFromRow(row)
events = append(events, event)
claimed[event.EventID] = true
}
acknowledged := publish(ctx, events)
marked := make([]pgtype.UUID, 0, len(acknowledged))
seen := make(map[uuid.UUID]bool, len(acknowledged))
for _, eventID := range acknowledged {
// An ID outside the batch could be locked by another relay, and the
// update would wait for it, so it is a caller error.
if !claimed[eventID] {
return errors.New("postgres.claimPending - acknowledged event is not in the claimed batch")
}
if seen[eventID] {
continue
}
seen[eventID] = true
marked = append(marked, pgtype.UUID{Bytes: eventID, Valid: true})
}
if len(marked) == 0 {
return nil
}
count, err := queries.MarkOutboxEventsPublished(ctx, marked)
if err != nil {
return fmt.Errorf("postgres.claimPending - mark published events: %w", relayDatabaseError(err))
}
if count != int64(len(marked)) {
return fmt.Errorf("postgres.claimPending - marked %d events, want %d", count, len(marked))
}
return nil
}
// Backlog reads the pending count and the age of the earliest pending event.
func (store *OutboxRelayStore) Backlog(ctx context.Context) (outbound.OutboxBacklog, error) {
row, err := sqlc.New(store.pool).GetOutboxBacklog(ctx)
if err != nil {
return outbound.OutboxBacklog{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", relayDatabaseError(err))
}
return outbound.OutboxBacklog{
Pending: row.PendingEvents,
OldestAge: time.Duration(row.OldestPendingAgeSeconds * float64(time.Second)),
}, nil
}
// milliseconds formats a duration as a PostgreSQL time setting in
// milliseconds, the unit set_config assumes for these parameters.
func milliseconds(duration time.Duration) string {
return strconv.FormatInt(duration.Milliseconds(), 10)
}
func outboxEventFromRow(row sqlc.LockPendingOutboxEventsRow) outbound.OutboxEvent {
return outbound.OutboxEvent{
EventID: row.EventID.Bytes,
EventType: row.EventType,
SchemaVersion: row.SchemaVersion,
AggregateType: row.AggregateType,
AggregateID: row.AggregateID.Bytes,
AggregateVersion: row.AggregateVersion,
Payload: json.RawMessage(row.Payload),
OccurredAt: row.OccurredAt.Time,
}
}
// relayDatabaseError keeps only the SQLSTATE of a PostgreSQL error, whose
// message or detail could quote an event payload, and drops the connection
// prefix of a connect error.
func relayDatabaseError(err error) error {
var pgError *pgconn.PgError
if errors.As(err, &pgError) {
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
return sanitizeConnectError(err)
}
@@ -0,0 +1,57 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/port/outbound"
)
func TestClaimPendingRejectsAnInvalidLimitBeforeTheDatabase(t *testing.T) {
// A nil pool proves that validation happens before any connection.
valid := OutboxRelayTimeouts{Statement: time.Second, IdleInTransaction: time.Second}
publish := func(context.Context, []outbound.OutboxEvent) []uuid.UUID {
t.Fatal("publish called for an invalid claim")
return nil
}
store := NewOutboxRelayStore(nil, valid)
for _, limit := range []int{0, -1, 1 << 31} {
if err := store.ClaimPending(t.Context(), limit, publish); err == nil {
t.Fatalf("ClaimPending(limit %d) accepted the limit", limit)
}
}
// A timeout that rounds to 0 ms would disable the server-side bound.
for _, timeouts := range []OutboxRelayTimeouts{
{Statement: time.Microsecond, IdleInTransaction: time.Second},
{Statement: time.Second},
} {
if err := NewOutboxRelayStore(nil, timeouts).ClaimPending(t.Context(), 1, publish); err == nil {
t.Fatalf("ClaimPending() accepted timeouts %+v", timeouts)
}
}
}
func TestRelayDatabaseErrorKeepsOnlyTheSQLState(t *testing.T) {
original := &pgconn.PgError{
Code: "22P02",
Message: `invalid input syntax for type json: "secret-payload"`,
Detail: `Token "secret-payload" is invalid.`,
}
err := relayDatabaseError(original)
if strings.Contains(err.Error(), "secret-payload") {
t.Fatalf("relayDatabaseError() kept the message: %v", err)
}
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != "22P02" {
t.Fatalf("relayDatabaseError() = %v, want SQLSTATE 22P02", err)
}
if conflict := relayDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) {
t.Fatalf("relayDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict)
}
}
@@ -15,11 +15,9 @@ import (
// requires the database before serving. The caller owns the pool and must
// close it.
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
poolConfig, err := pgxpool.ParseConfig(databaseURL)
poolConfig, err := parsePoolConfig(databaseURL)
if err != nil {
// pgx redacts passwords only on a best-effort basis, so the parse error
// is not wrapped to keep the connection string out of logs.
return nil, errors.New("postgres.NewPool - DATABASE_URL is not a valid PostgreSQL connection string")
return nil, err
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
@@ -28,6 +26,35 @@ func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
return pool, nil
}
// NewSizedPool is NewPool with at most maxConns connections, for a component
// whose concurrency is known, so it cannot take connections that request
// handling needs.
func NewSizedPool(ctx context.Context, databaseURL string, maxConns int32) (*pgxpool.Pool, error) {
if maxConns < 1 {
return nil, errors.New("postgres.NewSizedPool - maxConns must be positive")
}
poolConfig, err := parsePoolConfig(databaseURL)
if err != nil {
return nil, err
}
poolConfig.MaxConns = maxConns
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("postgres.NewSizedPool - create PostgreSQL pool: %w", err)
}
return pool, nil
}
func parsePoolConfig(databaseURL string) (*pgxpool.Config, error) {
poolConfig, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
// pgx redacts passwords only on a best-effort basis, so the parse error
// is not wrapped to keep the connection string out of logs.
return nil, errors.New("postgres.parsePoolConfig - DATABASE_URL is not a valid PostgreSQL connection string")
}
return poolConfig, nil
}
// sanitizeConnectError drops the pgx connection prefix, which names the
// database user and database, while keeping the network or server cause.
func sanitizeConnectError(err error) error {
@@ -11,6 +11,38 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const getOutboxBacklog = `-- name: GetOutboxBacklog :one
SELECT
(
SELECT count(*)
FROM outbox_events AS pending
WHERE pending.published_at IS NULL
)::bigint AS pending_events,
coalesce((
SELECT extract(EPOCH FROM clock_timestamp() - oldest.occurred_at)
FROM outbox_events AS oldest
WHERE oldest.published_at IS NULL
ORDER BY oldest.position
LIMIT 1
), 0)::float8 AS oldest_pending_age_seconds
`
type GetOutboxBacklogRow struct {
PendingEvents int64
OldestPendingAgeSeconds float64
}
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
// clock that set occurred_at.
func (q *Queries) GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error) {
row := q.db.QueryRow(ctx, getOutboxBacklog)
var i GetOutboxBacklogRow
err := row.Scan(&i.PendingEvents, &i.OldestPendingAgeSeconds)
return i, err
}
const insertOutboxEvent = `-- name: InsertOutboxEvent :exec
INSERT INTO outbox_events (
event_id,
@@ -53,3 +85,124 @@ func (q *Queries) InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventPa
)
return err
}
const lockPendingOutboxEvents = `-- name: LockPendingOutboxEvents :many
SELECT
pending.event_id,
pending.event_type,
pending.schema_version,
pending.aggregate_type,
pending.aggregate_id,
pending.aggregate_version,
pending.payload,
pending.occurred_at
FROM outbox_events AS pending
WHERE
pending.published_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM outbox_events AS earlier
WHERE
earlier.aggregate_type = pending.aggregate_type
AND earlier.aggregate_id = pending.aggregate_id
AND earlier.published_at IS NULL
AND (earlier.aggregate_version, earlier.position)
< (pending.aggregate_version, pending.position)
)
ORDER BY pending.position
LIMIT $1
FOR UPDATE OF pending SKIP LOCKED
`
type LockPendingOutboxEventsRow struct {
EventID pgtype.UUID
EventType string
SchemaVersion int32
AggregateType string
AggregateID pgtype.UUID
AggregateVersion int64
Payload []byte
OccurredAt pgtype.Timestamptz
}
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
// earlier row is locked by another relay or was just rolled back. Rows locked
// by another relay are skipped without waiting. The statement snapshot can
// only see a later version after the earlier version's transaction committed,
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
func (q *Queries) LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error) {
rows, err := q.db.Query(ctx, lockPendingOutboxEvents, batchLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []LockPendingOutboxEventsRow
for rows.Next() {
var i LockPendingOutboxEventsRow
if err := rows.Scan(
&i.EventID,
&i.EventType,
&i.SchemaVersion,
&i.AggregateType,
&i.AggregateID,
&i.AggregateVersion,
&i.Payload,
&i.OccurredAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markOutboxEventsPublished = `-- name: MarkOutboxEventsPublished :execrows
UPDATE outbox_events
SET published_at = clock_timestamp()
WHERE
event_id = ANY($1::uuid [])
AND published_at IS NULL
`
// Marks the events that the broker acknowledged. The relay passes only IDs
// whose rows its own transaction locked, so the statement never waits and the
// count equals the number of distinct IDs.
func (q *Queries) MarkOutboxEventsPublished(ctx context.Context, eventIds []pgtype.UUID) (int64, error) {
result, err := q.db.Exec(ctx, markOutboxEventsPublished, eventIds)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setRelayTransactionTimeouts = `-- name: SetRelayTransactionTimeouts :exec
SELECT
set_config('statement_timeout', $1::text, true),
set_config(
'idle_in_transaction_session_timeout',
$2::text,
true
)
`
type SetRelayTransactionTimeoutsParams struct {
StatementTimeoutMs string
IdleTimeoutMs string
}
// Bounds the claim transaction on the server. statement_timeout stops a
// statement that runs too long; idle_in_transaction_session_timeout ends the
// session, and with it the transaction and its row locks, when the client
// stays silent longer than a publish may take, for example after the process
// froze or lost the network without closing the connection. Both settings
// are local to the transaction.
func (q *Queries) SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error {
_, err := q.db.Exec(ctx, setRelayTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
return err
}
@@ -41,6 +41,11 @@ type Querier interface {
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
// clock that set occurred_at.
GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error)
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
@@ -55,6 +60,19 @@ type Querier interface {
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
// earlier row is locked by another relay or was just rolled back. Rows locked
// by another relay are skipped without waiting. The statement snapshot can
// only see a later version after the earlier version's transaction committed,
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
// Marks the events that the broker acknowledged. The relay passes only IDs
// whose rows its own transaction locked, so the statement never waits and the
// count equals the number of distinct IDs.
MarkOutboxEventsPublished(ctx context.Context, eventIds []pgtype.UUID) (int64, error)
// Verifies the email only for the registration version the consumed token
// was issued for.
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
@@ -64,6 +82,13 @@ type Querier interface {
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Bounds the claim transaction on the server. statement_timeout stops a
// statement that runs too long; idle_in_transaction_session_timeout ends the
// session, and with it the transaction and its row locks, when the client
// stays silent longer than a publish may take, for example after the process
// froze or lost the network without closing the connection. Both settings
// are local to the transaction.
SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error
// Records activity on an active session and reports whether it is active.
// The row is written only when last_seen_at is older than touch_cutoff, so
// frequent requests do not rewrite it. last_seen_at never moves back, and a
@@ -8,14 +8,31 @@ import (
client "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"lincodex/backend/internal/port/outbound"
)
type Metrics struct {
registry *client.Registry
requests *client.CounterVec
latency *client.HistogramVec
// relayEvents counts outbox events by relay outcome: published or
// failed. A failed event stays pending and is counted again on every
// retry.
relayEvents *client.CounterVec
// relayPending and relayOldestAge describe the unpublished outbox
// events. Every backend instance reports the same database-wide values,
// so dashboards aggregate them with max, not sum.
relayPending client.Gauge
relayOldestAge client.Gauge
}
// Outbox relay outcome label values.
const (
relayOutcomePublished = "published"
relayOutcomeFailed = "failed"
)
func New() *Metrics {
registry := client.NewRegistry()
requests := client.NewCounterVec(client.CounterOpts{
@@ -27,8 +44,51 @@ func New() *Metrics {
Help: "HTTP request duration in seconds.",
Buckets: client.DefBuckets,
}, []string{"method", "route"})
registry.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), requests, latency)
return &Metrics{registry: registry, requests: requests, latency: latency}
relayEvents := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_outbox_relay_events_total",
Help: "Outbox events handled by the relay, by outcome; failed events stay pending and are retried.",
}, []string{"outcome"})
relayPending := client.NewGauge(client.GaugeOpts{
Name: "lincodex_outbox_relay_pending_events",
Help: "Unpublished outbox events at the last backlog read by the relay.",
})
relayOldestAge := client.NewGauge(client.GaugeOpts{
Name: "lincodex_outbox_relay_oldest_pending_age_seconds",
Help: "Age of the earliest unpublished outbox event at the last backlog read by the relay; 0 without pending events.",
})
registry.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
requests, latency, relayEvents, relayPending, relayOldestAge,
)
// Expose both series from the start so rate queries see zero, not absence.
relayEvents.WithLabelValues(relayOutcomePublished)
relayEvents.WithLabelValues(relayOutcomeFailed)
return &Metrics{
registry: registry,
requests: requests,
latency: latency,
relayEvents: relayEvents,
relayPending: relayPending,
relayOldestAge: relayOldestAge,
}
}
// ObserveOutboxBacklog records the latest backlog read.
func (metrics *Metrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
metrics.relayPending.Set(float64(backlog.Pending))
metrics.relayOldestAge.Set(backlog.OldestAge.Seconds())
}
// ObserveOutboxRelayPass adds the events one relay pass published and those
// it claimed but could not publish.
func (metrics *Metrics) ObserveOutboxRelayPass(published, failed int) {
if published > 0 {
metrics.relayEvents.WithLabelValues(relayOutcomePublished).Add(float64(published))
}
if failed > 0 {
metrics.relayEvents.WithLabelValues(relayOutcomeFailed).Add(float64(failed))
}
}
func (metrics *Metrics) ObserveRequest(method, route string, status int, duration time.Duration) {
@@ -5,6 +5,8 @@ import (
"strings"
"testing"
"time"
"lincodex/backend/internal/port/outbound"
)
func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
@@ -21,3 +23,38 @@ func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
t.Fatalf("metrics output is missing request duration:\n%s", body)
}
}
func TestMetricsHandlerExposesOutboxRelayOutcomes(t *testing.T) {
metrics := New()
metrics.ObserveOutboxRelayPass(3, 0)
metrics.ObserveOutboxRelayPass(1, 2)
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
body := response.Body.String()
for _, want := range []string{
`lincodex_outbox_relay_events_total{outcome="published"} 4`,
`lincodex_outbox_relay_events_total{outcome="failed"} 2`,
} {
if !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s:\n%s", want, body)
}
}
}
func TestMetricsHandlerExposesTheOutboxBacklog(t *testing.T) {
metrics := New()
metrics.ObserveOutboxBacklog(outbound.OutboxBacklog{Pending: 42, OldestAge: 90 * time.Second})
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
body := response.Body.String()
for _, want := range []string{
"lincodex_outbox_relay_pending_events 42",
"lincodex_outbox_relay_oldest_pending_age_seconds 90",
} {
if !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s:\n%s", want, body)
}
}
}
+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()
@@ -0,0 +1,78 @@
package outbound
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/google/uuid"
)
// ErrEventDestinationMissing reports that the event bus has no destination
// for an event, for example a deleted topic. The relay runs
// EventPublisher.Prepare again before its next pass.
var ErrEventDestinationMissing = errors.New("event destination missing")
// OutboxBacklog describes the unpublished events at one moment.
type OutboxBacklog struct {
// Pending counts unpublished events.
Pending int64
// OldestAge is the age of the earliest unpublished event by position,
// measured by the database clock; zero without pending events.
OldestAge time.Duration
}
// OutboxEvent is a committed outbox row that the relay publishes. Payload is
// the stored jsonb object; PostgreSQL normalizes it, so it can differ in key
// order and whitespace from what the writer appended.
type OutboxEvent struct {
EventID uuid.UUID
EventType string
SchemaVersion int32
AggregateType string
AggregateID uuid.UUID
AggregateVersion int64
Payload json.RawMessage
// OccurredAt is the informational insert time. It does not define order.
OccurredAt time.Time
}
// PublishOutboxBatch publishes a locked batch and returns the IDs of the
// events that the event bus acknowledged. It must not return an ID it did not
// see acknowledged.
type PublishOutboxBatch func(ctx context.Context, events []OutboxEvent) (acknowledged []uuid.UUID)
// OutboxRelayStore hands pending outbox events to the relay under row locks.
type OutboxRelayStore interface {
// ClaimPending opens one transaction and locks up to limit pending events:
// for each aggregate only its earliest unpublished event, skipping rows
// that another relay holds. It calls publish with the events in position
// order while it holds the locks, marks exactly the returned IDs as
// published, and commits. With no pending event it returns without
// calling publish.
//
// If ctx ends or the commit fails after publish returned, nothing is
// marked and the acknowledged events are published again on a later
// pass with the same event IDs. An error from the store never says
// whether the event bus received the batch.
ClaimPending(ctx context.Context, limit int, publish PublishOutboxBatch) error
// Backlog reads the size and age of the unpublished events without
// locking them.
Backlog(ctx context.Context) (OutboxBacklog, error)
}
// EventPublisher delivers outbox events to the event bus.
type EventPublisher interface {
// Prepare makes the destinations ready, for example by creating missing
// topics. It is idempotent; the relay calls it before its first publish
// and repeats it with backoff until it succeeds.
Prepare(ctx context.Context) error
// Publish sends the events and waits until the event bus acknowledges
// each one or ctx ends. The result has one entry per event in input
// order: nil means durably acknowledged. An error matches
// ErrEventDestinationMissing when the destination does not exist. An
// event that is not acknowledged may still reach the event bus later, so
// a retry can deliver it twice with the same event ID.
Publish(ctx context.Context, events []OutboxEvent) []error
}
View File
Whitespace-only changes.
@@ -0,0 +1,40 @@
package outboxrelay
import (
"math/rand/v2"
"time"
)
// Backoff is a capped exponential delay with equal jitter: the ceiling starts
// at Initial, doubles with every consecutive failure, and stops at Max; the
// delay is half the ceiling plus a random share of the other half. The fixed
// half keeps retries from hammering a recovering broker, and the random half
// spreads several relays apart.
type Backoff struct {
Initial time.Duration
Max time.Duration
// jitter returns a value in [0, limit]. Tests replace it.
jitter func(limit time.Duration) time.Duration
}
// Delay returns the wait before the next attempt after failures consecutive
// failures. failures below 1 count as 1.
func (backoff Backoff) Delay(failures int) time.Duration {
ceiling := min(backoff.Initial, backoff.Max)
for attempt := 1; attempt < failures && ceiling < backoff.Max; attempt++ {
ceiling = min(ceiling*2, backoff.Max)
}
half := ceiling / 2
jitter := backoff.jitter
if jitter == nil {
jitter = randomJitter
}
return half + jitter(ceiling-half)
}
func randomJitter(limit time.Duration) time.Duration {
if limit <= 0 {
return 0
}
return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness.
}
@@ -0,0 +1,52 @@
package outboxrelay
import (
"testing"
"time"
)
func TestBackoffDoublesFromInitialToTheCap(t *testing.T) {
noJitter := func(time.Duration) time.Duration { return 0 }
fullJitter := func(limit time.Duration) time.Duration { return limit }
backoff := Backoff{Initial: 500 * time.Millisecond, Max: 5 * time.Second}
ceilings := []time.Duration{
500 * time.Millisecond, // failure 1
time.Second,
2 * time.Second,
4 * time.Second,
5 * time.Second, // capped
5 * time.Second,
}
for index, ceiling := range ceilings {
failures := index + 1
backoff.jitter = noJitter
if got := backoff.Delay(failures); got != ceiling/2 {
t.Fatalf("Delay(%d) without jitter = %s, want %s", failures, got, ceiling/2)
}
backoff.jitter = fullJitter
if got := backoff.Delay(failures); got != ceiling {
t.Fatalf("Delay(%d) with full jitter = %s, want %s", failures, got, ceiling)
}
}
backoff.jitter = fullJitter
if got := backoff.Delay(0); got != 500*time.Millisecond {
t.Fatalf("Delay(0) = %s, want the first delay", got)
}
if got := backoff.Delay(1 << 20); got != 5*time.Second {
t.Fatalf("Delay(many) = %s, want the cap", got)
}
}
func TestBackoffRandomJitterStaysWithinTheCeiling(t *testing.T) {
backoff := Backoff{Initial: 100 * time.Millisecond, Max: time.Second}
for failures := 1; failures <= 8; failures++ {
ceiling := min(100*time.Millisecond<<(failures-1), time.Second)
for range 50 {
delay := backoff.Delay(failures)
if delay < ceiling/2 || delay > ceiling {
t.Fatalf("Delay(%d) = %s, want between %s and %s", failures, delay, ceiling/2, ceiling)
}
}
}
}
@@ -0,0 +1,276 @@
// Package outboxrelay publishes committed transactional outbox events to the
// event bus with at-least-once delivery.
package outboxrelay
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
// Metrics records relay outcomes and the backlog without per-event labels.
type Metrics interface {
ObserveOutboxRelayPass(published, failed int)
ObserveOutboxBacklog(backlog outbound.OutboxBacklog)
}
// Settings are the named relay limits; config validates their ranges.
type Settings struct {
// BatchSize bounds the events one pass locks and publishes.
BatchSize int
// PollInterval is the wait after a pass that found no pending event.
PollInterval time.Duration
// Backoff is the wait after a failed pass or a failed Prepare.
Backoff Backoff
// ShutdownTimeout bounds how long a pass in progress may continue after
// Run's context ends. When it expires the pass is canceled and its
// transaction rolls back, so nothing it published is marked.
ShutdownTimeout time.Duration
// BacklogInterval is the least time between two backlog reads for the
// metrics, so a busy relay does not count the outbox on every pass. It
// also bounds one read.
BacklogInterval time.Duration
}
// Relay moves pending outbox events to the event bus. Several relays may run
// against one database: each pass locks its rows with SKIP LOCKED, and only
// the earliest unpublished event of an aggregate can be claimed, so one
// aggregate's events are published in order. A pass marks only events the
// broker acknowledged. An event acknowledged in a pass that does not commit
// is published again later with the same event ID; consumers deduplicate.
type Relay struct {
store outbound.OutboxRelayStore
publisher outbound.EventPublisher
metrics Metrics
logger *slog.Logger
settings Settings
}
func New(
store outbound.OutboxRelayStore,
publisher outbound.EventPublisher,
metrics Metrics,
logger *slog.Logger,
settings Settings,
) *Relay {
return &Relay{store: store, publisher: publisher, metrics: metrics, logger: logger, settings: settings}
}
// PassResult counts the events of one pass.
type PassResult struct {
// Claimed events were locked and handed to the publisher.
Claimed int
// Published events were acknowledged and marked in a committed
// transaction.
Published int
}
// PublishPending runs one pass: it locks a batch, publishes it, and marks the
// acknowledged events in the same transaction. A nil error means every
// claimed event was published. On an error Published counts only events whose
// mark committed.
func (relay *Relay) PublishPending(ctx context.Context) (PassResult, error) {
var (
result PassResult
acknowledged int
publishErr error
)
claimErr := relay.store.ClaimPending(ctx, relay.settings.BatchSize, func(ctx context.Context, events []outbound.OutboxEvent) []uuid.UUID {
result.Claimed = len(events)
ids, err := relay.publish(ctx, events)
acknowledged, publishErr = len(ids), err
return ids
})
if claimErr != nil {
return result, fmt.Errorf("Relay.PublishPending - claim pending events: %w", errors.Join(claimErr, publishErr))
}
result.Published = acknowledged
if publishErr != nil {
return result, fmt.Errorf("Relay.PublishPending - publish events: %w", publishErr)
}
return result, nil
}
// publish returns the acknowledged event IDs and, when some events were not
// acknowledged, an error with their count and the first cause. The other
// causes are dropped to keep one log line per pass.
func (relay *Relay) publish(ctx context.Context, events []outbound.OutboxEvent) ([]uuid.UUID, error) {
outcomes := relay.publisher.Publish(ctx, events)
if len(outcomes) != len(events) {
return nil, fmt.Errorf("Relay.publish - publisher returned %d results for %d events", len(outcomes), len(events))
}
acknowledged := make([]uuid.UUID, 0, len(events))
var firstErr error
for index, err := range outcomes {
if err == nil {
acknowledged = append(acknowledged, events[index].EventID)
continue
}
// A missing destination wins, so Run sees it and prepares again.
if firstErr == nil || (errors.Is(err, outbound.ErrEventDestinationMissing) && !errors.Is(firstErr, outbound.ErrEventDestinationMissing)) {
firstErr = err
}
}
if firstErr != nil {
return acknowledged, fmt.Errorf("Relay.publish - %d of %d events not acknowledged: %w", len(events)-len(acknowledged), len(events), firstErr)
}
return acknowledged, nil
}
// Run prepares the event bus and then publishes pending events until ctx
// ends. A pass that published events is followed immediately by the next one,
// even when some of its events failed; an empty pass waits PollInterval; a
// pass that published nothing and failed waits Backoff, which grows only
// across such passes. A pass that reports a missing destination makes Run
// call Prepare again first. Failures are logged and retried indefinitely, so
// Run returns only after ctx ends and the pass in progress finishes or
// ShutdownTimeout cancels it.
func (relay *Relay) Run(ctx context.Context) {
passCtx, stopPasses := relay.passContext(ctx)
defer stopPasses()
relay.logger.Info("outbox relay started",
slog.Int("batch_size", relay.settings.BatchSize),
slog.Duration("poll_interval", relay.settings.PollInterval),
)
defer relay.logger.Info("outbox relay stopped")
backlog := backlogRefresher{relay: relay}
failures := 0
needsPrepare := true
for {
if needsPrepare {
if !relay.prepare(ctx, &backlog) {
return
}
}
result, err := relay.PublishPending(passCtx)
relay.metrics.ObserveOutboxRelayPass(result.Published, result.Claimed-result.Published)
backlog.refresh(ctx)
needsPrepare = errors.Is(err, outbound.ErrEventDestinationMissing)
var delay time.Duration
delay, failures = relay.nextDelay(result, err, failures)
if !wait(ctx, delay) {
return
}
}
}
// nextDelay returns the wait before the next pass and the new count of
// consecutive failed passes that published nothing.
func (relay *Relay) nextDelay(result PassResult, err error, failures int) (time.Duration, int) {
switch {
case err != nil && result.Published > 0:
// The pass made progress, so the event bus works; the failed events
// are retried at once instead of slowing the others down.
relay.logger.Warn("outbox relay pass published part of its batch; the rest stay pending",
slog.Int("claimed", result.Claimed),
slog.Int("published", result.Published),
slog.Any("error", err),
)
return 0, 0
case err != nil:
failures++
delay := relay.settings.Backoff.Delay(failures)
relay.logger.Warn("outbox relay pass failed; unacknowledged events stay pending",
slog.Int("claimed", result.Claimed),
slog.Int("published", result.Published),
slog.Int("consecutive_failures", failures),
slog.Duration("retry_in", delay),
slog.Any("error", err),
)
return delay, failures
case result.Claimed > 0:
return 0, 0
default:
return relay.settings.PollInterval, 0
}
}
// prepare repeats Prepare with backoff until it succeeds or ctx ends. The
// backlog metrics keep refreshing meanwhile, so a growing outbox stays visible.
func (relay *Relay) prepare(ctx context.Context, backlog *backlogRefresher) bool {
for failures := 1; ; failures++ {
err := relay.publisher.Prepare(ctx)
if err == nil {
return true
}
backlog.refresh(ctx)
delay := relay.settings.Backoff.Delay(failures)
relay.logger.Warn("outbox relay could not prepare the event bus; events stay pending",
slog.Int("consecutive_failures", failures),
slog.Duration("retry_in", delay),
slog.Any("error", err),
)
if !wait(ctx, delay) {
return false
}
}
}
// backlogRefresher reads the outbox backlog for the metrics at most once per
// BacklogInterval.
type backlogRefresher struct {
relay *Relay
last time.Time
}
func (refresher *backlogRefresher) refresh(ctx context.Context) {
interval := refresher.relay.settings.BacklogInterval
if !refresher.last.IsZero() && time.Since(refresher.last) < interval {
return
}
refresher.last = time.Now()
readCtx, cancel := context.WithTimeout(ctx, interval)
defer cancel()
backlog, err := refresher.relay.store.Backlog(readCtx)
if err != nil {
// A read interrupted by shutdown is not worth a warning.
if ctx.Err() == nil {
refresher.relay.logger.Warn("outbox relay could not read the backlog; its metrics are stale", slog.Any("error", err))
}
return
}
refresher.relay.metrics.ObserveOutboxBacklog(backlog)
}
// passContext returns a context for passes that outlives ctx by at most
// ShutdownTimeout, so a pass in progress at shutdown can finish and mark what
// the broker acknowledged. stop releases the watcher goroutine.
func (relay *Relay) passContext(ctx context.Context) (context.Context, func()) {
passCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
stopWatching := context.AfterFunc(ctx, func() {
timer := time.NewTimer(relay.settings.ShutdownTimeout)
defer timer.Stop()
select {
case <-timer.C:
cancel()
case <-passCtx.Done():
}
})
return passCtx, func() {
stopWatching()
cancel()
}
}
// wait sleeps for delay and reports false when ctx ends first. A zero delay
// still reports a canceled context.
func wait(ctx context.Context, delay time.Duration) bool {
if delay <= 0 {
return ctx.Err() == nil
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
@@ -0,0 +1,431 @@
package outboxrelay
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
const (
testTimeout = 5 * time.Second
testInterval = time.Millisecond
)
var errBrokerDown = errors.New("broker down")
// fakeStore models the claim transaction: events acknowledged by publish are
// marked only when ctx is still live afterwards, as a commit would require.
type fakeStore struct {
mu sync.Mutex
pending []outbound.OutboxEvent
marked []uuid.UUID
passes int
backlogReads int
}
func newFakeStore(count int) *fakeStore {
store := &fakeStore{}
for version := range count {
store.pending = append(store.pending, outbound.OutboxEvent{
EventID: uuid.New(),
EventType: "test.changed",
SchemaVersion: 1,
AggregateType: "test",
AggregateID: uuid.New(),
AggregateVersion: int64(version + 1),
})
}
return store
}
func (store *fakeStore) ClaimPending(ctx context.Context, limit int, publish outbound.PublishOutboxBatch) error {
store.mu.Lock()
store.passes++
batch := slices.Clone(store.pending[:min(limit, len(store.pending))])
store.mu.Unlock()
if len(batch) == 0 {
return nil
}
acknowledged := publish(ctx, batch)
if err := ctx.Err(); err != nil {
return err
}
store.mu.Lock()
defer store.mu.Unlock()
for _, eventID := range acknowledged {
store.marked = append(store.marked, eventID)
store.pending = slices.DeleteFunc(store.pending, func(event outbound.OutboxEvent) bool { return event.EventID == eventID })
}
return nil
}
func (store *fakeStore) Backlog(context.Context) (outbound.OutboxBacklog, error) {
store.mu.Lock()
defer store.mu.Unlock()
store.backlogReads++
return outbound.OutboxBacklog{Pending: int64(len(store.pending))}, nil
}
func (store *fakeStore) reads() int {
store.mu.Lock()
defer store.mu.Unlock()
return store.backlogReads
}
func (store *fakeStore) state() (pending int, marked []uuid.UUID, passes int) {
store.mu.Lock()
defer store.mu.Unlock()
return len(store.pending), slices.Clone(store.marked), store.passes
}
type fakePublisher struct {
prepare func(ctx context.Context) error
publish func(ctx context.Context, events []outbound.OutboxEvent) []error
}
func (publisher fakePublisher) Prepare(ctx context.Context) error {
if publisher.prepare == nil {
return nil
}
return publisher.prepare(ctx)
}
func (publisher fakePublisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error {
return publisher.publish(ctx, events)
}
func acknowledgeAll(_ context.Context, events []outbound.OutboxEvent) []error {
return make([]error, len(events))
}
type countingMetrics struct {
mu sync.Mutex
published, failed int
backlogs []int64
}
func (metrics *countingMetrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.backlogs = append(metrics.backlogs, backlog.Pending)
}
func (metrics *countingMetrics) ObserveOutboxRelayPass(published, failed int) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.published += published
metrics.failed += failed
}
func (metrics *countingMetrics) totals() (published, failed int) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
return metrics.published, metrics.failed
}
func newTestRelay(store outbound.OutboxRelayStore, publisher outbound.EventPublisher, metrics Metrics, shutdownTimeout time.Duration) *Relay {
return New(store, publisher, metrics, slog.New(slog.DiscardHandler), Settings{
BatchSize: 2,
PollInterval: testInterval,
Backoff: Backoff{Initial: testInterval, Max: 4 * testInterval},
ShutdownTimeout: shutdownTimeout,
BacklogInterval: testInterval,
})
}
// runRelay starts Run and returns a function that cancels it and waits for
// it to return.
func runRelay(t *testing.T, relay *Relay) (stop func() time.Duration) {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
defer close(done)
relay.Run(ctx)
}()
return func() time.Duration {
started := time.Now()
cancel()
select {
case <-done:
case <-time.After(testTimeout):
t.Fatal("Run did not return after cancellation")
}
return time.Since(started)
}
}
func waitFor(t *testing.T, condition func() bool, description string) {
t.Helper()
deadline := time.Now().Add(testTimeout)
for !condition() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", description)
}
time.Sleep(testInterval)
}
}
func TestPublishPendingMarksOnlyAcknowledgedEvents(t *testing.T) {
store := newFakeStore(2)
relay := newTestRelay(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
return []error{nil, errBrokerDown}
}}, &countingMetrics{}, time.Second)
result, err := relay.PublishPending(t.Context())
if !errors.Is(err, errBrokerDown) {
t.Fatalf("PublishPending() error = %v, want the publish failure", err)
}
if result != (PassResult{Claimed: 2, Published: 1}) {
t.Fatalf("PublishPending() result = %+v, want 2 claimed and 1 published", result)
}
pending, marked, _ := store.state()
if pending != 1 || len(marked) != 1 {
t.Fatalf("pending %d, marked %v; want the failed event pending and one marked", pending, marked)
}
}
func TestPublishPendingMarksNothingWhenResultsDoNotMatchTheBatch(t *testing.T) {
store := newFakeStore(2)
relay := newTestRelay(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
return []error{nil}
}}, &countingMetrics{}, time.Second)
result, err := relay.PublishPending(t.Context())
if err == nil || result.Published != 0 {
t.Fatalf("PublishPending() = %+v, %v; want an error and nothing published", result, err)
}
if pending, marked, _ := store.state(); pending != 2 || len(marked) != 0 {
t.Fatalf("pending %d, marked %v; want every event pending", pending, marked)
}
}
func TestRunRetriesPrepareAndFailedPassesUntilEventsArePublished(t *testing.T) {
store := newFakeStore(5)
var mu sync.Mutex
prepareFailures, publishFailures := 2, 3
publisher := fakePublisher{
prepare: func(context.Context) error {
mu.Lock()
defer mu.Unlock()
if prepareFailures > 0 {
prepareFailures--
return errBrokerDown
}
return nil
},
publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
mu.Lock()
defer mu.Unlock()
if publishFailures > 0 {
publishFailures--
results := make([]error, len(events))
for index := range results {
results[index] = errBrokerDown
}
return results
}
return acknowledgeAll(ctx, events)
},
}
metrics := &countingMetrics{}
stop := runRelay(t, newTestRelay(store, publisher, metrics, time.Second))
waitFor(t, func() bool {
pending, _, _ := store.state()
return pending == 0
}, "every event to be published")
stop()
_, marked, _ := store.state()
if len(marked) != 5 {
t.Fatalf("marked %d events, want 5", len(marked))
}
if published, failed := metrics.totals(); published != 5 || failed != 6 {
t.Fatalf("metrics published=%d failed=%d, want 5 and 6 (three failed passes of two)", published, failed)
}
}
func TestRunLetsThePassInProgressFinishAfterCancellation(t *testing.T) {
store := newFakeStore(1)
publishing, release := make(chan struct{}), make(chan struct{})
publisher := fakePublisher{publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
close(publishing)
<-release
return acknowledgeAll(ctx, events)
}}
stop := runRelay(t, newTestRelay(store, publisher, &countingMetrics{}, testTimeout))
<-publishing
stopped := make(chan struct{})
go func() {
defer close(stopped)
stop()
}()
// Run must still be waiting for the pass after cancellation.
select {
case <-stopped:
t.Fatal("Run returned before the pass in progress finished")
case <-time.After(50 * time.Millisecond):
}
close(release)
<-stopped
if pending, marked, _ := store.state(); pending != 0 || len(marked) != 1 {
t.Fatalf("pending %d, marked %v; want the acknowledged event marked", pending, marked)
}
}
func TestRunCancelsAPassThatOutlivesTheShutdownTimeout(t *testing.T) {
const shutdownTimeout = 50 * time.Millisecond
store := newFakeStore(1)
publishing := make(chan struct{})
var once sync.Once
publisher := fakePublisher{publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
once.Do(func() { close(publishing) })
// A hung broker: the publish ends only with its context.
<-ctx.Done()
results := make([]error, len(events))
for index := range results {
results[index] = ctx.Err()
}
return results
}}
stop := runRelay(t, newTestRelay(store, publisher, &countingMetrics{}, shutdownTimeout))
<-publishing
if elapsed := stop(); elapsed < shutdownTimeout {
t.Fatalf("Run returned after %s, before the %s shutdown timeout", elapsed, shutdownTimeout)
}
if pending, marked, _ := store.state(); pending != 1 || len(marked) != 0 {
t.Fatalf("pending %d, marked %v; want the unacknowledged event pending", pending, marked)
}
}
func TestRunStopsDuringBackoffWithoutAnotherPass(t *testing.T) {
store := newFakeStore(1)
relay := New(store, fakePublisher{publish: func(context.Context, []outbound.OutboxEvent) []error {
return []error{errBrokerDown}
}}, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
BatchSize: 1,
PollInterval: testInterval,
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
ShutdownTimeout: time.Second,
BacklogInterval: time.Hour,
})
stop := runRelay(t, relay)
waitFor(t, func() bool {
_, _, passes := store.state()
return passes == 1
}, "the first pass")
if elapsed := stop(); elapsed > time.Second {
t.Fatalf("Run took %s to stop during backoff", elapsed)
}
if _, _, passes := store.state(); passes != 1 {
t.Fatalf("store saw %d passes, want 1", passes)
}
}
// hourBackoffRelay never retries a failed pass that published nothing within
// a test, so a test that finishes proves the relay did not back off.
func hourBackoffRelay(store outbound.OutboxRelayStore, publisher outbound.EventPublisher, backlogInterval time.Duration) *Relay {
return New(store, publisher, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{
BatchSize: 2,
PollInterval: testInterval,
Backoff: Backoff{Initial: time.Hour, Max: time.Hour},
ShutdownTimeout: time.Second,
BacklogInterval: backlogInterval,
})
}
func TestRunDoesNotBackOffAfterAPassThatMadeProgress(t *testing.T) {
store := newFakeStore(5)
poison := store.pending[0].EventID
publisher := fakePublisher{publish: func(_ context.Context, events []outbound.OutboxEvent) []error {
results := make([]error, len(events))
for index, event := range events {
if event.EventID == poison {
results[index] = errBrokerDown
}
}
return results
}}
stop := runRelay(t, hourBackoffRelay(store, publisher, time.Hour))
// The poison event leads every batch; the others drain only if a pass
// that published something is followed at once by the next one.
waitFor(t, func() bool {
pending, _, _ := store.state()
return pending == 1
}, "every event except the poison event to be published")
stop()
if _, marked, _ := store.state(); slices.Contains(marked, poison) {
t.Fatal("the failed event was marked as published")
}
}
func TestRunPreparesAgainAfterAMissingDestination(t *testing.T) {
store := newFakeStore(1)
var mu sync.Mutex
prepares, missing := 0, true
publisher := fakePublisher{
prepare: func(context.Context) error {
mu.Lock()
defer mu.Unlock()
prepares++
return nil
},
publish: func(ctx context.Context, events []outbound.OutboxEvent) []error {
mu.Lock()
defer mu.Unlock()
if missing {
missing = false
return []error{fmt.Errorf("produce: %w", outbound.ErrEventDestinationMissing)}
}
return acknowledgeAll(ctx, events)
},
}
relay := newTestRelay(store, publisher, &countingMetrics{}, time.Second)
stop := runRelay(t, relay)
waitFor(t, func() bool {
pending, _, _ := store.state()
return pending == 0
}, "the event to be published after the topic was prepared again")
stop()
mu.Lock()
defer mu.Unlock()
if prepares != 2 {
t.Fatalf("Prepare ran %d times, want 2 (start and after the missing destination)", prepares)
}
}
func TestRunRefreshesTheBacklogAtMostOncePerInterval(t *testing.T) {
store := newFakeStore(6)
metrics := &countingMetrics{}
relay := New(store, fakePublisher{publish: acknowledgeAll}, metrics, slog.New(slog.DiscardHandler), Settings{
BatchSize: 1,
PollInterval: testInterval,
Backoff: Backoff{Initial: testInterval, Max: testInterval},
ShutdownTimeout: time.Second,
BacklogInterval: time.Hour,
})
stop := runRelay(t, relay)
waitFor(t, func() bool {
pending, _, _ := store.state()
return pending == 0
}, "every event to be published")
stop()
_, _, passes := store.state()
if reads := store.reads(); reads != 1 || passes < 6 {
t.Fatalf("%d backlog reads over %d passes, want 1 read per interval", reads, passes)
}
metrics.mu.Lock()
defer metrics.mu.Unlock()
if len(metrics.backlogs) != 1 || metrics.backlogs[0] != 5 {
t.Fatalf("backlog observations %v, want one with the 5 events left after the first pass", metrics.backlogs)
}
}