From 6c3b34f73e76ec5ce99c33f504b6ba73938677e6 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 03:01:53 +0300 Subject: [PATCH] feat(outbox): relay committed outbox events to Kafka --- backend/config/config.go | 41 + backend/config/config_test.go | 53 ++ backend/config/kafka.go | 86 ++ backend/config/relay.go | 90 ++ backend/config/relay_test.go | 112 +++ .../00004_add_outbox_relay_index.sql | 13 + backend/db/queries/outbox.sql | 79 ++ backend/go.mod | 2 +- .../integration_test/kafka_helpers_test.go | 41 + backend/integration_test/outbox_relay_test.go | 767 ++++++++++++++++++ backend/integration_test/outbox_test.go | 16 +- .../adapter/secondary/kafka/envelope.go | 76 ++ .../adapter/secondary/kafka/envelope_test.go | 105 +++ .../adapter/secondary/kafka/publisher.go | 219 +++++ .../adapter/secondary/kafka/publisher_test.go | 151 ++++ .../secondary/postgres/outbox_relay.go | 181 +++++ .../secondary/postgres/outbox_relay_test.go | 57 ++ .../adapter/secondary/postgres/pool.go | 35 +- .../secondary/postgres/sqlc/outbox.sql.go | 153 ++++ .../secondary/postgres/sqlc/querier.go | 25 + .../adapter/secondary/prometheus/metrics.go | 64 +- .../secondary/prometheus/metrics_test.go | 37 + backend/internal/bootstrap/app.go | 41 +- backend/internal/bootstrap/relay.go | 92 +++ backend/internal/bootstrap/relay_test.go | 107 +++ backend/internal/bootstrap/wire.go | 1 + backend/internal/bootstrap/wire_gen.go | 10 +- .../internal/port/outbound/outbox_relay.go | 78 ++ backend/internal/worker/.gitkeep | 0 .../internal/worker/outboxrelay/backoff.go | 40 + .../worker/outboxrelay/backoff_test.go | 52 ++ backend/internal/worker/outboxrelay/relay.go | 276 +++++++ .../internal/worker/outboxrelay/relay_test.go | 431 ++++++++++ deploy/docker/docker-compose.yml | 5 + docs/en/ARCHITECTURE.md | 49 +- docs/en/DEPLOY.md | 35 +- docs/en/DEVELOPMENT.md | 12 +- docs/en/TESTING.md | 24 +- docs/ru/ARCHITECTURE.md | 49 +- docs/ru/DEPLOY.md | 35 +- docs/ru/DEVELOPMENT.md | 12 +- docs/ru/TESTING.md | 24 +- 42 files changed, 3731 insertions(+), 45 deletions(-) create mode 100644 backend/config/relay.go create mode 100644 backend/config/relay_test.go create mode 100644 backend/db/migrations/00004_add_outbox_relay_index.sql create mode 100644 backend/integration_test/outbox_relay_test.go create mode 100644 backend/internal/adapter/secondary/kafka/envelope.go create mode 100644 backend/internal/adapter/secondary/kafka/envelope_test.go create mode 100644 backend/internal/adapter/secondary/kafka/publisher.go create mode 100644 backend/internal/adapter/secondary/kafka/publisher_test.go create mode 100644 backend/internal/adapter/secondary/postgres/outbox_relay.go create mode 100644 backend/internal/adapter/secondary/postgres/outbox_relay_test.go create mode 100644 backend/internal/bootstrap/relay.go create mode 100644 backend/internal/bootstrap/relay_test.go create mode 100644 backend/internal/port/outbound/outbox_relay.go delete mode 100644 backend/internal/worker/.gitkeep create mode 100644 backend/internal/worker/outboxrelay/backoff.go create mode 100644 backend/internal/worker/outboxrelay/backoff_test.go create mode 100644 backend/internal/worker/outboxrelay/relay.go create mode 100644 backend/internal/worker/outboxrelay/relay_test.go diff --git a/backend/config/config.go b/backend/config/config.go index 23fae2d..3242e87 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -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 { diff --git a/backend/config/config_test.go b/backend/config/config_test.go index ec179cb..45a973c 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -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) + } + }) + } +} diff --git a/backend/config/kafka.go b/backend/config/kafka.go index aa1b4bb..62c216b 100644 --- a/backend/config/kafka.go +++ b/backend/config/kafka.go @@ -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. diff --git a/backend/config/relay.go b/backend/config/relay.go new file mode 100644 index 0000000..eb469de --- /dev/null +++ b/backend/config/relay.go @@ -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 +} diff --git a/backend/config/relay_test.go b/backend/config/relay_test.go new file mode 100644 index 0000000..101f5c6 --- /dev/null +++ b/backend/config/relay_test.go @@ -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) + } +} diff --git a/backend/db/migrations/00004_add_outbox_relay_index.sql b/backend/db/migrations/00004_add_outbox_relay_index.sql new file mode 100644 index 0000000..6d1e28b --- /dev/null +++ b/backend/db/migrations/00004_add_outbox_relay_index.sql @@ -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; diff --git a/backend/db/queries/outbox.sql b/backend/db/queries/outbox.sql index 0d5cbad..2af8e55 100644 --- a/backend/db/queries/outbox.sql +++ b/backend/db/queries/outbox.sql @@ -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 + ); diff --git a/backend/go.mod b/backend/go.mod index a70f523..ac32045 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -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 diff --git a/backend/integration_test/kafka_helpers_test.go b/backend/integration_test/kafka_helpers_test.go index b648900..1f61568 100644 --- a/backend/integration_test/kafka_helpers_test.go +++ b/backend/integration_test/kafka_helpers_test.go @@ -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 +} diff --git a/backend/integration_test/outbox_relay_test.go b/backend/integration_test/outbox_relay_test.go new file mode 100644 index 0000000..cd655e9 --- /dev/null +++ b/backend/integration_test/outbox_relay_test.go @@ -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) + } + } +} diff --git a/backend/integration_test/outbox_test.go b/backend/integration_test/outbox_test.go index aeb1d3c..6170e13 100644 --- a/backend/integration_test/outbox_test.go +++ b/backend/integration_test/outbox_test.go @@ -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 { diff --git a/backend/internal/adapter/secondary/kafka/envelope.go b/backend/internal/adapter/secondary/kafka/envelope.go new file mode 100644 index 0000000..4a3eb69 --- /dev/null +++ b/backend/internal/adapter/secondary/kafka/envelope.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/kafka/envelope_test.go b/backend/internal/adapter/secondary/kafka/envelope_test.go new file mode 100644 index 0000000..1ccd5e1 --- /dev/null +++ b/backend/internal/adapter/secondary/kafka/envelope_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/secondary/kafka/publisher.go b/backend/internal/adapter/secondary/kafka/publisher.go new file mode 100644 index 0000000..ddbab9c --- /dev/null +++ b/backend/internal/adapter/secondary/kafka/publisher.go @@ -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) +} diff --git a/backend/internal/adapter/secondary/kafka/publisher_test.go b/backend/internal/adapter/secondary/kafka/publisher_test.go new file mode 100644 index 0000000..6083440 --- /dev/null +++ b/backend/internal/adapter/secondary/kafka/publisher_test.go @@ -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) + } + }) + } +} diff --git a/backend/internal/adapter/secondary/postgres/outbox_relay.go b/backend/internal/adapter/secondary/postgres/outbox_relay.go new file mode 100644 index 0000000..fed9e85 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/outbox_relay.go @@ -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) +} diff --git a/backend/internal/adapter/secondary/postgres/outbox_relay_test.go b/backend/internal/adapter/secondary/postgres/outbox_relay_test.go new file mode 100644 index 0000000..b65bf93 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/outbox_relay_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/secondary/postgres/pool.go b/backend/internal/adapter/secondary/postgres/pool.go index 07b0b97..a37169b 100644 --- a/backend/internal/adapter/secondary/postgres/pool.go +++ b/backend/internal/adapter/secondary/postgres/pool.go @@ -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 { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go index fb8dcc9..251309f 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/outbox.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 39ee297..47222ff 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -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 diff --git a/backend/internal/adapter/secondary/prometheus/metrics.go b/backend/internal/adapter/secondary/prometheus/metrics.go index 33a3099..d9fcc1b 100644 --- a/backend/internal/adapter/secondary/prometheus/metrics.go +++ b/backend/internal/adapter/secondary/prometheus/metrics.go @@ -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) { diff --git a/backend/internal/adapter/secondary/prometheus/metrics_test.go b/backend/internal/adapter/secondary/prometheus/metrics_test.go index 9f53279..240899c 100644 --- a/backend/internal/adapter/secondary/prometheus/metrics_test.go +++ b/backend/internal/adapter/secondary/prometheus/metrics_test.go @@ -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) + } + } +} diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index 873ab7f..bdfe7c6 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -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, diff --git a/backend/internal/bootstrap/relay.go b/backend/internal/bootstrap/relay.go new file mode 100644 index 0000000..a5326e0 --- /dev/null +++ b/backend/internal/bootstrap/relay.go @@ -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, + } +} diff --git a/backend/internal/bootstrap/relay_test.go b/backend/internal/bootstrap/relay_test.go new file mode 100644 index 0000000..d88fff9 --- /dev/null +++ b/backend/internal/bootstrap/relay_test.go @@ -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) + } +} diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 4f3e4aa..9ffdd52 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -47,6 +47,7 @@ func initialize( v1.NewHandler, v1.NewDenyAllSecurity, httpadapter.NewRouter, + newOutboxRelay, NewApplication, ), ) diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index ae487f1..8b385ff 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -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() diff --git a/backend/internal/port/outbound/outbox_relay.go b/backend/internal/port/outbound/outbox_relay.go new file mode 100644 index 0000000..50972eb --- /dev/null +++ b/backend/internal/port/outbound/outbox_relay.go @@ -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 +} diff --git a/backend/internal/worker/.gitkeep b/backend/internal/worker/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/worker/outboxrelay/backoff.go b/backend/internal/worker/outboxrelay/backoff.go new file mode 100644 index 0000000..ffc8415 --- /dev/null +++ b/backend/internal/worker/outboxrelay/backoff.go @@ -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. +} diff --git a/backend/internal/worker/outboxrelay/backoff_test.go b/backend/internal/worker/outboxrelay/backoff_test.go new file mode 100644 index 0000000..9281424 --- /dev/null +++ b/backend/internal/worker/outboxrelay/backoff_test.go @@ -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) + } + } + } +} diff --git a/backend/internal/worker/outboxrelay/relay.go b/backend/internal/worker/outboxrelay/relay.go new file mode 100644 index 0000000..a0402c2 --- /dev/null +++ b/backend/internal/worker/outboxrelay/relay.go @@ -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 + } +} diff --git a/backend/internal/worker/outboxrelay/relay_test.go b/backend/internal/worker/outboxrelay/relay_test.go new file mode 100644 index 0000000..1482c72 --- /dev/null +++ b/backend/internal/worker/outboxrelay/relay_test.go @@ -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) + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index a0dedda..4c89ced 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -213,6 +213,11 @@ services: expose: - "8080" - "9090" + # SHUTDOWN_TIMEOUT (10s by default) bounds both the HTTP shutdown and the + # outbox relay pass in progress, which run at the same time. The grace + # period leaves room for that and for closing connections, so Docker does + # not kill the process while a pass is committing. + stop_grace_period: 20s restart: unless-stopped logging: driver: json-file diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 00a3e9e..c9cb953 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -50,7 +50,7 @@ Redis is part of the core Compose project and connects through `backend/internal SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup. -The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node and the `outbox_events` table with its transactional writer exists, while the Go Kafka client and the relay are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. +The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. Event consumers are not implemented yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help. ### Transactional outbox @@ -75,7 +75,42 @@ The outbox uniqueness rule is a backstop, not concurrency control. Aggregate upd `domain.NewDomainEvent` validates the event. The compact JSON payload is limited to 16 KiB and 32 nesting levels; numbers must fit a float64; NUL characters are rejected because jsonb cannot store them. jsonb normalizes the stored payload (key order, whitespace, duplicate keys), so consumers compare JSON values rather than bytes. Payloads carry identifiers and minimal facts only, never contact data, tokens, passwords, or resume and document contents. -Planned relay contract (TASK-009): the relay selects unpublished rows (`published_at IS NULL`) ordered by `position` on every pass and never keeps an `occurred_at` or `position` watermark, because a row with a smaller position can become visible after a larger one commits. It publishes the events of one aggregate in `aggregate_version` order and then sets `published_at`. Also planned: retry bookkeeping (attempt count and last error, added by an additive migration), retention of published rows, topics, and idempotent consumers. Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. +The relay that publishes these rows is described in [Outbox relay](#outbox-relay). Still planned: retry bookkeeping columns (attempt count and last error), retention of published rows, and idempotent consumers (TASK-010). Bootstrap does not wire the transactor yet because no product usecase uses it; the first business transaction wires it together with a shared pool. + +### Outbox relay + +Implemented (TASK-009): the relay loop in `backend/internal/worker/outboxrelay/`, the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports (`backend/internal/port/outbound/outbox_relay.go`), the PostgreSQL store (`adapter/secondary/postgres/outbox_relay.go`), and the franz-go producer (`adapter/secondary/kafka/`). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when `RELAY_ENABLED=false` or `DATABASE_URL` is unset; the outbox then keeps the events. Settings are listed in [DEPLOY.md](DEPLOY.md#outbox-relay). + +One pass is one READ COMMITTED transaction: + +1. `SetRelayTransactionTimeouts` sets `statement_timeout` to `RELAY_STATEMENT_TIMEOUT` and `idle_in_transaction_session_timeout` to `RELAY_PRODUCE_TIMEOUT + RELAY_STATEMENT_TIMEOUT` for this transaction only (`SET LOCAL` through `set_config`). The pass context already cancels a slow pass of a live process; these server-side limits also hold when the process freezes or loses the network without closing the connection, so the server ends the transaction and releases its row locks instead of waiting for TCP keepalive. +2. `LockPendingOutboxEvents` selects rows with `published_at IS NULL` in `position` order, at most `RELAY_BATCH_SIZE`, with `FOR UPDATE OF pending SKIP LOCKED`. A row qualifies only when it is the earliest unpublished event of its aggregate (lowest `aggregate_version`, then `position`). There is no `position` or `occurred_at` watermark; every pass scans the unpublished rows again. +3. The relay publishes the batch and waits for the broker acknowledgements, at most `RELAY_PRODUCE_TIMEOUT`. +4. `MarkOutboxEventsPublished` sets `published_at` for exactly the acknowledged event IDs, and the transaction commits. + +Several relays, for example several backend instances, can run against one database. SKIP LOCKED lets them take different rows without waiting. Plain SKIP LOCKED would let a second relay skip a locked version 1 and publish version 2 first; the earliest-event rule prevents that, because version 2 does not qualify while version 1 is unpublished, whether another relay holds it, a failed pass left it pending, or a pass rolled back. The rule relies on aggregate writers checking the expected version: version 2 then commits only after version 1, so a statement that sees version 2 also sees version 1. Migration `00004_add_outbox_relay_index.sql` adds the partial index `(aggregate_type, aggregate_id, aggregate_version, position) WHERE published_at IS NULL` for this check. Trade-off: a pass publishes at most one event per aggregate, so a burst of N events of one aggregate needs N passes. A pass that found events starts the next one immediately, and different aggregates share a batch and spread across relays. + +Selection cost. The plan is a nested-loop anti join: an index scan of `outbox_events_unpublished_idx` in `position` order, one probe of `outbox_events_unpublished_aggregate_idx` per scanned row, and LIMIT on top, with no sort over the backlog; the generic plan of the prepared statement is the same. A pass reads rows until it has found `RELAY_BATCH_SIZE` aggregate heads, so it reads every non-head row in front of them. Measured with `EXPLAIN ANALYZE` on PostgreSQL in a scratch container with 100,000 pending rows and a batch of 100: 0.2 ms and 100 rows read when versions of 1,000 aggregates interleave; 16 ms and 9,901 rows read when each aggregate's 100 versions are contiguous; 225 ms and about 50,000 rows read when one aggregate has 50,000 pending versions ahead of 1,000 other aggregates. In the last case the hot aggregate drains one version per pass and every pass reads its remaining versions again, so draining k pending versions of one aggregate costs O(k²) row reads. Product aggregates change a few times per business action, so k stays small; a large k appears only when a writer emits many versions of one aggregate during a long Kafka outage. Publishing several consecutive versions of an aggregate whose head a pass has locked would remove that cost and is a possible later change. + +Kafka record: + +- Topic: `KAFKA_EVENTS_TOPIC`, `lincodex.domain.events` by default. All events go to one topic; consumers filter by `event_type`. One topic is enough while consumers are few, and per-aggregate order needs only the key. +- Key: `:`. The default franz-go partitioner hashes the key, so all events of an aggregate land in one partition in publication order. +- Value: a compact JSON envelope with `envelope_version` (currently 1; changes only with the envelope fields), `event_id`, `event_type`, `schema_version` (the payload layout version of that event type), `aggregate_type`, `aggregate_id`, `aggregate_version`, `occurred_at` (RFC 3339 in UTC, informational), and `payload` (the stored jsonb object, so key order can differ from what the writer appended). +- Headers: `event_id`, `event_type`, `schema_version`, so a consumer can deduplicate and route without decoding the value. + +The producer uses acks from all in-sync replicas and idempotent writes (the franz-go default). By default franz-go cannot fail an in-flight idempotent record until the broker answers, so behind a frozen broker the record and every later record of its partition would wait indefinitely. The relay enables `AllowIdempotentProduceCancellation`, which lets the delivery timeout and the pass deadline fail such a record, and `Publish` stops waiting at the deadline in any case. The client retries a record at most five times within one publish; later attempts belong to the next pass. Kafka does not create topics on demand: before its first pass the relay calls `Prepare`, which creates `KAFKA_EVENTS_TOPIC` through `kadm` with `KAFKA_EVENTS_TOPIC_PARTITIONS`, `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` (-1 by default, the broker's `default.replication.factor`), and, when set, `min.insync.replicas` from `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` (otherwise the broker default). It accepts an existing topic without changing it and logs one warning when that topic has another partition count or, with an explicit replication factor, another replication factor. A failed `Prepare` does not block startup: the relay retries it with backoff and events stay pending. When a publish reports an unknown topic, for example after the topic was deleted, the relay calls `Prepare` again before its next pass. With acks from all in-sync replicas, a write is durable only on `min.insync.replicas` brokers; the production requirement is in [DEPLOY.md](DEPLOY.md#outbox-relay). With `KAFKA_PROVISION_TOPICS=false` the topic is managed outside the backend. Adding partitions later moves keys to other partitions, so per-aggregate order is not guaranteed across that change. + +Failure semantics: + +- Kafka unavailable: the publish fails within `RELAY_PRODUCE_TIMEOUT`, nothing is marked, and the rows stay pending. The relay logs a warning with counts and the error (event IDs and broker errors, never payloads), waits a backoff, and retries indefinitely. The backoff starts at `RELAY_BACKOFF_INITIAL`, doubles with every consecutive failure up to `RELAY_BACKOFF_MAX`, and waits half the current value plus a random share of the other half. Business transactions write only to PostgreSQL, so an outage never rolls back a saved business action. +- Partial acknowledgement: only acknowledged events are marked; the rest are retried on later passes. Because a pass holds at most one event per aggregate, a failed event never lets a later version of its aggregate through. A pass that published at least one event resets the backoff and is followed by the next pass at once, so a failing event does not slow down the others; the backoff grows only across passes that published nothing. +- A failure after publish and before commit, including a crash or a lost database connection: the rows stay unpublished and a later pass publishes them again with the same `event_id`. A record whose publish timed out can also reach the broker later. Delivery is at least once: consumers must deduplicate by `event_id` and ignore an `aggregate_version` they already applied, because a late duplicate of an earlier version can follow a later version. +- Shutdown: when the process receives SIGTERM, the relay starts no new pass. A pass in progress has `SHUTDOWN_TIMEOUT` to finish and commit; after that it is canceled and its transaction rolls back. An unacknowledged event is never marked. Bootstrap closes the producer and the relay's pool only after the relay stopped. +- The transaction stays open during the publish, holding row locks on at most `RELAY_BATCH_SIZE` outbox rows and one connection for at most `RELAY_PRODUCE_TIMEOUT`. Business writes only insert new rows and are not blocked; the bound also limits how long the open transaction delays vacuum. A smaller batch or timeout shortens it. +- An event the broker rejects every time (a poison event; not expected, because the payload is at most 16 KiB and the topic is provisioned) blocks its own aggregate. While a pass still publishes other events, the relay keeps going at full speed. Because `ORDER BY position` returns the oldest heads first, every pass claims the poison heads again; when `RELAY_BATCH_SIZE` or more aggregate heads are poison, they fill the whole batch, no pass publishes anything, and the relay stalls at one pass per `RELAY_BACKOFF_MAX` while the backlog grows. An operator sees `failed` in `lincodex_outbox_relay_events_total` rising while `published` stays flat, `lincodex_outbox_relay_oldest_pending_age_seconds` growing, and warnings with the event IDs of the batch. The usual causes are on the Kafka side (the topic, its ACLs, or `min.insync.replicas` above the live replicas); after that is fixed, the next pass publishes everything. A raised `RELAY_BATCH_SIZE` lets other aggregates through meanwhile. There is no dead-letter path: an event that can never be published needs a decision by the owners of its consumers, and marking it published by hand skips it for every consumer. + +The metric `lincodex_outbox_relay_events_total{outcome}` counts published and failed events; a pending event is counted as failed on every attempt. The gauges `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` show the unpublished events and the age of the earliest one by `position`, measured by the database clock. The relay reads them with `GetOutboxBacklog`, which uses the partial index, at most once every 15 seconds, also while it retries `Prepare`, so a busy relay does not count the outbox on every pass. Every backend instance reports the same database-wide values; aggregate them with `max`. `/readyz` does not check Kafka, so a Kafka outage does not take the API out of service. ### Mail transport @@ -202,7 +237,7 @@ backend/ usecase/identity/ password validation before hashing (Credentials) usecase/policy/ publication of policy versions and the demo policy seed usecase/notification/mailtemplate/ pure rendering of versioned service emails for identity and delivery usecases (not wired yet) - port/outbound/ readiness, cache, object storage, transaction, outbox, identity, policy, password hashing, and mail boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, identity, policy, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -211,14 +246,16 @@ backend/ router.go chi composition adapter/secondary/ argon2id/ Argon2id password hasher with a memory budget + kafka/ franz-go event publisher: record envelope and events topic provisioning mail/disabled/ mail transport that sends nothing and reports the channel unavailable mail/resend/ mail transport that sends one request to the Resend HTTP API per message ml/api/ generated client from backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, outbox writer, identity and policy repositories, health check + postgres/ pool, migrator, transactor, outbox writer and relay store, identity and policy repositories, health check postgres/sqlc/ generated SQL adapter redis/ cache adapter and Redis check seaweedfs/ S3 adapter and bucket check prometheus/ bounded Go/process and request metrics + worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown bootstrap/ configuration, wiring, lifecycle, shutdown db/ embedded migrations and SQL queries; outbox, identity, and policy tables codegen/ ogen and sqlc configs @@ -227,9 +264,9 @@ backend/ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`. -Product domain types and usecase modules, the SMTP and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. +Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging; the identity usecases (verification and password reset) and the planned delivery usecase are expected to call it, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index d053632..7c082bb 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -51,21 +51,50 @@ The named `kafka_data` volume mounts at `/var/lib/kafka/data` and stores topic l Changing the value after the volume is formatted stops Kafka from starting with that volume. -Automatic topic creation is disabled: writing to a missing topic fails instead of creating it. Create each topic explicitly; provisioning topics for product events belongs to later work. Kafka CLI tools inherit the broker's `KAFKA_HEAP_OPTS`, so give them a small heap when running them in the container. For example, a manual technical check with the default `app` project: +Automatic topic creation is disabled: writing to a missing topic fails instead of creating it. The backend creates its events topic itself (see [Outbox relay](#outbox-relay)); create any other topic explicitly. Kafka CLI tools inherit the broker's `KAFKA_HEAP_OPTS`, so give them a small heap when running them in the container. For example, a manual technical check with the default `app` project: docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \ --bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \ --partitions 1 --replication-factor 1 -The Compose health check runs `kafka-broker-api-versions.sh` against `localhost:9092`, so Kafka is healthy only after the broker answers API requests. `make -C deploy smoke` waits for that health check together with the other core services; it does not publish or read events. +The Compose health check runs `kafka-broker-api-versions.sh` against `localhost:9092`, so Kafka is healthy only after the broker answers API requests. `make -C deploy smoke` waits for that health check together with the other core services; it does not check the relay or read events. -The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The backend has no Kafka client yet: it does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. +The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The outbox relay connects to these brokers in the background: the backend does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. `PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login will use it once they are implemented. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. +### Outbox relay + +The backend runs the outbox relay in its own process next to the HTTP servers. The relay publishes committed outbox events to Kafka; its design is in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay). Compose passes none of the settings below, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup. + +| Variable | Default | Meaning | +| --- | --- | --- | +| `RELAY_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, the relay does not run and events stay in the outbox. | +| `RELAY_BATCH_SIZE` | `100` | Events one pass locks and publishes, from 1 to 1000. | +| `RELAY_POLL_INTERVAL` | `1s` | Wait after a pass that found no pending event, from 10ms to 5m. | +| `RELAY_PRODUCE_TIMEOUT` | `10s` | Longest wait for the broker acknowledgements of one pass and for topic creation, from 1s to 2m. The pass keeps its transaction open for that long at most. | +| `RELAY_STATEMENT_TIMEOUT` | `5s` | Server-side `statement_timeout` of each SQL statement of a pass, from 100ms to 1m. The pass transaction also gets `idle_in_transaction_session_timeout` of `RELAY_PRODUCE_TIMEOUT` plus this value, so PostgreSQL ends the transaction of a frozen or disconnected backend and releases its locks. | +| `RELAY_BACKOFF_INITIAL` | `500ms` | Wait after the first failed pass; it doubles with each consecutive failure. | +| `RELAY_BACKOFF_MAX` | `30s` | Longest wait between retries, from `RELAY_BACKOFF_INITIAL` to 10m. | +| `KAFKA_EVENTS_TOPIC` | `lincodex.domain.events` | Topic for all domain events: up to 249 letters, digits, dots, underscores, or hyphens. | +| `KAFKA_EVENTS_TOPIC_PARTITIONS` | `3` | Partitions of a topic the relay creates, from 1 to 1000. | +| `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` | `-1` | Replication factor of a topic the relay creates: -1 takes the broker's `default.replication.factor`, otherwise from 1 to the broker count. | +| `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` | unset | `min.insync.replicas` of a topic the relay creates, at least 1 and not above an explicit replication factor. Unset leaves the broker default. | +| `KAFKA_PROVISION_TOPICS` | `true` | With `false` the relay never creates the topic, and every publish fails until the topic exists. | + +`SHUTDOWN_TIMEOUT` also bounds the relay: a pass in progress at shutdown has that long to finish, otherwise it rolls back and its events stay pending. Compose gives the backend `stop_grace_period: 20s`, more than the default 10s `SHUTDOWN_TIMEOUT`, so Docker does not kill the process while a pass commits; raise it together with `SHUTDOWN_TIMEOUT`. + +The single-node stand creates the topic with the broker defaults of the Compose Kafka: replication factor 1 and `min.insync.replicas` 1. That is acceptable only for this stand: one broker cannot replicate, and losing its volume loses the events. A production cluster needs at least three brokers, a replication factor of at least 3, and `min.insync.replicas` 2, either as broker defaults or through `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR=3` and `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS=2`. The producer always uses acks from all in-sync replicas, so with these values an acknowledged event survives the loss of one broker, and writes stop rather than land on a single replica when two of three brokers are down. + +The relay creates a missing topic and never changes an existing one; when the existing topic has another partition count or replication factor than configured, the relay logs one warning. Adding partitions to the topic later moves aggregate keys to other partitions, so per-aggregate order is not guaranteed across that change. + +When Kafka is unavailable, the backend still starts and serves the API. The relay logs warnings such as `outbox relay could not prepare the event bus` or `outbox relay pass failed` with the retry delay and keeps retrying; events stay in `outbox_events` until Kafka answers. In Compose the backend does not wait for the Kafka health check, so these warnings are expected during the first seconds after `make -C deploy up`. Relay logs carry the `outbox_relay` component and contain event IDs, counts, and broker errors, never payloads. + +The internal /metrics endpoint shows the backlog: `lincodex_outbox_relay_pending_events` and `lincodex_outbox_relay_oldest_pending_age_seconds` are refreshed at most every 15 seconds, and `lincodex_outbox_relay_events_total` counts the `published` and `failed` outcomes. A growing age with a flat `published` count means the relay is stuck; the relay warnings name the event IDs, and [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay) describes the causes. Every backend instance reports the same backlog, so aggregate it with `max`. Published rows stay in `outbox_events`; their retention is not implemented yet. + ## Mail The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 679d007..eb34637 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -44,7 +44,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b | chi | v5.3.2 | backend/go.mod | | pgx | v5.11.0 | backend/go.mod | | testcontainers-go | v0.44.0, including modules/postgres | backend/go.mod | -| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; integration tests only | backend/go.mod | +| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; outbox relay producer and integration tests | backend/go.mod | What exists now: @@ -53,11 +53,11 @@ What exists now: - Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). -- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. backend/config parses and validates `KAFKA_BROKERS`, but the application has no Kafka client, topics, or readiness check for Kafka. The franz-go client is used only by the integration test helpers; see [TESTING.md](TESTING.md#integration-test-bootstrap). +- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka, and nothing consumes the events yet. - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, a Kafka client in the application, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, event consumers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -179,6 +179,12 @@ At startup the backend publishes `domain.DemoProductPolicyV1()` as version 1 of A record that depends on policy values adds `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, stores the version it used, and reads it back by ID; do not recompute an existing record through `GetEffective`. Tests use their own values and do not stand in for the demo policy. Since `product` is the only family and the table refuses TRUNCATE, the integration tests give every case its own database. A new document layout needs a new `schema_version` and decoder; do not edit the golden document in `backend/internal/domain/policy_test.go` to accept a changed canonical form. See [ARCHITECTURE.md](ARCHITECTURE.md#product-policy-versions). +### Outbox relay + +The relay moves committed `outbox_events` rows to Kafka. The loop and its backoff live in `backend/internal/worker/outboxrelay/`; it depends on the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports in `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` runs the claim transaction with the `LockPendingOutboxEvents` and `MarkOutboxEventsPublished` queries from `backend/db/queries/outbox.sql`, and `kafka.Publisher` in `backend/internal/adapter/secondary/kafka/` builds the record envelope, provisions the topic, and produces with franz-go. `bootstrap.newOutboxRelay` creates the relay with its own PostgreSQL pool of at most two connections and its own Kafka client, and the application runs it while the HTTP servers run. Product code never calls the relay: a usecase only appends events with `UnitOfWork.Outbox()` in its business transaction. + +A directly launched backend with `DATABASE_URL` set runs the relay against `KAFKA_BROKERS` (`localhost:9092` by default). Without a reachable broker it keeps logging retry warnings and the events stay pending; set `RELAY_ENABLED=false` when you do not need publication. Selection, ordering, envelope, and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay); settings are in [DEPLOY.md](DEPLOY.md#outbox-relay); tests are in [TESTING.md](TESTING.md#outbox-relay-tests). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 111e2d3..e25ce2e 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -37,11 +37,11 @@ Security checks run separately: `make -C security check` scans source/dependenci ## Current scaffold coverage -Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no outbox relay or product events in Kafka, and no real model inference to validate as product behavior. +Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product events or event consumers in Kafka, and no real model inference to validate as product behavior. API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. -Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, and the backend startup log for `EMAIL_PROVIDER=disabled`. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. +Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. ## Browser E2E suite @@ -69,7 +69,25 @@ Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it app Kafka is not part of `bootstrap(t)` and starts only for tests that select `bootstrap(t, kafkaService)`. It runs the same `apache/kafka:latest` image as Compose with the same KRaft settings, including `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. The client listener is advertised on the dynamic host port, inter-broker and controller traffic stay on container loopback, and the data and declared image volumes use tmpfs, so a test broker leaves no volumes. Bootstrap sets `env.Config.KafkaBrokers` and creates `env.KafkaAdmin` from franz-go `kadm`. -`kafka_helpers_test.go` contains the helpers. `env.createKafkaTopic(ctx, t, partitions)` creates a topic with a unique random name and registers its deletion in `t.Cleanup` before creation, so the topic is removed even when the test fails. The broker never creates topics on demand: a test creates every topic it uses. `env.newKafkaClient(t, options...)` returns a `kgo` client that closes when `t` finishes. `produceKafkaRecords` and `env.consumeKafkaRecords` have bounded timeouts; the consumer reads partitions from the start without a consumer group, so no group offsets remain. The container is terminated in the cleanup of the test that called bootstrap, including after a failure. +`kafka_helpers_test.go` contains the helpers. `env.createKafkaTopic(ctx, t, partitions)` creates a topic with a unique random name and registers its deletion in `t.Cleanup` before creation, so the topic is removed even when the test fails. The broker never creates topics on demand: a test creates every topic it uses. `env.newKafkaClient(t, options...)` returns a `kgo` client that closes when `t` finishes. `produceKafkaRecords` and `env.consumeKafkaRecords` have bounded timeouts; the consumer reads partitions from the start without a consumer group, so no group offsets remain. The container is terminated in the cleanup of the test that called bootstrap, including after a failure. `env.pauseKafka(ctx, t)` freezes the broker with `docker pause` and returns a function that resumes it; cleanup also resumes it. A paused broker keeps its port and accepts connections but never answers, which models a hung broker. A stopped and restarted container would get a new host port that neither the advertised listener nor the clients follow, and its tmpfs topics would be gone. + +## Outbox relay tests + +Unit tests (`make -C backend test`) cover the record envelope, key, and headers and an invalid payload that is not quoted in the error (`internal/adapter/secondary/kafka/`), a publish and a topic creation that fail within the produce timeout plus a 2-second scheduling margin when the broker is unreachable (the tests assert the elapsed time), the mapping of an unknown topic to `ErrEventDestinationMissing`, the comparison of an existing topic with the configured layout, the backoff schedule with and without jitter, relay passes that mark only acknowledged events, retries after failed `Prepare` calls and passes, no backoff after a pass that published part of its batch while a poison event leads every batch, a new `Prepare` after a missing destination, at most one backlog read per interval, a pass in progress that finishes after cancellation, a pass canceled by the shutdown timeout, a stop during backoff (`internal/worker/outboxrelay/`), the relay and topic settings, including the broker-default replication factor and `min.insync.replicas` (`config/`), SQLSTATE-only database errors and timeouts that would round to no limit (`internal/adapter/secondary/postgres/`), the relay counter and backlog gauges, and an application that runs the relay while serving and stops it with the servers (`internal/bootstrap/`). + +`TestOutboxRelay` in `backend/integration_test/outbox_relay_test.go` uses `bootstrap(t, postgresService, kafkaService)`, writes events through the transactor with a test aggregate, and runs these sequential cases, each with its own topic: + +- A committed event is published as the documented envelope with its key and headers, and `published_at` is set. +- Kafka outage: with the broker paused, a business transaction still commits, the relay pass fails within the produce timeout, both events stay pending, and the business rows are intact. After the broker resumes, the relay publishes both and a consumer receives them with their `event_id`. +- Failure between publish and mark: a publisher wrapper produces for real and then cancels the pass, as a killed process would; the row stays pending, and a new relay publishes it again, so the topic holds two records with the same `event_id`. +- Competing claims: while one claim holds the earliest events of two aggregates, a second claim on a pool with a 500 ms `lock_timeout` gets only the third aggregate, without waiting and without the first aggregate's version 2; the next pass gets version 2. +- Two relays run while 12 concurrent writers each commit 8 versions of their own aggregate. Every event is published, each aggregate stays in one partition, and the first delivery of each version follows `aggregate_version` order. A publisher wrapper adds 10 ms to every publish so the relays' passes overlap; the test logs how many events each relay published. +- Shutdown with the broker paused and a 30-second produce timeout: the relay stops no sooner than the 1-second shutdown timeout and within 5 seconds after it, so only the shutdown timeout could have ended the pass; its event stays pending, and no connection stays busy. +- Idle timeout: a claim whose publish callback ignores its context for 2 seconds, with a 300 ms `idle_in_transaction_session_timeout`, fails with SQLSTATE 25P03; the event stays pending, and no connection stays busy. +- `Backlog` reports zero for an empty outbox and two pending events with a positive age after two writes. +- `Prepare` creates a topic with the configured partitions, the broker default replication factor, and a topic-level `min.insync.replicas`, and accepts the topic again. + +The suite runs against one broker and one PostgreSQL. It does not measure throughput or latency, does not cover broker failover or replication, and does not test consumers; consumer deduplication is TASK-010. ## Integration test sharding diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index a46a5e4..0981e14 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -50,7 +50,7 @@ Redis входит в основной Compose и подключен через SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Загрузка резюме, проверка прав, ограничения содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование. -Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, таблица `outbox_events` и ее транзакционная запись уже есть, а Go клиент Kafka и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. +Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Потребители событий пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. ### Transactional outbox @@ -75,7 +75,42 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction `domain.NewDomainEvent` проверяет событие. Компактный JSON payload ограничен 16 KiB и 32 уровнями вложенности; числа должны помещаться в float64; символы NUL отклоняются, потому что jsonb не может их хранить. jsonb нормализует сохраненный payload (порядок ключей, пробелы, дублирующиеся ключи), поэтому потребители сравнивают JSON-значения, а не байты. Payload содержит только идентификаторы и минимальные факты, но не контакты, токены, пароли, содержимое резюме и документов. -Запланированный контракт relay (TASK-009): на каждом проходе relay выбирает неопубликованные строки (`published_at IS NULL`) в порядке `position` и никогда не хранит watermark по `occurred_at` или `position`, потому что строка с меньшей позицией может стать видимой после фиксации строки с большей. События одного агрегата он публикует в порядке `aggregate_version` и затем заполняет `published_at`. Также запланированы учет повторов (счетчик попыток и последняя ошибка, добавятся аддитивной миграцией), хранение опубликованных строк, топики и идемпотентные потребители. Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. +Relay, который публикует эти строки, описан в разделе [Relay outbox](#relay-outbox). Еще запланированы колонки учета повторов (счетчик попыток и последняя ошибка), хранение опубликованных строк и идемпотентные потребители (TASK-010). Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. + +### Relay outbox + +Реализовано (TASK-009): цикл relay в `backend/internal/worker/outboxrelay/`, порты `outbound.OutboxRelayStore` и `outbound.EventPublisher` (`backend/internal/port/outbound/outbox_relay.go`), хранилище PostgreSQL (`adapter/secondary/postgres/outbox_relay.go`) и producer на franz-go (`adapter/secondary/kafka/`). Bootstrap запускает relay вместе с HTTP-серверами в том же процессе и останавливает его при завершении. У relay свой пул PostgreSQL не больше чем на два соединения: одно для транзакции захвата и одно для чтения размера очереди, поэтому он не забирает соединения у обработки запросов. Relay не запускается при `RELAY_ENABLED=false` или без `DATABASE_URL`; тогда события остаются в outbox. Настройки перечислены в [DEPLOY.md](DEPLOY.md#relay-outbox). + +Один проход - одна транзакция READ COMMITTED: + +1. `SetRelayTransactionTimeouts` задает только для этой транзакции (`SET LOCAL` через `set_config`) `statement_timeout` равным `RELAY_STATEMENT_TIMEOUT` и `idle_in_transaction_session_timeout` равным `RELAY_PRODUCE_TIMEOUT + RELAY_STATEMENT_TIMEOUT`. Контекст прохода и так отменяет медленный проход живого процесса; ограничения на стороне сервера действуют и тогда, когда процесс завис или потерял сеть, не закрыв соединение: сервер завершает транзакцию и снимает ее блокировки строк, а не ждет TCP keepalive. +2. `LockPendingOutboxEvents` выбирает строки с `published_at IS NULL` в порядке `position`, не больше `RELAY_BATCH_SIZE`, с `FOR UPDATE OF pending SKIP LOCKED`. Строка подходит, только если это самое раннее неопубликованное событие своего агрегата (наименьшая `aggregate_version`, затем `position`). Watermark по `position` или `occurred_at` нет; каждый проход заново просматривает неопубликованные строки. +3. Relay публикует пачку и ждет подтверждений брокера не дольше `RELAY_PRODUCE_TIMEOUT`. +4. `MarkOutboxEventsPublished` заполняет `published_at` ровно для подтвержденных ID событий, и транзакция фиксируется. + +Против одной базы могут работать несколько relay, например несколько экземпляров backend. SKIP LOCKED позволяет им брать разные строки без ожидания. При обычном SKIP LOCKED второй relay мог бы пропустить заблокированную версию 1 и первым опубликовать версию 2; правило самого раннего события это исключает: версия 2 не подходит, пока версия 1 не опубликована, независимо от того, держит ли ее другой relay, оставил ли ее в ожидании неудачный проход или проход откатился. Правило опирается на то, что writer агрегата проверяет ожидаемую версию: тогда версия 2 фиксируется только после версии 1, и запрос, который видит версию 2, видит и версию 1. Миграция `00004_add_outbox_relay_index.sql` добавляет для этой проверки частичный индекс `(aggregate_type, aggregate_id, aggregate_version, position) WHERE published_at IS NULL`. Компромисс: за проход публикуется не больше одного события агрегата, поэтому серии из N событий одного агрегата нужно N проходов. Проход, который нашел события, сразу запускает следующий, а разные агрегаты попадают в одну пачку и распределяются между relay. + +Стоимость выбора. План - nested loop anti join: index scan по `outbox_events_unpublished_idx` в порядке `position`, одна проба `outbox_events_unpublished_aggregate_idx` на каждую прочитанную строку и LIMIT сверху, без сортировки всей очереди; generic plan подготовленного запроса такой же. Проход читает строки, пока не найдет `RELAY_BATCH_SIZE` голов агрегатов, поэтому читает и все строки не-голов перед ними. Замер `EXPLAIN ANALYZE` на PostgreSQL во временном контейнере со 100 000 ожидающих строк и пачкой 100: 0,2 ms и 100 прочитанных строк, когда версии 1 000 агрегатов перемешаны; 16 ms и 9 901 строка, когда 100 версий каждого агрегата идут подряд; 225 ms и около 50 000 строк, когда у одного агрегата 50 000 ожидающих версий впереди 1 000 других агрегатов. В последнем случае горячий агрегат уходит по одной версии за проход, и каждый проход заново читает его оставшиеся версии, поэтому разбор k ожидающих версий одного агрегата стоит O(k²) чтений строк. Продуктовые агрегаты меняются несколько раз за бизнес-действие, так что k остается небольшим; большое k появляется, только если writer выпускает много версий одного агрегата во время долгого сбоя Kafka. Публикация нескольких подряд идущих версий агрегата, голову которого проход уже заблокировал, убрала бы эту стоимость; это возможное будущее изменение. + +Запись Kafka: + +- Топик: `KAFKA_EVENTS_TOPIC`, по умолчанию `lincodex.domain.events`. Все события идут в один топик; потребители фильтруют по `event_type`. Пока потребителей немного, одного топика достаточно, а для порядка внутри агрегата нужен только ключ. +- Ключ: `:`. Partitioner franz-go по умолчанию хеширует ключ, поэтому все события агрегата попадают в одну партицию в порядке публикации. +- Значение: компактный JSON-конверт с полями `envelope_version` (сейчас 1; меняется только вместе с полями конверта), `event_id`, `event_type`, `schema_version` (версия формата payload этого типа события), `aggregate_type`, `aggregate_id`, `aggregate_version`, `occurred_at` (RFC 3339 в UTC, только для информации) и `payload` (сохраненный jsonb-объект, поэтому порядок ключей может отличаться от записанного). +- Заголовки: `event_id`, `event_type`, `schema_version`, чтобы потребитель мог убрать дубликаты и выбрать обработчик, не декодируя значение. + +Producer требует подтверждения от всех in-sync реплик и использует идемпотентную запись (значение franz-go по умолчанию). По умолчанию franz-go не может завершить ошибкой идемпотентную запись, которая уже отправлена, пока брокер не ответит, поэтому за замершим брокером эта запись и все следующие записи ее партиции ждали бы бесконечно. Relay включает `AllowIdempotentProduceCancellation`: тогда такую запись завершают таймаут доставки и срок прохода, а `Publish` в любом случае перестает ждать по сроку. Внутри одной публикации клиент повторяет запись не больше пяти раз; следующие попытки делает уже следующий проход. Kafka не создает топики по запросу: перед первым проходом relay вызывает `Prepare`, который через `kadm` создает `KAFKA_EVENTS_TOPIC` с `KAFKA_EVENTS_TOPIC_PARTITIONS`, `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` (по умолчанию -1, то есть `default.replication.factor` брокера) и, если задано, `min.insync.replicas` из `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` (иначе значение брокера по умолчанию). Существующий топик он принимает без изменений и один раз пишет предупреждение, если у топика другое число партиций или, при явно заданном факторе репликации, другой фактор репликации. Ошибка `Prepare` не блокирует старт: relay повторяет его с backoff, события остаются в ожидании. Если публикация сообщает о неизвестном топике, например после его удаления, relay снова вызывает `Prepare` перед следующим проходом. При подтверждении от всех in-sync реплик запись надежна только на `min.insync.replicas` брокерах; требование для production описано в [DEPLOY.md](DEPLOY.md#relay-outbox). При `KAFKA_PROVISION_TOPICS=false` топиком управляют вне backend. Добавление партиций позже переносит ключи в другие партиции, поэтому порядок внутри агрегата через такое изменение не гарантируется. + +Поведение при сбоях: + +- Kafka недоступна: публикация завершается ошибкой не позже `RELAY_PRODUCE_TIMEOUT`, ничего не отмечается, строки остаются в ожидании. Relay пишет предупреждение со счетчиками и ошибкой (ID событий и ошибки брокера, без payload), ждет backoff и повторяет без ограничения числа попыток. Backoff начинается с `RELAY_BACKOFF_INITIAL`, удваивается после каждой следующей неудачи до `RELAY_BACKOFF_MAX` и равен половине текущего значения плюс случайная доля второй половины. Бизнес-транзакции пишут только в PostgreSQL, поэтому сбой Kafka никогда не откатывает сохраненное бизнес-действие. +- Частичное подтверждение: отмечаются только подтвержденные события, остальные повторяются на следующих проходах. Поскольку проход держит не больше одного события агрегата, неудачное событие никогда не пропускает вперед более позднюю версию своего агрегата. Проход, который опубликовал хотя бы одно событие, сбрасывает backoff, и следующий проход начинается сразу, поэтому неудачное событие не замедляет остальные; backoff растет только между проходами, которые ничего не опубликовали. +- Сбой после публикации и до commit, включая падение процесса или потерю соединения с базой: строки остаются неопубликованными, и следующий проход публикует их снова с тем же `event_id`. Запись, публикация которой завершилась по таймауту, тоже может дойти до брокера позже. Доставка - at least once: потребители должны убирать дубликаты по `event_id` и пропускать уже примененную `aggregate_version`, потому что поздний дубликат ранней версии может прийти после более поздней. +- Остановка: после SIGTERM relay не начинает новых проходов. Проход в работе получает `SHUTDOWN_TIMEOUT`, чтобы закончить и зафиксироваться; затем он отменяется, и его транзакция откатывается. Неподтвержденное событие никогда не отмечается. Bootstrap закрывает producer и пул relay только после остановки relay. +- Во время публикации транзакция остается открытой и держит блокировки не больше чем `RELAY_BATCH_SIZE` строк outbox и одно соединение не дольше `RELAY_PRODUCE_TIMEOUT`. Бизнес-запись только вставляет новые строки и не блокируется; тот же предел ограничивает, насколько открытая транзакция задерживает vacuum. Меньшая пачка или таймаут сокращают это время. +- Событие, которое брокер отклоняет каждый раз (ядовитое событие; не ожидается, потому что payload не больше 16 KiB, а топик создается заранее), блокирует свой агрегат. Пока проход публикует другие события, relay работает на полной скорости. Поскольку `ORDER BY position` возвращает самые старые головы первыми, каждый проход снова захватывает ядовитые головы; если таких голов агрегатов `RELAY_BATCH_SIZE` или больше, они занимают всю пачку, ни один проход ничего не публикует, и relay застревает на одном проходе за `RELAY_BACKOFF_MAX`, пока очередь растет. Оператор видит, что в `lincodex_outbox_relay_events_total` растет `failed`, а `published` стоит на месте, что растет `lincodex_outbox_relay_oldest_pending_age_seconds`, и видит предупреждения с ID событий пачки. Обычная причина на стороне Kafka (топик, его ACL или `min.insync.replicas` больше числа живых реплик); после ее устранения следующий проход публикует все. Увеличенный `RELAY_BATCH_SIZE` тем временем пропускает другие агрегаты. Пути dead letter нет: событие, которое никогда не удастся опубликовать, требует решения владельцев его потребителей, а ручная отметка о публикации пропускает его для всех потребителей. + +Метрика `lincodex_outbox_relay_events_total{outcome}` считает опубликованные и неудачные события; событие в ожидании учитывается как неудачное при каждой попытке. Gauge-метрики `lincodex_outbox_relay_pending_events` и `lincodex_outbox_relay_oldest_pending_age_seconds` показывают число неопубликованных событий и возраст самого раннего из них по `position` по часам базы. Relay читает их запросом `GetOutboxBacklog`, который использует частичный индекс, не чаще раза в 15 секунд, в том числе пока повторяет `Prepare`, поэтому занятый relay не считает outbox на каждом проходе. Все экземпляры backend сообщают одни и те же значения для всей базы; агрегируйте их через `max`. `/readyz` не проверяет Kafka, поэтому сбой Kafka не выводит API из работы. ### Почтовый транспорт @@ -202,7 +237,7 @@ backend/ usecase/identity/ проверка пароля до хеширования (Credentials) usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем для usecase identity и доставки (пока не подключен) - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, политики, хеширования паролей и почты + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации событий, identity, политики, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -211,14 +246,16 @@ backend/ router.go сборка chi router adapter/secondary/ argon2id/ hasher паролей Argon2id с бюджетом памяти + kafka/ publisher событий на franz-go: конверт записи и создание топика событий mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend ml/api/ generated client из backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, запись outbox, репозитории identity и политики, health check + postgres/ pool, migrator, transactor, запись outbox и хранилище relay, репозитории identity и политики, health check postgres/sqlc/ generated SQL adapter redis/ адаптер кеша и проверка Redis seaweedfs/ S3-адаптер и проверка bucket prometheus/ ограниченные Go/process и request metrics + worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка bootstrap/ конфигурация, wiring, lifecycle, shutdown db/ встроенные миграции и SQL-запросы; таблицы outbox, identity и политики codegen/ конфигурация ogen и sqlc @@ -227,9 +264,9 @@ backend/ Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`. -`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. +`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования; его должны вызывать usecase identity (подтверждение почты и сброс пароля) и запланированный usecase доставки, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 0ef7979..da70163 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -53,21 +53,50 @@ Kafka использует официальный образ `apache/kafka:lates После форматирования volume смена значения не даст Kafka запуститься с этим volume. -Автоматическое создание топиков отключено: запись в отсутствующий топик завершается ошибкой, а не создает его. Создавайте каждый топик явно; создание топиков для продуктовых событий относится к следующим задачам. CLI-утилиты Kafka наследуют `KAFKA_HEAP_OPTS` брокера, поэтому при запуске в контейнере задавайте им небольшой heap. Пример ручной технической проверки для проекта по умолчанию `app`: +Автоматическое создание топиков отключено: запись в отсутствующий топик завершается ошибкой, а не создает его. Топик событий backend создает сам (см. [Relay outbox](#relay-outbox)); любой другой топик создавайте явно. CLI-утилиты Kafka наследуют `KAFKA_HEAP_OPTS` брокера, поэтому при запуске в контейнере задавайте им небольшой heap. Пример ручной технической проверки для проекта по умолчанию `app`: docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \ --bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \ --partitions 1 --replication-factor 1 -Compose healthcheck запускает `kafka-broker-api-versions.sh` против `localhost:9092`, поэтому Kafka считается healthy только после того, как брокер отвечает на API-запросы. `make -C deploy smoke` ждет этот healthcheck вместе с остальными core сервисами, но не публикует и не читает события. +Compose healthcheck запускает `kafka-broker-api-versions.sh` против `localhost:9092`, поэтому Kafka считается healthy только после того, как брокер отвечает на API-запросы. `make -C deploy smoke` ждет этот healthcheck вместе с остальными core сервисами, но не проверяет relay и не читает события. -Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Kafka клиента в backend пока нет: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь. +Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Relay outbox подключается к этим брокерам в фоне: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь. `PASSWORD_HASH_CONCURRENCY` задает бюджет памяти Argon2id в вычислениях по 64 MiB и четыре lanes каждое (от 1 до 4). Compose передает значение из `.env`, по умолчанию 1, потому что у backend-контейнера 1 CPU и 768 MB: второе вычисление только добавило бы 64 MiB, деля тот же CPU. Backend, запущенный напрямую без переменной, берет меньшее из 2 и GOMAXPROCS. Следующие регистрации и входы ждут память, пока не завершится контекст запроса. Compose также задает `GOMEMLIMIT=600MiB`, примерно 78% лимита контейнера, чтобы сборщик Go освобождал память завершенных вычислений раньше, чем контейнеру ее не хватит; меняйте его вместе с лимитом памяти. Значение читается и проверяется при старте; регистрация и вход начнут его использовать, когда будут реализованы. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. +### Relay outbox + +Backend запускает relay outbox в своем процессе рядом с HTTP-серверами. Relay публикует зафиксированные события outbox в Kafka; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#relay-outbox). Compose не передает ни одну из настроек ниже, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает старт. + +| Переменная | По умолчанию | Назначение | +| --- | --- | --- | +| `RELAY_ENABLED` | `true` | `true` или `false`. При `false` или без `DATABASE_URL` relay не работает, и события остаются в outbox. | +| `RELAY_BATCH_SIZE` | `100` | Сколько событий проход блокирует и публикует, от 1 до 1000. | +| `RELAY_POLL_INTERVAL` | `1s` | Пауза после прохода, который не нашел ожидающих событий, от 10ms до 5m. | +| `RELAY_PRODUCE_TIMEOUT` | `10s` | Наибольшее ожидание подтверждений брокера для одного прохода и создания топика, от 1s до 2m. Столько же, не больше, проход держит транзакцию открытой. | +| `RELAY_STATEMENT_TIMEOUT` | `5s` | `statement_timeout` на стороне сервера для каждого SQL-запроса прохода, от 100ms до 1m. Транзакция прохода также получает `idle_in_transaction_session_timeout`, равный `RELAY_PRODUCE_TIMEOUT` плюс это значение, поэтому PostgreSQL завершает транзакцию зависшего или отключившегося backend и снимает его блокировки. | +| `RELAY_BACKOFF_INITIAL` | `500ms` | Пауза после первого неудачного прохода; удваивается после каждой следующей неудачи. | +| `RELAY_BACKOFF_MAX` | `30s` | Наибольшая пауза между повторами, от `RELAY_BACKOFF_INITIAL` до 10m. | +| `KAFKA_EVENTS_TOPIC` | `lincodex.domain.events` | Топик всех доменных событий: до 249 латинских букв, цифр, точек, подчеркиваний или дефисов. | +| `KAFKA_EVENTS_TOPIC_PARTITIONS` | `3` | Число партиций топика, который создает relay, от 1 до 1000. | +| `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR` | `-1` | Фактор репликации топика, который создает relay: -1 берет `default.replication.factor` брокера, иначе от 1 до числа брокеров. | +| `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS` | не задано | `min.insync.replicas` топика, который создает relay: не меньше 1 и не больше явно заданного фактора репликации. Если не задано, действует значение брокера по умолчанию. | +| `KAFKA_PROVISION_TOPICS` | `true` | При `false` relay никогда не создает топик, и каждая публикация завершается ошибкой, пока топика нет. | + +`SHUTDOWN_TIMEOUT` ограничивает и relay: проход, который идет в момент остановки, получает это время, чтобы закончить, иначе он откатывается, и его события остаются в ожидании. Compose задает backend `stop_grace_period: 20s`, больше `SHUTDOWN_TIMEOUT` по умолчанию (10s), чтобы Docker не убил процесс во время фиксации прохода; увеличивайте его вместе с `SHUTDOWN_TIMEOUT`. + +Одноузловой стенд создает топик со значениями по умолчанию брокера из Compose: фактор репликации 1 и `min.insync.replicas` 1. Это допустимо только для такого стенда: один брокер не может реплицировать данные, и потеря его volume означает потерю событий. Production-кластеру нужны не меньше трех брокеров, фактор репликации не меньше 3 и `min.insync.replicas` 2 - либо как значения брокера по умолчанию, либо через `KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR=3` и `KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS=2`. Producer всегда требует подтверждения от всех in-sync реплик, поэтому с этими значениями подтвержденное событие переживает потерю одного брокера, а при недоступности двух брокеров из трех запись останавливается, а не попадает на единственную реплику. + +Relay создает отсутствующий топик и никогда не меняет существующий; если у существующего топика другое число партиций или другой фактор репликации, relay один раз пишет предупреждение. Если позже добавить топику партиции, ключи агрегатов перейдут в другие партиции, поэтому порядок внутри агрегата через такое изменение не гарантируется. + +Если Kafka недоступна, backend все равно стартует и обслуживает API. Relay пишет предупреждения вроде `outbox relay could not prepare the event bus` или `outbox relay pass failed` с паузой до повтора и продолжает повторять; события остаются в `outbox_events`, пока Kafka не ответит. В Compose backend не ждет healthcheck Kafka, поэтому в первые секунды после `make -C deploy up` такие предупреждения ожидаемы. Логи relay помечены компонентом `outbox_relay` и содержат ID событий, счетчики и ошибки брокера, но никогда не payload. + +Очередь неопубликованных событий видна на внутреннем endpoint /metrics: `lincodex_outbox_relay_pending_events` и `lincodex_outbox_relay_oldest_pending_age_seconds` обновляются не чаще раза в 15 секунд, а `lincodex_outbox_relay_events_total` считает исходы `published` и `failed`. Если возраст растет, а счетчик `published` стоит на месте, relay застрял; предупреждения relay называют ID событий, а причины описаны в [ARCHITECTURE.md](ARCHITECTURE.md#relay-outbox). Все экземпляры backend сообщают одну и ту же очередь, поэтому агрегируйте ее через `max`. Опубликованные строки остаются в `outbox_events`; срок их хранения пока не реализован. + ## Почта Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 157d7b8..79225e5 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -44,7 +44,7 @@ Frontend зависимости выбираются из актуальных s | chi | v5.3.2 | backend/go.mod | | pgx | v5.11.0 | backend/go.mod | | testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod | -| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; только integration tests | backend/go.mod | +| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; producer relay outbox и integration tests | backend/go.mod | Что есть сейчас: @@ -53,11 +53,11 @@ Frontend зависимости выбираются из актуальных s - Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). -- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. backend/config разбирает и проверяет `KAFKA_BROKERS`, но в приложении нет клиента Kafka, топиков и проверки Kafka в readiness. Клиент franz-go используется только helpers интеграционных тестов; см. [TESTING.md](TESTING.md#bootstrap-интеграционных-тестов). +- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka, и события пока никто не читает. - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, клиент Kafka в приложении, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, потребители событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -179,6 +179,12 @@ goose выполняет каждую миграцию в отдельной т Запись, которая зависит от значений политики, добавляет `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)`, хранит использованную версию и читает ее обратно по ID; не пересчитывайте существующую запись через `GetEffective`. Тесты используют собственные значения и не подменяют демонстрационную политику. Поскольку `product` - единственное семейство, а таблица отклоняет TRUNCATE, интеграционные тесты дают каждому случаю отдельную базу данных. Новой структуре документа нужны новая `schema_version` и свой декодер; не меняйте golden-документ в `backend/internal/domain/policy_test.go`, чтобы принять измененную каноническую форму. См. [ARCHITECTURE.md](ARCHITECTURE.md#версии-продуктовой-политики). +### Relay outbox + +Relay переносит зафиксированные строки `outbox_events` в Kafka. Цикл и его backoff находятся в `backend/internal/worker/outboxrelay/`; он зависит от портов `outbound.OutboxRelayStore` и `outbound.EventPublisher` в `backend/internal/port/outbound/outbox_relay.go`. `postgres.OutboxRelayStore` выполняет транзакцию захвата запросами `LockPendingOutboxEvents` и `MarkOutboxEventsPublished` из `backend/db/queries/outbox.sql`, а `kafka.Publisher` в `backend/internal/adapter/secondary/kafka/` собирает конверт записи, создает топик и публикует через franz-go. `bootstrap.newOutboxRelay` создает relay с собственным пулом PostgreSQL не больше чем на два соединения и собственным клиентом Kafka, а приложение запускает его, пока работают HTTP-серверы. Продуктовый код relay не вызывает: usecase только добавляет события через `UnitOfWork.Outbox()` в своей бизнес-транзакции. + +Backend, запущенный напрямую с `DATABASE_URL`, запускает relay против `KAFKA_BROKERS` (по умолчанию `localhost:9092`). Без доступного брокера он продолжает писать предупреждения о повторах, а события остаются в ожидании; если публикация не нужна, задайте `RELAY_ENABLED=false`. Выбор строк, порядок, конверт и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#relay-outbox), настройки - в [DEPLOY.md](DEPLOY.md#relay-outbox), тесты - в [TESTING.md](TESTING.md#тесты-relay-outbox). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 5a2a3e2..e447396 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -37,11 +37,11 @@ make -C ml check-generated использует datamodel-code-generator --check ## Что покрывает текущий каркас -Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет relay для outbox и продуктовых событий в Kafka и нет реального model inference, которые можно было бы проверить как бизнес-результат. +Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых событий и их потребителей в Kafka и нет реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. -Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. +Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. ## Браузерный E2E набор @@ -69,7 +69,25 @@ Bootstrap поднимает инфраструктуру и клиенты. Е Kafka не входит в `bootstrap(t)` и запускается только для тестов, которые выбирают `bootstrap(t, kafkaService)`. Используется тот же образ `apache/kafka:latest`, что и в Compose, с теми же настройками KRaft, включая `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. Клиентский listener объявляется на динамическом порту хоста, трафик между брокерами и контроллером остается на loopback контейнера, а данные и объявленные в образе volume размещаются в tmpfs, поэтому тестовый брокер не оставляет volume. Bootstrap заполняет `env.Config.KafkaBrokers` и создает `env.KafkaAdmin` на основе `kadm` из franz-go. -Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx, t, partitions)` создает топик с уникальным случайным именем и до создания регистрирует его удаление в `t.Cleanup`, поэтому топик удаляется и после падения теста. Брокер не создает топики по запросу: тест сам создает каждый нужный ему топик. `env.newKafkaClient(t, options...)` возвращает клиент `kgo`, который закрывается по завершении `t`. У `produceKafkaRecords` и `env.consumeKafkaRecords` ограниченные таймауты; consumer читает партиции с начала без consumer group, поэтому смещения группы не остаются. Контейнер останавливается и удаляется в cleanup теста, который вызвал bootstrap, в том числе после падения. +Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx, t, partitions)` создает топик с уникальным случайным именем и до создания регистрирует его удаление в `t.Cleanup`, поэтому топик удаляется и после падения теста. Брокер не создает топики по запросу: тест сам создает каждый нужный ему топик. `env.newKafkaClient(t, options...)` возвращает клиент `kgo`, который закрывается по завершении `t`. У `produceKafkaRecords` и `env.consumeKafkaRecords` ограниченные таймауты; consumer читает партиции с начала без consumer group, поэтому смещения группы не остаются. Контейнер останавливается и удаляется в cleanup теста, который вызвал bootstrap, в том числе после падения. `env.pauseKafka(ctx, t)` замораживает брокер через `docker pause` и возвращает функцию, которая его возобновляет; cleanup тоже возобновляет брокер. Приостановленный брокер сохраняет порт и принимает соединения, но не отвечает, что моделирует зависший брокер. Остановленный и снова запущенный контейнер получил бы новый порт на хосте, за которым не следуют ни объявленный listener, ни клиенты, а его топики в tmpfs пропали бы. + +## Тесты relay outbox + +Unit-тесты (`make -C backend test`) покрывают конверт записи, ключ и заголовки, а также ошибку для некорректного payload без его цитирования (`internal/adapter/secondary/kafka/`), публикацию и создание топика, которые завершаются ошибкой в пределах таймаута публикации плюс 2 секунды запаса на планирование, когда брокер недоступен (тесты проверяют затраченное время), преобразование неизвестного топика в `ErrEventDestinationMissing`, сравнение существующего топика с настроенной раскладкой, расписание backoff с jitter и без него, проходы relay, которые отмечают только подтвержденные события, повторы после неудачных `Prepare` и проходов, отсутствие backoff после прохода, который опубликовал часть пачки, пока ядовитое событие стоит первым в каждой пачке, повторный `Prepare` после отсутствующего назначения, не больше одного чтения размера очереди за интервал, проход в работе, который завершается после отмены, проход, отмененный таймаутом остановки, остановку во время backoff (`internal/worker/outboxrelay/`), настройки relay и топика, включая фактор репликации и `min.insync.replicas` по умолчанию брокера (`config/`), ошибки базы только с SQLSTATE и таймауты, которые округлились бы до отсутствия ограничения (`internal/adapter/secondary/postgres/`), счетчик relay и gauge-метрики очереди и приложение, которое запускает relay вместе с серверами и останавливает его вместе с ними (`internal/bootstrap/`). + +`TestOutboxRelay` в `backend/integration_test/outbox_relay_test.go` использует `bootstrap(t, postgresService, kafkaService)`, пишет события через transactor с тестовым агрегатом и последовательно выполняет случаи, у каждого свой топик: + +- Зафиксированное событие публикуется в документированном конверте с ключом и заголовками, и заполняется `published_at`. +- Сбой Kafka: при приостановленном брокере бизнес-транзакция все равно фиксируется, проход relay завершается ошибкой в пределах таймаута публикации, оба события остаются в ожидании, бизнес-строки не тронуты. После возобновления брокера relay публикует оба события, и потребитель получает их с их `event_id`. +- Сбой между публикацией и отметкой: обертка publisher действительно публикует, а затем отменяет проход, как при убитом процессе; строка остается в ожидании, новый relay публикует ее снова, и в топике две записи с одним `event_id`. +- Конкурирующий захват: пока один захват держит самые ранние события двух агрегатов, второй захват через пул с `lock_timeout` 500 ms получает только третий агрегат, не ожидая блокировок и без версии 2 первого агрегата; следующий проход получает версию 2. +- Два relay работают, пока 12 параллельных writer фиксируют по 8 версий своего агрегата. Публикуются все события, каждый агрегат остается в одной партиции, а первая доставка каждой версии идет в порядке `aggregate_version`. Обертка publisher добавляет 10 ms к каждой публикации, чтобы проходы relay пересекались; тест пишет в лог, сколько событий опубликовал каждый relay. +- Остановка при приостановленном брокере и таймауте публикации 30 секунд: relay останавливается не раньше таймаута остановки в 1 секунду и не позже 5 секунд после него, поэтому проход мог завершить только таймаут остановки; его событие остается в ожидании, и ни одно соединение не остается занятым. +- Таймаут простоя: захват, callback публикации которого 2 секунды игнорирует свой контекст, при `idle_in_transaction_session_timeout` 300 ms завершается ошибкой SQLSTATE 25P03; событие остается в ожидании, и ни одно соединение не остается занятым. +- `Backlog` возвращает ноль для пустого outbox и два ожидающих события с положительным возрастом после двух записей. +- `Prepare` создает топик с настроенным числом партиций, фактором репликации брокера по умолчанию и `min.insync.replicas` на уровне топика и повторно принимает существующий топик. + +Набор работает с одним брокером и одним PostgreSQL. Он не измеряет пропускную способность и задержку, не покрывает переключение брокеров и репликацию и не тестирует потребителей; удаление дубликатов у потребителя относится к TASK-010. ## Шардирование интеграционных тестов