From 3adb0ef9e429a7e6947718e57d793c376cf33220 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 03:59:57 +0300 Subject: [PATCH] feat(events): add idempotent Kafka event consumer runtime --- backend/config/config.go | 28 + backend/config/consumer.go | 169 +++ backend/config/consumer_test.go | 126 ++ .../00005_create_event_consumer_tables.sql | 95 ++ backend/db/queries/event_consumer.sql | 63 + backend/go.mod | 2 +- .../integration_test/event_consumer_test.go | 1207 +++++++++++++++++ backend/integration_test/outbox_relay_test.go | 3 +- .../postgres_migrations_test.go | 19 +- .../adapter/secondary/kafka/consumer.go | 290 ++++ .../adapter/secondary/kafka/consumer_test.go | 78 ++ .../adapter/secondary/kafka/envelope.go | 95 ++ .../adapter/secondary/kafka/envelope_test.go | 105 ++ .../secondary/postgres/event_consumer.go | 206 +++ .../secondary/postgres/event_consumer_test.go | 80 ++ .../secondary/postgres/outbox_relay.go | 19 +- .../secondary/postgres/outbox_relay_test.go | 10 +- .../postgres/sqlc/event_consumer.sql.go | 133 ++ .../adapter/secondary/postgres/sqlc/models.go | 22 + .../secondary/postgres/sqlc/querier.go | 17 + .../adapter/secondary/prometheus/metrics.go | 47 + .../secondary/prometheus/metrics_test.go | 28 + backend/internal/bootstrap/app.go | 39 +- backend/internal/bootstrap/consumers.go | 133 ++ backend/internal/bootstrap/consumers_test.go | 206 +++ backend/internal/bootstrap/relay.go | 3 +- backend/internal/bootstrap/relay_test.go | 5 +- backend/internal/bootstrap/wire.go | 1 + backend/internal/bootstrap/wire_gen.go | 11 +- backend/internal/domain/domain_event.go | 6 +- .../internal/port/inbound/event_handler.go | 34 + .../internal/port/outbound/event_consumer.go | 137 ++ .../internal/worker/eventconsumer/consumer.go | 481 +++++++ .../worker/eventconsumer/consumer_test.go | 788 +++++++++++ backend/internal/worker/outboxrelay/relay.go | 23 +- .../internal/worker/outboxrelay/relay_test.go | 9 +- .../backoff.go => retry/retry.go} | 25 +- .../backoff_test.go => retry/retry_test.go} | 21 +- deploy/docker/docker-compose.yml | 15 +- docs/en/ARCHITECTURE.md | 60 +- docs/en/DEPLOY.md | 69 +- docs/en/DEVELOPMENT.md | 16 +- docs/en/TESTING.md | 27 +- docs/ru/ARCHITECTURE.md | 60 +- docs/ru/DEPLOY.md | 69 +- docs/ru/DEVELOPMENT.md | 16 +- docs/ru/TESTING.md | 27 +- 47 files changed, 5018 insertions(+), 105 deletions(-) create mode 100644 backend/config/consumer.go create mode 100644 backend/config/consumer_test.go create mode 100644 backend/db/migrations/00005_create_event_consumer_tables.sql create mode 100644 backend/db/queries/event_consumer.sql create mode 100644 backend/integration_test/event_consumer_test.go create mode 100644 backend/internal/adapter/secondary/kafka/consumer.go create mode 100644 backend/internal/adapter/secondary/kafka/consumer_test.go create mode 100644 backend/internal/adapter/secondary/postgres/event_consumer.go create mode 100644 backend/internal/adapter/secondary/postgres/event_consumer_test.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/event_consumer.sql.go create mode 100644 backend/internal/bootstrap/consumers.go create mode 100644 backend/internal/bootstrap/consumers_test.go create mode 100644 backend/internal/port/inbound/event_handler.go create mode 100644 backend/internal/port/outbound/event_consumer.go create mode 100644 backend/internal/worker/eventconsumer/consumer.go create mode 100644 backend/internal/worker/eventconsumer/consumer_test.go rename backend/internal/worker/{outboxrelay/backoff.go => retry/retry.go} (63%) rename backend/internal/worker/{outboxrelay/backoff_test.go => retry/retry_test.go} (75%) diff --git a/backend/config/config.go b/backend/config/config.go index 3242e87..8a55584 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -59,6 +59,24 @@ type Config struct { RelayStatementTimeout time.Duration RelayBackoffInitial time.Duration RelayBackoffMax time.Duration + // ConsumerEnabled runs the registered event consumers next to the HTTP + // servers. + ConsumerEnabled bool + // ConsumerGroupPrefix and a consumer name form the consumer group ID. + ConsumerGroupPrefix string + ConsumerMaxAttempts int + ConsumerBackoffInitial time.Duration + ConsumerBackoffMax time.Duration + // ConsumerHandlerTimeout bounds one consumer transaction. + ConsumerHandlerTimeout time.Duration + ConsumerMaxPollRecords int + ConsumerCommitTimeout time.Duration + // ConsumerShutdownGrace bounds the record in progress after shutdown + // begins. + ConsumerShutdownGrace time.Duration + // ConsumerRebalanceTimeout is the Kafka rebalance timeout of every + // consumer group member. + ConsumerRebalanceTimeout time.Duration // EmailProvider selects the only active mail transport. Settings of the // other transports are not loaded. EmailProvider EmailProvider @@ -118,6 +136,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadRelay(lookup); err != nil { return Config{}, err } + if err := config.loadConsumer(lookup); err != nil { + return Config{}, err + } if err := config.loadMail(lookup); err != nil { return Config{}, err } @@ -183,6 +204,11 @@ func (config Config) Validate() error { if config.ShutdownTimeout <= 0 { return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive") } + // The consumer shutdown grace is checked against SHUTDOWN_TIMEOUT, so it + // follows that check. + if err := config.ValidateConsumer(); err != nil { + return err + } switch config.LogLevel { case "debug", "info", "warn", "error": default: @@ -207,6 +233,8 @@ func DatabaseURLFromEnv(lookup LookupEnv) string { // boolOrDefault accepts only "true" or "false", ignoring case and surrounding // spaces. strconv.ParseBool would also accept 1, t, and similar shorthands, // which are easy to mistype in deployment files. +// +//nolint:unparam // Every setting names its own default; that all current defaults are true is a coincidence. func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) { value, ok := lookup(key) if !ok { diff --git a/backend/config/consumer.go b/backend/config/consumer.go new file mode 100644 index 0000000..abc2345 --- /dev/null +++ b/backend/config/consumer.go @@ -0,0 +1,169 @@ +package config + +import ( + "errors" + "fmt" + "strings" + "time" +) + +const ( + // The consumer runtime runs by default. It starts a consumer only for a + // registered handler, and none is registered yet. + defaultConsumerEnabled = true + // defaultConsumerGroupPrefix is joined with a consumer name by a dot to + // form the Kafka consumer group ID, for example "lincodex.". + defaultConsumerGroupPrefix = "lincodex" + // maxConsumerGroupPrefixLength leaves room for the consumer name in the + // group ID, which the code limits to 64 characters. + maxConsumerGroupPrefixLength = 128 + // defaultConsumerMaxAttempts bounds the handler attempts for one event + // before it is dead-lettered. + defaultConsumerMaxAttempts = 5 + maxConsumerMaxAttempts = 20 + // The wait after a failed attempt starts at the initial delay, doubles + // per consecutive failure, and stops growing at the maximum. + defaultConsumerBackoffInitial = 500 * time.Millisecond + defaultConsumerBackoffMax = 10 * time.Second + maxConsumerBackoff = 5 * time.Minute + // defaultConsumerHandlerTimeout bounds one transaction: the dedup marker, + // the handler, and the commit. It keeps the worst case of one record + // below the default rebalance timeout; see validateConsumerRebalance. + defaultConsumerHandlerTimeout = 5 * time.Second + minConsumerHandlerTimeout = 100 * time.Millisecond + maxConsumerHandlerTimeout = 5 * time.Minute + // defaultConsumerMaxPollRecords bounds the records of one poll, which a + // consumer processes while it holds group rebalancing. + defaultConsumerMaxPollRecords = 100 + maxConsumerMaxPollRecords = 10000 + // defaultConsumerCommitTimeout bounds one offset commit. + defaultConsumerCommitTimeout = 5 * time.Second + minConsumerCommitTimeout = 100 * time.Millisecond + maxConsumerCommitTimeout = time.Minute + // defaultConsumerShutdownGrace is how long the record in progress may + // continue after shutdown begins. + defaultConsumerShutdownGrace = 5 * time.Second + // defaultConsumerRebalanceTimeout is the franz-go and Kafka default, + // set explicitly so the budget check below uses the real value. + defaultConsumerRebalanceTimeout = time.Minute + minConsumerRebalanceTimeout = 10 * time.Second + maxConsumerRebalanceTimeout = 30 * time.Minute + // consumerRebalanceMargin covers the poll, the heartbeat that notices + // the rebalance, and scheduling, on top of the worst case of one record. + consumerRebalanceMargin = 5 * time.Second +) + +func (config *Config) loadConsumer(lookup LookupEnv) error { + var err error + if config.ConsumerEnabled, err = boolOrDefault(lookup, "CONSUMER_ENABLED", defaultConsumerEnabled); err != nil { + return err + } + config.ConsumerGroupPrefix = strings.TrimSpace(valueOrDefault(lookup, "CONSUMER_GROUP_PREFIX", defaultConsumerGroupPrefix)) + if config.ConsumerMaxAttempts, err = intOrDefault(lookup, "CONSUMER_MAX_ATTEMPTS", defaultConsumerMaxAttempts); err != nil { + return err + } + if config.ConsumerBackoffInitial, err = durationOrDefault(lookup, "CONSUMER_BACKOFF_INITIAL", defaultConsumerBackoffInitial); err != nil { + return err + } + if config.ConsumerBackoffMax, err = durationOrDefault(lookup, "CONSUMER_BACKOFF_MAX", defaultConsumerBackoffMax); err != nil { + return err + } + if config.ConsumerHandlerTimeout, err = durationOrDefault(lookup, "CONSUMER_HANDLER_TIMEOUT", defaultConsumerHandlerTimeout); err != nil { + return err + } + if config.ConsumerMaxPollRecords, err = intOrDefault(lookup, "CONSUMER_MAX_POLL_RECORDS", defaultConsumerMaxPollRecords); err != nil { + return err + } + if config.ConsumerCommitTimeout, err = durationOrDefault(lookup, "CONSUMER_COMMIT_TIMEOUT", defaultConsumerCommitTimeout); err != nil { + return err + } + if config.ConsumerShutdownGrace, err = durationOrDefault(lookup, "CONSUMER_SHUTDOWN_GRACE", defaultConsumerShutdownGrace); err != nil { + return err + } + config.ConsumerRebalanceTimeout, err = durationOrDefault(lookup, "CONSUMER_REBALANCE_TIMEOUT", defaultConsumerRebalanceTimeout) + return err +} + +// ValidateConsumer checks the consumer settings even when consumers are +// disabled, so enabling them later cannot surface an old mistake. +func (config Config) ValidateConsumer() error { + // A group ID allows any characters, but the prefix also appears in logs + // and broker ACLs, so it follows the topic name rules. + if len(config.ConsumerGroupPrefix) > maxConsumerGroupPrefixLength || !kafkaTopicNamePattern.MatchString(config.ConsumerGroupPrefix) { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_GROUP_PREFIX must be 1 to %d letters, digits, dots, underscores, or hyphens", maxConsumerGroupPrefixLength) + } + if err := config.validateConsumerRetries(); err != nil { + return err + } + if err := config.validateConsumerTimeouts(); err != nil { + return err + } + return config.validateConsumerRebalance() +} + +func (config Config) validateConsumerRetries() error { + if config.ConsumerMaxAttempts < 1 || config.ConsumerMaxAttempts > maxConsumerMaxAttempts { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS must be between 1 and %d", maxConsumerMaxAttempts) + } + if config.ConsumerBackoffInitial <= 0 { + return errors.New("Config.ValidateConsumer - CONSUMER_BACKOFF_INITIAL must be positive") + } + if config.ConsumerBackoffMax < config.ConsumerBackoffInitial || config.ConsumerBackoffMax > maxConsumerBackoff { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_BACKOFF_MAX must be between CONSUMER_BACKOFF_INITIAL and %s", maxConsumerBackoff) + } + if config.ConsumerMaxPollRecords < 1 || config.ConsumerMaxPollRecords > maxConsumerMaxPollRecords { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS must be between 1 and %d", maxConsumerMaxPollRecords) + } + return nil +} + +func (config Config) validateConsumerTimeouts() error { + if config.ConsumerHandlerTimeout < minConsumerHandlerTimeout || config.ConsumerHandlerTimeout > maxConsumerHandlerTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT must be between %s and %s", minConsumerHandlerTimeout, maxConsumerHandlerTimeout) + } + if config.ConsumerCommitTimeout < minConsumerCommitTimeout || config.ConsumerCommitTimeout > maxConsumerCommitTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT must be between %s and %s", minConsumerCommitTimeout, maxConsumerCommitTimeout) + } + // The grace runs while the HTTP servers drain, so it must fit in the + // shutdown budget of the process. + if config.ConsumerShutdownGrace <= 0 || config.ConsumerShutdownGrace > config.ShutdownTimeout { + return errors.New("Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE must be positive and at most SHUTDOWN_TIMEOUT") + } + return nil +} + +// validateConsumerRebalance keeps the slowest record below the rebalance +// timeout. A consumer holds group rebalancing while it processes a poll and +// commits after every record that needed a retry, so one record is the unit +// that must fit: every handler attempt, the longest wait before each retry, +// the dead letter write, and the offset commit. A member that exceeds the +// timeout is removed from the group, and its records are processed again. +// Database outages are not part of the budget: they are retried without a +// bound, and the removal they can cause is harmless because of the markers. +func (config Config) validateConsumerRebalance() error { + if config.ConsumerRebalanceTimeout < minConsumerRebalanceTimeout || config.ConsumerRebalanceTimeout > maxConsumerRebalanceTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between %s and %s", minConsumerRebalanceTimeout, maxConsumerRebalanceTimeout) + } + worstRecord := config.consumerRecordBudget() + if worstRecord+consumerRebalanceMargin > config.ConsumerRebalanceTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed the worst case of one record (%s) by %s; lower CONSUMER_MAX_ATTEMPTS, CONSUMER_HANDLER_TIMEOUT, CONSUMER_BACKOFF_MAX, or CONSUMER_COMMIT_TIMEOUT, or raise the timeout", + worstRecord, consumerRebalanceMargin) + } + return nil +} + +// consumerRecordBudget is the longest time one record can take without a +// database outage: CONSUMER_MAX_ATTEMPTS handler attempts, the longest +// backoff before each retry, one dead letter write, and one offset commit. +// The backoff ceiling starts at CONSUMER_BACKOFF_INITIAL and doubles up to +// CONSUMER_BACKOFF_MAX, as the workers' retry.Backoff does. +func (config Config) consumerRecordBudget() time.Duration { + attempts := config.ConsumerMaxAttempts + budget := time.Duration(attempts+1) * config.ConsumerHandlerTimeout + ceiling := min(config.ConsumerBackoffInitial, config.ConsumerBackoffMax) + for retry := 1; retry < attempts; retry++ { + budget += ceiling + ceiling = min(ceiling*2, config.ConsumerBackoffMax) + } + return budget + config.ConsumerCommitTimeout +} diff --git a/backend/config/consumer_test.go b/backend/config/consumer_test.go new file mode 100644 index 0000000..dca2557 --- /dev/null +++ b/backend/config/consumer_test.go @@ -0,0 +1,126 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvConsumerDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !settings.ConsumerEnabled || settings.ConsumerGroupPrefix != "lincodex" || settings.ConsumerMaxAttempts != 5 || + settings.ConsumerBackoffInitial != 500*time.Millisecond || settings.ConsumerBackoffMax != 10*time.Second || + settings.ConsumerHandlerTimeout != 5*time.Second || settings.ConsumerMaxPollRecords != 100 || + settings.ConsumerCommitTimeout != 5*time.Second || settings.ConsumerShutdownGrace != 5*time.Second || + settings.ConsumerRebalanceTimeout != time.Minute { + t.Fatalf("unexpected consumer defaults: %+v", consumerSettings(settings)) + } + // Six handler timeouts (five attempts and the dead letter write), the + // backoff ceilings 0.5s, 1s, 2s, and 4s, and one commit; the deployment + // guide quotes this value. + if budget := settings.consumerRecordBudget(); budget != 42500*time.Millisecond { + t.Fatalf("default record budget = %s, want 42.5s", budget) + } +} + +func TestLoadFromEnvReadsConsumerSettings(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "CONSUMER_ENABLED": " False ", + "CONSUMER_GROUP_PREFIX": " stand-1.lincodex ", + "CONSUMER_MAX_ATTEMPTS": "20", + "CONSUMER_BACKOFF_INITIAL": "1s", + "CONSUMER_BACKOFF_MAX": "1s", + "CONSUMER_HANDLER_TIMEOUT": "100ms", + "CONSUMER_MAX_POLL_RECORDS": "10000", + "CONSUMER_COMMIT_TIMEOUT": "1m", + "CONSUMER_SHUTDOWN_GRACE": "20s", + "SHUTDOWN_TIMEOUT": "20s", + // 21 handler timeouts, 19 waits of 1s, and one commit fit easily. + "CONSUMER_REBALANCE_TIMEOUT": "10m", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.ConsumerEnabled || settings.ConsumerGroupPrefix != "stand-1.lincodex" || settings.ConsumerMaxAttempts != 20 || + settings.ConsumerBackoffInitial != time.Second || settings.ConsumerBackoffMax != time.Second || + settings.ConsumerRebalanceTimeout != 10*time.Minute || + settings.ConsumerHandlerTimeout != 100*time.Millisecond || settings.ConsumerMaxPollRecords != 10000 || + settings.ConsumerCommitTimeout != time.Minute || settings.ConsumerShutdownGrace != 20*time.Second { + t.Fatalf("consumer settings were not loaded: %+v", consumerSettings(settings)) + } +} + +func TestLoadFromEnvRejectsConsumerSettings(t *testing.T) { + tests := []struct { + key, value, want string + }{ + {key: "CONSUMER_ENABLED", value: "on", want: "config.boolOrDefault - CONSUMER_ENABLED"}, + {key: "CONSUMER_GROUP_PREFIX", value: "", want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"}, + {key: "CONSUMER_GROUP_PREFIX", value: "group/secret", want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"}, + {key: "CONSUMER_GROUP_PREFIX", value: strings.Repeat("g", 129), want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"}, + {key: "CONSUMER_MAX_ATTEMPTS", value: "", want: "config.intOrDefault - CONSUMER_MAX_ATTEMPTS"}, + {key: "CONSUMER_MAX_ATTEMPTS", value: "0", want: "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS"}, + {key: "CONSUMER_MAX_ATTEMPTS", value: "21", want: "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS"}, + {key: "CONSUMER_BACKOFF_INITIAL", value: "soon", want: "config.durationOrDefault - parse CONSUMER_BACKOFF_INITIAL"}, + {key: "CONSUMER_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_INITIAL"}, + {key: "CONSUMER_BACKOFF_INITIAL", value: "11s", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_MAX"}, + {key: "CONSUMER_BACKOFF_MAX", value: "6m", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_MAX"}, + {key: "CONSUMER_HANDLER_TIMEOUT", value: "99ms", want: "Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT"}, + {key: "CONSUMER_HANDLER_TIMEOUT", value: "6m", want: "Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT"}, + {key: "CONSUMER_MAX_POLL_RECORDS", value: "0", want: "Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS"}, + {key: "CONSUMER_MAX_POLL_RECORDS", value: "10001", want: "Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS"}, + {key: "CONSUMER_COMMIT_TIMEOUT", value: "99ms", want: "Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT"}, + {key: "CONSUMER_COMMIT_TIMEOUT", value: "61s", want: "Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT"}, + {key: "CONSUMER_SHUTDOWN_GRACE", value: "0s", want: "Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE"}, + // Longer than the default SHUTDOWN_TIMEOUT of 10s. + {key: "CONSUMER_SHUTDOWN_GRACE", value: "11s", want: "Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE"}, + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "soon", want: "config.durationOrDefault - parse CONSUMER_REBALANCE_TIMEOUT"}, + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "9s", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between"}, + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "31m", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between"}, + // The default 42.5s budget plus the 5s margin exceeds 45s. + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "45s", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed"}, + // Twenty attempts with the default timeouts need several minutes. + {key: "CONSUMER_MAX_ATTEMPTS", value: "20", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed"}, + } + 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 TestValidateConsumerChecksSettingsEvenWhenDisabled(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"CONSUMER_ENABLED": "false"})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + settings.ConsumerMaxAttempts = 0 + if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS") { + t.Fatalf("Validate() error = %v, want the consumer attempts error", err) + } +} + +// consumerSettings collects the consumer fields for failure messages. +func consumerSettings(settings Config) map[string]any { + return map[string]any{ + "enabled": settings.ConsumerEnabled, + "group_prefix": settings.ConsumerGroupPrefix, + "max_attempts": settings.ConsumerMaxAttempts, + "backoff_initial": settings.ConsumerBackoffInitial, + "backoff_max": settings.ConsumerBackoffMax, + "handler_timeout": settings.ConsumerHandlerTimeout, + "max_poll": settings.ConsumerMaxPollRecords, + "commit_timeout": settings.ConsumerCommitTimeout, + "shutdown_grace": settings.ConsumerShutdownGrace, + "rebalance": settings.ConsumerRebalanceTimeout, + } +} diff --git a/backend/db/migrations/00005_create_event_consumer_tables.sql b/backend/db/migrations/00005_create_event_consumer_tables.sql new file mode 100644 index 0000000..27587ec --- /dev/null +++ b/backend/db/migrations/00005_create_event_consumer_tables.sql @@ -0,0 +1,95 @@ +-- +goose Up +-- Idempotent event consumers. The event bus delivers at least once, so a +-- consumer records every event it applied in the same transaction as the +-- effect. A repeated or concurrent delivery of the same event to the same +-- consumer finds the marker and skips the effect. +-- There is no index on processed_at yet: every applied event would pay for +-- it, and nothing reads by time until marker retention is implemented. +CREATE TABLE consumer_processed_events ( + -- Stable consumer name from the code; also the consumer group suffix. + consumer_name text NOT NULL, + event_id uuid NOT NULL, + processed_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT consumer_processed_events_pkey PRIMARY KEY ( + consumer_name, event_id + ), + CONSTRAINT consumer_processed_events_consumer_name_format CHECK ( + char_length(consumer_name) <= 64 + AND consumer_name ~ '^[a-z][a-z0-9_]*$' + ) +); + +-- Records a consumer could not apply: a value that is not a valid event +-- envelope, an event the handler rejected, or one whose retries ran out. The +-- consumer commits the offset after writing the row, so one bad record does +-- not stop its partition. The record value is not stored: a valid event is +-- still in outbox_events under its event_id, and an invalid record can be +-- read from Kafka by topic, partition, and offset while the topic retains +-- it. value_sha256 identifies that exact value without keeping a copy of +-- data that may later be personal. +CREATE TABLE consumer_dead_letters ( + id bigint GENERATED ALWAYS AS IDENTITY, + consumer_name text NOT NULL, + topic text NOT NULL, + kafka_partition integer NOT NULL, + kafka_offset bigint NOT NULL, + -- From the envelope, or from the event_id header of an invalid record; + -- NULL when neither holds a UUID. + event_id uuid, + -- NULL when the record is not a valid envelope. + event_type text, + error_class text NOT NULL, + -- Short sanitized cause; never the record value. + reason text NOT NULL, + -- Handler attempts made; 0 for a record that was never handed to it. + attempts integer NOT NULL, + value_size integer NOT NULL, + value_sha256 bytea NOT NULL, + dead_lettered_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT consumer_dead_letters_pkey PRIMARY KEY (id), + -- A record delivered again, after a crash before the offset commit or a + -- rewind of the group, updates its row instead of adding one. The value + -- digest is part of the key: a topic that was deleted and created again + -- reuses offsets, and a different value at a reused position is another + -- record that keeps its own row. + CONSTRAINT consumer_dead_letters_record_key UNIQUE ( + consumer_name, topic, kafka_partition, kafka_offset, value_sha256 + ), + CONSTRAINT consumer_dead_letters_consumer_name_format CHECK ( + char_length(consumer_name) <= 64 + AND consumer_name ~ '^[a-z][a-z0-9_]*$' + ), + CONSTRAINT consumer_dead_letters_topic_length CHECK ( + char_length(topic) BETWEEN 1 AND 249 + ), + CONSTRAINT consumer_dead_letters_position_not_negative CHECK ( + kafka_partition >= 0 AND kafka_offset >= 0 + ), + CONSTRAINT consumer_dead_letters_event_type_length CHECK ( + char_length(event_type) <= 128 + ), + CONSTRAINT consumer_dead_letters_error_class_known CHECK ( + error_class IN ( + 'invalid_record', + 'handler_rejected', + 'handler_panic', + 'retries_exhausted' + ) + ), + CONSTRAINT consumer_dead_letters_reason_length CHECK ( + char_length(reason) BETWEEN 1 AND 512 + ), + CONSTRAINT consumer_dead_letters_attempts_not_negative CHECK ( + attempts >= 0 + ), + CONSTRAINT consumer_dead_letters_value_size_not_negative CHECK ( + value_size >= 0 + ), + CONSTRAINT consumer_dead_letters_value_sha256_size CHECK ( + octet_length(value_sha256) = 32 + ) +); + +-- +goose Down +DROP TABLE consumer_dead_letters; +DROP TABLE consumer_processed_events; diff --git a/backend/db/queries/event_consumer.sql b/backend/db/queries/event_consumer.sql new file mode 100644 index 0000000..5582841 --- /dev/null +++ b/backend/db/queries/event_consumer.sql @@ -0,0 +1,63 @@ +-- Records that a consumer applies an event, in the transaction of the effect. +-- It returns 0 rows when the marker exists. While another transaction holds +-- an uncommitted marker for the same key, the insert waits for it: after a +-- commit it returns 0, after a rollback it inserts. So a concurrent duplicate +-- never runs the effect at the same time as the first delivery. +-- name: InsertProcessedEventMarker :execrows +INSERT INTO consumer_processed_events (consumer_name, event_id) +VALUES (sqlc.arg(consumer_name), sqlc.arg(event_id)) +ON CONFLICT (consumer_name, event_id) DO NOTHING; + +-- Stores a record that a consumer could not apply. A second delivery of the +-- same record (same position and value) refreshes the outcome of its row: +-- after a rewind the handler may fail differently. A different value at a +-- reused position, after the topic was recreated, gets its own row. +-- name: InsertConsumerDeadLetter :exec +INSERT INTO consumer_dead_letters ( + consumer_name, + topic, + kafka_partition, + kafka_offset, + event_id, + event_type, + error_class, + reason, + attempts, + value_size, + value_sha256 +) VALUES ( + sqlc.arg(consumer_name), + sqlc.arg(topic), + sqlc.arg(kafka_partition), + sqlc.arg(kafka_offset), + sqlc.narg(event_id), + sqlc.narg(event_type), + sqlc.arg(error_class), + sqlc.arg(reason), + sqlc.arg(attempts), + sqlc.arg(value_size), + sqlc.arg(value_sha256) +) +ON CONFLICT ( + consumer_name, topic, kafka_partition, kafka_offset, value_sha256 +) DO UPDATE SET + event_id = excluded.event_id, + event_type = excluded.event_type, + error_class = excluded.error_class, + reason = excluded.reason, + attempts = excluded.attempts, + dead_lettered_at = clock_timestamp(); + +-- Bounds a consumer transaction on the server, local to the transaction. +-- statement_timeout stops a slow statement; idle_in_transaction_session_timeout +-- ends the session of a process that froze or lost the network inside the +-- handler, which releases the processed-event marker that a concurrent +-- duplicate waits for. +-- name: SetConsumerTransactionTimeouts :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 ac32045..7c39019 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -23,6 +23,7 @@ require ( github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 github.com/twmb/franz-go v1.22.1 github.com/twmb/franz-go/pkg/kadm v1.19.0 + github.com/twmb/franz-go/pkg/kmsg v1.14.0 github.com/wahrwelt-kit/go-cachekit v0.7.0 github.com/wahrwelt-kit/go-httpkit v0.7.0 github.com/wahrwelt-kit/go-logkit v0.6.0 @@ -345,7 +346,6 @@ require ( github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 // indirect - github.com/twmb/franz-go/pkg/kmsg v1.14.0 // indirect github.com/ultraware/funlen v0.2.0 // indirect github.com/ultraware/whitespace v0.2.0 // indirect github.com/uudashr/gocognit v1.2.1 // indirect diff --git a/backend/integration_test/event_consumer_test.go b/backend/integration_test/event_consumer_test.go new file mode 100644 index 0000000..dc3bb08 --- /dev/null +++ b/backend/integration_test/event_consumer_test.go @@ -0,0 +1,1207 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "log/slog" + "maps" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" + + "lincodex/backend/internal/adapter/secondary/kafka" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/eventconsumer" + "lincodex/backend/internal/worker/retry" +) + +const ( + consumerTestTimeout = 5 * time.Minute + // consumerWaitTimeout bounds every wait for a consumer to reach a state; + // it covers the group join and the first fetch on a loaded machine. + consumerWaitTimeout = time.Minute + // consumerStopTimeout bounds Run's return after cancellation: the grace + // plus one commit and margin. + consumerStopTimeout = 15 * time.Second + consumerName = "integration_effects" + consumerEventType = "test.effect_requested" + consumerAggregate = "test_effect" + consumerMaxAttempts = 3 + consumerShortBackoff = 10 * time.Millisecond + // consumerPoisonBackoff makes every retry wait between 100ms and 200ms, + // long enough to tell backoff from a hot loop. + consumerPoisonBackoff = 200 * time.Millisecond + consumerPoisonMinimumGap = consumerPoisonBackoff / 2 + // consumerPoisonBudget bounds the whole retry sequence of one poison + // event: the attempts are fast, so it is the backoff plus a large margin. + consumerPoisonBudget = 5 * time.Second + // consumerHandlerTime outlasts lockWaitTimeout, so a race test on a slow + // machine fails on the lock wait it asserts, not on an attempt timeout. + consumerHandlerTime = 2 * lockWaitTimeout + consumerCommitTimeout = 5 * time.Second + consumerGrace = 2 * time.Second + // consumerShortGrace lets a stuck handler be canceled quickly. + consumerShortGrace = 300 * time.Millisecond + // consumerQuietPeriod is how long a test watches that a finished consumer + // does not touch a record again. + consumerQuietPeriod = 500 * time.Millisecond + effectsTable = "effects" + effectsSchema = "consumer_test" + racingApplication = "consumer_race_second" +) + +var ( + effectsIdentifier = pgx.Identifier{effectsSchema, effectsTable} + createEffectsTable = fmt.Sprintf(` + CREATE SCHEMA %[1]s; + -- No unique key: a second effect for an event must stay visible. + CREATE TABLE %[2]s ( + event_id uuid NOT NULL, + consumer_name text NOT NULL + )`, pgx.Identifier{effectsSchema}.Sanitize(), effectsIdentifier.Sanitize()) + errEffectFailed = errors.New("effect failed") +) + +// effectHandler is the test-only consumer: it writes one row per applied +// event into a table that exists only in this test, then runs hook inside +// the same transaction. +type effectHandler struct { + hook func(ctx context.Context, tx pgx.Tx, event outbound.ConsumedEvent) error + + mu sync.Mutex + calls map[uuid.UUID][]time.Time +} + +func newEffectHandler(hook func(context.Context, pgx.Tx, outbound.ConsumedEvent) error) *effectHandler { + return &effectHandler{hook: hook, calls: make(map[uuid.UUID][]time.Time)} +} + +func (*effectHandler) ConsumerName() string { return consumerName } + +func (*effectHandler) Handles(eventType string) bool { return eventType == consumerEventType } + +func (handler *effectHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error { + handler.mu.Lock() + handler.calls[event.EventID] = append(handler.calls[event.EventID], time.Now()) + handler.mu.Unlock() + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return errors.New("unit of work is not a PostgreSQL transaction") + } + if _, err := tx.Exec(ctx, "INSERT INTO "+effectsIdentifier.Sanitize()+" (event_id, consumer_name) VALUES ($1, $2)", event.EventID, consumerName); err != nil { + return err + } + if handler.hook == nil { + return nil + } + return handler.hook(ctx, tx, event) +} + +func (handler *effectHandler) callTimes(eventID uuid.UUID) []time.Time { + handler.mu.Lock() + defer handler.mu.Unlock() + return append([]time.Time(nil), handler.calls[eventID]...) +} + +func (handler *effectHandler) totalCalls() int { + handler.mu.Lock() + defer handler.mu.Unlock() + total := 0 + for _, calls := range handler.calls { + total += len(calls) + } + return total +} + +// consumerHarness owns the database side of consumer tests. +type consumerHarness struct { + env *testEnvironment + pool *pgxpool.Pool + store *postgresadapter.EventConsumerStore +} + +func TestEventConsumer(t *testing.T) { + env := bootstrap(t, postgresService, kafkaService) + ctx, cancel := context.WithTimeout(t.Context(), consumerTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + for _, statement := range []string{createEffectsTable, createTestAccountsTable} { + if _, err := pool.Exec(ctx, statement); err != nil { + t.Fatalf("create test-only tables: %v", err) + } + } + harness := &consumerHarness{ + env: env, + pool: pool, + store: postgresadapter.NewEventConsumerStore(pool, consumerHandlerTime), + } + // Subtests share tables and run sequentially; each starts from empty + // tables and uses its own topic and consumer group. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, + effectsIdentifier, + pgx.Identifier{"consumer_processed_events"}, + pgx.Identifier{"consumer_dead_letters"}, + outboxEventsTable, + testAccountsTable, + ) + } + + t.Run("an event delivered three times on two partitions is applied once", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 2) + repeated, other := newConsumerEnvelope(), newConsumerEnvelope() + producer := env.newKafkaClient(t, kgo.RecordPartitioner(kgo.ManualPartitioner())) + produceKafkaRecords(ctx, t, producer, + envelopeRecord(t, topic, 0, repeated), + envelopeRecord(t, topic, 1, repeated), + envelopeRecord(t, topic, 0, repeated), + envelopeRecord(t, topic, 1, other), + ) + handler := newEffectHandler(nil) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2, 1: 2}) + harness.assertEffects(ctx, t, repeated.EventID, 1) + harness.assertEffects(ctx, t, other.EventID, 1) + harness.assertMarkers(ctx, t, 2) + assertConsumerMetric(t, metrics, "records", "applied", 2) + assertConsumerMetric(t, metrics, "records", "duplicate", 2) + }) + + t.Run("two deliveries of one event racing on the marker apply it once", func(t *testing.T) { + reset(t) + record := consumedRecord(newConsumerEnvelope()) + inEffect := make(chan struct{}) + releaseFirst := make(chan struct{}) + first := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + close(inEffect) + return awaitOrCancel(ctx, releaseFirst, nil) + }) + second := newEffectHandler(nil) + firstSource, secondSource := newStaticSource(record), newStaticSource(record) + firstMetrics, secondMetrics := prometheus.New(), prometheus.New() + + runWithSource(ctx, t, firstSource, first, harness.store, firstMetrics, consumerTestSettings(consumerGrace)) + awaitSignal(ctx, t, inEffect, "the first delivery to hold its marker") + // The first transaction holds the uncommitted marker. The second + // delivery's marker insert must wait for it instead of running the + // effect in parallel. + racingPool := env.newPoolWithApplicationName(ctx, t, racingApplication) + runWithSource(ctx, t, secondSource, second, postgresadapter.NewEventConsumerStore(racingPool, consumerHandlerTime), secondMetrics, consumerTestSettings(consumerGrace)) + if waitEvent, waiting := waitForLockWait(ctx, pool, racingApplication); !waiting { + t.Fatalf("the second delivery did not wait for the first marker; last wait event %q", waitEvent) + } + close(releaseFirst) + + firstSource.waitForCommit(ctx, t) + secondSource.waitForCommit(ctx, t) + harness.assertEffects(ctx, t, record.EventID, 1) + if calls := len(second.callTimes(record.EventID)); calls != 0 { + t.Fatalf("the second delivery ran the handler %d times after the first committed", calls) + } + assertConsumerMetric(t, firstMetrics, "records", "applied", 1) + assertConsumerMetric(t, secondMetrics, "records", "duplicate", 1) + }) + + t.Run("when the first of two racing deliveries rolls back the second applies the event once", func(t *testing.T) { + reset(t) + record := consumedRecord(newConsumerEnvelope()) + inEffect := make(chan struct{}) + failFirst := make(chan struct{}) + var firstCalls atomic.Int64 + first := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + if firstCalls.Add(1) == 1 { + close(inEffect) + return awaitOrCancel(ctx, failFirst, errEffectFailed) + } + return nil + }) + second := newEffectHandler(nil) + firstSource, secondSource := newStaticSource(record), newStaticSource(record) + firstMetrics, secondMetrics := prometheus.New(), prometheus.New() + + // The first delivery retries only after the second one committed, + // with a margin of 100ms or more over a commit of one row. + firstSettings := consumerTestSettings(consumerGrace) + firstSettings.Backoff = retry.Backoff{Initial: consumerPoisonBackoff, Max: consumerPoisonBackoff} + runWithSource(ctx, t, firstSource, first, harness.store, firstMetrics, firstSettings) + awaitSignal(ctx, t, inEffect, "the first delivery to hold its marker") + racingPool := env.newPoolWithApplicationName(ctx, t, racingApplication) + runWithSource(ctx, t, secondSource, second, postgresadapter.NewEventConsumerStore(racingPool, consumerHandlerTime), secondMetrics, consumerTestSettings(consumerGrace)) + if waitEvent, waiting := waitForLockWait(ctx, pool, racingApplication); !waiting { + t.Fatalf("the second delivery did not wait for the first marker; last wait event %q", waitEvent) + } + close(failFirst) + + firstSource.waitForCommit(ctx, t) + secondSource.waitForCommit(ctx, t) + harness.assertEffects(ctx, t, record.EventID, 1) + // The second delivery applied the event after the rollback; the + // first one's retry then found the marker. + assertConsumerMetric(t, secondMetrics, "records", "applied", 1) + assertConsumerMetric(t, firstMetrics, "records", "duplicate", 1) + assertConsumerMetric(t, firstMetrics, "failures", "handler", 1) + }) + + t.Run("a consumer stopped before its commit leaves the record to its successor, which applies it once", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + group := newConsumerGroup() + + effectWritten := make(chan struct{}) + stuck := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + close(effectWritten) + // The effect row is written; the process now "dies" before the + // commit: the handler outlives the shutdown grace. + <-ctx.Done() + return ctx.Err() + }) + stop := harness.startConsumer(ctx, t, topic, group, stuck, prometheus.New(), consumerShortGrace) + awaitSignal(ctx, t, effectWritten, "the first consumer to reach the handler") + stop() + + harness.assertEffects(ctx, t, event.EventID, 0) + harness.assertMarkers(ctx, t, 0) + if offsets := env.committedOffsets(ctx, t, group, topic); len(offsets) != 0 { + t.Fatalf("the stopped consumer committed %v for unfinished work", offsets) + } + + successor := newEffectHandler(nil) + metrics := prometheus.New() + harness.startConsumer(ctx, t, topic, group, successor, metrics, consumerGrace) + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + harness.assertEffects(ctx, t, event.EventID, 1) + assertConsumerMetric(t, metrics, "records", "applied", 1) + }) + + t.Run("a record whose effect committed before a crash is a duplicate on redelivery", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + // The earlier instance committed the effect and the marker, then + // crashed before it committed the offset. + applied, err := harness.store.ApplyOnce(ctx, consumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return newEffectHandler(nil).Handle(ctx, unit, consumedRecord(event).Event) + }) + if err != nil || !applied { + t.Fatalf("ApplyOnce() = %t, %v; want the first application", applied, err) + } + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + handler := newEffectHandler(nil) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + harness.assertEffects(ctx, t, event.EventID, 1) + if calls := handler.totalCalls(); calls != 0 { + t.Fatalf("handler ran %d times for a redelivered event", calls) + } + assertConsumerMetric(t, metrics, "records", "duplicate", 1) + }) + + t.Run("an invalid record is dead-lettered once and later records on its partition are applied", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + headerID := uuid.New() + invalidValue := []byte(`{"envelope_version":1,"payload":"secret-value"`) + valid := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), + &kgo.Record{Topic: topic, Value: invalidValue, Headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte(headerID.String())}}}, + envelopeRecord(t, topic, -1, valid), + ) + handler := newEffectHandler(nil) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2}) + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 1 { + t.Fatalf("dead letters = %d, want 1", len(letters)) + } + assertDeadLetter(t, letters[0], deadLetterRow{ + topic: topic, partition: 0, offset: 0, eventID: &headerID, + errorClass: string(outbound.DeadLetterInvalidRecord), attempts: 0, + valueSize: len(invalidValue), valueSHA256: sha256.Sum256(invalidValue), + }) + if strings.Contains(letters[0].reason, "secret") { + t.Fatalf("dead letter reason quotes the value: %q", letters[0].reason) + } + harness.assertEffects(ctx, t, valid.EventID, 1) + if calls := handler.totalCalls(); calls != 1 { + t.Fatalf("handler ran %d times, want only for the valid record", calls) + } + assertConsumerMetric(t, metrics, "records", "dead_lettered", 1) + assertConsumerMetric(t, metrics, "records", "applied", 1) + // The dead letter is final: the consumer does not come back to it. + time.Sleep(consumerQuietPeriod) + if again := harness.readDeadLetters(ctx, t); len(again) != 1 { + t.Fatalf("dead letters = %d after the quiet period, want 1", len(again)) + } + }) + + t.Run("a handler that keeps failing is retried with backoff a bounded number of times, then dead-lettered", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + poison, next := newConsumerEnvelope(), newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, poison), envelopeRecord(t, topic, -1, next)) + handler := newEffectHandler(func(_ context.Context, _ pgx.Tx, event outbound.ConsumedEvent) error { + if event.EventID == poison.EventID { + // The effect row was written; the failure must roll it back. + return errEffectFailed + } + return nil + }) + metrics := prometheus.New() + group := newConsumerGroup() + settings := consumerTestSettings(consumerGrace) + settings.Backoff = retry.Backoff{Initial: consumerPoisonBackoff, Max: consumerPoisonBackoff} + harness.startConsumerWith(ctx, t, topic, group, handler, metrics, settings) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2}) + calls := handler.callTimes(poison.EventID) + if len(calls) != consumerMaxAttempts { + t.Fatalf("poison event attempts = %d, want %d", len(calls), consumerMaxAttempts) + } + for index := 1; index < len(calls); index++ { + if gap := calls[index].Sub(calls[index-1]); gap < consumerPoisonMinimumGap { + t.Fatalf("attempt %d followed the previous one after %s, want at least %s", index+1, gap, consumerPoisonMinimumGap) + } + } + if spent := calls[len(calls)-1].Sub(calls[0]); spent > consumerPoisonBudget { + t.Fatalf("retries took %s, want at most %s", spent, consumerPoisonBudget) + } + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 1 { + t.Fatalf("dead letters = %d, want 1", len(letters)) + } + value := envelopeValue(t, poison) + eventType := consumerEventType + assertDeadLetter(t, letters[0], deadLetterRow{ + topic: topic, partition: 0, offset: 0, eventID: &poison.EventID, eventType: &eventType, + errorClass: string(outbound.DeadLetterRetriesExhausted), attempts: consumerMaxAttempts, + valueSize: len(value), valueSHA256: sha256.Sum256(value), + }) + if !strings.Contains(letters[0].reason, errEffectFailed.Error()) { + t.Fatalf("dead letter reason = %q, want the handler error", letters[0].reason) + } + harness.assertEffects(ctx, t, poison.EventID, 0) + harness.assertEffects(ctx, t, next.EventID, 1) + assertConsumerMetric(t, metrics, "failures", "handler", consumerMaxAttempts) + assertConsumerMetric(t, metrics, "records", "dead_lettered", 1) + // No hot loop: after the dead letter the handler is not called again. + time.Sleep(consumerQuietPeriod) + if again := len(handler.callTimes(poison.EventID)); again != consumerMaxAttempts { + t.Fatalf("poison event attempts grew to %d after the dead letter", again) + } + }) + + t.Run("a connection killed inside the handler rolls back on the server, and a new member applies the event once", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + group := newConsumerGroup() + + killed := make(chan struct{}) + var backendPID atomic.Int32 + crashing := newEffectHandler(func(ctx context.Context, tx pgx.Tx, _ outbound.ConsumedEvent) error { + // The effect row and the marker are written but not committed. + // Ending the backend is what a crashed process or a dropped + // connection leaves behind: only the server can roll back. + var pid int32 + if err := tx.QueryRow(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil { + return err + } + backendPID.Store(pid) + var terminated bool + if err := pool.QueryRow(ctx, "SELECT pg_terminate_backend($1)", pid).Scan(&terminated); err != nil || !terminated { + return fmt.Errorf("terminate backend %d: %t, %w", pid, terminated, err) + } + close(killed) + <-ctx.Done() + return ctx.Err() + }) + stop := harness.startConsumer(ctx, t, topic, group, crashing, prometheus.New(), consumerShortGrace) + awaitSignal(ctx, t, killed, "the handler to end its own backend") + stop() + + waitFor(ctx, t, "the terminated backend to disappear", func() bool { + var alive bool + err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = $1)", backendPID.Load()).Scan(&alive) + return err == nil && !alive + }) + harness.assertEffects(ctx, t, event.EventID, 0) + harness.assertMarkers(ctx, t, 0) + if offsets := env.committedOffsets(ctx, t, group, topic); len(offsets) != 0 { + t.Fatalf("the crashed member committed %v", offsets) + } + + successor := newEffectHandler(nil) + metrics := prometheus.New() + harness.startConsumer(ctx, t, topic, group, successor, metrics, consumerGrace) + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + harness.assertEffects(ctx, t, event.EventID, 1) + assertConsumerMetric(t, metrics, "records", "applied", 1) + }) + + t.Run("a handler that ignores a failed statement ends in a dead letter instead of retrying forever", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + swallowing := newEffectHandler(func(ctx context.Context, tx pgx.Tx, _ outbound.ConsumedEvent) error { + // The failed statement aborts the transaction; the handler + // hides the error, so PostgreSQL refuses the commit. + _, _ = tx.Exec(ctx, "SELECT 1 / 0") + return nil + }) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, swallowing, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 1 || letters[0].errorClass != string(outbound.DeadLetterRetriesExhausted) || letters[0].attempts != consumerMaxAttempts { + t.Fatalf("dead letters = %+v, want one retries_exhausted after %d attempts", letters, consumerMaxAttempts) + } + if calls := len(swallowing.callTimes(event.EventID)); calls != consumerMaxAttempts { + t.Fatalf("handler ran %d times, want %d", calls, consumerMaxAttempts) + } + harness.assertEffects(ctx, t, event.EventID, 0) + harness.assertMarkers(ctx, t, 0) + assertConsumerMetric(t, metrics, "failures", "handler", consumerMaxAttempts) + assertConsumerMetric(t, metrics, "failures", "store", 0) + }) + + t.Run("a repeated dead letter updates its row, and another value at the same position gets its own", func(t *testing.T) { + reset(t) + letter := outbound.DeadLetter{ + Consumer: consumerName, Topic: "integration-dead-letters", Partition: 1, Offset: 7, + EventID: uuid.New(), EventType: consumerEventType, ErrorClass: outbound.DeadLetterHandlerRejected, + Reason: "first failure", Attempts: 1, ValueSize: 3, ValueSHA256: sha256.Sum256([]byte("one")), + } + if err := harness.store.RecordDeadLetter(ctx, letter); err != nil { + t.Fatalf("RecordDeadLetter() error = %v", err) + } + // After a rewind the same record fails again, differently. + again := letter + again.ErrorClass, again.Reason, again.Attempts = outbound.DeadLetterRetriesExhausted, "second failure", consumerMaxAttempts + if err := harness.store.RecordDeadLetter(ctx, again); err != nil { + t.Fatalf("RecordDeadLetter() again error = %v", err) + } + // A recreated topic reuses the position for another record. + other := letter + other.EventID, other.ValueSHA256 = uuid.New(), sha256.Sum256([]byte("two")) + if err := harness.store.RecordDeadLetter(ctx, other); err != nil { + t.Fatalf("RecordDeadLetter() other error = %v", err) + } + + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 2 { + t.Fatalf("dead letters = %d, want 2", len(letters)) + } + if letters[0].errorClass != string(outbound.DeadLetterRetriesExhausted) || letters[0].reason != "second failure" || + letters[0].attempts != consumerMaxAttempts || letters[0].valueSHA256 != letter.ValueSHA256 { + t.Fatalf("repeated dead letter = %+v, want the second outcome", letters[0]) + } + if letters[1].valueSHA256 != other.ValueSHA256 || *letters[1].eventID != other.EventID { + t.Fatalf("dead letter of the other value = %+v", letters[1]) + } + }) + + t.Run("a member joining while another holds a record takes over without a lost or repeated effect", func(t *testing.T) { + reset(t) + harness.runRebalanceHandover(ctx, t) + }) + + t.Run("an event appended to the outbox reaches the consumer through the relay", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + relayHarness := &relayHarness{ + env: env, + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts), + } + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + relayHarness.save(ctx, t, account, event) + relay := relayHarness.newRelay(relayHarness.newPublisher(t, topic)) + if result, err := relay.PublishPending(ctx); err != nil || result.Published != 1 { + t.Fatalf("PublishPending() = %+v, %v; want one event published", result, err) + } + + var received atomic.Pointer[outbound.ConsumedEvent] + handler := accountHandler{received: &received} + metrics := prometheus.New() + group := newConsumerGroup() + source, _ := harness.newSource(t, topic, group) + consumer, err := eventconsumer.New(handler, source, harness.store, metrics, slog.New(slog.DiscardHandler), consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, consumer) + + waitFor(ctx, t, "the relayed event to be applied", func() bool { return received.Load() != nil }) + got := received.Load() + if got.EventID != event.EventID() || got.AggregateID != account.id || got.AggregateVersion != account.version || + got.EventType != testAccountEventType || got.AggregateType != testAggregateType { + t.Fatalf("consumed event %+v does not match the outbox event %s", got, event.EventID()) + } + assertJSONEqual(t, got.Payload, accountPayload(account)) + }) +} + +// accountHandler records the account event it consumed. +type accountHandler struct { + received *atomic.Pointer[outbound.ConsumedEvent] +} + +func (accountHandler) ConsumerName() string { return "integration_relay_check" } + +func (accountHandler) Handles(eventType string) bool { return eventType == testAccountEventType } + +func (handler accountHandler) Handle(_ context.Context, _ outbound.UnitOfWork, event outbound.ConsumedEvent) error { + handler.received.Store(&event) + return nil +} + +func consumerTestSettings(grace time.Duration) eventconsumer.Settings { + return eventconsumer.Settings{ + MaxAttempts: consumerMaxAttempts, + Backoff: retry.Backoff{Initial: consumerShortBackoff, Max: consumerShortBackoff}, + HandlerTimeout: consumerHandlerTime, + CommitTimeout: consumerCommitTimeout, + ShutdownGrace: grace, + } +} + +func newConsumerGroup() string { + return "integration-consumer-" + strings.ToLower(rand.Text()) +} + +// newSource creates a group member for topic. close leaves the group; it +// also runs when t finishes, after the consumer stopped. +func (harness *consumerHarness) newSource(t *testing.T, topic, group string) (source *kafka.EventSource, close func()) { + t.Helper() + settings := harness.env.Config + settings.KafkaEventsTopic = topic + settings.ConsumerCommitTimeout = consumerCommitTimeout + source, closeSource, err := kafka.NewEventSource(settings, group, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewEventSource() error = %v", err) + } + var once sync.Once + close = func() { once.Do(closeSource) } + t.Cleanup(close) + return source, close +} + +func (harness *consumerHarness) startConsumer( + ctx context.Context, + t *testing.T, + topic, group string, + handler *effectHandler, + metrics *prometheus.Metrics, + grace time.Duration, +) (stop func()) { + t.Helper() + return harness.startConsumerWith(ctx, t, topic, group, handler, metrics, consumerTestSettings(grace)) +} + +// startConsumerWith runs a consumer of topic in group. stop cancels it, +// waits until Run returned, and then leaves the group, as bootstrap does. +func (harness *consumerHarness) startConsumerWith( + ctx context.Context, + t *testing.T, + topic, group string, + handler *effectHandler, + metrics *prometheus.Metrics, + settings eventconsumer.Settings, +) (stop func()) { + t.Helper() + source, closeSource := harness.newSource(t, topic, group) + consumer, err := eventconsumer.New(handler, source, harness.store, metrics, slog.New(slog.DiscardHandler), settings) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + stopRun := runConsumer(ctx, t, consumer) + return func() { + t.Helper() + stopRun() + closeSource() + } +} + +// runWithSource runs a consumer of a static source with store. +func runWithSource( + ctx context.Context, + t *testing.T, + source *staticSource, + handler *effectHandler, + store outbound.EventConsumerStore, + metrics *prometheus.Metrics, + settings eventconsumer.Settings, +) { + t.Helper() + consumer, err := eventconsumer.New(handler, source, store, metrics, slog.New(slog.DiscardHandler), settings) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, consumer) +} + +// runConsumer runs consumer until the returned stop or the end of t. +func runConsumer(ctx context.Context, t *testing.T, consumer *eventconsumer.Consumer) (stop func()) { + t.Helper() + runCtx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + go func() { + defer close(done) + consumer.Run(runCtx) + }() + var once sync.Once + stop = func() { + once.Do(func() { + cancel() + select { + case <-done: + case <-time.After(consumerStopTimeout): + t.Errorf("consumer %s did not stop within %s", consumer.Name(), consumerStopTimeout) + } + }) + } + t.Cleanup(stop) + return stop +} + +// staticSource delivers one batch, then waits for ctx, and records the +// committed offsets. It stands in for Kafka where a test needs two +// consumers to receive the same record at a moment it controls. +type staticSource struct { + mu sync.Mutex + batch []outbound.ConsumedRecord + committed []int64 + commitSeen chan struct{} +} + +func newStaticSource(records ...outbound.ConsumedRecord) *staticSource { + return &staticSource{batch: records, commitSeen: make(chan struct{})} +} + +func (source *staticSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) { + source.mu.Lock() + batch := source.batch + source.batch = nil + source.mu.Unlock() + if len(batch) > 0 { + return batch, nil + } + <-ctx.Done() + return nil, ctx.Err() +} + +func (source *staticSource) Commit(_ context.Context, finished []outbound.ConsumedRecord) error { + source.mu.Lock() + defer source.mu.Unlock() + for _, record := range finished { + source.committed = append(source.committed, record.Offset) + } + select { + case <-source.commitSeen: + default: + close(source.commitSeen) + } + return nil +} + +func (*staticSource) Release() {} + +func (source *staticSource) waitForCommit(ctx context.Context, t *testing.T) { + t.Helper() + select { + case <-source.commitSeen: + case <-ctx.Done(): + t.Fatal("the consumer did not commit its record") + case <-time.After(consumerWaitTimeout): + t.Fatal("the consumer did not commit its record") + } +} + +func newConsumerEnvelope() receivedEnvelope { + return receivedEnvelope{ + EnvelopeVersion: kafka.EnvelopeVersion, + EventID: uuid.New(), + EventType: consumerEventType, + SchemaVersion: 1, + AggregateType: consumerAggregate, + AggregateID: uuid.New(), + AggregateVersion: 1, + OccurredAt: time.Now().UTC(), + Payload: json.RawMessage(`{"step":1}`), + } +} + +func envelopeValue(t *testing.T, envelope receivedEnvelope) []byte { + t.Helper() + value, err := json.Marshal(envelope) + if err != nil { + t.Fatalf("encode envelope: %v", err) + } + return value +} + +// envelopeRecord builds a record as the relay writes it. A negative +// partition leaves the choice to the producer's partitioner. +func envelopeRecord(t *testing.T, topic string, partition int32, envelope receivedEnvelope) *kgo.Record { + t.Helper() + record := &kgo.Record{ + Topic: topic, + // A distinct key per record lets a duplicate land on another + // partition, as a manual partitioner sends it. + Key: []byte(envelope.AggregateType + ":" + envelope.AggregateID.String()), + Value: envelopeValue(t, envelope), + Headers: []kgo.RecordHeader{ + {Key: "event_id", Value: []byte(envelope.EventID.String())}, + {Key: "event_type", Value: []byte(envelope.EventType)}, + {Key: "schema_version", Value: []byte(strconv.Itoa(int(envelope.SchemaVersion)))}, + }, + } + if partition >= 0 { + record.Partition = partition + } + return record +} + +// consumedRecord is the decoded form of envelope at offset 0. +func consumedRecord(envelope receivedEnvelope) outbound.ConsumedRecord { + return outbound.ConsumedRecord{ + Topic: "static", + EventID: envelope.EventID, + Event: outbound.ConsumedEvent{ + EventID: envelope.EventID, + EventType: envelope.EventType, + SchemaVersion: envelope.SchemaVersion, + AggregateType: envelope.AggregateType, + AggregateID: envelope.AggregateID, + AggregateVersion: envelope.AggregateVersion, + OccurredAt: envelope.OccurredAt, + Payload: envelope.Payload, + }, + } +} + +// committedOffsets returns the committed offsets of group on topic. The +// coordinator of a new group can be unavailable for a moment while Kafka +// creates the offsets topic, so it retries retriable errors. +func (env *testEnvironment) committedOffsets(ctx context.Context, t *testing.T, group, topic string) map[int32]int64 { + t.Helper() + var offsets map[int32]int64 + var lastErr error + waitFor(ctx, t, "the offsets of group "+group, func() bool { + offsets, lastErr = env.fetchCommittedOffsets(ctx, group, topic) + if lastErr != nil && !kerr.IsRetriable(lastErr) { + t.Fatalf("fetch offsets of group %s: %v", group, lastErr) + } + return lastErr == nil + }) + return offsets +} + +func (env *testEnvironment) fetchCommittedOffsets(ctx context.Context, group, topic string) (map[int32]int64, error) { + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + offsets := make(map[int32]int64) + responses, err := env.KafkaAdmin.FetchOffsets(ctx, group) + if errors.Is(err, kerr.GroupIDNotFound) { + return offsets, nil + } + if err != nil { + return nil, err + } + responses.Each(func(response kadm.OffsetResponse) { + if response.Topic == topic && response.Err == nil && response.At >= 0 { + offsets[response.Partition] = response.At + } + }) + return offsets, nil +} + +func (env *testEnvironment) waitForCommittedOffsets(ctx context.Context, t *testing.T, group, topic string, want map[int32]int64) { + t.Helper() + waitFor(ctx, t, fmt.Sprintf("group %s to commit %v", group, want), func() bool { + got, err := env.fetchCommittedOffsets(ctx, group, topic) + if err != nil && !kerr.IsRetriable(err) { + t.Fatalf("fetch offsets of group %s: %v", group, err) + } + return err == nil && maps.Equal(got, want) + }) +} + +// waitFor polls condition until it holds or consumerWaitTimeout passes. +func waitFor(ctx context.Context, t *testing.T, what string, condition func() bool) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, consumerWaitTimeout) + defer cancel() + ticker := time.NewTicker(readinessInterval) + defer ticker.Stop() + for !condition() { + select { + case <-ctx.Done(): + t.Fatalf("timed out waiting for %s", what) + case <-ticker.C: + } + } +} + +func (env *testEnvironment) newPoolWithApplicationName(ctx context.Context, t *testing.T, name string) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.ConnConfig.RuntimeParams["application_name"] = name + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create PostgreSQL pool %s: %v", name, err) + } + t.Cleanup(pool.Close) + return pool +} + +func (harness *consumerHarness) assertEffects(ctx context.Context, t *testing.T, eventID uuid.UUID, want int) { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+effectsIdentifier.Sanitize()+" WHERE event_id = $1", eventID).Scan(&count); err != nil { + t.Fatalf("count effects: %v", err) + } + if count != want { + t.Fatalf("event %s has %d effect rows, want %d", eventID, count, want) + } +} + +func (harness *consumerHarness) assertMarkers(ctx context.Context, t *testing.T, want int) { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consumer_processed_events WHERE consumer_name = $1", consumerName).Scan(&count); err != nil { + t.Fatalf("count processed event markers: %v", err) + } + if count != want { + t.Fatalf("processed event markers = %d, want %d", count, want) + } +} + +type deadLetterRow struct { + consumer string + topic string + partition int32 + offset int64 + eventID *uuid.UUID + eventType *string + errorClass string + reason string + attempts int + valueSize int + valueSHA256 [32]byte +} + +func (harness *consumerHarness) readDeadLetters(ctx context.Context, t *testing.T) []deadLetterRow { + t.Helper() + rows, err := harness.pool.Query(ctx, ` + SELECT consumer_name, topic, kafka_partition, kafka_offset, event_id, event_type, + error_class, reason, attempts, value_size, value_sha256 + FROM consumer_dead_letters ORDER BY id`) + if err != nil { + t.Fatalf("read dead letters: %v", err) + } + letters, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (deadLetterRow, error) { + var letter deadLetterRow + var digest []byte + err := row.Scan(&letter.consumer, &letter.topic, &letter.partition, &letter.offset, &letter.eventID, &letter.eventType, + &letter.errorClass, &letter.reason, &letter.attempts, &letter.valueSize, &digest) + copy(letter.valueSHA256[:], digest) + return letter, err + }) + if err != nil { + t.Fatalf("scan dead letters: %v", err) + } + return letters +} + +func assertDeadLetter(t *testing.T, got, want deadLetterRow) { + t.Helper() + sameID := (got.eventID == nil) == (want.eventID == nil) && (got.eventID == nil || *got.eventID == *want.eventID) + sameType := (got.eventType == nil) == (want.eventType == nil) && (got.eventType == nil || *got.eventType == *want.eventType) + if got.consumer != consumerName || got.topic != want.topic || got.partition != want.partition || got.offset != want.offset || + !sameID || !sameType || got.errorClass != want.errorClass || got.attempts != want.attempts || + got.valueSize != want.valueSize || got.valueSHA256 != want.valueSHA256 || got.reason == "" { + t.Fatalf("dead letter %+v, want %+v", got, want) + } +} + +// assertConsumerMetric reads lincodex_event_consumer__total for the +// test consumer and one outcome or stage label from the scrape output. +func assertConsumerMetric(t *testing.T, metrics *prometheus.Metrics, kind, label string, want int) { + t.Helper() + labelName := map[string]string{"records": "outcome", "failures": "stage"}[kind] + response := httptest.NewRecorder() + metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + prefix := fmt.Sprintf(`lincodex_event_consumer_%s_total{consumer=%q,%s=%q} `, kind, consumerName, labelName, label) + for line := range strings.SplitSeq(response.Body.String(), "\n") { + if value, found := strings.CutPrefix(line, prefix); found { + if value != strconv.Itoa(want) { + t.Fatalf("%s%s, want %d", prefix, value, want) + } + return + } + } + t.Fatalf("metrics output has no series %s", prefix) +} + +// awaitOrCancel waits for release inside a handler and returns result, or the +// context error when the attempt ends first, so a failed test never leaves a +// handler blocked. +func awaitOrCancel(ctx context.Context, release <-chan struct{}, result error) error { + select { + case <-release: + return result + case <-ctx.Done(): + return ctx.Err() + } +} + +// awaitSignal waits for signal within consumerWaitTimeout. +func awaitSignal(ctx context.Context, t *testing.T, signal <-chan struct{}, what string) { + t.Helper() + select { + case <-signal: + case <-ctx.Done(): + t.Fatalf("test ended while waiting for %s", what) + case <-time.After(consumerWaitTimeout): + t.Fatalf("timed out waiting for %s", what) + } +} + +// failingCommits makes every offset commit of one member fail, as a +// coordinator that keeps rejecting commits would. The member's finished +// positions then stay pending, and only the revocation of a partition can +// commit them. It records the offsets the member tried to commit. +type failingCommits struct { + *kafka.EventSource + + succeeded atomic.Int64 + mu sync.Mutex + attempted map[int32][]int64 +} + +func (source *failingCommits) Commit(ctx context.Context, finished []outbound.ConsumedRecord) error { + source.mu.Lock() + for _, record := range finished { + source.attempted[record.Partition] = append(source.attempted[record.Partition], record.Offset) + } + source.mu.Unlock() + canceled, cancel := context.WithCancel(ctx) + cancel() + err := source.EventSource.Commit(canceled, finished) + if err == nil { + source.succeeded.Add(1) + } + return err +} + +func (source *failingCommits) attemptedOffsets(partition int32) []int64 { + source.mu.Lock() + defer source.mu.Unlock() + return append([]int64(nil), source.attempted[partition]...) +} + +// runRebalanceHandover lets a second member join a group while the first one +// holds a record, so the rebalance has to wait for it. The first member's +// commits fail, so the position of the partition it gives up reaches Kafka +// only through the commit in its revocation. +func (harness *consumerHarness) runRebalanceHandover(ctx context.Context, t *testing.T) { + t.Helper() + env := harness.env + logger := slog.New(slog.DiscardHandler) + topic := env.createKafkaTopic(ctx, t, 2) + group := newConsumerGroup() + producer := env.newKafkaClient(t, kgo.RecordPartitioner(kgo.ManualPartitioner())) + first := [2]receivedEnvelope{newConsumerEnvelope(), newConsumerEnvelope()} + produceKafkaRecords(ctx, t, producer, envelopeRecord(t, topic, 0, first[0]), envelopeRecord(t, topic, 1, first[1])) + + held, release := make(chan struct{}), make(chan struct{}) + var holding sync.Once + holder := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + hold := false + holding.Do(func() { hold = true }) + if !hold { + return nil + } + close(held) + return awaitOrCancel(ctx, release, nil) + }) + holderSource, closeHolder := harness.newSource(t, topic, group) + failing := &failingCommits{EventSource: holderSource, attempted: make(map[int32][]int64)} + holderConsumer, err := eventconsumer.New(holder, failing, harness.store, prometheus.New(), logger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + stopHolder := runConsumer(ctx, t, holderConsumer) + awaitSignal(ctx, t, held, "the first member to hold a record") + + joiner := newEffectHandler(nil) + joinerSource, _ := harness.newSource(t, topic, group) + joinerMetrics := prometheus.New() + joinerConsumer, err := eventconsumer.New(joiner, joinerSource, harness.store, joinerMetrics, logger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, joinerConsumer) + // The join starts a rebalance that cannot finish while the first member + // holds its polled records. + env.waitForGroupState(ctx, t, group, "PreparingRebalance") + close(release) + // Cooperative rebalancing first revokes the partition that moves, then + // assigns it to the joiner in a second round. + env.waitForBalancedGroup(ctx, t, group, 2) + + // After the handover each member owns one partition. One new event per + // partition shows which partition moved. + second := [2]receivedEnvelope{newConsumerEnvelope(), newConsumerEnvelope()} + produceKafkaRecords(ctx, t, producer, envelopeRecord(t, topic, 0, second[0]), envelopeRecord(t, topic, 1, second[1])) + all := []receivedEnvelope{first[0], first[1], second[0], second[1]} + waitFor(ctx, t, "every event to be applied", func() bool { + for _, event := range all { + if harness.countEffects(ctx, t, event.EventID) == 0 { + return false + } + } + return true + }) + moved := int32(-1) + for partition := range int32(2) { + if len(joiner.callTimes(second[partition].EventID)) > 0 { + moved = partition + } + } + if moved < 0 { + t.Fatal("the joining member applied no event, so no partition moved") + } + kept := 1 - moved + + for _, event := range all { + harness.assertEffects(ctx, t, event.EventID, 1) + } + for partition := range int32(2) { + if calls := len(holder.callTimes(first[partition].EventID)); calls != 1 { + t.Fatalf("the first member handled the first event of partition %d %d times, want once before the rebalance", partition, calls) + } + } + if failing.succeeded.Load() != 0 { + t.Fatal("a commit of the first member succeeded, so the revocation path was not needed") + } + // The moved partition's position was committed in the revocation: the + // joiner started after the first event instead of receiving it again. + if calls := len(joiner.callTimes(first[moved].EventID)); calls != 0 { + t.Fatalf("the joiner applied the moved partition's first event %d times", calls) + } + assertConsumerMetric(t, joinerMetrics, "records", "duplicate", 0) + // No commit for the moved partition came from the first member after it + // lost the partition. + if offsets := failing.attemptedOffsets(moved); len(offsets) != 1 || offsets[0] != 0 { + t.Fatalf("the first member tried to commit offsets %v of the moved partition %d, want only 0", offsets, moved) + } + if calls := len(holder.callTimes(second[moved].EventID)); calls != 0 { + t.Fatalf("the first member handled the moved partition's second event %d times", calls) + } + waitFor(ctx, t, "the joiner to commit the moved partition", func() bool { + offsets, err := env.fetchCommittedOffsets(ctx, group, topic) + return err == nil && offsets[moved] == 2 + }) + + // Leaving the group revokes the kept partition, and the revocation + // commits its pending position; the moved partition is not rewound. + stopHolder() + closeHolder() + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{moved: 2, kept: 2}) + assertConsumerMetric(t, joinerMetrics, "records", "duplicate", 0) +} + +func (env *testEnvironment) waitForGroupState(ctx context.Context, t *testing.T, group, state string) { + t.Helper() + last := "" + waitFor(ctx, t, "group "+group+" to reach state "+state, func() bool { + requestCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + described, err := env.KafkaAdmin.DescribeGroups(requestCtx, group) + if err != nil { + return false + } + if detail, ok := described[group]; ok && detail.Err == nil { + last = detail.State + } + return last == state + }) +} + +func (harness *consumerHarness) countEffects(ctx context.Context, t *testing.T, eventID uuid.UUID) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+effectsIdentifier.Sanitize()+" WHERE event_id = $1", eventID).Scan(&count); err != nil { + t.Fatalf("count effects: %v", err) + } + return count +} + +// waitForBalancedGroup waits until group is stable with members members that +// each own at least one partition. +func (env *testEnvironment) waitForBalancedGroup(ctx context.Context, t *testing.T, group string, members int) { + t.Helper() + waitFor(ctx, t, fmt.Sprintf("group %s to give each of %d members a partition", group, members), func() bool { + requestCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + described, err := env.KafkaAdmin.DescribeGroups(requestCtx, group) + if err != nil { + return false + } + detail, ok := described[group] + if !ok || detail.Err != nil || detail.State != "Stable" || len(detail.Members) != members { + return false + } + for _, member := range detail.Members { + assignment, ok := member.Assigned.AsConsumer() + if !ok || len(assignment.Topics) == 0 || len(assignment.Topics[0].Partitions) == 0 { + return false + } + } + return true + }) +} diff --git a/backend/integration_test/outbox_relay_test.go b/backend/integration_test/outbox_relay_test.go index cd655e9..a074ea5 100644 --- a/backend/integration_test/outbox_relay_test.go +++ b/backend/integration_test/outbox_relay_test.go @@ -25,6 +25,7 @@ import ( "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/worker/outboxrelay" + "lincodex/backend/internal/worker/retry" ) const ( @@ -497,7 +498,7 @@ func (harness *relayHarness) newRelayWithMetrics(publisher outbound.EventPublish return outboxrelay.New(harness.store, publisher, metrics, slog.New(slog.DiscardHandler), outboxrelay.Settings{ BatchSize: relayBatchSize, PollInterval: relayPollInterval, - Backoff: outboxrelay.Backoff{Initial: relayBackoffInitial, Max: relayBackoffMax}, + Backoff: retry.Backoff{Initial: relayBackoffInitial, Max: relayBackoffMax}, ShutdownTimeout: relayShutdownTimeout, BacklogInterval: relayBacklogInterval, }) diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go index f9bef38..782a6d0 100644 --- a/backend/integration_test/postgres_migrations_test.go +++ b/backend/integration_test/postgres_migrations_test.go @@ -24,13 +24,16 @@ const ( identityMigrationVersion = 2 // policyMigrationVersion creates policyTableNames and policyFunctionNames. policyMigrationVersion = 3 + // consumerMigrationVersion creates consumerTableNames. + consumerMigrationVersion = 5 ) var ( - // Tables created by 00001, 00002, and 00003. + // Tables created by 00001, 00002, 00003, and 00005. outboxTables = []string{"outbox_events"} identityTableNames = []string{"users", "email_tokens", "sessions"} policyTableNames = []string{"policy_versions"} + consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"} // Trigger functions created by 00003. policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"} ) @@ -61,8 +64,9 @@ func TestPostgresMigrations(t *testing.T) { assertTablesExist(ctx, t, pool, true, identityTableNames...) assertTablesExist(ctx, t, pool, true, policyTableNames...) assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...) + assertTablesExist(ctx, t, pool, true, consumerTableNames...) - identityRolledBack, policyRolledBack := false, false + identityRolledBack, policyRolledBack, consumerRolledBack := false, false, false for rolledBack := 0; ; rolledBack++ { result, err := migrator.DownOne(ctx) if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { @@ -74,6 +78,12 @@ func TestPostgresMigrations(t *testing.T) { if err != nil { t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) } + if result.Version == consumerMigrationVersion { + // The consumer migration removes only its own tables. + assertTablesExist(ctx, t, pool, false, consumerTableNames...) + assertTablesExist(ctx, t, pool, true, outboxTables...) + consumerRolledBack = true + } if result.Version == policyMigrationVersion { // The policy migration rolls back its table, triggers, and // function and leaves the identity tables. @@ -90,8 +100,8 @@ func TestPostgresMigrations(t *testing.T) { identityRolledBack = true } } - if !identityRolledBack || !policyRolledBack { - t.Fatalf("migrations %d and %d were not both rolled back", identityMigrationVersion, policyMigrationVersion) + if !identityRolledBack || !policyRolledBack || !consumerRolledBack { + t.Fatalf("migrations %d, %d, and %d were not all rolled back", identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion) } assertTablesExist(ctx, t, pool, false, outboxTables...) assertTablesExist(ctx, t, pool, false, identityTableNames...) @@ -130,6 +140,7 @@ func TestPostgresMigrations(t *testing.T) { assertTablesExist(ctx, t, pool, true, identityTableNames...) assertTablesExist(ctx, t, pool, true, policyTableNames...) assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...) + assertTablesExist(ctx, t, pool, true, consumerTableNames...) assertAllApplied(ctx, t, migrator, total) }) diff --git a/backend/internal/adapter/secondary/kafka/consumer.go b/backend/internal/adapter/secondary/kafka/consumer.go new file mode 100644 index 0000000..1fd4966 --- /dev/null +++ b/backend/internal/adapter/secondary/kafka/consumer.go @@ -0,0 +1,290 @@ +package kafka + +import ( + "context" + "errors" + "fmt" + "log/slog" + "slices" + "sync" + "time" + + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" + "github.com/twmb/franz-go/pkg/kmsg" + + "lincodex/backend/config" + "lincodex/backend/internal/port/outbound" +) + +// leaveGroupMargin is added to CONSUMER_COMMIT_TIMEOUT to bound leaving the +// group at close: the leave revokes the partitions, and the revocation may +// commit finished records whose earlier commit failed. A broker that does not +// answer in time cannot hold shutdown; a member that could not leave is +// removed by the broker after the session timeout. +const leaveGroupMargin = 2 * time.Second + +// EventSource implements outbound.EventSource with a franz-go consumer group +// member. Autocommit is off and rebalancing is blocked from a poll until +// Release, so an offset is committed only for records the consumer finished +// and only while this member still owns their partitions. +type EventSource struct { + client *kgo.Client + logger *slog.Logger + maxPollRecords int + commitTimeout time.Duration + leaveTimeout time.Duration + + mu sync.Mutex + // epochs holds the leader epoch of every record of the last poll, which + // the commit carries for log truncation detection. + epochs map[recordPosition]int32 + // polled holds the offsets of the last poll per partition in order, so + // Commit can refuse finished records that skip one. + polled map[topicPartition][]int64 + // pending holds, per partition, the position after the last finished + // record that is not committed yet: a commit failed, and a later commit + // or the revocation of the partition retries it. + pending map[string]map[int32]kgo.EpochOffset +} + +type topicPartition struct { + topic string + partition int32 +} + +type recordPosition struct { + topic string + partition int32 + offset int64 +} + +var _ outbound.EventSource = (*EventSource)(nil) + +// NewEventSource creates a member of group that consumes KAFKA_EVENTS_TOPIC +// without connecting; franz-go dials brokers on first poll. A group without +// a committed offset starts at the earliest retained record, so a new +// consumer never skips an event. The returned cleanup leaves the group and +// closes the client; call it only after the consumer stopped polling. +func NewEventSource(settings config.Config, group string, logger *slog.Logger) (*EventSource, func(), error) { + source := &EventSource{ + logger: logger, + maxPollRecords: settings.ConsumerMaxPollRecords, + commitTimeout: settings.ConsumerCommitTimeout, + leaveTimeout: settings.ConsumerCommitTimeout + leaveGroupMargin, + epochs: make(map[recordPosition]int32), + polled: make(map[topicPartition][]int64), + pending: make(map[string]map[int32]kgo.EpochOffset), + } + client, err := kgo.NewClient( + kgo.SeedBrokers(settings.KafkaBrokers...), + kgo.ConsumerGroup(group), + kgo.ConsumeTopics(settings.KafkaEventsTopic), + kgo.DisableAutoCommit(), + kgo.BlockRebalanceOnPoll(), + // Set explicitly: config checks that the slowest record fits in it. + kgo.RebalanceTimeout(settings.ConsumerRebalanceTimeout), + kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), + kgo.OnPartitionsRevoked(source.onRevoked), + kgo.OnPartitionsLost(source.onLost), + ) + if err != nil { + return nil, nil, fmt.Errorf("kafka.NewEventSource - create Kafka client: %w", err) + } + source.client = client + return source, source.close, nil +} + +// Poll returns the records of the next fetch in partition order. Fetch +// errors of single partitions are joined into the error; records of other +// partitions are still returned. +func (source *EventSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) { + fetches := source.client.PollRecords(ctx, source.maxPollRecords) + if err := ctx.Err(); err != nil { + return nil, err + } + if fetches.IsClientClosed() { + return nil, errors.New("EventSource.Poll - Kafka client is closed") + } + var fetchErr error + fetches.EachError(func(topic string, partition int32, err error) { + fetchErr = errors.Join(fetchErr, fmt.Errorf("EventSource.Poll - fetch %s partition %d: %w", topic, partition, err)) + }) + records := make([]outbound.ConsumedRecord, 0, fetches.NumRecords()) + source.mu.Lock() + clear(source.epochs) + clear(source.polled) + fetches.EachRecord(func(record *kgo.Record) { + source.epochs[recordPosition{topic: record.Topic, partition: record.Partition, offset: record.Offset}] = record.LeaderEpoch + partition := topicPartition{topic: record.Topic, partition: record.Partition} + source.polled[partition] = append(source.polled[partition], record.Offset) + records = append(records, decodeRecord(record)) + }) + source.mu.Unlock() + return records, fetchErr +} + +// Commit commits the position after the last finished record of each +// partition, together with any earlier position whose commit failed. +func (source *EventSource) Commit(ctx context.Context, finished []outbound.ConsumedRecord) error { + source.mu.Lock() + if err := source.checkPrefix(finished); err != nil { + source.mu.Unlock() + return err + } + for _, record := range finished { + epoch := source.epochs[recordPosition{topic: record.Topic, partition: record.Partition, offset: record.Offset}] + partitions := source.pending[record.Topic] + if partitions == nil { + partitions = make(map[int32]kgo.EpochOffset) + source.pending[record.Topic] = partitions + } + next := kgo.EpochOffset{Epoch: epoch, Offset: record.Offset + 1} + if current, ok := partitions[record.Partition]; !ok || current.Less(next) { + partitions[record.Partition] = next + } + } + offsets := clonePending(source.pending, nil) + source.mu.Unlock() + + if err := source.commitOffsets(ctx, offsets); err != nil { + return err + } + source.forgetCommitted(offsets) + return nil +} + +// checkPrefix verifies that, for every partition, the finished records are +// the first records of the last poll in order without a gap, so a commit can +// never move a partition past a record that was not finished. The caller +// holds mu. +func (source *EventSource) checkPrefix(finished []outbound.ConsumedRecord) error { + seen := make(map[topicPartition]int, len(source.polled)) + for _, record := range finished { + partition := topicPartition{topic: record.Topic, partition: record.Partition} + polled, index := source.polled[partition], seen[partition] + if index >= len(polled) || polled[index] != record.Offset { + return fmt.Errorf("EventSource.Commit - record at %s partition %d offset %d is not the next record of the last poll", record.Topic, record.Partition, record.Offset) + } + seen[partition] = index + 1 + } + return nil +} + +// Release allows the group to rebalance until the next poll. +func (source *EventSource) Release() { + source.client.AllowRebalance() +} + +// onRevoked commits finished records of the revoked partitions whose +// earlier commit failed. Unfinished records were never marked finished, so +// they are not committed and the next owner processes them. +func (source *EventSource) onRevoked(ctx context.Context, _ *kgo.Client, revoked map[string][]int32) { + source.mu.Lock() + offsets := clonePending(source.pending, revoked) + source.dropPending(revoked) + source.mu.Unlock() + if len(offsets) == 0 { + return + } + commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), source.commitTimeout) + defer cancel() + if err := source.commitOffsets(commitCtx, offsets); err != nil { + source.logger.Warn("event consumer could not commit finished records of revoked partitions; the next owner processes them again", + slog.Any("error", err)) + } +} + +// onLost drops pending positions: the member no longer belongs to the group +// generation, so a commit would fail, and the next owner starts from the +// last committed offset. +func (source *EventSource) onLost(_ context.Context, _ *kgo.Client, lost map[string][]int32) { + source.mu.Lock() + source.dropPending(lost) + source.mu.Unlock() + if len(lost) > 0 { + source.logger.Warn("event consumer lost its partitions; uncommitted records will be processed again") + } +} + +func (source *EventSource) commitOffsets(ctx context.Context, offsets map[string]map[int32]kgo.EpochOffset) error { + if len(offsets) == 0 { + return nil + } + var commitErr error + source.client.CommitOffsetsSync(ctx, offsets, func(_ *kgo.Client, _ *kmsg.OffsetCommitRequest, response *kmsg.OffsetCommitResponse, err error) { + if err != nil { + commitErr = err + return + } + for _, topic := range response.Topics { + for _, partition := range topic.Partitions { + if err := kerr.ErrorForCode(partition.ErrorCode); err != nil { + commitErr = errors.Join(commitErr, fmt.Errorf("partition %d: %w", partition.Partition, err)) + } + } + } + }) + if commitErr != nil { + return fmt.Errorf("EventSource.commitOffsets - commit offsets: %w", commitErr) + } + return nil +} + +// forgetCommitted removes pending positions that the commit covered and that +// did not advance meanwhile. +func (source *EventSource) forgetCommitted(committed map[string]map[int32]kgo.EpochOffset) { + source.mu.Lock() + defer source.mu.Unlock() + for topic, partitions := range committed { + for partition, offset := range partitions { + if source.pending[topic][partition] == offset { + delete(source.pending[topic], partition) + } + } + if len(source.pending[topic]) == 0 { + delete(source.pending, topic) + } + } +} + +func (source *EventSource) dropPending(partitions map[string][]int32) { + for topic, numbers := range partitions { + for _, partition := range numbers { + delete(source.pending[topic], partition) + } + if len(source.pending[topic]) == 0 { + delete(source.pending, topic) + } + } +} + +// close leaves the group, which revokes the partitions and commits finished +// records whose commit failed, and closes the client. +func (source *EventSource) close() { + ctx, cancel := context.WithTimeout(context.Background(), source.leaveTimeout) + defer cancel() + if err := source.client.LeaveGroupContext(ctx); err != nil { + source.logger.Warn("event consumer could not leave its group; the broker removes it after the session timeout", + slog.Any("error", err)) + } + source.client.CloseAllowingRebalance() +} + +// clonePending copies the pending positions, limited to the partitions in +// only when only is not nil. +func clonePending(pending map[string]map[int32]kgo.EpochOffset, only map[string][]int32) map[string]map[int32]kgo.EpochOffset { + result := make(map[string]map[int32]kgo.EpochOffset) + for topic, partitions := range pending { + for partition, offset := range partitions { + if only != nil && !slices.Contains(only[topic], partition) { + continue + } + if result[topic] == nil { + result[topic] = make(map[int32]kgo.EpochOffset) + } + result[topic][partition] = offset + } + } + return result +} diff --git a/backend/internal/adapter/secondary/kafka/consumer_test.go b/backend/internal/adapter/secondary/kafka/consumer_test.go new file mode 100644 index 0000000..2d96131 --- /dev/null +++ b/backend/internal/adapter/secondary/kafka/consumer_test.go @@ -0,0 +1,78 @@ +package kafka + +import ( + "testing" + + "github.com/twmb/franz-go/pkg/kgo" + + "lincodex/backend/internal/port/outbound" +) + +func TestEventSourceCommitAcceptsOnlyAPrefixOfTheLastPollPerPartition(t *testing.T) { + newSource := func() *EventSource { + source := &EventSource{ + epochs: make(map[recordPosition]int32), + polled: make(map[topicPartition][]int64), + pending: make(map[string]map[int32]kgo.EpochOffset), + } + // The last poll returned offsets 4, 5, 6 of partition 0 and 9 of + // partition 1. + for partition, offsets := range map[int32][]int64{0: {4, 5, 6}, 1: {9}} { + for _, offset := range offsets { + source.epochs[recordPosition{topic: testTopic, partition: partition, offset: offset}] = 1 + key := topicPartition{topic: testTopic, partition: partition} + source.polled[key] = append(source.polled[key], offset) + } + } + return source + } + record := func(partition int32, offset int64) outbound.ConsumedRecord { + return outbound.ConsumedRecord{Topic: testTopic, Partition: partition, Offset: offset} + } + rejected := map[string][]outbound.ConsumedRecord{ + "not from the last poll": {record(0, 7)}, + "gap": {record(0, 4), record(0, 6)}, + "skips the first record": {record(0, 5)}, + "out of order": {record(0, 5), record(0, 4)}, + "repeated record": {record(0, 4), record(0, 4)}, + "another topic": {{Topic: "other", Partition: 0, Offset: 4}}, + } + for name, finished := range rejected { + t.Run(name, func(t *testing.T) { + source := newSource() + if err := source.Commit(t.Context(), finished); err == nil { + t.Fatal("Commit() accepted records that are not a prefix of the last poll") + } + if len(source.pending) != 0 { + t.Fatalf("Commit() kept a pending position for rejected records: %v", source.pending) + } + }) + } + // Interleaved partitions are fine as long as each one is a prefix. + source := newSource() + if err := source.checkPrefix([]outbound.ConsumedRecord{record(0, 4), record(1, 9), record(0, 5)}); err != nil { + t.Fatalf("checkPrefix() rejected a valid prefix: %v", err) + } +} + +func TestPendingPositionsAreLimitedAndForgottenPerPartition(t *testing.T) { + source := &EventSource{pending: map[string]map[int32]kgo.EpochOffset{ + testTopic: {0: {Epoch: 1, Offset: 10}, 1: {Epoch: 1, Offset: 20}}, + }} + revoked := clonePending(source.pending, map[string][]int32{testTopic: {1}}) + if len(revoked[testTopic]) != 1 || revoked[testTopic][1].Offset != 20 { + t.Fatalf("clonePending() = %v, want only partition 1", revoked) + } + + committed := clonePending(source.pending, nil) + // Partition 0 advanced while the commit was in flight, so it stays. + source.pending[testTopic][0] = kgo.EpochOffset{Epoch: 1, Offset: 11} + source.forgetCommitted(committed) + if len(source.pending[testTopic]) != 1 || source.pending[testTopic][0].Offset != 11 { + t.Fatalf("pending after forgetCommitted() = %v, want only the advanced partition 0", source.pending) + } + source.dropPending(map[string][]int32{testTopic: {0}}) + if len(source.pending) != 0 { + t.Fatalf("pending after dropPending() = %v, want none", source.pending) + } +} diff --git a/backend/internal/adapter/secondary/kafka/envelope.go b/backend/internal/adapter/secondary/kafka/envelope.go index 4a3eb69..d936964 100644 --- a/backend/internal/adapter/secondary/kafka/envelope.go +++ b/backend/internal/adapter/secondary/kafka/envelope.go @@ -1,6 +1,7 @@ package kafka import ( + "bytes" "encoding/json" "fmt" "strconv" @@ -9,6 +10,7 @@ import ( "github.com/google/uuid" "github.com/twmb/franz-go/pkg/kgo" + "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) @@ -74,3 +76,96 @@ func newRecord(topic string, event outbound.OutboxEvent) (*kgo.Record, error) { }, }, nil } + +// decodeRecord turns a consumed record into an event. A value that is not a +// valid envelope yields a record whose Invalid error matches +// outbound.ErrInvalidEventRecord; the error names the broken rule and never +// quotes the value. EventID then comes from the event_id header when it holds +// a UUID, so an operator can still find the event. +func decodeRecord(record *kgo.Record) outbound.ConsumedRecord { + consumed := outbound.ConsumedRecord{ + Topic: record.Topic, + Partition: record.Partition, + Offset: record.Offset, + Value: record.Value, + } + headerID, headerErr := uuid.Parse(recordHeader(record, headerEventID)) + if headerErr == nil { + consumed.EventID = headerID + } + event, err := decodeEnvelope(record.Value) + if err == nil && headerErr == nil && headerID != event.EventID { + // A consumer that deduplicated by the header would disagree with one + // that reads the value, so the record is not trusted. + err = invalidRecord("event_id header differs from the envelope") + } + if err != nil { + consumed.Invalid = err + return consumed + } + consumed.Event = event + consumed.EventID = event.EventID + return consumed +} + +func decodeEnvelope(value []byte) (outbound.ConsumedEvent, error) { + var decoded envelope + // The json error is dropped: its text can quote part of the value. + if err := json.Unmarshal(value, &decoded); err != nil { + return outbound.ConsumedEvent{}, invalidRecord("value is not a JSON event envelope") + } + if decoded.EnvelopeVersion != EnvelopeVersion { + return outbound.ConsumedEvent{}, invalidRecord("unsupported envelope_version") + } + if decoded.EventID == uuid.Nil { + return outbound.ConsumedEvent{}, invalidRecord("event_id is missing") + } + identity := domain.DomainEventInput{ + EventType: decoded.EventType, + SchemaVersion: decoded.SchemaVersion, + AggregateType: decoded.AggregateType, + AggregateID: decoded.AggregateID, + AggregateVersion: decoded.AggregateVersion, + } + if err := identity.ValidateIdentity(); err != nil { + return outbound.ConsumedEvent{}, fmt.Errorf("kafka.decodeEnvelope - %w: %w", outbound.ErrInvalidEventRecord, err) + } + if decoded.OccurredAt.IsZero() { + return outbound.ConsumedEvent{}, invalidRecord("occurred_at is missing") + } + if !isJSONObject(decoded.Payload) { + return outbound.ConsumedEvent{}, invalidRecord("payload is not a JSON object") + } + return outbound.ConsumedEvent{ + EventID: decoded.EventID, + EventType: decoded.EventType, + SchemaVersion: decoded.SchemaVersion, + AggregateType: decoded.AggregateType, + AggregateID: decoded.AggregateID, + AggregateVersion: decoded.AggregateVersion, + OccurredAt: decoded.OccurredAt, + Payload: decoded.Payload, + }, nil +} + +// isJSONObject reports whether raw, which json.Unmarshal already checked, is +// an object rather than another value or null. +func isJSONObject(raw json.RawMessage) bool { + trimmed := bytes.TrimLeft(raw, " \t\r\n") + return len(trimmed) > 0 && trimmed[0] == '{' +} + +func invalidRecord(reason string) error { + return fmt.Errorf("kafka.decodeEnvelope - %s: %w", reason, outbound.ErrInvalidEventRecord) +} + +// recordHeader returns the last value of the header key, or "" without one. +func recordHeader(record *kgo.Record, key string) string { + value := "" + for _, header := range record.Headers { + if header.Key == key { + value = string(header.Value) + } + } + return value +} diff --git a/backend/internal/adapter/secondary/kafka/envelope_test.go b/backend/internal/adapter/secondary/kafka/envelope_test.go index 1ccd5e1..e25cc99 100644 --- a/backend/internal/adapter/secondary/kafka/envelope_test.go +++ b/backend/internal/adapter/secondary/kafka/envelope_test.go @@ -2,11 +2,13 @@ package kafka import ( "encoding/json" + "errors" "strings" "testing" "time" "github.com/google/uuid" + "github.com/twmb/franz-go/pkg/kgo" "lincodex/backend/internal/port/outbound" ) @@ -103,3 +105,106 @@ func TestNewRecordRejectsAnInvalidPayloadWithoutQuotingIt(t *testing.T) { t.Fatalf("newRecord() error = %v, want the event ID", err) } } + +func TestDecodeRecordReadsWhatNewRecordWrites(t *testing.T) { + want := testEvent() + record, err := newRecord(testTopic, want) + if err != nil { + t.Fatalf("newRecord() error = %v", err) + } + record.Partition, record.Offset = 2, 41 + + consumed := decodeRecord(record) + if consumed.Invalid != nil { + t.Fatalf("decodeRecord() Invalid = %v", consumed.Invalid) + } + got := consumed.Event + if consumed.Topic != testTopic || consumed.Partition != 2 || consumed.Offset != 41 || consumed.EventID != want.EventID || + got.EventID != want.EventID || got.EventType != want.EventType || got.SchemaVersion != want.SchemaVersion || + got.AggregateType != want.AggregateType || got.AggregateID != want.AggregateID || + got.AggregateVersion != want.AggregateVersion || !got.OccurredAt.Equal(want.OccurredAt) { + t.Fatalf("decodeRecord() = %+v, want the fields of %+v", consumed, want) + } + if string(got.Payload) != `{"user_id":"6f1c2b8e-1d2a-4c3b-9a8e-0f1e2d3c4b5a","nested":{"n":1}}` { + t.Fatalf("payload = %s", got.Payload) + } + if string(consumed.Value) != string(record.Value) { + t.Fatal("decodeRecord() did not keep the raw value") + } +} + +func TestDecodeRecordRejectsInvalidEnvelopesWithoutQuotingThem(t *testing.T) { + valid, err := newRecord(testTopic, testEvent()) + if err != nil { + t.Fatalf("newRecord() error = %v", err) + } + headerID := testEvent().EventID + withField := func(field string, value any) []byte { + var fields map[string]any + if err := json.Unmarshal(valid.Value, &fields); err != nil { + t.Fatalf("decode test envelope: %v", err) + } + if value == nil { + delete(fields, field) + } else { + fields[field] = value + } + encoded, err := json.Marshal(fields) + if err != nil { + t.Fatalf("encode test envelope: %v", err) + } + return encoded + } + tests := []struct { + name string + value []byte + headers []kgo.RecordHeader + want string + }{ + {name: "not JSON", value: []byte("secret-value"), want: "value is not a JSON event envelope"}, + {name: "wrong type", value: withField("event_id", "secret-value"), want: "value is not a JSON event envelope"}, + {name: "future envelope", value: withField("envelope_version", 2), want: "unsupported envelope_version"}, + {name: "no event ID", value: withField("event_id", nil), want: "event_id is missing"}, + {name: "bad event type", value: withField("event_type", "Secret Value"), want: "event type must be"}, + {name: "zero schema", value: withField("schema_version", 0), want: "schema version must be positive"}, + {name: "no aggregate", value: withField("aggregate_id", nil), want: "aggregate ID must not be nil"}, + {name: "zero version", value: withField("aggregate_version", 0), want: "aggregate version must be positive"}, + {name: "no time", value: withField("occurred_at", nil), want: "occurred_at is missing"}, + {name: "array payload", value: withField("payload", []string{"secret-value"}), want: "payload is not a JSON object"}, + {name: "null payload", value: withField("payload", nil), want: "payload is not a JSON object"}, + { + name: "header mismatch", + value: valid.Value, + headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte(uuid.NewString())}}, + want: "event_id header differs from the envelope", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + headers := test.headers + if headers == nil { + headers = []kgo.RecordHeader{{Key: "event_id", Value: []byte(headerID.String())}} + } + consumed := decodeRecord(&kgo.Record{Topic: testTopic, Value: test.value, Headers: headers}) + if !errors.Is(consumed.Invalid, outbound.ErrInvalidEventRecord) { + t.Fatalf("Invalid = %v, want ErrInvalidEventRecord", consumed.Invalid) + } + if !strings.Contains(consumed.Invalid.Error(), test.want) { + t.Fatalf("Invalid = %v, want %q", consumed.Invalid, test.want) + } + if strings.Contains(consumed.Invalid.Error(), "secret") || strings.Contains(consumed.Invalid.Error(), "Secret") { + t.Fatalf("Invalid quotes the value: %v", consumed.Invalid) + } + if test.headers == nil && consumed.EventID != headerID { + t.Fatalf("EventID = %s, want the header event ID", consumed.EventID) + } + }) + } +} + +func TestDecodeRecordWithoutAnEventIDHeaderLeavesItNil(t *testing.T) { + consumed := decodeRecord(&kgo.Record{Topic: testTopic, Value: []byte("{}"), Headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte("not-a-uuid")}}}) + if consumed.Invalid == nil || consumed.EventID != uuid.Nil { + t.Fatalf("decodeRecord() = %+v, want an invalid record without an event ID", consumed) + } +} diff --git a/backend/internal/adapter/secondary/postgres/event_consumer.go b/backend/internal/adapter/secondary/postgres/event_consumer.go new file mode 100644 index 0000000..9ac832d --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/event_consumer.go @@ -0,0 +1,206 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "math" + "strings" + "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" +) + +// SQLSTATE classes that classifyCommitError separates. +const ( + sqlStateClassLength = 2 + integrityConstraintClass = "23" + transactionRollbackClass = "40" +) + +// EventConsumerStore implements outbound.EventConsumerStore with a pgx pool +// owned by the caller. Each ApplyOnce holds one connection and one +// transaction for the duration of the handler. +type EventConsumerStore struct { + pool *pgxpool.Pool + // transactionTimeout is set as statement_timeout and + // idle_in_transaction_session_timeout of every ApplyOnce transaction. + transactionTimeout time.Duration +} + +var _ outbound.EventConsumerStore = (*EventConsumerStore)(nil) + +// NewEventConsumerStore bounds each transaction on the server by +// transactionTimeout, the consumer's handler timeout. The caller's context +// already cancels the work of a live process; the server-side limits also +// end the transaction of a process that froze or lost the network, so the +// marker it holds does not block a concurrent duplicate indefinitely. +func NewEventConsumerStore(pool *pgxpool.Pool, transactionTimeout time.Duration) *EventConsumerStore { + return &EventConsumerStore{pool: pool, transactionTimeout: transactionTimeout} +} + +// ApplyOnce inserts the marker first and runs apply only when the insert +// added it. INSERT ... ON CONFLICT DO NOTHING is used rather than a plain +// INSERT that fails on the unique key: it waits for a concurrent transaction +// holding the same key exactly as the plain insert would, but a duplicate +// then reports zero rows instead of aborting the transaction with SQLSTATE +// 23505, so no error decides control flow and PostgreSQL logs no error for +// an expected duplicate. +func (store *EventConsumerStore) ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply outbound.ApplyEvent) (bool, error) { + // PostgreSQL reads 0 as no limit, so a value below one millisecond would + // silently remove the bound. + if store.transactionTimeout < time.Millisecond { + return false, errors.New("EventConsumerStore.ApplyOnce - transaction timeout must be at least 1ms") + } + if ctx.Value(transactionContextKey{}) != nil { + return false, fmt.Errorf("EventConsumerStore.ApplyOnce - begin transaction: %w", outbound.ErrNestedTransaction) + } + tx, err := store.pool.BeginTx(ctx, transactionOptions) + if err != nil { + return false, fmt.Errorf("EventConsumerStore.ApplyOnce - begin transaction: %w", sanitizeConnectError(err)) + } + finished := false + defer func() { + // Runs only when apply panics; the panic keeps its stack and the + // rollback error cannot change that outcome. + if !finished { + _ = rollback(ctx, tx) + } + }() + + applied, applyErr := store.applyInTransaction(ctx, tx, consumer, eventID, apply) + finished = true + if applyErr != nil || !applied { + if rollbackErr := rollback(ctx, tx); rollbackErr != nil { + return false, errors.Join(applyErr, fmt.Errorf("EventConsumerStore.ApplyOnce - roll back transaction: %w", rollbackErr)) + } + return false, applyErr + } + if err := tx.Commit(ctx); err != nil { + return false, fmt.Errorf("EventConsumerStore.ApplyOnce - commit transaction: %w", classifyCommitError(err)) + } + return true, nil +} + +// classifyCommitError separates a commit that PostgreSQL refused from one +// that failed in transport. A refusal is deterministic or caused by +// concurrent writers, so the consumer counts it as a handler attempt instead +// of retrying it as a database outage forever: +// +// - pgx.ErrTxCommitRollback: a statement of the handler failed and the +// handler returned nil anyway, so PostgreSQL rolled the aborted +// transaction back; +// - SQLSTATE class 23: a deferred integrity constraint failed at commit; +// - SQLSTATE class 40: a serialization failure or deadlock, which a retry +// usually resolves, so it matches outbound.ErrTransactionConflict. +// +// Connection and network errors pass through as store failures. +func classifyCommitError(err error) error { + if errors.Is(err, pgx.ErrTxCommitRollback) { + return fmt.Errorf("postgres.classifyCommitError - transaction was aborted by a failed statement: %w", outbound.ErrEventEffectRejected) + } + var pgError *pgconn.PgError + if errors.As(err, &pgError) && len(pgError.Code) == len(deadlockDetectedCode) { + safe := &databaseError{code: pgError.Code, constraint: pgError.ConstraintName} + switch pgError.Code[:sqlStateClassLength] { + case integrityConstraintClass: + return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrEventEffectRejected, safe) + case transactionRollbackClass: + return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrTransactionConflict, safe) + } + } + return sanitizedDatabaseError(err) +} + +// sanitizedApplyError keeps the identity of a handler error for errors.Is +// and errors.As but replaces the text of a PostgreSQL error inside it, whose +// message can quote row values, with its SQLSTATE and constraint. The +// consumer logs this text and stores it with a dead letter. +type sanitizedApplyError struct { + text string + cause error +} + +func (err *sanitizedApplyError) Error() string { return err.text } + +func (err *sanitizedApplyError) Unwrap() error { return err.cause } + +func sanitizeApplyError(err error) error { + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + return err + } + safe := (&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}).Error() + text := strings.ReplaceAll(err.Error(), pgError.Error(), safe) + // A handler that formatted the message itself may still carry it. + if pgError.Message != "" && strings.Contains(text, pgError.Message) { + text = "handler failed: " + safe + } + return &sanitizedApplyError{text: text, cause: err} +} + +func (store *EventConsumerStore) applyInTransaction( + ctx context.Context, + tx pgx.Tx, + consumer string, + eventID uuid.UUID, + apply outbound.ApplyEvent, +) (bool, error) { + queries := sqlc.New(tx) + timeout := milliseconds(store.transactionTimeout) + err := queries.SetConsumerTransactionTimeouts(ctx, sqlc.SetConsumerTransactionTimeoutsParams{ + StatementTimeoutMs: timeout, + IdleTimeoutMs: timeout, + }) + if err != nil { + return false, fmt.Errorf("postgres.applyInTransaction - set transaction timeouts: %w", sanitizedDatabaseError(err)) + } + inserted, err := queries.InsertProcessedEventMarker(ctx, sqlc.InsertProcessedEventMarkerParams{ + ConsumerName: consumer, + EventID: pgtype.UUID{Bytes: eventID, Valid: true}, + }) + if err != nil { + return false, fmt.Errorf("postgres.applyInTransaction - insert processed event marker: %w", sanitizedDatabaseError(err)) + } + if inserted == 0 { + return false, nil + } + unit := &UnitOfWork{tx: tx, queries: queries} + // The error of apply is returned without a store location, so the caller + // keeps its identity; only PostgreSQL text inside it is replaced. + if err := apply(context.WithValue(ctx, transactionContextKey{}, true), unit); err != nil { + return false, sanitizeApplyError(markTransactionConflict(err)) + } + return true, nil +} + +// RecordDeadLetter stores letter outside any consumer transaction. +func (store *EventConsumerStore) RecordDeadLetter(ctx context.Context, letter outbound.DeadLetter) error { + if letter.Attempts < 0 || letter.Attempts > math.MaxInt32 || letter.ValueSize < 0 || letter.ValueSize > math.MaxInt32 { + return errors.New("EventConsumerStore.RecordDeadLetter - attempts and value size must fit a non-negative int32") + } + params := sqlc.InsertConsumerDeadLetterParams{ + ConsumerName: letter.Consumer, + Topic: letter.Topic, + KafkaPartition: letter.Partition, + KafkaOffset: letter.Offset, + EventID: pgtype.UUID{Bytes: letter.EventID, Valid: letter.EventID != uuid.Nil}, + EventType: pgtype.Text{String: letter.EventType, Valid: letter.EventType != ""}, + ErrorClass: string(letter.ErrorClass), + Reason: letter.Reason, + Attempts: int32(letter.Attempts), + ValueSize: int32(letter.ValueSize), + ValueSha256: letter.ValueSHA256[:], + } + if err := sqlc.New(store.pool).InsertConsumerDeadLetter(ctx, params); err != nil { + return fmt.Errorf("EventConsumerStore.RecordDeadLetter - insert dead letter: %w", sanitizedDatabaseError(err)) + } + return nil +} diff --git a/backend/internal/adapter/secondary/postgres/event_consumer_test.go b/backend/internal/adapter/secondary/postgres/event_consumer_test.go new file mode 100644 index 0000000..9128cf5 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/event_consumer_test.go @@ -0,0 +1,80 @@ +package postgres + +import ( + "errors" + "fmt" + "net" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +func TestClassifyCommitErrorSeparatesRefusalsFromTransportFailures(t *testing.T) { + tests := []struct { + name string + err error + rejected bool + conflict bool + forbidText string + }{ + {name: "aborted transaction", err: pgx.ErrTxCommitRollback, rejected: true}, + { + name: "deferred unique violation", + err: &pgconn.PgError{Code: "23505", ConstraintName: "effects_key", Message: "duplicate key secret-value"}, + rejected: true, + forbidText: "secret-value", + }, + {name: "serialization failure", err: &pgconn.PgError{Code: "40001", Message: "could not serialize"}, conflict: true}, + {name: "deadlock", err: &pgconn.PgError{Code: "40P01"}, conflict: true}, + {name: "network", err: &net.OpError{Op: "read", Err: errors.New("connection reset")}}, + {name: "server shutdown", err: &pgconn.PgError{Code: "57P01", Message: "terminating connection secret-value"}, forbidText: "secret-value"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := classifyCommitError(test.err) + if got := errors.Is(err, outbound.ErrEventEffectRejected); got != test.rejected { + t.Fatalf("classifyCommitError() = %v, rejected = %t, want %t", err, got, test.rejected) + } + if got := errors.Is(err, outbound.ErrTransactionConflict); got != test.conflict { + t.Fatalf("classifyCommitError() = %v, conflict = %t, want %t", err, got, test.conflict) + } + if test.forbidText != "" && strings.Contains(err.Error(), test.forbidText) { + t.Fatalf("classifyCommitError() kept the PostgreSQL message: %v", err) + } + }) + } +} + +func TestSanitizeApplyErrorKeepsIdentityButDropsThePostgreSQLMessage(t *testing.T) { + pgError := &pgconn.PgError{Severity: "ERROR", Code: "22P02", Message: `invalid input syntax for type uuid: "secret-value"`} + wrapped := fmt.Errorf("apply effect: %w: %w", inbound.ErrEventRejected, pgError) + + err := sanitizeApplyError(wrapped) + if strings.Contains(err.Error(), "secret-value") { + t.Fatalf("sanitizeApplyError() kept the message: %v", err) + } + if !strings.Contains(err.Error(), "apply effect") || !strings.Contains(err.Error(), "22P02") { + t.Fatalf("sanitizeApplyError() = %q, want the handler context and the SQLSTATE", err) + } + var found *pgconn.PgError + if !errors.Is(err, inbound.ErrEventRejected) || !errors.As(err, &found) { + t.Fatalf("sanitizeApplyError() lost the error identity: %v", err) + } + + // A handler that copied only the message into its own text. + copied := fmt.Errorf("apply effect failed with %s: %w", pgError.Message, errors.New("cause")) + copied = fmt.Errorf("%w (%w)", copied, pgError) + if err := sanitizeApplyError(copied); strings.Contains(err.Error(), "secret-value") { + t.Fatalf("sanitizeApplyError() kept a copied message: %v", err) + } + + plain := errors.New("plain handler failure") + if err := sanitizeApplyError(plain); err != plain { //nolint:errorlint // The same value proves the pass-through. + t.Fatalf("sanitizeApplyError() changed an error without PostgreSQL text: %v", err) + } +} diff --git a/backend/internal/adapter/secondary/postgres/outbox_relay.go b/backend/internal/adapter/secondary/postgres/outbox_relay.go index fed9e85..6ed81dc 100644 --- a/backend/internal/adapter/secondary/postgres/outbox_relay.go +++ b/backend/internal/adapter/secondary/postgres/outbox_relay.go @@ -81,7 +81,7 @@ func (store *OutboxRelayStore) ClaimPending(ctx context.Context, limit int, publ return claimErr } if err := tx.Commit(ctx); err != nil { - return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", relayDatabaseError(err)) + return fmt.Errorf("OutboxRelayStore.ClaimPending - commit transaction: %w", sanitizedDatabaseError(err)) } return nil } @@ -93,11 +93,11 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe IdleTimeoutMs: milliseconds(timeouts.IdleInTransaction), }) if err != nil { - return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", relayDatabaseError(err)) + return fmt.Errorf("postgres.claimPending - set transaction timeouts: %w", sanitizedDatabaseError(err)) } rows, err := queries.LockPendingOutboxEvents(ctx, limit) if err != nil { - return fmt.Errorf("postgres.claimPending - lock pending events: %w", relayDatabaseError(err)) + return fmt.Errorf("postgres.claimPending - lock pending events: %w", sanitizedDatabaseError(err)) } if len(rows) == 0 { return nil @@ -130,7 +130,7 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe } count, err := queries.MarkOutboxEventsPublished(ctx, marked) if err != nil { - return fmt.Errorf("postgres.claimPending - mark published events: %w", relayDatabaseError(err)) + return fmt.Errorf("postgres.claimPending - mark published events: %w", sanitizedDatabaseError(err)) } if count != int64(len(marked)) { return fmt.Errorf("postgres.claimPending - marked %d events, want %d", count, len(marked)) @@ -142,7 +142,7 @@ func claimPending(ctx context.Context, tx pgx.Tx, limit int32, timeouts OutboxRe 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{}, fmt.Errorf("OutboxRelayStore.Backlog - read backlog: %w", sanitizedDatabaseError(err)) } return outbound.OutboxBacklog{ Pending: row.PendingEvents, @@ -169,10 +169,11 @@ func outboxEventFromRow(row sqlc.LockPendingOutboxEventsRow) outbound.OutboxEven } } -// 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 { +// sanitizedDatabaseError keeps only the SQLSTATE and constraint of a +// PostgreSQL error, whose message or detail could quote an event payload, and +// drops the connection prefix of a connect error. The relay and the event +// consumers use it. +func sanitizedDatabaseError(err error) error { var pgError *pgconn.PgError if errors.As(err, &pgError) { return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) diff --git a/backend/internal/adapter/secondary/postgres/outbox_relay_test.go b/backend/internal/adapter/secondary/postgres/outbox_relay_test.go index b65bf93..ab99264 100644 --- a/backend/internal/adapter/secondary/postgres/outbox_relay_test.go +++ b/backend/internal/adapter/secondary/postgres/outbox_relay_test.go @@ -43,15 +43,15 @@ func TestRelayDatabaseErrorKeepsOnlyTheSQLState(t *testing.T) { Message: `invalid input syntax for type json: "secret-payload"`, Detail: `Token "secret-payload" is invalid.`, } - err := relayDatabaseError(original) + err := sanitizedDatabaseError(original) if strings.Contains(err.Error(), "secret-payload") { - t.Fatalf("relayDatabaseError() kept the message: %v", err) + t.Fatalf("sanitizedDatabaseError() kept the message: %v", err) } var stateError sqlStateError if !errors.As(err, &stateError) || stateError.SQLState() != "22P02" { - t.Fatalf("relayDatabaseError() = %v, want SQLSTATE 22P02", err) + t.Fatalf("sanitizedDatabaseError() = %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) + if conflict := sanitizedDatabaseError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(conflict, outbound.ErrTransactionConflict) { + t.Fatalf("sanitizedDatabaseError(deadlock) = %v, want ErrTransactionConflict", conflict) } } diff --git a/backend/internal/adapter/secondary/postgres/sqlc/event_consumer.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/event_consumer.sql.go new file mode 100644 index 0000000..f0e28ba --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/event_consumer.sql.go @@ -0,0 +1,133 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: event_consumer.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const insertConsumerDeadLetter = `-- name: InsertConsumerDeadLetter :exec +INSERT INTO consumer_dead_letters ( + consumer_name, + topic, + kafka_partition, + kafka_offset, + event_id, + event_type, + error_class, + reason, + attempts, + value_size, + value_sha256 +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10, + $11 +) +ON CONFLICT ( + consumer_name, topic, kafka_partition, kafka_offset, value_sha256 +) DO UPDATE SET + event_id = excluded.event_id, + event_type = excluded.event_type, + error_class = excluded.error_class, + reason = excluded.reason, + attempts = excluded.attempts, + dead_lettered_at = clock_timestamp() +` + +type InsertConsumerDeadLetterParams struct { + ConsumerName string + Topic string + KafkaPartition int32 + KafkaOffset int64 + EventID pgtype.UUID + EventType pgtype.Text + ErrorClass string + Reason string + Attempts int32 + ValueSize int32 + ValueSha256 []byte +} + +// Stores a record that a consumer could not apply. A second delivery of the +// same record (same position and value) refreshes the outcome of its row: +// after a rewind the handler may fail differently. A different value at a +// reused position, after the topic was recreated, gets its own row. +func (q *Queries) InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error { + _, err := q.db.Exec(ctx, insertConsumerDeadLetter, + arg.ConsumerName, + arg.Topic, + arg.KafkaPartition, + arg.KafkaOffset, + arg.EventID, + arg.EventType, + arg.ErrorClass, + arg.Reason, + arg.Attempts, + arg.ValueSize, + arg.ValueSha256, + ) + return err +} + +const insertProcessedEventMarker = `-- name: InsertProcessedEventMarker :execrows +INSERT INTO consumer_processed_events (consumer_name, event_id) +VALUES ($1, $2) +ON CONFLICT (consumer_name, event_id) DO NOTHING +` + +type InsertProcessedEventMarkerParams struct { + ConsumerName string + EventID pgtype.UUID +} + +// Records that a consumer applies an event, in the transaction of the effect. +// It returns 0 rows when the marker exists. While another transaction holds +// an uncommitted marker for the same key, the insert waits for it: after a +// commit it returns 0, after a rollback it inserts. So a concurrent duplicate +// never runs the effect at the same time as the first delivery. +func (q *Queries) InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error) { + result, err := q.db.Exec(ctx, insertProcessedEventMarker, arg.ConsumerName, arg.EventID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const setConsumerTransactionTimeouts = `-- name: SetConsumerTransactionTimeouts :exec +SELECT + set_config('statement_timeout', $1::text, true), + set_config( + 'idle_in_transaction_session_timeout', + $2::text, + true + ) +` + +type SetConsumerTransactionTimeoutsParams struct { + StatementTimeoutMs string + IdleTimeoutMs string +} + +// Bounds a consumer transaction on the server, local to the transaction. +// statement_timeout stops a slow statement; idle_in_transaction_session_timeout +// ends the session of a process that froze or lost the network inside the +// handler, which releases the processed-event marker that a concurrent +// duplicate waits for. +func (q *Queries) SetConsumerTransactionTimeouts(ctx context.Context, arg SetConsumerTransactionTimeoutsParams) error { + _, err := q.db.Exec(ctx, setConsumerTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 5b96401..7ef3966 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -8,6 +8,28 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +type ConsumerDeadLetter struct { + ID int64 + ConsumerName string + Topic string + KafkaPartition int32 + KafkaOffset int64 + EventID pgtype.UUID + EventType pgtype.Text + ErrorClass string + Reason string + Attempts int32 + ValueSize int32 + ValueSha256 []byte + DeadLetteredAt pgtype.Timestamptz +} + +type ConsumerProcessedEvent struct { + ConsumerName string + EventID pgtype.UUID + ProcessedAt pgtype.Timestamptz +} + type EmailToken struct { ID pgtype.UUID UserID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 47222ff..660bbc7 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -49,6 +49,11 @@ type Querier interface { 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) + // Stores a record that a consumer could not apply. A second delivery of the + // same record (same position and value) refreshes the outcome of its row: + // after a rewind the handler may fail differently. A different value at a + // reused position, after the topic was recreated, gets its own row. + InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error // Stores a version and returns the stored row with the publication time and @@ -57,6 +62,12 @@ type Querier interface { // surrounding transaction. created_at is never taken from the caller, and a // NULL effective_at means "at publication". InsertPolicyVersion(ctx context.Context, arg InsertPolicyVersionParams) (PolicyVersion, error) + // Records that a consumer applies an event, in the transaction of the effect. + // It returns 0 rows when the marker exists. While another transaction holds + // an uncommitted marker for the same key, the insert waits for it: after a + // commit it returns 0, after a rollback it inserts. So a concurrent duplicate + // never runs the effect at the same time as the first delivery. + InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error) InsertSession(ctx context.Context, arg InsertSessionParams) error InsertUser(ctx context.Context, arg InsertUserParams) error InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) @@ -82,6 +93,12 @@ 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 a consumer transaction on the server, local to the transaction. + // statement_timeout stops a slow statement; idle_in_transaction_session_timeout + // ends the session of a process that froze or lost the network inside the + // handler, which releases the processed-event marker that a concurrent + // duplicate waits for. + SetConsumerTransactionTimeouts(ctx context.Context, arg SetConsumerTransactionTimeoutsParams) 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 diff --git a/backend/internal/adapter/secondary/prometheus/metrics.go b/backend/internal/adapter/secondary/prometheus/metrics.go index d9fcc1b..410f510 100644 --- a/backend/internal/adapter/secondary/prometheus/metrics.go +++ b/backend/internal/adapter/secondary/prometheus/metrics.go @@ -25,6 +25,12 @@ type Metrics struct { // so dashboards aggregate them with max, not sum. relayPending client.Gauge relayOldestAge client.Gauge + // consumerRecords counts consumed records by consumer and final + // outcome; every record ends with exactly one outcome. + consumerRecords *client.CounterVec + // consumerFailures counts every failed consumer operation, including the + // last handler attempt before a dead letter, by the stage that failed. + consumerFailures *client.CounterVec } // Outbox relay outcome label values. @@ -33,6 +39,13 @@ const ( relayOutcomeFailed = "failed" ) +// Event consumer label values. They mirror the eventconsumer constants, which +// this adapter does not import; PrepareEventConsumer creates these series. +var ( + consumerOutcomes = []string{"applied", "duplicate", "ignored", "dead_lettered"} + consumerStages = []string{"handler", "store", "poll", "commit"} +) + func New() *Metrics { registry := client.NewRegistry() requests := client.NewCounterVec(client.CounterOpts{ @@ -56,10 +69,19 @@ func New() *Metrics { 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.", }) + consumerRecords := client.NewCounterVec(client.CounterOpts{ + Name: "lincodex_event_consumer_records_total", + Help: "Event bus records finished by a consumer, by outcome: applied, duplicate, ignored, or dead_lettered.", + }, []string{"consumer", "outcome"}) + consumerFailures := client.NewCounterVec(client.CounterOpts{ + Name: "lincodex_event_consumer_failures_total", + Help: "Failed event consumer operations, including the last handler attempt before a dead letter, by stage: handler, store, poll, or commit.", + }, []string{"consumer", "stage"}) registry.MustRegister( collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), requests, latency, relayEvents, relayPending, relayOldestAge, + consumerRecords, consumerFailures, ) // Expose both series from the start so rate queries see zero, not absence. relayEvents.WithLabelValues(relayOutcomePublished) @@ -71,9 +93,34 @@ func New() *Metrics { relayEvents: relayEvents, relayPending: relayPending, relayOldestAge: relayOldestAge, + + consumerRecords: consumerRecords, + consumerFailures: consumerFailures, } } +// PrepareEventConsumer exposes every series of consumer at zero, so an alert +// on the first dead letter sees an increase instead of a new series. +func (metrics *Metrics) PrepareEventConsumer(consumer string) { + for _, outcome := range consumerOutcomes { + metrics.consumerRecords.WithLabelValues(consumer, outcome) + } + for _, stage := range consumerStages { + metrics.consumerFailures.WithLabelValues(consumer, stage) + } +} + +// ObserveConsumedRecord counts one finished record. +func (metrics *Metrics) ObserveConsumedRecord(consumer, outcome string) { + metrics.consumerRecords.WithLabelValues(consumer, outcome).Inc() +} + +// ObserveConsumerFailure counts one failed handler attempt, store +// operation, poll, or offset commit. +func (metrics *Metrics) ObserveConsumerFailure(consumer, stage string) { + metrics.consumerFailures.WithLabelValues(consumer, stage).Inc() +} + // ObserveOutboxBacklog records the latest backlog read. func (metrics *Metrics) ObserveOutboxBacklog(backlog outbound.OutboxBacklog) { metrics.relayPending.Set(float64(backlog.Pending)) diff --git a/backend/internal/adapter/secondary/prometheus/metrics_test.go b/backend/internal/adapter/secondary/prometheus/metrics_test.go index 240899c..2bc7946 100644 --- a/backend/internal/adapter/secondary/prometheus/metrics_test.go +++ b/backend/internal/adapter/secondary/prometheus/metrics_test.go @@ -58,3 +58,31 @@ func TestMetricsHandlerExposesTheOutboxBacklog(t *testing.T) { } } } + +func TestMetricsHandlerExposesEventConsumerOutcomes(t *testing.T) { + metrics := New() + metrics.PrepareEventConsumer("audit_log") + metrics.ObserveConsumedRecord("audit_log", "applied") + metrics.ObserveConsumedRecord("audit_log", "applied") + metrics.ObserveConsumedRecord("audit_log", "dead_lettered") + metrics.ObserveConsumerFailure("audit_log", "handler") + + response := httptest.NewRecorder() + metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil)) + body := response.Body.String() + for _, want := range []string{ + `lincodex_event_consumer_records_total{consumer="audit_log",outcome="applied"} 2`, + `lincodex_event_consumer_records_total{consumer="audit_log",outcome="dead_lettered"} 1`, + // Prepared series are exposed at zero before the first observation. + `lincodex_event_consumer_records_total{consumer="audit_log",outcome="duplicate"} 0`, + `lincodex_event_consumer_records_total{consumer="audit_log",outcome="ignored"} 0`, + `lincodex_event_consumer_failures_total{consumer="audit_log",stage="handler"} 1`, + `lincodex_event_consumer_failures_total{consumer="audit_log",stage="store"} 0`, + `lincodex_event_consumer_failures_total{consumer="audit_log",stage="poll"} 0`, + `lincodex_event_consumer_failures_total{consumer="audit_log",stage="commit"} 0`, + } { + 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 bdfe7c6..3a1a911 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -9,6 +9,7 @@ import ( "net/http" "os" "os/signal" + "sync" "syscall" "time" @@ -36,6 +37,9 @@ type Application struct { // relay publishes outbox events while the servers run. It is nil when // the relay is disabled or the database is not configured. relay *outboxrelay.Relay + // consumers apply events from the event bus while the servers run. The + // list is empty until a handler is registered in eventHandlers. + consumers eventConsumers } func NewApplication( @@ -45,6 +49,7 @@ func NewApplication( logger *slog.Logger, mailSender outbound.MailSender, relay *outboxrelay.Relay, + consumers eventConsumers, ) *Application { return &Application{ config: config, @@ -53,6 +58,7 @@ func NewApplication( logger: logger, mailSender: mailSender, relay: relay, + consumers: consumers, } } @@ -149,11 +155,11 @@ func (application *Application) run(ctx context.Context) error { slog.String("metrics_addr", application.config.MetricsAddr), ) - // The relay stops when the servers stop, including after a server + // The workers stop when the servers stop, including after a server // failure that leaves ctx running. runCtx, stopRun := context.WithCancel(ctx) defer stopRun() - relayStopped := application.startRelay(runCtx) + workersStopped := application.startWorkers(runCtx) apiServer := newHTTPServer(application.apiHandler) metricsServer := newHTTPServer(application.metrics.Handler()) @@ -167,23 +173,30 @@ func (application *Application) run(ctx context.Context) error { ) application.logger.Info("servers stopped") stopRun() - // The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, so - // the cleanup that closes its pool and producer runs after it. - <-relayStopped + // The relay finishes its pass in progress within SHUTDOWN_TIMEOUT and + // each consumer its record in progress within CONSUMER_SHUTDOWN_GRACE + // plus one offset commit, so the cleanup that closes their pools, + // producer, and group members runs after all of them stopped. + <-workersStopped + application.logger.Info("workers stopped") return err } -// startRelay runs the relay until ctx ends and returns a channel that closes -// when it has stopped. -func (application *Application) startRelay(ctx context.Context) <-chan struct{} { - stopped := make(chan struct{}) - if application.relay == nil { - close(stopped) - return stopped +// startWorkers runs the relay and every consumer until ctx ends and returns +// a channel that closes when all of them have stopped. The workers stop +// together with the servers; none of them depends on another. +func (application *Application) startWorkers(ctx context.Context) <-chan struct{} { + var workers sync.WaitGroup + if application.relay != nil { + workers.Go(func() { application.relay.Run(ctx) }) } + for _, consumer := range application.consumers { + workers.Go(func() { consumer.Run(ctx) }) + } + stopped := make(chan struct{}) go func() { defer close(stopped) - application.relay.Run(ctx) + workers.Wait() }() return stopped } diff --git a/backend/internal/bootstrap/consumers.go b/backend/internal/bootstrap/consumers.go new file mode 100644 index 0000000..1bce698 --- /dev/null +++ b/backend/internal/bootstrap/consumers.go @@ -0,0 +1,133 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "math" + "sync" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/kafka" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/worker/eventconsumer" + "lincodex/backend/internal/worker/retry" +) + +// consumerGroupSeparator joins CONSUMER_GROUP_PREFIX and a consumer name. +const consumerGroupSeparator = "." + +// eventConsumers are the consumers that run next to the HTTP servers. +type eventConsumers []*eventconsumer.Consumer + +var _ eventconsumer.Metrics = (*prometheus.Metrics)(nil) + +// eventHandlers lists the handlers that get a consumer. It is empty because +// no product module consumes domain events yet; a module adds its handler +// here, and its consumer then starts with the next deployment. +func eventHandlers() []inbound.EventHandler { + return nil +} + +func newEventConsumers( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + metrics *prometheus.Metrics, +) (eventConsumers, func(), error) { + return buildEventConsumers(ctx, settings, logger, metrics, eventHandlers()) +} + +// buildEventConsumers builds one consumer per handler and the resources they +// own: one PostgreSQL pool shared by all of them and one Kafka group member +// each. Nothing connects here, so an unavailable Kafka or database never +// blocks startup; the consumers retry in the background. It returns no +// consumer when CONSUMER_ENABLED is false, when no handler is registered, or +// when DATABASE_URL is unset. +func buildEventConsumers( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + metrics eventconsumer.Metrics, + handlers []inbound.EventHandler, +) (eventConsumers, func(), error) { + switch { + case !settings.ConsumerEnabled: + logger.Info("event consumers are disabled") + return nil, func() {}, nil + case len(handlers) == 0: + logger.Info("no event consumer is registered") + return nil, func() {}, nil + case settings.DatabaseURL == "": + logger.Warn("event consumers skipped because DATABASE_URL is not set") + return nil, func() {}, nil + } + // A consumer processes one record at a time and writes a dead letter + // only after its transaction ended, so it needs one connection. + poolSize := len(handlers) + if poolSize > math.MaxInt32 { + return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - %d handlers exceed the pool size limit", poolSize) + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, int32(poolSize)) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create pool: %w", err) + } + store := postgres.NewEventConsumerStore(pool, settings.ConsumerHandlerTimeout) + consumers := make(eventConsumers, 0, len(handlers)) + closers := make([]func(), 0, len(handlers)) + cleanup := func() { + // The application stops every consumer before this runs, so no + // record is in progress while the members leave their groups. They + // leave in parallel, so shutdown waits for the slowest leave rather + // than for the sum of them. + var leaving sync.WaitGroup + for _, closeSource := range closers { + leaving.Go(closeSource) + } + leaving.Wait() + pool.Close() + } + names := make(map[string]bool, len(handlers)) + for _, handler := range handlers { + name := handler.ConsumerName() + if names[name] { + cleanup() + return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - consumer %s is registered twice", name) + } + names[name] = true + group := settings.ConsumerGroupPrefix + consumerGroupSeparator + name + consumerLogger := logger.With( + slog.String("component", "event_consumer"), + slog.String("topic", settings.KafkaEventsTopic), + slog.String("group", group), + ) + source, closeSource, err := kafka.NewEventSource(settings, group, consumerLogger) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create Kafka group member for %s: %w", name, err) + } + closers = append(closers, closeSource) + consumer, err := eventconsumer.New(handler, source, store, metrics, consumerLogger, consumerSettings(settings)) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("bootstrap.buildEventConsumers - create consumer: %w", err) + } + consumers = append(consumers, consumer) + } + return consumers, cleanup, nil +} + +func consumerSettings(settings config.Config) eventconsumer.Settings { + return eventconsumer.Settings{ + MaxAttempts: settings.ConsumerMaxAttempts, + Backoff: retry.Backoff{ + Initial: settings.ConsumerBackoffInitial, + Max: settings.ConsumerBackoffMax, + }, + HandlerTimeout: settings.ConsumerHandlerTimeout, + CommitTimeout: settings.ConsumerCommitTimeout, + ShutdownGrace: settings.ConsumerShutdownGrace, + } +} diff --git a/backend/internal/bootstrap/consumers_test.go b/backend/internal/bootstrap/consumers_test.go new file mode 100644 index 0000000..a2c64d3 --- /dev/null +++ b/backend/internal/bootstrap/consumers_test.go @@ -0,0 +1,206 @@ +package bootstrap + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/eventconsumer" +) + +type namedHandler string + +func (handler namedHandler) ConsumerName() string { return string(handler) } +func (namedHandler) Handles(string) bool { return true } +func (namedHandler) Handle(context.Context, outbound.UnitOfWork, outbound.ConsumedEvent) error { + return nil +} + +func consumerTestConfig(t *testing.T) config.Config { + t.Helper() + settings, err := config.LoadFromEnv(func(key string) (string, bool) { + value, ok := map[string]string{ + "SEAWEEDFS_ACCESS_KEY": "test-access", + "SEAWEEDFS_SECRET_KEY": "test-secret", + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "no-reply@example.com", + "APP_PUBLIC_URL": "http://localhost:8080", + "DATABASE_URL": "postgres://app@127.0.0.1:1/app", + }[key] + return value, ok + }) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + return settings +} + +func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + disabled := consumerTestConfig(t) + disabled.ConsumerEnabled = false + noDatabase := consumerTestConfig(t) + noDatabase.DatabaseURL = "" + tests := []struct { + name string + settings config.Config + handlers []inbound.EventHandler + }{ + {name: "disabled", settings: disabled, handlers: []inbound.EventHandler{namedHandler("audit")}}, + {name: "no handler registered", settings: consumerTestConfig(t)}, + {name: "database not configured", settings: noDatabase, handlers: []inbound.EventHandler{namedHandler("audit")}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + consumers, cleanup, err := buildEventConsumers(t.Context(), test.settings, logger, prometheus.New(), test.handlers) + if err != nil { + t.Fatalf("buildEventConsumers() error = %v", err) + } + cleanup() + if len(consumers) != 0 { + t.Fatalf("buildEventConsumers() built %d consumers without work to do", len(consumers)) + } + }) + } +} + +func TestBootstrapRegistersNoEventHandlerYet(t *testing.T) { + if handlers := eventHandlers(); len(handlers) != 0 { + t.Fatalf("eventHandlers() = %d handlers; update the documentation when the first consumer is registered", len(handlers)) + } +} + +func TestBuildEventConsumersBuildsOneConsumerPerHandler(t *testing.T) { + settings := consumerTestConfig(t) + consumers, cleanup, err := buildEventConsumers(t.Context(), settings, slog.New(slog.DiscardHandler), prometheus.New(), + []inbound.EventHandler{namedHandler("audit"), namedHandler("search_index")}) + if err != nil { + t.Fatalf("buildEventConsumers() error = %v", err) + } + // Nothing connected, so closing the group members returns at once. + closed := make(chan struct{}) + go func() { + defer close(closed) + cleanup() + }() + select { + case <-closed: + case <-time.After(relayLifecycleTimeout): + t.Fatal("cleanup did not return") + } + if len(consumers) != 2 || consumers[0].Name() != "audit" || consumers[1].Name() != "search_index" { + t.Fatalf("buildEventConsumers() = %v, want audit and search_index", consumers) + } +} + +func TestBuildEventConsumersRejectsInvalidRegistrations(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + tests := map[string][]inbound.EventHandler{ + "duplicate name": {namedHandler("audit"), namedHandler("audit")}, + "invalid name": {namedHandler("Audit-Log")}, + } + for name, handlers := range tests { + t.Run(name, func(t *testing.T) { + _, _, err := buildEventConsumers(t.Context(), consumerTestConfig(t), logger, prometheus.New(), handlers) + if err == nil { + t.Fatal("buildEventConsumers() accepted an invalid registration") + } + }) + } +} + +func TestEventConsumerLabelsMatchThePreparedMetrics(t *testing.T) { + metrics := prometheus.New() + metrics.PrepareEventConsumer("audit") + response := httptest.NewRecorder() + metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + body := response.Body.String() + for _, outcome := range []string{eventconsumer.OutcomeApplied, eventconsumer.OutcomeDuplicate, eventconsumer.OutcomeIgnored, eventconsumer.OutcomeDeadLettered} { + if want := `lincodex_event_consumer_records_total{consumer="audit",outcome="` + outcome + `"} 0`; !strings.Contains(body, want) { + t.Fatalf("metrics output is missing %s", want) + } + } + for _, stage := range []string{eventconsumer.StageHandler, eventconsumer.StageStore, eventconsumer.StagePoll, eventconsumer.StageCommit} { + if want := `lincodex_event_consumer_failures_total{consumer="audit",stage="` + stage + `"} 0`; !strings.Contains(body, want) { + t.Fatalf("metrics output is missing %s", want) + } + } +} + +// blockingSource returns nothing and counts polls until ctx ends. +type blockingSource struct { + polls atomic.Int64 + running atomic.Bool +} + +func (source *blockingSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) { + source.polls.Add(1) + source.running.Store(true) + <-ctx.Done() + source.running.Store(false) + return nil, ctx.Err() +} + +func (*blockingSource) Commit(context.Context, []outbound.ConsumedRecord) error { return nil } +func (*blockingSource) Release() {} + +type unusedStore struct{} + +func (unusedStore) ApplyOnce(context.Context, string, uuid.UUID, outbound.ApplyEvent) (bool, error) { + return false, nil +} +func (unusedStore) RecordDeadLetter(context.Context, outbound.DeadLetter) error { return nil } + +func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) { + metrics := prometheus.New() + logger := slog.New(slog.DiscardHandler) + source := &blockingSource{} + settings := consumerSettings(consumerTestConfig(t)) + consumer, err := eventconsumer.New(namedHandler("audit"), source, unusedStore{}, metrics, logger, settings) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + application := NewApplication(config.Config{ + HTTPAddr: "127.0.0.1:0", + MetricsAddr: "127.0.0.1:0", + ShutdownTimeout: time.Second, + }, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + finished := make(chan error, 1) + go func() { finished <- application.run(ctx) }() + + deadline := time.Now().Add(relayLifecycleTimeout) + for source.polls.Load() < 1 { + if time.Now().After(deadline) { + t.Fatal("the consumer did not poll while the servers ran") + } + time.Sleep(time.Millisecond) + } + cancel() + select { + case err := <-finished: + if err != nil { + t.Fatalf("run() error = %v", err) + } + case <-time.After(relayLifecycleTimeout): + t.Fatal("run() did not return after cancellation") + } + // run returns only after the consumer stopped polling, so the cleanup + // that closes its group member never races a poll. + if source.running.Load() { + t.Fatal("the consumer was still polling after run() returned") + } +} diff --git a/backend/internal/bootstrap/relay.go b/backend/internal/bootstrap/relay.go index a5326e0..3044ee6 100644 --- a/backend/internal/bootstrap/relay.go +++ b/backend/internal/bootstrap/relay.go @@ -11,6 +11,7 @@ import ( "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/worker/outboxrelay" + "lincodex/backend/internal/worker/retry" ) const ( @@ -71,7 +72,7 @@ func relaySettings(settings config.Config) outboxrelay.Settings { return outboxrelay.Settings{ BatchSize: settings.RelayBatchSize, PollInterval: settings.RelayPollInterval, - Backoff: outboxrelay.Backoff{ + Backoff: retry.Backoff{ Initial: settings.RelayBackoffInitial, Max: settings.RelayBackoffMax, }, diff --git a/backend/internal/bootstrap/relay_test.go b/backend/internal/bootstrap/relay_test.go index d88fff9..66c9d79 100644 --- a/backend/internal/bootstrap/relay_test.go +++ b/backend/internal/bootstrap/relay_test.go @@ -12,6 +12,7 @@ import ( "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/worker/outboxrelay" + "lincodex/backend/internal/worker/retry" ) const relayLifecycleTimeout = 5 * time.Second @@ -67,7 +68,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) { relay := outboxrelay.New(store, readyPublisher{}, metrics, logger, outboxrelay.Settings{ BatchSize: 1, PollInterval: time.Millisecond, - Backoff: outboxrelay.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, + Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, ShutdownTimeout: time.Second, BacklogInterval: time.Second, }) @@ -75,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) { HTTPAddr: "127.0.0.1:0", MetricsAddr: "127.0.0.1:0", ShutdownTimeout: time.Second, - }, http.NotFoundHandler(), metrics, logger, nil, relay) + }, http.NotFoundHandler(), metrics, logger, nil, relay, nil) ctx, cancel := context.WithCancel(t.Context()) defer cancel() diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 9ffdd52..42f47a9 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -48,6 +48,7 @@ func initialize( v1.NewDenyAllSecurity, httpadapter.NewRouter, newOutboxRelay, + newEventConsumers, NewApplication, ), ) diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 8b385ff..36bd912 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -62,8 +62,17 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay) + bootstrapEventConsumers, cleanup5, err := newEventConsumers(ctx, config2, logger, metrics) + if err != nil { + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers) return application, func() { + cleanup5() cleanup4() cleanup3() cleanup2() diff --git a/backend/internal/domain/domain_event.go b/backend/internal/domain/domain_event.go index 0f8188a..f3f0c48 100644 --- a/backend/internal/domain/domain_event.go +++ b/backend/internal/domain/domain_event.go @@ -69,7 +69,7 @@ type DomainEventInput struct { // NewDomainEvent validates input and assigns a time-ordered UUIDv7 event ID. // The stored payload is the compact form of input.Payload. func NewDomainEvent(input DomainEventInput) (DomainEvent, error) { - if err := input.validateIdentity(); err != nil { + if err := input.ValidateIdentity(); err != nil { return DomainEvent{}, err } payload, err := compactPayload(input.Payload) @@ -91,7 +91,9 @@ func NewDomainEvent(input DomainEventInput) (DomainEvent, error) { }, nil } -func (input DomainEventInput) validateIdentity() error { +// ValidateIdentity checks every field except the payload. Event consumers +// use it to apply the same rules to an event read from the event bus. +func (input DomainEventInput) ValidateIdentity() error { if len(input.EventType) > maxDomainEventTypeLength || !domainEventTypePattern.MatchString(input.EventType) { return invalidDomainEvent("event type must be a lowercase dotted name of at most 128 bytes") } diff --git a/backend/internal/port/inbound/event_handler.go b/backend/internal/port/inbound/event_handler.go new file mode 100644 index 0000000..ad1f2a9 --- /dev/null +++ b/backend/internal/port/inbound/event_handler.go @@ -0,0 +1,34 @@ +package inbound + +import ( + "context" + "errors" + + "lincodex/backend/internal/port/outbound" +) + +// ErrEventRejected marks a handler failure that a retry cannot fix, for +// example an unsupported schema_version or a payload that breaks the +// contract of its event type. The consumer dead-letters the event at once +// instead of retrying it. +var ErrEventRejected = errors.New("event rejected by handler") + +// EventHandler applies domain events from the event bus to this service's +// own state. The consumer runtime calls Handle inside the transaction that +// records the event as processed, so the effect and the dedup marker commit +// together and a repeated delivery is skipped. +type EventHandler interface { + // ConsumerName is a stable snake_case name of at most 64 characters. It + // scopes deduplication and names the consumer group, so renaming it + // makes the consumer process every retained event again. + ConsumerName() string + // Handles reports whether the handler applies events of eventType. + // Other events are acknowledged without a transaction. + Handles(eventType string) bool + // Handle applies event with unit and the context it receives only. An + // error rolls back the effect and the marker. An error matching + // ErrEventRejected is final; any other error is retried with backoff a + // bounded number of times. Errors must not quote the payload or personal + // data, because the reason is logged and stored with the dead letter. + Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error +} diff --git a/backend/internal/port/outbound/event_consumer.go b/backend/internal/port/outbound/event_consumer.go new file mode 100644 index 0000000..f965e87 --- /dev/null +++ b/backend/internal/port/outbound/event_consumer.go @@ -0,0 +1,137 @@ +package outbound + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/google/uuid" +) + +var ( + // ErrInvalidEventRecord reports a record on the event bus that is not a + // valid event envelope. Retrying cannot fix it. + ErrInvalidEventRecord = errors.New("invalid event record") + + // ErrEventEffectRejected reports that PostgreSQL refused to commit the + // effect of a handler that returned nil: the handler ignored a failed + // statement, so the transaction was aborted, or a deferred integrity + // constraint (SQLSTATE class 23) failed at commit. Nothing was committed. + // The consumer counts it as a failed handler attempt, because the same + // event usually fails the same way again. + ErrEventEffectRejected = errors.New("event effect rejected by the database") +) + +// ConsumedEvent is a domain event decoded from the event bus. It carries the +// fields that the relay published from the outbox row. +type ConsumedEvent struct { + EventID uuid.UUID + EventType string + SchemaVersion int32 + AggregateType string + AggregateID uuid.UUID + // AggregateVersion orders the events of one aggregate. Delivery is at + // least once, so a late duplicate of an earlier version can arrive after + // a later version; a handler that keeps aggregate state ignores versions + // it has already passed. + AggregateVersion int64 + // OccurredAt is the informational insert time of the outbox row. + OccurredAt time.Time + // Payload is the JSON object stored in the outbox row. + Payload json.RawMessage +} + +// ConsumedRecord is one record read from the event bus, in partition order. +type ConsumedRecord struct { + Topic string + Partition int32 + Offset int64 + // Event is the decoded envelope. It is valid only when Invalid is nil. + Event ConsumedEvent + // Invalid reports a value that is not a valid event envelope. It matches + // ErrInvalidEventRecord and never quotes the value. + Invalid error + // EventID is the event ID of a valid record, or for an invalid record the + // value of its event_id header; uuid.Nil when neither is a UUID. + EventID uuid.UUID + // Value is the raw record value. It may hold personal data later, so it + // must not reach logs, errors, or metrics. + Value []byte +} + +// EventSource reads the event bus as one member of a consumer group. +type EventSource interface { + // Poll waits for the next records, in partition order, and holds group + // rebalancing until Release. It may return records together with an + // error that reports fetch problems of other partitions. After ctx ends + // it returns ctx.Err(). + Poll(ctx context.Context) ([]ConsumedRecord, error) + // Commit stores, for each partition, the position after the last of the + // finished records, so the group resumes after them. finished must be in + // partition order and must not skip a record of the last poll. A failed + // commit leaves the records to be delivered again. + Commit(ctx context.Context, finished []ConsumedRecord) error + // Release lets the group rebalance after the polled records were + // finished or abandoned. Every Poll is followed by one Release. + Release() +} + +// ApplyEvent applies one event inside the transaction of its dedup marker. +type ApplyEvent func(ctx context.Context, unit UnitOfWork) error + +// DeadLetter describes a record that a consumer could not apply. +type DeadLetter struct { + Consumer string + Topic string + Partition int32 + Offset int64 + // EventID is uuid.Nil when the record had no event ID. + EventID uuid.UUID + // EventType is empty for an invalid record. + EventType string + ErrorClass DeadLetterClass + // Reason is a short sanitized cause without the record value. + Reason string + Attempts int + ValueSize int + ValueSHA256 [32]byte +} + +// DeadLetterClass is a bounded cause of a dead letter. +type DeadLetterClass string + +const ( + // DeadLetterInvalidRecord is a value that is not a valid event envelope. + DeadLetterInvalidRecord DeadLetterClass = "invalid_record" + // DeadLetterHandlerRejected is an event the handler can never apply. + DeadLetterHandlerRejected DeadLetterClass = "handler_rejected" + // DeadLetterHandlerPanic is an event whose handler panicked. + DeadLetterHandlerPanic DeadLetterClass = "handler_panic" + // DeadLetterRetriesExhausted is an event whose handler kept failing. + DeadLetterRetriesExhausted DeadLetterClass = "retries_exhausted" +) + +// EventConsumerStore keeps the dedup markers and dead letters of consumers. +type EventConsumerStore interface { + // ApplyOnce opens a transaction, records that consumer processes eventID, + // runs apply in the same transaction, and commits. When the marker + // already exists it rolls back without calling apply and reports + // applied=false. A concurrent call for the same consumer and eventID + // waits until the first transaction ends: after its commit it reports a + // duplicate, after its rollback it applies the event itself. + // + // An error from apply rolls the transaction back and is returned with its + // identity; its text keeps no PostgreSQL message, which could quote row + // values. A commit that PostgreSQL refuses returns an error matching + // ErrEventEffectRejected, and a serialization failure or deadlock + // (SQLSTATE class 40) one matching ErrTransactionConflict. A network + // failure during commit leaves the outcome unknown; a retry is then + // either applied or reported as a duplicate. + ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply ApplyEvent) (applied bool, err error) + // RecordDeadLetter stores letter. A letter for the same consumer, record + // position, and value replaces the outcome of the existing row; a + // different value at the same position, after the topic was recreated, + // gets its own row. + RecordDeadLetter(ctx context.Context, letter DeadLetter) error +} diff --git a/backend/internal/worker/eventconsumer/consumer.go b/backend/internal/worker/eventconsumer/consumer.go new file mode 100644 index 0000000..94f1432 --- /dev/null +++ b/backend/internal/worker/eventconsumer/consumer.go @@ -0,0 +1,481 @@ +// Package eventconsumer runs idempotent handlers of domain events from the +// event bus with at-least-once delivery. +package eventconsumer + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "log/slog" + "regexp" + "runtime/debug" + "strings" + "time" + "unicode" + + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/retry" +) + +// Record outcome label values. A record ends with exactly one of them. +const ( + // OutcomeApplied: the handler's effect and the marker committed. + OutcomeApplied = "applied" + // OutcomeDuplicate: the marker existed, so the effect was skipped. + OutcomeDuplicate = "duplicate" + // OutcomeIgnored: the handler does not handle the event type. + OutcomeIgnored = "ignored" + // OutcomeDeadLettered: the record was stored as a dead letter. + OutcomeDeadLettered = "dead_lettered" +) + +// Failure stage label values. Every failed operation is counted, including +// the last handler attempt before a dead letter. +const ( + // StageHandler: the handler returned an error, panicked, or timed out, + // or PostgreSQL refused to commit its effect. + StageHandler = "handler" + // StageStore: the transaction, the marker, the commit transport, or the + // dead letter write failed outside the handler. + StageStore = "store" + // StagePoll: a poll of the event bus failed. + StagePoll = "poll" + // StageCommit: an offset commit failed. + StageCommit = "commit" +) + +// maxReasonLength bounds the stored and logged failure reason. +const maxReasonLength = 256 + +// consumerNamePattern matches the database constraint on consumer names. +var consumerNamePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) + +// errHandlerPanic replaces the value of a handler panic, which could quote +// the event. +var errHandlerPanic = errors.New("handler panicked") + +// Metrics records consumer outcomes. Labels are the consumer name, which the +// code defines, and the constants of this package. +type Metrics interface { + // PrepareEventConsumer exposes the consumer's series at zero, so rate + // and increase queries see the first event. + PrepareEventConsumer(consumer string) + ObserveConsumedRecord(consumer, outcome string) + ObserveConsumerFailure(consumer, stage string) +} + +// Settings are the named consumer limits; config validates their ranges. +type Settings struct { + // MaxAttempts bounds the handler attempts for one event before it is + // dead-lettered. A commit that PostgreSQL refuses counts as an attempt; + // a database that cannot be reached does not. + MaxAttempts int + // Backoff is the wait after a failed attempt. + Backoff retry.Backoff + // HandlerTimeout bounds one attempt: the transaction with the marker, + // the handler, and the commit, or one dead letter write. + HandlerTimeout time.Duration + // CommitTimeout bounds one offset commit. + CommitTimeout time.Duration + // ShutdownGrace is how long an attempt in progress may continue after + // Run's context ends. When it expires the attempt is canceled, its + // transaction rolls back, and its offset is not committed. + ShutdownGrace time.Duration +} + +// Consumer delivers the records of one consumer group to one handler. +// Records are processed one at a time in poll order, which keeps the order +// within each partition. An offset is committed only after the record's +// transaction committed or its dead letter was stored, so a crash at any +// point delivers the record again and the marker turns the repeat into a +// duplicate. +type Consumer struct { + name string + handler inbound.EventHandler + source outbound.EventSource + store outbound.EventConsumerStore + metrics Metrics + logger *slog.Logger + settings Settings +} + +// New checks the handler's consumer name and the settings. The name scopes +// the dedup markers in the database, so an invalid one is a startup error. +func New( + handler inbound.EventHandler, + source outbound.EventSource, + store outbound.EventConsumerStore, + metrics Metrics, + logger *slog.Logger, + settings Settings, +) (*Consumer, error) { + name := handler.ConsumerName() + if !consumerNamePattern.MatchString(name) { + return nil, errors.New("eventconsumer.New - consumer name must be 1 to 64 lowercase letters, digits, or underscores starting with a letter") + } + if settings.MaxAttempts < 1 || settings.HandlerTimeout <= 0 || settings.CommitTimeout <= 0 || settings.ShutdownGrace <= 0 { + return nil, fmt.Errorf("eventconsumer.New - consumer %s needs positive attempts and timeouts", name) + } + metrics.PrepareEventConsumer(name) + return &Consumer{ + name: name, + handler: handler, + source: source, + store: store, + metrics: metrics, + logger: logger.With(slog.String("consumer", name)), + settings: settings, + }, nil +} + +// Name returns the consumer name. +func (consumer *Consumer) Name() string { + return consumer.name +} + +// Run polls and processes records until ctx ends. Failures are logged and +// retried, so Run returns only after ctx ends and the record in progress +// finished or ShutdownGrace canceled it. Records that were polled but not +// finished are not committed; the group delivers them again. +func (consumer *Consumer) Run(ctx context.Context) { + workCtx, stopWork := consumer.workContext(ctx) + defer stopWork() + consumer.logger.Info("event consumer started") + defer consumer.logger.Info("event consumer stopped") + + pollFailures := 0 + for ctx.Err() == nil { + records, err := consumer.source.Poll(ctx) + if ctx.Err() != nil { + // Records polled while stopping are not started. + consumer.source.Release() + return + } + if err != nil { + consumer.metrics.ObserveConsumerFailure(consumer.name, StagePoll) + } + finished := consumer.processBatch(ctx, workCtx, records) + consumer.commit(ctx, finished) + consumer.source.Release() + if err == nil || len(records) > 0 { + pollFailures = 0 + if err != nil { + consumer.logger.Warn("event consumer poll reported errors", slog.Any("error", err)) + } + continue + } + pollFailures++ + delay := consumer.settings.Backoff.Delay(pollFailures) + consumer.logger.Warn("event consumer poll failed", + slog.Int("consecutive_failures", pollFailures), + slog.Duration("retry_in", delay), + slog.Any("error", err), + ) + if !retry.Wait(ctx, delay) { + return + } + } +} + +// processBatch processes records in order and returns the finished prefix. +// It stops at the first record that shutdown abandoned. After a record that +// needed a retry or a dead letter it commits the prefix at once: a slow +// batch is the one most likely to outlast the rebalance timeout, and the +// member that takes over then does not repeat finished work. +func (consumer *Consumer) processBatch(ctx, workCtx context.Context, records []outbound.ConsumedRecord) []outbound.ConsumedRecord { + for index, record := range records { + if ctx.Err() != nil { + return records[:index] + } + finished, slow := consumer.process(ctx, workCtx, record) + if !finished { + return records[:index] + } + if slow && index < len(records)-1 { + consumer.commit(ctx, records[:index+1]) + } + } + return records +} + +func (consumer *Consumer) commit(ctx context.Context, finished []outbound.ConsumedRecord) { + if len(finished) == 0 { + return + } + // The commit runs after shutdown began too: finished work must be + // stored so the next member does not repeat it. + commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), consumer.settings.CommitTimeout) + defer cancel() + if err := consumer.source.Commit(commitCtx, finished); err != nil { + consumer.metrics.ObserveConsumerFailure(consumer.name, StageCommit) + consumer.logger.Warn("event consumer could not commit offsets; the records will be delivered again and deduplicated", + slog.Int("records", len(finished)), + slog.Any("error", err), + ) + } +} + +// process handles one record. finished reports that it was applied, a +// duplicate, ignored, or dead-lettered; it is false only when ctx ended +// first. slow reports that the record needed a retry or a dead letter. +func (consumer *Consumer) process(ctx, workCtx context.Context, record outbound.ConsumedRecord) (finished, slow bool) { + if record.Invalid != nil { + return consumer.deadLetter(ctx, workCtx, record, outbound.DeadLetterInvalidRecord, record.Invalid, 0), true + } + handles, err := consumer.handles(record.Event) + if err != nil { + consumer.metrics.ObserveConsumerFailure(consumer.name, StageHandler) + return consumer.deadLetter(ctx, workCtx, record, outbound.DeadLetterHandlerPanic, err, 0), true + } + if !handles { + consumer.metrics.ObserveConsumedRecord(consumer.name, OutcomeIgnored) + return true, false + } + return consumer.apply(ctx, workCtx, record) +} + +// apply runs attempts until the event is applied or a duplicate, its handler +// failures end in a dead letter, or ctx ends. +func (consumer *Consumer) apply(ctx, workCtx context.Context, record outbound.ConsumedRecord) (finished, slow bool) { + handlerFailures, storeFailures := 0, 0 + for { + applied, handlerErr, storeErr := consumer.attempt(workCtx, record.Event) + if handlerErr == nil && storeErr == nil { + outcome := OutcomeDuplicate + if applied { + outcome = OutcomeApplied + } + consumer.metrics.ObserveConsumedRecord(consumer.name, outcome) + consumer.logger.Debug("event consumed", recordAttributes(record, slog.String("outcome", outcome))...) + return true, handlerFailures+storeFailures > 0 + } + // A failure while stopping may be the shutdown itself, so it is + // neither retried nor dead-lettered; the record is delivered again. + if ctx.Err() != nil { + return false, true + } + var delay time.Duration + if handlerErr != nil { + consumer.metrics.ObserveConsumerFailure(consumer.name, StageHandler) + handlerFailures++ + if class, final := finalHandlerFailure(handlerErr, handlerFailures, consumer.settings.MaxAttempts); final { + return consumer.deadLetter(ctx, workCtx, record, class, handlerErr, handlerFailures), true + } + delay = consumer.settings.Backoff.Delay(handlerFailures) + consumer.logger.Warn("event handler failed; retrying", + recordAttributes(record, + slog.Int("attempt", handlerFailures), + slog.Int("max_attempts", consumer.settings.MaxAttempts), + slog.Duration("retry_in", delay), + slog.String("reason", sanitizeReason(handlerErr)), + )..., + ) + } else { + consumer.metrics.ObserveConsumerFailure(consumer.name, StageStore) + storeFailures++ + delay = consumer.settings.Backoff.Delay(storeFailures) + consumer.logger.Warn("event consumer could not use the database; retrying", + recordAttributes(record, + slog.Int("consecutive_failures", storeFailures), + slog.Duration("retry_in", delay), + slog.String("error", sanitizeReason(storeErr)), + )..., + ) + } + if !retry.Wait(ctx, delay) { + return false, true + } + } +} + +// finalHandlerFailure reports whether a handler failure ends the retries +// and with which dead letter class. +func finalHandlerFailure(err error, failures, maxAttempts int) (outbound.DeadLetterClass, bool) { + switch { + case errors.Is(err, errHandlerPanic): + return outbound.DeadLetterHandlerPanic, true + case errors.Is(err, inbound.ErrEventRejected): + return outbound.DeadLetterHandlerRejected, true + case failures >= maxAttempts: + return outbound.DeadLetterRetriesExhausted, true + default: + return "", false + } +} + +// attempt runs one transaction. handlerErr is a failure the event causes: +// the handler's own error, as the store returns it with PostgreSQL text +// removed, or a commit PostgreSQL refused or aborted as a serialization +// failure or deadlock. Those use up an attempt, so a handler that ignores a +// failed statement ends in a dead letter instead of retrying forever. +// storeErr is any other failure outside the handler, such as a lost +// connection; it does not use up attempts because the event is not at fault. +func (consumer *Consumer) attempt(workCtx context.Context, event outbound.ConsumedEvent) (applied bool, handlerErr, storeErr error) { + ctx, cancel := context.WithTimeout(workCtx, consumer.settings.HandlerTimeout) + defer cancel() + handlerFailed := false + applied, err := consumer.store.ApplyOnce(ctx, consumer.name, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + err := consumer.callHandler(ctx, unit, event) + handlerFailed = err != nil + return err + }) + switch { + case err == nil: + return applied, nil, nil + case handlerFailed, errors.Is(err, outbound.ErrEventEffectRejected), errors.Is(err, outbound.ErrTransactionConflict): + return false, err, nil + default: + return false, nil, err + } +} + +// handles asks the handler whether it applies eventType. A panic there is +// treated like a panic in Handle. +func (consumer *Consumer) handles(event outbound.ConsumedEvent) (handles bool, err error) { + defer func() { + if recovered := recover(); recovered != nil { + consumer.logPanic(event) + handles, err = false, errHandlerPanic + } + }() + return consumer.handler.Handles(event.EventType), nil +} + +// callHandler turns a panic into a final failure, so one event cannot crash +// the process again on every delivery. The stack is logged; the panic value +// is not, because it could quote the event. +func (consumer *Consumer) callHandler(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) (err error) { + defer func() { + if recovered := recover(); recovered != nil { + consumer.logPanic(event) + err = errHandlerPanic + } + }() + return consumer.handler.Handle(ctx, unit, event) +} + +func (consumer *Consumer) logPanic(event outbound.ConsumedEvent) { + consumer.logger.Error("event handler panicked", + slog.String("event_id", event.EventID.String()), + slog.String("event_type", event.EventType), + slog.String("stack", string(debug.Stack())), + ) +} + +// deadLetter stores the record as a dead letter, retrying the write with +// backoff until it succeeds, and reports false only when ctx ended first. +// The offset is committed only after the row exists, so a database outage +// never loses a record. +func (consumer *Consumer) deadLetter( + ctx, workCtx context.Context, + record outbound.ConsumedRecord, + class outbound.DeadLetterClass, + cause error, + attempts int, +) bool { + letter := outbound.DeadLetter{ + Consumer: consumer.name, + Topic: record.Topic, + Partition: record.Partition, + Offset: record.Offset, + EventID: record.EventID, + ErrorClass: class, + Reason: sanitizeReason(cause), + Attempts: attempts, + ValueSize: len(record.Value), + ValueSHA256: sha256.Sum256(record.Value), + } + if record.Invalid == nil { + letter.EventType = record.Event.EventType + } + for failures := 1; ; failures++ { + err := consumer.writeDeadLetter(workCtx, letter) + if err == nil { + consumer.metrics.ObserveConsumedRecord(consumer.name, OutcomeDeadLettered) + consumer.logger.Error("event dead-lettered; the offset is committed and the record needs an operator", + recordAttributes(record, + slog.String("error_class", string(class)), + slog.Int("attempts", attempts), + slog.String("reason", letter.Reason), + )..., + ) + return true + } + if ctx.Err() != nil { + return false + } + consumer.metrics.ObserveConsumerFailure(consumer.name, StageStore) + delay := consumer.settings.Backoff.Delay(failures) + consumer.logger.Warn("event consumer could not store a dead letter; the offset stays uncommitted", + recordAttributes(record, + slog.Int("consecutive_failures", failures), + slog.Duration("retry_in", delay), + slog.Any("error", err), + )..., + ) + if !retry.Wait(ctx, delay) { + return false + } + } +} + +func (consumer *Consumer) writeDeadLetter(workCtx context.Context, letter outbound.DeadLetter) error { + ctx, cancel := context.WithTimeout(workCtx, consumer.settings.HandlerTimeout) + defer cancel() + return consumer.store.RecordDeadLetter(ctx, letter) +} + +// workContext returns a context for attempts that outlives ctx by at most +// ShutdownGrace, so an attempt in progress at shutdown can commit. stop +// releases the watcher goroutine. +func (consumer *Consumer) workContext(ctx context.Context) (context.Context, func()) { + workCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) + stopWatching := context.AfterFunc(ctx, func() { + timer := time.NewTimer(consumer.settings.ShutdownGrace) + defer timer.Stop() + select { + case <-timer.C: + cancel() + case <-workCtx.Done(): + } + }) + return workCtx, func() { + stopWatching() + cancel() + } +} + +// recordAttributes identifies a record in logs without its value. +func recordAttributes(record outbound.ConsumedRecord, extra ...any) []any { + attributes := []any{ + slog.String("topic", record.Topic), + slog.Int("partition", int(record.Partition)), + slog.Int64("offset", record.Offset), + slog.String("event_id", record.EventID.String()), + } + if record.Invalid == nil { + attributes = append(attributes, slog.String("event_type", record.Event.EventType)) + } + return append(attributes, extra...) +} + +// sanitizeReason keeps a short single-line cause. Handler errors must not +// carry personal data already; this also bounds what a mistake can expose. +func sanitizeReason(err error) string { + reason := strings.Map(func(character rune) rune { + if unicode.IsControl(character) || !unicode.IsPrint(character) { + return ' ' + } + return character + }, err.Error()) + reason = strings.TrimSpace(reason) + if runes := []rune(reason); len(runes) > maxReasonLength { + reason = string(runes[:maxReasonLength]) + } + if reason == "" { + return "unspecified failure" + } + return reason +} diff --git a/backend/internal/worker/eventconsumer/consumer_test.go b/backend/internal/worker/eventconsumer/consumer_test.go new file mode 100644 index 0000000..0bc3c2e --- /dev/null +++ b/backend/internal/worker/eventconsumer/consumer_test.go @@ -0,0 +1,788 @@ +package eventconsumer + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/retry" +) + +const ( + testTimeout = 5 * time.Second + testInterval = time.Millisecond + testConsumer = "test_consumer" + testTopic = "events" + handledType = "test.changed" + unhandledType = "test.other" + // testGrace is short so shutdown tests finish quickly, and far above + // the time a finished attempt needs. + testGrace = 200 * time.Millisecond +) + +var ( + errTransient = errors.New("transient handler failure") + errDatabase = errors.New("database unavailable") +) + +// fakeSource returns its batches in order, one per poll, and then blocks +// until ctx ends. It records commits and checks that every poll is released. +type fakeSource struct { + mu sync.Mutex + batches [][]outbound.ConsumedRecord + commits [][]outbound.ConsumedRecord + polls int + releases int + pollErr error + commitErr error + drained chan struct{} +} + +func newFakeSource(batches ...[]outbound.ConsumedRecord) *fakeSource { + return &fakeSource{batches: batches, drained: make(chan struct{})} +} + +func (source *fakeSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) { + source.mu.Lock() + source.polls++ + if source.pollErr != nil { + err := source.pollErr + source.mu.Unlock() + return nil, err + } + if len(source.batches) > 0 { + batch := source.batches[0] + source.batches = source.batches[1:] + source.mu.Unlock() + return batch, nil + } + source.mu.Unlock() + select { + case <-source.drained: + default: + close(source.drained) + } + <-ctx.Done() + return nil, ctx.Err() +} + +func (source *fakeSource) Commit(_ context.Context, finished []outbound.ConsumedRecord) error { + source.mu.Lock() + defer source.mu.Unlock() + if source.commitErr != nil { + return source.commitErr + } + source.commits = append(source.commits, finished) + return nil +} + +func (source *fakeSource) Release() { + source.mu.Lock() + source.releases++ + source.mu.Unlock() +} + +// committedOffsets returns every committed offset once, in the order of its +// first commit. A commit always repeats the prefix of its batch. +func (source *fakeSource) committedOffsets() []int64 { + source.mu.Lock() + defer source.mu.Unlock() + var offsets []int64 + seen := make(map[int64]bool) + for _, commit := range source.commits { + for _, record := range commit { + if !seen[record.Offset] { + seen[record.Offset] = true + offsets = append(offsets, record.Offset) + } + } + } + return offsets +} + +func (source *fakeSource) commitCount() int { + source.mu.Lock() + defer source.mu.Unlock() + return len(source.commits) +} + +// fakeStore models the dedup transaction: apply runs only for a new marker, +// and the marker is kept only when apply succeeds and ctx is still live at +// commit time. +type fakeStore struct { + mu sync.Mutex + markers map[uuid.UUID]bool + deadLetters []outbound.DeadLetter + // applyFailures and letterFailures fail that many calls before the + // store reaches the handler or stores the letter. + applyFailures int + letterFailures int + applyCalls int + // commitErrors are returned, one per call, after apply returned nil, as + // a commit that PostgreSQL refused. + commitErrors []error +} + +func newFakeStore() *fakeStore { + return &fakeStore{markers: make(map[uuid.UUID]bool)} +} + +func (store *fakeStore) ApplyOnce(ctx context.Context, consumer string, eventID uuid.UUID, apply outbound.ApplyEvent) (bool, error) { + store.mu.Lock() + store.applyCalls++ + if consumer != testConsumer { + store.mu.Unlock() + return false, fmt.Errorf("unexpected consumer %q", consumer) + } + if store.applyFailures > 0 { + store.applyFailures-- + store.mu.Unlock() + return false, errDatabase + } + if store.markers[eventID] { + store.mu.Unlock() + return false, nil + } + store.mu.Unlock() + if err := apply(ctx, nil); err != nil { + return false, err + } + if err := ctx.Err(); err != nil { + return false, err + } + store.mu.Lock() + if len(store.commitErrors) > 0 { + err := store.commitErrors[0] + store.commitErrors = store.commitErrors[1:] + store.mu.Unlock() + return false, err + } + store.mu.Unlock() + store.mu.Lock() + store.markers[eventID] = true + store.mu.Unlock() + return true, nil +} + +func (store *fakeStore) RecordDeadLetter(ctx context.Context, letter outbound.DeadLetter) error { + store.mu.Lock() + defer store.mu.Unlock() + if store.letterFailures > 0 { + store.letterFailures-- + return errDatabase + } + if err := ctx.Err(); err != nil { + return err + } + store.deadLetters = append(store.deadLetters, letter) + return nil +} + +func (store *fakeStore) letters() []outbound.DeadLetter { + store.mu.Lock() + defer store.mu.Unlock() + return append([]outbound.DeadLetter(nil), store.deadLetters...) +} + +// fakeHandler applies handledType events through handle, which defaults to +// success, and records every call. +type fakeHandler struct { + mu sync.Mutex + calls []time.Time + events []uuid.UUID + handle func(ctx context.Context, event outbound.ConsumedEvent, call int) error +} + +func (*fakeHandler) ConsumerName() string { return testConsumer } + +func (*fakeHandler) Handles(eventType string) bool { return eventType == handledType } + +func (handler *fakeHandler) Handle(ctx context.Context, _ outbound.UnitOfWork, event outbound.ConsumedEvent) error { + handler.mu.Lock() + handler.calls = append(handler.calls, time.Now()) + handler.events = append(handler.events, event.EventID) + call := len(handler.calls) + handle := handler.handle + handler.mu.Unlock() + if handle == nil { + return nil + } + return handle(ctx, event, call) +} + +func (handler *fakeHandler) callTimes() []time.Time { + handler.mu.Lock() + defer handler.mu.Unlock() + return append([]time.Time(nil), handler.calls...) +} + +type fakeMetrics struct { + mu sync.Mutex + prepared []string + outcomes map[string]int + failures map[string]int +} + +func newFakeMetrics() *fakeMetrics { + return &fakeMetrics{outcomes: make(map[string]int), failures: make(map[string]int)} +} + +func (metrics *fakeMetrics) PrepareEventConsumer(consumer string) { + metrics.mu.Lock() + defer metrics.mu.Unlock() + metrics.prepared = append(metrics.prepared, consumer) +} + +func (metrics *fakeMetrics) ObserveConsumedRecord(_, outcome string) { + metrics.mu.Lock() + defer metrics.mu.Unlock() + metrics.outcomes[outcome]++ +} + +func (metrics *fakeMetrics) ObserveConsumerFailure(_, stage string) { + metrics.mu.Lock() + defer metrics.mu.Unlock() + metrics.failures[stage]++ +} + +func (metrics *fakeMetrics) outcome(name string) int { + metrics.mu.Lock() + defer metrics.mu.Unlock() + return metrics.outcomes[name] +} + +func (metrics *fakeMetrics) failure(stage string) int { + metrics.mu.Lock() + defer metrics.mu.Unlock() + return metrics.failures[stage] +} + +type harness struct { + source *fakeSource + store *fakeStore + handler *fakeHandler + metrics *fakeMetrics + consumer *Consumer +} + +func testSettings() Settings { + return Settings{ + MaxAttempts: 3, + Backoff: retry.Backoff{Initial: testInterval, Max: testInterval}, + HandlerTimeout: testTimeout, + CommitTimeout: testTimeout, + ShutdownGrace: testGrace, + } +} + +func newHarness(t *testing.T, settings Settings, batches ...[]outbound.ConsumedRecord) *harness { + t.Helper() + h := &harness{ + source: newFakeSource(batches...), + store: newFakeStore(), + handler: &fakeHandler{}, + metrics: newFakeMetrics(), + } + consumer, err := New(h.handler, h.source, h.store, h.metrics, slog.New(slog.DiscardHandler), settings) + if err != nil { + t.Fatalf("New() error = %v", err) + } + h.consumer = consumer + return h +} + +// run starts the consumer and returns a function that cancels it and waits +// until Run returned. +func (h *harness) run(t *testing.T) (stop func()) { + t.Helper() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { + defer close(done) + h.consumer.Run(ctx) + }() + stopped := false + stop = func() { + t.Helper() + if stopped { + return + } + stopped = true + cancel() + select { + case <-done: + case <-time.After(testTimeout): + t.Fatal("Run() did not return after cancellation") + } + } + t.Cleanup(stop) + return stop +} + +// runUntilDrained runs the consumer until the source has no batch left, then +// stops it. +func (h *harness) runUntilDrained(t *testing.T) { + t.Helper() + stop := h.run(t) + select { + case <-h.source.drained: + case <-time.After(testTimeout): + t.Fatal("the consumer did not poll every batch") + } + stop() +} + +func event(offset int64, eventType string) outbound.ConsumedRecord { + eventID := uuid.New() + return outbound.ConsumedRecord{ + Topic: testTopic, + Partition: 0, + Offset: offset, + EventID: eventID, + Value: []byte(fmt.Sprintf(`{"event_id":%q}`, eventID)), + Event: outbound.ConsumedEvent{ + EventID: eventID, + EventType: eventType, + SchemaVersion: 1, + AggregateType: "test", + AggregateID: uuid.New(), + AggregateVersion: 1, + OccurredAt: time.Now(), + Payload: []byte(`{}`), + }, + } +} + +func assertOffsets(t *testing.T, got []int64, want ...int64) { + t.Helper() + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("committed offsets = %v, want %v", got, want) + } +} + +func TestNewRejectsInvalidNamesAndSettings(t *testing.T) { + logger := slog.New(slog.DiscardHandler) + for _, name := range []string{"", "Upper", "1st", "with-dash", strings.Repeat("a", 65)} { + _, err := New(namedHandler(name), newFakeSource(), newFakeStore(), newFakeMetrics(), logger, testSettings()) + if err == nil { + t.Fatalf("New() accepted consumer name %q", name) + } + } + settings := testSettings() + settings.MaxAttempts = 0 + if _, err := New(&fakeHandler{}, newFakeSource(), newFakeStore(), newFakeMetrics(), logger, settings); err == nil { + t.Fatal("New() accepted zero attempts") + } +} + +type namedHandler string + +func (handler namedHandler) ConsumerName() string { return string(handler) } +func (namedHandler) Handles(string) bool { return true } +func (namedHandler) Handle(context.Context, outbound.UnitOfWork, outbound.ConsumedEvent) error { + return nil +} + +func TestConsumerAppliesSkipsDuplicatesAndCommitsInOrder(t *testing.T) { + first := event(10, handledType) + duplicate := event(11, handledType) + duplicate.EventID, duplicate.Event.EventID = first.EventID, first.EventID + ignored := event(12, unhandledType) + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{first, duplicate, ignored}) + + h.runUntilDrained(t) + + assertOffsets(t, h.source.committedOffsets(), 10, 11, 12) + if got := len(h.handler.callTimes()); got != 1 { + t.Fatalf("handler ran %d times, want once", got) + } + for outcome, want := range map[string]int{OutcomeApplied: 1, OutcomeDuplicate: 1, OutcomeIgnored: 1, OutcomeDeadLettered: 0} { + if got := h.metrics.outcome(outcome); got != want { + t.Fatalf("outcome %s = %d, want %d", outcome, got, want) + } + } + if h.source.releases != h.source.polls { + t.Fatalf("released %d of %d polls", h.source.releases, h.source.polls) + } + if len(h.metrics.prepared) != 1 || h.metrics.prepared[0] != testConsumer { + t.Fatalf("prepared metrics for %v, want the consumer", h.metrics.prepared) + } +} + +func TestConsumerRetriesStoreFailuresWithoutUsingAttemptsAndCommitsAfterSuccess(t *testing.T) { + record := event(0, handledType) + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{record}) + // More failures than MaxAttempts: a database outage must not dead-letter + // a valid event. + h.store.applyFailures = 5 + + h.runUntilDrained(t) + + assertOffsets(t, h.source.committedOffsets(), 0) + if got := h.metrics.failure(StageStore); got != 5 { + t.Fatalf("store failures = %d, want 5", got) + } + if got := h.metrics.outcome(OutcomeApplied); got != 1 { + t.Fatalf("applied = %d, want 1", got) + } + if letters := h.store.letters(); len(letters) != 0 { + t.Fatalf("a store outage produced %d dead letters", len(letters)) + } +} + +func TestConsumerDeadLettersAfterBoundedRetriesWithBackoff(t *testing.T) { + poison := event(0, handledType) + next := event(1, handledType) + settings := testSettings() + settings.MaxAttempts = 4 + backoffFloor := 10 * time.Millisecond + // Initial equals Max, so every wait is between half the value and the + // value: at least backoffFloor. + settings.Backoff = retry.Backoff{Initial: 2 * backoffFloor, Max: 2 * backoffFloor} + h := newHarness(t, settings, []outbound.ConsumedRecord{poison, next}) + var commitsBeforeNext int + h.handler.handle = func(_ context.Context, event outbound.ConsumedEvent, _ int) error { + if event.EventID == poison.EventID { + return fmt.Errorf("handler: %w", errTransient) + } + commitsBeforeNext = h.source.commitCount() + return nil + } + + h.runUntilDrained(t) + + calls := h.handler.callTimes() + // Four attempts for the poison event and one for the next event. + if len(calls) != settings.MaxAttempts+1 { + t.Fatalf("handler ran %d times, want %d", len(calls), settings.MaxAttempts+1) + } + for index := 1; index < settings.MaxAttempts; index++ { + if gap := calls[index].Sub(calls[index-1]); gap < backoffFloor { + t.Fatalf("attempt %d followed the previous one after %s, want at least %s", index+1, gap, backoffFloor) + } + } + letters := h.store.letters() + if len(letters) != 1 { + t.Fatalf("dead letters = %d, want 1", len(letters)) + } + letter := letters[0] + if letter.ErrorClass != outbound.DeadLetterRetriesExhausted || letter.Attempts != settings.MaxAttempts || + letter.EventID != poison.EventID || letter.EventType != handledType || letter.Offset != 0 || + letter.Topic != testTopic || letter.ValueSize != len(poison.Value) || letter.ValueSHA256 != sha256.Sum256(poison.Value) || + !strings.Contains(letter.Reason, errTransient.Error()) { + t.Fatalf("unexpected dead letter %+v", letter) + } + // The partition moves on: the next event is applied, and both offsets + // are committed after the dead letter was stored. The dead letter's + // offset is committed before the next record starts, so a member that + // takes over after a rebalance timeout does not repeat the retries. + assertOffsets(t, h.source.committedOffsets(), 0, 1) + if commitsBeforeNext != 1 { + t.Fatalf("commits before the next record = %d, want the prefix commit after the dead letter", commitsBeforeNext) + } + if got := h.metrics.failure(StageHandler); got != settings.MaxAttempts { + t.Fatalf("handler failures = %d, want %d", got, settings.MaxAttempts) + } + if h.metrics.outcome(OutcomeDeadLettered) != 1 || h.metrics.outcome(OutcomeApplied) != 1 { + t.Fatalf("outcomes = %v", h.metrics.outcomes) + } +} + +func TestConsumerDeadLettersFinalFailuresAtOnce(t *testing.T) { + tests := []struct { + name string + handle func(context.Context, outbound.ConsumedEvent, int) error + class outbound.DeadLetterClass + }{ + { + name: "rejected", + handle: func(context.Context, outbound.ConsumedEvent, int) error { + return fmt.Errorf("unsupported schema version: %w", inbound.ErrEventRejected) + }, + class: outbound.DeadLetterHandlerRejected, + }, + { + name: "panic", + handle: func(context.Context, outbound.ConsumedEvent, int) error { + panic("payload secret") + }, + class: outbound.DeadLetterHandlerPanic, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)}) + h.handler.handle = test.handle + + h.runUntilDrained(t) + + if got := len(h.handler.callTimes()); got != 1 { + t.Fatalf("handler ran %d times, want once", got) + } + letters := h.store.letters() + if len(letters) != 1 || letters[0].ErrorClass != test.class || letters[0].Attempts != 1 { + t.Fatalf("dead letters = %+v, want one %s", letters, test.class) + } + if strings.Contains(letters[0].Reason, "secret") { + t.Fatalf("dead letter reason %q quotes the panic value", letters[0].Reason) + } + assertOffsets(t, h.source.committedOffsets(), 0) + }) + } +} + +func TestConsumerDeadLettersInvalidRecordsWithoutTheHandler(t *testing.T) { + invalid := outbound.ConsumedRecord{ + Topic: testTopic, + Partition: 2, + Offset: 7, + EventID: uuid.New(), + Value: []byte("not json \x00 with\nnewline"), + Invalid: fmt.Errorf("value is not a JSON event envelope\nsecond line: %w", outbound.ErrInvalidEventRecord), + } + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{invalid}) + // The first write of the dead letter fails; the offset must wait for it. + h.store.letterFailures = 2 + + h.runUntilDrained(t) + + if got := len(h.handler.callTimes()); got != 0 { + t.Fatalf("handler ran %d times for an invalid record", got) + } + letters := h.store.letters() + if len(letters) != 1 { + t.Fatalf("dead letters = %d, want 1", len(letters)) + } + letter := letters[0] + if letter.ErrorClass != outbound.DeadLetterInvalidRecord || letter.Attempts != 0 || letter.EventType != "" || + letter.EventID != invalid.EventID || letter.Partition != 2 || letter.Offset != 7 || strings.ContainsAny(letter.Reason, "\n\x00") { + t.Fatalf("unexpected dead letter %+v", letter) + } + assertOffsets(t, h.source.committedOffsets(), 7) + if got := h.metrics.failure(StageStore); got != 2 { + t.Fatalf("store failures = %d, want 2", got) + } +} + +func TestConsumerShutdownAbandonsUnfinishedRecordsWithoutCommitting(t *testing.T) { + blocked := event(0, handledType) + later := event(1, handledType) + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{blocked, later}) + started := make(chan struct{}) + h.handler.handle = func(ctx context.Context, _ outbound.ConsumedEvent, _ int) error { + close(started) + // The effect is written but the handler outlives the grace, as a + // stuck dependency would; the transaction must roll back. + <-ctx.Done() + return ctx.Err() + } + stop := h.run(t) + <-started + + stopping := time.Now() + stop() + + if elapsed := time.Since(stopping); elapsed < testGrace || elapsed > testGrace+time.Second { + t.Fatalf("Run() returned %s after cancellation, want about the %s grace", elapsed, testGrace) + } + assertOffsets(t, h.source.committedOffsets()) + if got := len(h.handler.callTimes()); got != 1 { + t.Fatalf("handler ran %d times, want only the abandoned record", got) + } + if letters := h.store.letters(); len(letters) != 0 { + t.Fatalf("shutdown produced dead letters: %+v", letters) + } + if h.source.releases != h.source.polls { + t.Fatalf("released %d of %d polls", h.source.releases, h.source.polls) + } +} + +func TestConsumerShutdownLetsTheRecordInProgressFinishWithinTheGrace(t *testing.T) { + inProgress := event(0, handledType) + notStarted := event(1, handledType) + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{inProgress, notStarted}) + started := make(chan struct{}) + release := make(chan struct{}) + h.handler.handle = func(_ context.Context, event outbound.ConsumedEvent, _ int) error { + if event.EventID == inProgress.EventID { + close(started) + <-release + } + return nil + } + stop := h.run(t) + <-started + go func() { + time.Sleep(testGrace / 4) + close(release) + }() + + stop() + + // The finished record is committed; the next one was never started. + assertOffsets(t, h.source.committedOffsets(), 0) + if got := len(h.handler.callTimes()); got != 1 { + t.Fatalf("handler ran %d times, want once", got) + } +} + +func TestConsumerDoesNotRetryDuringShutdown(t *testing.T) { + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)}) + settings := testSettings() + settings.Backoff = retry.Backoff{Initial: time.Hour, Max: time.Hour} + h.consumer.settings = settings + failed := make(chan struct{}) + h.handler.handle = func(context.Context, outbound.ConsumedEvent, int) error { + close(failed) + return errTransient + } + stop := h.run(t) + <-failed + + stopping := time.Now() + stop() + + if elapsed := time.Since(stopping); elapsed > time.Second { + t.Fatalf("Run() waited %s for a backoff after cancellation", elapsed) + } + assertOffsets(t, h.source.committedOffsets()) + if letters := h.store.letters(); len(letters) != 0 { + t.Fatalf("shutdown dead-lettered a retryable failure: %+v", letters) + } +} + +func TestConsumerBacksOffWhenPollFails(t *testing.T) { + h := newHarness(t, testSettings()) + h.source.pollErr = errors.New("broker unavailable") + settings := testSettings() + settings.Backoff = retry.Backoff{Initial: 20 * time.Millisecond, Max: 20 * time.Millisecond} + h.consumer.settings = settings + stop := h.run(t) + time.Sleep(200 * time.Millisecond) + stop() + + h.source.mu.Lock() + polls := h.source.polls + h.source.mu.Unlock() + // Each failed poll waits at least 10ms, so 200ms allow about 20 polls; a + // hot loop would make thousands. + if polls < 2 || polls > 25 { + t.Fatalf("polls = %d in 200ms, want a few with backoff", polls) + } +} + +func TestConsumerKeepsFinishedRecordsWhenTheCommitFails(t *testing.T) { + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)}) + h.source.commitErr = errors.New("rebalance in progress") + + h.runUntilDrained(t) + + // The failed commit is only logged; the record is applied once and its + // redelivery would be a duplicate. + if got := h.metrics.outcome(OutcomeApplied); got != 1 { + t.Fatalf("applied = %d, want 1", got) + } +} + +func TestSanitizeReasonBoundsAndFlattensTheCause(t *testing.T) { + long := strings.Repeat("é", maxReasonLength+10) + if got := []rune(sanitizeReason(errors.New(long))); len(got) != maxReasonLength { + t.Fatalf("reason has %d characters, want %d", len(got), maxReasonLength) + } + if got := sanitizeReason(errors.New("a\nb\tc\x00")); got != "a b c" { + t.Fatalf("sanitizeReason() = %q, want %q", got, "a b c") + } + if got := sanitizeReason(errors.New("\t\x00 ")); got != "unspecified failure" { + t.Fatalf("sanitizeReason() = %q for a blank cause", got) + } +} + +func TestConsumerSpendsAttemptsOnCommitsThePostgreSQLRefuses(t *testing.T) { + // The handler swallowed a failed statement and returned nil, so every + // commit is refused. Without counting attempts this would retry forever. + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)}) + refused := fmt.Errorf("commit: %w", outbound.ErrEventEffectRejected) + h.store.commitErrors = []error{refused, refused, refused} + + h.runUntilDrained(t) + + letters := h.store.letters() + if len(letters) != 1 || letters[0].ErrorClass != outbound.DeadLetterRetriesExhausted || letters[0].Attempts != 3 { + t.Fatalf("dead letters = %+v, want one retries_exhausted after 3 attempts", letters) + } + if got := len(h.handler.callTimes()); got != 3 { + t.Fatalf("handler ran %d times, want 3", got) + } + if got := h.metrics.failure(StageHandler); got != 3 { + t.Fatalf("handler failures = %d, want 3", got) + } + if got := h.metrics.failure(StageStore); got != 0 { + t.Fatalf("store failures = %d, want 0", got) + } + assertOffsets(t, h.source.committedOffsets(), 0) +} + +func TestConsumerRetriesASerializationFailureAsAnAttempt(t *testing.T) { + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)}) + h.store.commitErrors = []error{fmt.Errorf("commit: %w", outbound.ErrTransactionConflict)} + + h.runUntilDrained(t) + + if h.metrics.outcome(OutcomeApplied) != 1 || h.metrics.failure(StageHandler) != 1 || len(h.store.letters()) != 0 { + t.Fatalf("outcomes = %v, failures = %v, letters = %d; want one counted retry and the event applied", + h.metrics.outcomes, h.metrics.failures, len(h.store.letters())) + } +} + +// panickyHandles panics while routing. +type panickyHandles struct{ fakeHandler } + +func (*panickyHandles) Handles(string) bool { panic("routing secret") } + +func TestConsumerDeadLettersAPanicWhileRouting(t *testing.T) { + source, store, metrics := newFakeSource([]outbound.ConsumedRecord{event(0, handledType)}), newFakeStore(), newFakeMetrics() + consumer, err := New(&panickyHandles{}, source, store, metrics, slog.New(slog.DiscardHandler), testSettings()) + if err != nil { + t.Fatalf("New() error = %v", err) + } + h := &harness{source: source, store: store, handler: &fakeHandler{}, metrics: metrics, consumer: consumer} + + h.runUntilDrained(t) + + letters := store.letters() + if len(letters) != 1 || letters[0].ErrorClass != outbound.DeadLetterHandlerPanic || letters[0].Attempts != 0 || + strings.Contains(letters[0].Reason, "secret") { + t.Fatalf("dead letters = %+v, want one handler_panic without the panic value", letters) + } + assertOffsets(t, source.committedOffsets(), 0) +} + +func TestConsumerCountsPollAndCommitFailures(t *testing.T) { + h := newHarness(t, testSettings(), []outbound.ConsumedRecord{event(0, handledType)}) + h.source.commitErr = errors.New("coordinator unavailable") + + h.runUntilDrained(t) + + if got := h.metrics.failure(StageCommit); got != 1 { + t.Fatalf("commit failures = %d, want 1", got) + } + + polling := newHarness(t, testSettings()) + polling.source.pollErr = errors.New("broker unavailable") + stop := polling.run(t) + time.Sleep(20 * time.Millisecond) + stop() + if got := polling.metrics.failure(StagePoll); got < 1 { + t.Fatalf("poll failures = %d, want at least 1", got) + } +} diff --git a/backend/internal/worker/outboxrelay/relay.go b/backend/internal/worker/outboxrelay/relay.go index a0402c2..906a5a3 100644 --- a/backend/internal/worker/outboxrelay/relay.go +++ b/backend/internal/worker/outboxrelay/relay.go @@ -12,6 +12,7 @@ import ( "github.com/google/uuid" "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/retry" ) // Metrics records relay outcomes and the backlog without per-event labels. @@ -27,7 +28,7 @@ type Settings struct { // 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 + Backoff retry.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. @@ -155,7 +156,7 @@ func (relay *Relay) Run(ctx context.Context) { needsPrepare = errors.Is(err, outbound.ErrEventDestinationMissing) var delay time.Duration delay, failures = relay.nextDelay(result, err, failures) - if !wait(ctx, delay) { + if !retry.Wait(ctx, delay) { return } } @@ -207,7 +208,7 @@ func (relay *Relay) prepare(ctx context.Context, backlog *backlogRefresher) bool slog.Duration("retry_in", delay), slog.Any("error", err), ) - if !wait(ctx, delay) { + if !retry.Wait(ctx, delay) { return false } } @@ -258,19 +259,3 @@ func (relay *Relay) passContext(ctx context.Context) (context.Context, func()) { 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 index 1482c72..4d10fc6 100644 --- a/backend/internal/worker/outboxrelay/relay_test.go +++ b/backend/internal/worker/outboxrelay/relay_test.go @@ -13,6 +13,7 @@ import ( "github.com/google/uuid" "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/retry" ) const ( @@ -136,7 +137,7 @@ func newTestRelay(store outbound.OutboxRelayStore, publisher outbound.EventPubli return New(store, publisher, metrics, slog.New(slog.DiscardHandler), Settings{ BatchSize: 2, PollInterval: testInterval, - Backoff: Backoff{Initial: testInterval, Max: 4 * testInterval}, + Backoff: retry.Backoff{Initial: testInterval, Max: 4 * testInterval}, ShutdownTimeout: shutdownTimeout, BacklogInterval: testInterval, }) @@ -314,7 +315,7 @@ func TestRunStopsDuringBackoffWithoutAnotherPass(t *testing.T) { }}, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{ BatchSize: 1, PollInterval: testInterval, - Backoff: Backoff{Initial: time.Hour, Max: time.Hour}, + Backoff: retry.Backoff{Initial: time.Hour, Max: time.Hour}, ShutdownTimeout: time.Second, BacklogInterval: time.Hour, }) @@ -337,7 +338,7 @@ func hourBackoffRelay(store outbound.OutboxRelayStore, publisher outbound.EventP return New(store, publisher, &countingMetrics{}, slog.New(slog.DiscardHandler), Settings{ BatchSize: 2, PollInterval: testInterval, - Backoff: Backoff{Initial: time.Hour, Max: time.Hour}, + Backoff: retry.Backoff{Initial: time.Hour, Max: time.Hour}, ShutdownTimeout: time.Second, BacklogInterval: backlogInterval, }) @@ -409,7 +410,7 @@ func TestRunRefreshesTheBacklogAtMostOncePerInterval(t *testing.T) { relay := New(store, fakePublisher{publish: acknowledgeAll}, metrics, slog.New(slog.DiscardHandler), Settings{ BatchSize: 1, PollInterval: testInterval, - Backoff: Backoff{Initial: testInterval, Max: testInterval}, + Backoff: retry.Backoff{Initial: testInterval, Max: testInterval}, ShutdownTimeout: time.Second, BacklogInterval: time.Hour, }) diff --git a/backend/internal/worker/outboxrelay/backoff.go b/backend/internal/worker/retry/retry.go similarity index 63% rename from backend/internal/worker/outboxrelay/backoff.go rename to backend/internal/worker/retry/retry.go index ffc8415..4b1f237 100644 --- a/backend/internal/worker/outboxrelay/backoff.go +++ b/backend/internal/worker/retry/retry.go @@ -1,6 +1,9 @@ -package outboxrelay +// Package retry holds the waiting rules that the background workers share: +// a capped exponential backoff with jitter and a context-aware sleep. +package retry import ( + "context" "math/rand/v2" "time" ) @@ -8,8 +11,8 @@ import ( // 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. +// half keeps retries from hammering a recovering dependency, and the random +// half spreads several workers apart. type Backoff struct { Initial time.Duration Max time.Duration @@ -38,3 +41,19 @@ func randomJitter(limit time.Duration) time.Duration { } return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness. } + +// 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/backoff_test.go b/backend/internal/worker/retry/retry_test.go similarity index 75% rename from backend/internal/worker/outboxrelay/backoff_test.go rename to backend/internal/worker/retry/retry_test.go index 9281424..cc85e03 100644 --- a/backend/internal/worker/outboxrelay/backoff_test.go +++ b/backend/internal/worker/retry/retry_test.go @@ -1,6 +1,7 @@ -package outboxrelay +package retry import ( + "context" "testing" "time" ) @@ -50,3 +51,21 @@ func TestBackoffRandomJitterStaysWithinTheCeiling(t *testing.T) { } } } + +func TestWaitStopsWhenTheContextEnds(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if Wait(ctx, 0) { + t.Fatal("Wait(canceled, 0) = true, want false") + } + started := time.Now() + if Wait(ctx, time.Hour) { + t.Fatal("Wait(canceled, 1h) = true, want false") + } + if elapsed := time.Since(started); elapsed > time.Second { + t.Fatalf("Wait(canceled, 1h) took %s", elapsed) + } + if !Wait(t.Context(), time.Millisecond) { + t.Fatal("Wait(live, 1ms) = false, want true") + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 4c89ced..f1a33c0 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -213,11 +213,16 @@ 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 + # Shutdown budget with the defaults (see docs/en/DEPLOY.md): + # - in parallel: the HTTP shutdown (SHUTDOWN_TIMEOUT, 10s), the relay + # pass (10s plus a 5s rollback), and each event consumer + # (CONSUMER_SHUTDOWN_GRACE 5s, a 5s rollback, CONSUMER_COMMIT_TIMEOUT + # 5s): 15s; + # - then the consumers leave their groups in parallel (commit timeout + # plus 2s) and the clients close (about 1s): 8s. + # About 23s in total; 30s leaves a margin so Docker does not kill the + # process while a pass or a consumer transaction is committing. + stop_grace_period: 30s restart: unless-stopped logging: driver: json-file diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index c9cb953..f2cfe6b 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, 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. +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. The [event consumer](#event-consumers) runtime applies events idempotently; no product consumer is registered 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,7 @@ 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. -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. +The relay that publishes these rows is described in [Outbox relay](#outbox-relay). Idempotent consumers are described in [Event consumers](#event-consumers). Still planned: retry bookkeeping columns (attempt count and last error) and retention of published rows. 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 @@ -112,6 +112,46 @@ Failure semantics: 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. +### Event consumers + +Implemented (TASK-010): the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. No product handler is registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns an empty list, so the running backend starts no consumer and opens no consumer pool or Kafka group. The integration tests run the runtime with a test-only handler that writes into a table the test creates; there is no invented business effect. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). + +A handler implements three methods: + +- `ConsumerName()`: a snake_case name of at most 64 characters. It names the Kafka consumer group `.` and scopes deduplication, so renaming a consumer makes it process every retained event again. +- `Handles(eventType)`: events of other types are counted as `ignored` and committed without a transaction. +- `Handle(ctx, unit, event)`: receives the decoded envelope and an `outbound.UnitOfWork` bound to the transaction that holds the dedup marker. The effect must use only that unit. An error that wraps `inbound.ErrEventRejected` is final; any other error is retried. Errors must not quote the payload or personal data, because their text is logged and stored with a dead letter. + +Deduplication uses `event_id` only. Order by `aggregate_version` stays with the handler: a replayed dead letter can arrive after a later version of its aggregate, so a handler that keeps aggregate state ignores a version it has already passed. + +One record is processed as follows: + +1. The Kafka adapter decodes the envelope. It requires `envelope_version` 1, a non-nil `event_id`, the domain rules of `domain.NewDomainEvent` for type, schema version, aggregate type, ID, and version, a non-zero `occurred_at`, a JSON object `payload`, and an `event_id` header, when present, equal to the envelope field. A record that breaks a rule is an invalid record; the handler never sees it. The error names the broken rule and never quotes the value. +2. One READ COMMITTED transaction sets `statement_timeout` and `idle_in_transaction_session_timeout` to `CONSUMER_HANDLER_TIMEOUT` for this transaction only, runs `INSERT INTO consumer_processed_events (consumer_name, event_id) ... ON CONFLICT DO NOTHING`, and checks the row count. Zero rows means the event was applied before: the transaction rolls back and the record is a `duplicate`. One row means the handler runs in the same transaction, and the effect commits together with the marker. +3. The offset is committed only after that commit, or after the dead letter row is stored. + +Why `ON CONFLICT DO NOTHING` in the same transaction as the effect. The marker is inserted before the effect, so the effect runs only while its transaction holds the uncommitted marker. A concurrent delivery of the same event, from another instance or after a rebalance, waits on that unique key until the first transaction ends: after a commit its insert affects zero rows and it skips the effect; after a rollback its insert succeeds and it applies the event itself. The effect therefore never runs twice or in parallel, and the outcome does not depend on timing. A plain `INSERT` that fails on the unique key waits the same way, but a duplicate then aborts the transaction with SQLSTATE 23505, puts an expected case into the PostgreSQL error log, and drives control flow by error. Checking with a `SELECT` before the insert leaves a race window under READ COMMITTED. The server-side timeouts end the transaction of a frozen process, so its marker cannot block a duplicate indefinitely. + +Offsets and partitions. Each consumer is one member of its group with autocommit off and franz-go `BlockRebalanceOnPoll`. It polls at most `CONSUMER_MAX_POLL_RECORDS` records and processes them one at a time in poll order, which keeps the order within every partition. After the batch it commits, for each partition, the position after the last finished record (with its leader epoch), and only then allows a rebalance. Because rebalances wait for that point, a commit never lands on a partition the member no longer owns. A failed commit is logged; the position is retried with the next commit and when the partition is revoked, and dropped when the partition is lost, in which case the next owner receives the records again and the markers turn them into duplicates. A new group starts at the earliest retained record, so a new consumer never skips an event. The adapter refuses a commit whose finished records are not, per partition, the first records of the last poll without a gap, so a commit can never move past an unfinished record. + +Rebalance budget. A batch holds rebalancing while it runs. If it takes longer than the rebalance timeout, the broker removes the member, its commit fails, and the new owner reprocesses from the last committed offset; deduplication makes that harmless, but the work is repeated. The timeout is set explicitly from `CONSUMER_REBALANCE_TIMEOUT` (60 seconds by default), and configuration refuses to start when the slowest record does not fit in it with a 5-second margin. The slowest record without a database outage is `CONSUMER_MAX_ATTEMPTS` handler attempts, the longest backoff before each retry, one dead letter write (each bounded by `CONSUMER_HANDLER_TIMEOUT`), and one offset commit (`CONSUMER_COMMIT_TIMEOUT`): 42.5 seconds with the defaults. A record is the unit because the consumer commits the finished prefix of a batch right after every record that needed a retry or a dead letter, so a member removed during the next slow record does not make its successor repeat the earlier ones. A database outage is not part of the budget: store failures are retried without a bound, and the removal they can cause only repeats work. The alternative, stopping a batch early when franz-go reports a blocked rebalance (`OnPartitionsCallbackBlocked`), would leave polled but unprocessed records behind on the partitions the member keeps; they would be skipped unless the fetch position were rewound with `SetOffsets`, which franz-go documents as prone to odd interactions inside a poll loop. The static budget is simpler and testable. + +Failures, retries, and dead letters: + +- Handler error: up to `CONSUMER_MAX_ATTEMPTS` attempts with the same backoff as the relay: the wait starts at `CONSUMER_BACKOFF_INITIAL`, doubles up to `CONSUMER_BACKOFF_MAX`, and is half the current value plus a random share of the other half. Each attempt is bounded by `CONSUMER_HANDLER_TIMEOUT` and rolls back its effect and marker. When the attempts run out, the record becomes a dead letter of class `retries_exhausted`. `inbound.ErrEventRejected` gives `handler_rejected` after one attempt. A handler panic is recovered, the transaction rolls back, the stack is logged without the panic value, and the record becomes `handler_panic`, so one event cannot crash the process on every delivery. +- Invalid record: a dead letter of class `invalid_record` with zero attempts. +- Refused commit: when the handler returns nil but PostgreSQL refuses the commit, the event is at fault, not the database. `pgx.ErrTxCommitRollback` (the handler ignored a failed statement, so the transaction was aborted) and SQLSTATE class 23 (a deferred integrity constraint) match `outbound.ErrEventEffectRejected`; class 40 (serialization failure or deadlock) matches `outbound.ErrTransactionConflict`. Both count as a handler attempt and are retried with backoff, so a deterministic refusal ends in `retries_exhausted` instead of a retry loop without end. Class 40 is transient by nature and usually succeeds on the next attempt; it still uses up an attempt so that a handler that deadlocks every time cannot retry forever. The same applies to a panic in `Handles`, which gives `handler_panic` without an attempt. +- Store failure (begin, marker, a commit lost in transport, or the dead letter write): it does not use up the handler's attempts, because the event is not at fault. The consumer retries with the same backoff until the database answers or shutdown begins, and never dead-letters a record because the database was down. The offset stays uncommitted meanwhile, so a database outage stops the partition without a hot loop and loses nothing. +- After the dead letter row exists, the offset is committed and the partition continues with the next record. A dead letter writes no marker, so a later replay of the event is applied. + +`consumer_dead_letters` stores the consumer name, topic, partition, offset, `event_id` (from the envelope, or from the `event_id` header of an invalid record; NULL when neither is a UUID), `event_type` (NULL for an invalid record), the class, a reason of at most 256 printable characters, the attempt count, the value size, its SHA-256, and the time. A unique key on consumer, topic, partition, offset, and value digest keeps one row per record: when the same record fails again, after a crash before its offset commit or a rewind of the group, the row gets the new class, reason, attempt count, and time. The digest is part of the key because a topic that was deleted and created again reuses offsets; a different value at a reused position is another record and keeps its own row instead of being dropped. Handler errors reach the reason and the logs only after the store replaced the text of any PostgreSQL error in them with its SQLSTATE and constraint, because a PostgreSQL message can quote row values. The record value itself is not stored. A valid event is still in `outbox_events` under its `event_id`, which is also the replay source, so a second copy would only duplicate data that events may carry later and that a dead letter table would keep without a retention rule. An invalid record did not come from the relay; while the topic retains it, an operator can read it by topic, partition, and offset, and the SHA-256 confirms it is the same value. The replay procedure is in [DEPLOY.md](DEPLOY.md#dead-letters-and-replay). + +Lifecycle. Startup runs the migrations, then wire builds the consumers: one PostgreSQL pool shared by all of them with one connection per consumer (a consumer holds one transaction at a time and writes a dead letter only after it ended) and one franz-go client per consumer. Nothing connects at that point, so an unavailable Kafka or database does not block startup. The application opens its listeners, starts the relay and every consumer next to the HTTP servers, and serves. On SIGTERM the HTTP servers, the relay, and the consumers stop at the same time; none depends on another. A consumer starts no new record and abandons any backoff wait at once. An attempt in progress has `CONSUMER_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back. Finished records are committed within `CONSUMER_COMMIT_TIMEOUT`; unfinished records are never committed, so the next member of the group processes them. Bootstrap waits for all workers before the cleanup, in which the members leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2 seconds (the final revocation commits only finished positions), and then the pool closes. The whole shutdown budget is in [DEPLOY.md](DEPLOY.md#event-consumers). + +Trade-offs: one consumer processes one record at a time on one connection. Parallel processing comes from more backend instances in the same group, up to the partition count of the topic (3 by default). Markers are kept indefinitely; their retention is planned and must outlast the replay horizon, because deleting a marker lets a replay of that event apply again. The retention task also adds the index on `processed_at` that it needs; until then every applied event would pay for an index that nothing reads. + +The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records by `applied`, `duplicate`, `ignored`, or `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter, by `handler`, `store`, `poll` (a failed poll of the event bus), or `commit` (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload. + ### Mail transport Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet; the delivery layer is planned. Settings are described in [DEPLOY.md](DEPLOY.md#mail). @@ -233,11 +273,11 @@ backend/ internal/ domain/ flat package; DomainEvent, identity types, product policy usecase/health/ operational readiness usecase - port/inbound/ readiness input boundary + port/inbound/ readiness and event handler input boundaries 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, outbox relay, event publishing, identity, policy, password hashing, and mail boundaries + port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, policy, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -246,18 +286,20 @@ 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 + kafka/ franz-go event publisher and consumer group member: record envelope, its decoding, 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 and relay store, identity and policy repositories, health check + postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer 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 + worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown + worker/retry/ backoff with jitter and a context-aware wait shared by the workers bootstrap/ configuration, wiring, lifecycle, shutdown - db/ embedded migrations and SQL queries; outbox, identity, and policy tables + db/ embedded migrations and SQL queries; outbox, identity, policy, and event consumer tables codegen/ ogen and sqlc configs pkg/ reserved for justified shared technical helpers ``` @@ -266,7 +308,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate. 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, 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. +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, the event consumer runtime with no registered product handler, 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/`. @@ -410,7 +452,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo ## Future extensions -Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table and its transactional writer are implemented (see "Transactional outbox" above); the relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. +Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); product consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI. k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 0f90ad2..5628bb4 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -85,7 +85,7 @@ The backend runs the outbox relay in its own process next to the HTTP servers. T | `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`. +`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: 30s`, which covers the whole shutdown budget described under [Event consumers](#event-consumers), 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. @@ -95,6 +95,73 @@ When Kafka is unavailable, the backend still starts and serves the API. The rela 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. +### Event consumers + +The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `.`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: no product handler is registered, so the backend logs `no event consumer is registered`, starts no consumer, and opens no consumer group; the settings below take effect once a handler exists. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled. + +| Variable | Default | Meaning | +| --- | --- | --- | +| `CONSUMER_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no consumer runs, and events wait in Kafka for as long as the topic retains them. | +| `CONSUMER_GROUP_PREFIX` | `lincodex` | Prefix of every consumer group ID, up to 128 letters, digits, dots, underscores, or hyphens. Changing it starts new groups that read the topic from its earliest retained record; the dedup markers turn events that were already applied into duplicates. | +| `CONSUMER_MAX_ATTEMPTS` | `5` | Handler attempts for one event before it becomes a dead letter, from 1 to 20. Database failures outside the handler do not count. Must fit the rebalance budget below. | +| `CONSUMER_BACKOFF_INITIAL` | `500ms` | Wait after the first failed attempt; it doubles with each consecutive failure. | +| `CONSUMER_BACKOFF_MAX` | `10s` | Longest wait between attempts, from `CONSUMER_BACKOFF_INITIAL` to 5m. | +| `CONSUMER_HANDLER_TIMEOUT` | `5s` | Bound of one attempt and of one dead letter write, from 100ms to 5m. It is also the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the consumer transaction. | +| `CONSUMER_MAX_POLL_RECORDS` | `100` | Records of one poll, from 1 to 10000. A consumer processes them while it holds group rebalancing, so a smaller value shortens that hold. | +| `CONSUMER_COMMIT_TIMEOUT` | `5s` | Bound of one offset commit, from 100ms to 1m. | +| `CONSUMER_SHUTDOWN_GRACE` | `5s` | Time the record in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back, the offset stays uncommitted, and the next member processes the record. | +| `CONSUMER_REBALANCE_TIMEOUT` | `60s` | Kafka rebalance timeout of every consumer group member, from 10s to 30m. Startup fails unless it exceeds the slowest record by 5 seconds. | + +Rebalance budget. A consumer holds group rebalancing while it processes a poll, and a member that holds it longer than `CONSUMER_REBALANCE_TIMEOUT` is removed from the group, so its records are processed again by the next owner. The slowest record without a database outage takes `CONSUMER_MAX_ATTEMPTS` + 1 times `CONSUMER_HANDLER_TIMEOUT` (the attempts and the dead letter write), the longest backoff before each retry, and one `CONSUMER_COMMIT_TIMEOUT`. With the defaults that is 6 x 5s + (0.5 + 1 + 2 + 4)s + 5s = 42.5s, below 60s - 5s. A configuration that does not fit fails at startup with the computed value; lower the attempts or timeouts, or raise `CONSUMER_REBALANCE_TIMEOUT`, which also makes the group wait longer for a member that stopped responding. After every record that needed a retry or a dead letter the consumer commits at once, so only one slow record has to fit, not a whole poll. + +Shutdown budget with the defaults: + +1. In parallel: the HTTP servers drain within `SHUTDOWN_TIMEOUT` (10s); a relay pass gets the same 10s and up to 5s to roll back; every consumer gets `CONSUMER_SHUTDOWN_GRACE` (5s) for the record in progress, up to 5s to roll back a canceled transaction, and `CONSUMER_COMMIT_TIMEOUT` (5s) for its offsets. This phase ends after at most 15s. +2. Then all consumers leave their groups in parallel, each within `CONSUMER_COMMIT_TIMEOUT` plus 2s (7s), and the clients and pools close in about 1s. + +That is about 23s regardless of the number of consumers. Compose gives the backend `stop_grace_period: 30s`, so Docker does not kill the process while a transaction commits; raise it when you raise `SHUTDOWN_TIMEOUT`, `CONSUMER_SHUTDOWN_GRACE`, or `CONSUMER_COMMIT_TIMEOUT`. + +A consumer needs one PostgreSQL connection; all consumers of a process share one pool sized to their count. Several backend instances share a group's partitions, so at most `KAFKA_EVENTS_TOPIC_PARTITIONS` instances process a consumer's events at once; the others stay idle members. + +Operators watch two counters on the internal /metrics endpoint. `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records: `applied`, `duplicate` (expected after a redelivery), `ignored` (another event type), and `dead_lettered`. Alert on any increase of `dead_lettered`; every series exists at zero from the consumer's start, so `increase(...[15m]) > 0` fires on the first dead letter. `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter: a rising `store` count with flat `applied` means the consumer cannot reach PostgreSQL and its partition waits; a rising `handler` count means events keep failing; a rising `poll` count means the consumer cannot read Kafka (broker down, missing topic, or a group error); a rising `commit` count means offsets are not stored, so records will be delivered again after a restart or rebalance. Alert on `poll` or `commit` failures that continue for several minutes, for example `increase(...{stage=~"poll|commit"}[5m]) > 0` held for 10 minutes. Consumer logs carry the `event_consumer` component, the group, topic, partition, offset, event ID, and event type, never the record value. A dead letter is logged at error level as `event dead-lettered; the offset is committed and the record needs an operator` with the class and reason. + +#### Dead letters and replay + +A dead letter is a record the consumer gave up on so that its partition can continue. `error_class` says why: + +- `invalid_record`: the value is not a valid event envelope. It did not come from the relay; find the producer that writes to the topic. It cannot be replayed as it is. +- `handler_rejected`: the handler reported that the event can never be applied, for example an unknown `schema_version`. +- `handler_panic`: the handler panicked; the log line `event handler panicked` with the same event ID holds the stack. +- `retries_exhausted`: the handler failed `CONSUMER_MAX_ATTEMPTS` times, for example because of a bug or a dependency it calls. + +List them with psql in the database container (default `app` project): + + docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ + exec postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"' + + SELECT id, consumer_name, error_class, event_id, event_type, topic, + kafka_partition, kafka_offset, attempts, reason, dead_lettered_at + FROM consumer_dead_letters ORDER BY id; + +The table holds no record value; `value_size` and `value_sha256` identify the value. Replay a dead letter only after its cause is fixed, usually by deploying a corrected handler: + +1. Replay one event from the outbox. For a dead letter with an `event_id` and a class other than `invalid_record`, publish the event again: + + UPDATE outbox_events SET published_at = NULL WHERE event_id = ''; + + The relay publishes it again with the same `event_id` at a new offset. Every consumer receives it: those that applied it find their marker and count a `duplicate`, and the consumer that failed applies it, because a dead letter writes no marker. This works as long as the outbox row exists (published rows are not deleted yet), also after Kafka dropped the original record. The event can arrive after later versions of its aggregate; handlers ignore versions they have already passed. +2. Or rewind the group while Kafka still retains the record. Kafka resets offsets only for an empty group, so stop every member first (stop the backend instances or set `CONSUMER_ENABLED=false`). A member that was killed instead of stopped stays in the group until its session timeout (45 seconds by default) ends; run the command below with `--describe` instead of the reset options and wait until it lists no active member. Then: + + docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ + exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-consumer-groups.sh \ + --bootstrap-server localhost:9092 --group lincodex. \ + --topic lincodex.domain.events: --reset-offsets --to-offset --execute + + The group then reads that partition again from the offset. Records it already applied are duplicates; other dead letters in the range are attempted again, and one that fails again updates its row with the new class, reason, and attempt count instead of adding another. `--describe` also shows the group's offsets and lag. +3. Check the result and close the dead letter: the event is applied when `SELECT 1 FROM consumer_processed_events WHERE consumer_name = '' AND event_id = ''` returns a row. Then delete the row with `DELETE FROM consumer_dead_letters WHERE id = `, or keep it as a record of the incident. + +To inspect an `invalid_record` while the topic retains it, read exactly that record with `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic --partition --offset --max-messages 1` and compare its SHA-256 with `value_sha256`. The value can contain personal data, so do not paste it into tickets or chats. + ## 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 444d3cd..5333312 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; outbox relay producer and integration tests | backend/go.mod | +| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; outbox relay producer, event consumer group members, 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. 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. +- 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. The event consumer runtime exists, but no product handler is registered, so nothing consumes the events yet; see [Event consumers](#event-consumers). - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. - 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, 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). +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, product 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`), the `policy_versions` table, and the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`) 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 @@ -181,10 +181,18 @@ A record that depends on policy values adds `policy_version_id uuid NOT NULL REF ### 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. +The relay moves committed `outbox_events` rows to Kafka. The loop lives in `backend/internal/worker/outboxrelay/` and its backoff in `backend/internal/worker/retry/`; 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). +### Event consumers + +The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`. + +No product handler is registered yet. To add one, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does. + +A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-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 c14aff4..c2623f7 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -38,7 +38,7 @@ 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), 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. +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)), the event consumer runtime (see [Event consumer tests](#event-consumer-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 product 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. @@ -74,7 +74,7 @@ Kafka is not part of `bootstrap(t)` and starts only for tests that select `boots ## 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/`). +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 shared backoff schedule with and without jitter (`internal/worker/retry/`), 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: @@ -88,7 +88,28 @@ Unit tests (`make -C backend test`) cover the record envelope, key, and headers - `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. +The suite runs against one broker and one PostgreSQL. It does not measure throughput or latency, and does not cover broker failover or replication. Consumers are covered in [Event consumer tests](#event-consumer-tests). + +## Event consumer tests + +Unit tests (`make -C backend test`) cover the consumer runtime with a fake source, store, and handler (`internal/worker/eventconsumer/`): applied, duplicate, and ignored records committed in poll order; store failures retried beyond the attempt limit without a dead letter, with the offset committed only after the store succeeded; a handler that keeps failing, retried exactly `MaxAttempts` times with at least the minimum backoff between attempts, then dead-lettered with its event ID, type, value size, and SHA-256 while the next record is applied; `ErrEventRejected` and a panic dead-lettered after one attempt without quoting the panic value; an invalid record dead-lettered without calling the handler, with the commit waiting until two failed dead letter writes succeed; a shutdown that abandons a stuck handler after the grace without committing it or anything after it; a record that finishes within the grace and is committed while the next one is not started; no retry and no dead letter during shutdown; backoff after failed polls; commits that PostgreSQL refuses after the handler swallowed an error, counted as attempts and ending in `retries_exhausted`; a serialization conflict at commit retried as an attempt; a panic in `Handles` dead-lettered without quoting its value; the prefix commit right after a dead letter, before the next record starts; `poll` and `commit` failure counts; and the reason sanitizer. The PostgreSQL adapter tests classify refused, conflicting, and transport commit failures and check that handler errors keep their identity without the PostgreSQL message. They also cover envelope decoding and its round trip with the producer, every rejected envelope rule without quoting the value, and commit bookkeeping of the group member, including the refusal of finished records that are not a gap-free prefix of the last poll per partition (`internal/adapter/secondary/kafka/`), the consumer settings and the rebalance budget, including the documented 42.5-second default (`config/`), the consumer counters (`internal/adapter/secondary/prometheus/`), and in `internal/bootstrap/` the skip cases, one consumer per handler, rejected duplicate and invalid names, the empty handler list, label values that match the prepared metrics, and an application that runs a consumer while serving and returns only after it stopped polling. + +`TestEventConsumer` in `backend/integration_test/event_consumer_test.go` uses `bootstrap(t, postgresService, kafkaService)`. Its handler exists only in the test: it writes one row per applied event into `consumer_test.effects`, a table without a unique key that the test creates, so a second effect would stay visible. The sequential cases, each with its own topic and group, are: + +- One event ID delivered three times, twice on partition 0 and once on partition 1, next to another event: the group commits both partitions, each event has exactly one effect row and one marker, and the counters show 2 `applied` and 2 `duplicate`. +- Two consumers race on one event without Kafka: each reads the same record from an in-memory source. The first holds its uncommitted marker inside the handler until the test sees, in `pg_stat_activity`, the second consumer's marker insert waiting for a lock; then the first commits. The result is one effect, `applied` for the first and `duplicate` for the second, without the second calling its handler. +- The same race where the first handler fails after the second started waiting: the first rolls back, the second applies the event, and the first's retry finds the marker. One effect row. +- Restart before commit: a handler writes its effect and then blocks past a 300 ms shutdown grace, as a process killed before the commit. After the stop there is no effect row, no marker, and no committed offset for the group. A new consumer in the same group receives the record, applies it once, and commits offset 1. +- Crash after the database commit but before the offset commit: the effect and marker are committed directly, then the record is consumed. It is a `duplicate`, the handler is not called, and the offset is committed. +- Invalid record followed by a valid one on one partition: one dead letter row with offset 0, the header event ID, class `invalid_record`, zero attempts, the value size and SHA-256, and a reason that does not quote the value; the valid event is applied; offset 2 is committed; the `dead_lettered` counter is 1; and no further dead letter appears within 500 ms. +- A handler that always fails for one event, with 3 attempts and a 200 ms backoff: exactly 3 attempts at least 100 ms apart and within 5 seconds, a `retries_exhausted` dead letter with the event ID, type, and handler error, no effect row of that event because every attempt rolled back, the next event applied, offset 2 committed, a handler failure count of 3, and no further attempt within 500 ms. +- Hard crash before commit: the handler writes its effect, reads its own backend PID, and ends that backend with `pg_terminate_backend`, as a crashed process or a dropped connection would. The backend disappears from `pg_stat_activity`, no effect row, marker, or committed offset remains, and a new member of the group applies the event once. +- A handler that runs `SELECT 1 / 0`, ignores the error, and returns nil: PostgreSQL refuses each commit, the consumer counts 3 handler attempts and no store failure, writes a `retries_exhausted` dead letter, commits offset 1, and leaves no effect or marker. +- Dead letter upsert: the same record written twice keeps one row with the second outcome; another value at the same position gets its own row. +- Rebalance handover with two members of one group: the first member's commits always fail, and it holds a record while a second member joins; the test waits until the group is in `PreparingRebalance`, releases the record, and waits until the group is stable with one partition per member. Each of four events has exactly one effect, the first member handled both first-round events before the rebalance, the joiner received nothing of the moved partition's first round (its position was committed in the revocation, the only commit path left) and counted no duplicate, the first member never tried to commit or handle a record of the moved partition after losing it, and after the first member leaves, the group's offsets are 2 on both partitions, so the moved partition was not rewound. +- An event appended to the outbox through the transactor, published by the relay, and consumed: the decoded event matches the outbox row, so the producer and consumer agree on the envelope. + +`TestPostgresMigrations` also checks that migration 00005 creates and drops both consumer tables. The suite uses one broker, one PostgreSQL, and test-only handlers. It does not measure throughput, does not cover a rebalance under load or with more than two members, broker failover, a member removed after the rebalance timeout, or a real product handler, and does not check alert delivery. ## Integration test sharding diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 0981e14..2764dfd 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` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Потребители событий пока не реализованы. 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. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; продуктовые обработчики пока не зарегистрированы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу. ### Transactional outbox @@ -75,7 +75,7 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction `domain.NewDomainEvent` проверяет событие. Компактный JSON payload ограничен 16 KiB и 32 уровнями вложенности; числа должны помещаться в float64; символы NUL отклоняются, потому что jsonb не может их хранить. jsonb нормализует сохраненный payload (порядок ключей, пробелы, дублирующиеся ключи), поэтому потребители сравнивают JSON-значения, а не байты. Payload содержит только идентификаторы и минимальные факты, но не контакты, токены, пароли, содержимое резюме и документов. -Relay, который публикует эти строки, описан в разделе [Relay outbox](#relay-outbox). Еще запланированы колонки учета повторов (счетчик попыток и последняя ошибка), хранение опубликованных строк и идемпотентные потребители (TASK-010). Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. +Relay, который публикует эти строки, описан в разделе [Relay outbox](#relay-outbox). Идемпотентные потребители описаны в разделе [Обработчики событий](#обработчики-событий). Еще запланированы колонки учета повторов (счетчик попыток и последняя ошибка) и хранение опубликованных строк. Bootstrap пока не подключает transactor, потому что его не использует ни один продуктовый usecase; первая бизнес-транзакция подключит его вместе с общим пулом. ### Relay outbox @@ -112,6 +112,46 @@ Producer требует подтверждения от всех in-sync реп Метрика `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 из работы. +### Обработчики событий + +Реализовано (TASK-010): runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Продуктовых обработчиков нет: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает пустой список, поэтому работающий backend не запускает ни одного обработчика и не открывает для них пул PostgreSQL и группу Kafka. Интеграционные тесты запускают runtime с тестовым обработчиком, который пишет в таблицу, созданную самим тестом; выдуманного бизнес-эффекта нет. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). + +Обработчик реализует три метода: + +- `ConsumerName()`: имя в snake_case длиной не больше 64 символов. Оно задает consumer group Kafka `.` и область дедупликации, поэтому переименованный обработчик заново обрабатывает все события, которые еще хранит топик. +- `Handles(eventType)`: события других типов учитываются как `ignored` и подтверждаются без транзакции. +- `Handle(ctx, unit, event)`: получает декодированный конверт и `outbound.UnitOfWork`, привязанный к транзакции с маркером дедупликации. Эффект использует только этот unit. Ошибка, которая оборачивает `inbound.ErrEventRejected`, окончательная; остальные ошибки повторяются. Ошибки не должны цитировать payload или персональные данные, потому что их текст попадает в журнал и в dead letter. + +Дедупликация идет только по `event_id`. Порядок по `aggregate_version` остается задачей обработчика: повторно запущенный dead letter может прийти после более поздней версии своего агрегата, поэтому обработчик, который хранит состояние агрегата, пропускает уже пройденную версию. + +Одна запись обрабатывается так: + +1. Адаптер Kafka декодирует конверт. Он требует `envelope_version` 1, непустой `event_id`, правила `domain.NewDomainEvent` для типа, версии схемы, типа, ID и версии агрегата, ненулевой `occurred_at`, JSON-объект в `payload` и заголовок `event_id`, если он есть, равный полю конверта. Запись, нарушающая правило, считается невалидной; обработчик ее не видит. Ошибка называет нарушенное правило и никогда не цитирует значение. +2. Одна транзакция READ COMMITTED задает `statement_timeout` и `idle_in_transaction_session_timeout` равными `CONSUMER_HANDLER_TIMEOUT` только для себя, выполняет `INSERT INTO consumer_processed_events (consumer_name, event_id) ... ON CONFLICT DO NOTHING` и проверяет число строк. Ноль строк значит, что событие уже применено: транзакция откатывается, запись считается `duplicate`. Одна строка значит, что обработчик выполняется в той же транзакции и эффект фиксируется вместе с маркером. +3. Offset фиксируется только после этого commit или после записи строки dead letter. + +Почему `ON CONFLICT DO NOTHING` в одной транзакции с эффектом. Маркер вставляется до эффекта, поэтому эффект выполняется только пока его транзакция держит незафиксированный маркер. Параллельная доставка того же события, из другого экземпляра или после ребалансировки, ждет на этом уникальном ключе, пока первая транзакция не завершится: после commit ее вставка затрагивает ноль строк, и эффект пропускается; после rollback ее вставка проходит, и она применяет событие сама. Поэтому эффект не выполняется дважды или параллельно, и результат не зависит от времени. Обычный `INSERT`, который падает на уникальном ключе, ждет так же, но дубликат тогда прерывает транзакцию с SQLSTATE 23505, пишет ожидаемый случай в журнал ошибок PostgreSQL и управляет логикой через ошибку. Проверка через `SELECT` перед вставкой оставляет окно гонки при READ COMMITTED. Серверные таймауты завершают транзакцию зависшего процесса, поэтому его маркер не может бесконечно блокировать дубликат. + +Offsets и партиции. Каждый обработчик - один участник своей группы с выключенным autocommit и режимом franz-go `BlockRebalanceOnPoll`. Он забирает не больше `CONSUMER_MAX_POLL_RECORDS` записей и обрабатывает их по одной в порядке получения, что сохраняет порядок внутри каждой партиции. После пачки он фиксирует для каждой партиции позицию после последней завершенной записи (вместе с ее leader epoch) и только потом разрешает ребалансировку. Ребалансировка ждет этого момента, поэтому commit не попадает в партицию, которой участник уже не владеет. Неудачный commit записывается в журнал; позиция повторяется со следующим commit и при отзыве партиции и отбрасывается при потере партиции, тогда следующий владелец получает записи снова, а маркеры превращают их в дубликаты. Новая группа начинает с самой ранней хранимой записи, поэтому новый обработчик не пропускает события. Адаптер отвергает commit, если завершенные записи не являются для каждой партиции первыми записями последнего чтения без пропусков, поэтому commit никогда не перескакивает незавершенную запись. + +Бюджет ребалансировки. Пачка держит ребалансировку, пока выполняется. Если она длится дольше rebalance timeout, брокер исключает участника, его commit не проходит, и новый владелец обрабатывает записи заново с последнего зафиксированного offset; дедупликация делает это безопасным, но работа повторяется. Таймаут задается явно из `CONSUMER_REBALANCE_TIMEOUT` (по умолчанию 60 секунд), а конфигурация не дает запуститься, если самая медленная запись не помещается в него с запасом 5 секунд. Самая медленная запись без отказа базы - это `CONSUMER_MAX_ATTEMPTS` попыток обработчика, наибольший backoff перед каждым повтором, одна запись dead letter (каждая ограничена `CONSUMER_HANDLER_TIMEOUT`) и один commit offset (`CONSUMER_COMMIT_TIMEOUT`): 42,5 секунды со значениями по умолчанию. Единицей служит запись, потому что обработчик фиксирует завершенное начало пачки сразу после каждой записи, которой понадобился повтор или dead letter, и участник, исключенный во время следующей медленной записи, не заставляет преемника повторять предыдущие. Отказ базы в бюджет не входит: сбои хранилища повторяются без ограничения, а исключение, которое они могут вызвать, лишь повторяет работу. Альтернатива - прерывать пачку, когда franz-go сообщает о заблокированной ребалансировке (`OnPartitionsCallbackBlocked`), - оставила бы прочитанные, но не обработанные записи в партициях, которые участник сохраняет; они были бы пропущены, если не перемотать позицию чтения через `SetOffsets`, а franz-go описывает такой вызов внутри цикла чтения как источник странных эффектов. Статический бюджет проще и проверяется тестами. + +Сбои, повторы и dead letters: + +- Ошибка обработчика: до `CONSUMER_MAX_ATTEMPTS` попыток с тем же backoff, что у relay: ожидание начинается с `CONSUMER_BACKOFF_INITIAL`, удваивается до `CONSUMER_BACKOFF_MAX` и равно половине текущего значения плюс случайная доля второй половины. Каждая попытка ограничена `CONSUMER_HANDLER_TIMEOUT` и откатывает свой эффект и маркер. Когда попытки заканчиваются, запись становится dead letter класса `retries_exhausted`. `inbound.ErrEventRejected` дает `handler_rejected` после одной попытки. Panic обработчика перехватывается, транзакция откатывается, стек пишется в журнал без значения panic, а запись становится `handler_panic`, поэтому одно событие не роняет процесс при каждой доставке. +- Невалидная запись: dead letter класса `invalid_record` с нулем попыток. +- Отвергнутый commit: если обработчик вернул nil, а PostgreSQL отказался фиксировать транзакцию, виновато событие, а не база. `pgx.ErrTxCommitRollback` (обработчик проигнорировал упавший запрос, и транзакция была прервана) и SQLSTATE класса 23 (отложенное ограничение целостности) соответствуют `outbound.ErrEventEffectRejected`; класс 40 (сбой сериализации или взаимная блокировка) соответствует `outbound.ErrTransactionConflict`. Оба считаются попыткой обработчика и повторяются с backoff, поэтому детерминированный отказ заканчивается `retries_exhausted`, а не бесконечными повторами. Класс 40 по природе временный и обычно проходит со следующей попытки; он все равно расходует попытку, чтобы обработчик, который каждый раз попадает во взаимную блокировку, не повторялся вечно. То же относится к panic в `Handles`: она дает `handler_panic` без попытки. +- Сбой хранилища (начало транзакции, маркер, commit, потерянный в сети, или запись dead letter): он не расходует попытки обработчика, потому что событие не виновато. Обработчик повторяет с тем же backoff, пока база не ответит или не начнется остановка, и никогда не отправляет запись в dead letters из-за недоступной базы. Offset тем временем не фиксируется, поэтому отказ базы останавливает партицию без горячего цикла и без потерь. +- Когда строка dead letter записана, offset фиксируется, и партиция продолжает со следующей записи. Dead letter не пишет маркер, поэтому повторный запуск события потом применит его. + +`consumer_dead_letters` хранит имя обработчика, топик, партицию, offset, `event_id` (из конверта или из заголовка `event_id` невалидной записи; NULL, если ни то ни другое не UUID), `event_type` (NULL для невалидной записи), класс, причину не длиннее 256 печатных символов, число попыток, размер значения, его SHA-256 и время. Уникальный ключ по обработчику, топику, партиции, offset и хешу значения оставляет одну строку на запись: когда та же запись падает снова, после падения до commit offset или перемотки группы, строка получает новые класс, причину, число попыток и время. Хеш входит в ключ, потому что удаленный и заново созданный топик повторно использует offsets; другое значение на той же позиции - это другая запись, и она получает свою строку, а не теряется. Ошибки обработчика попадают в причину и журналы только после того, как хранилище заменило текст ошибки PostgreSQL внутри них на SQLSTATE и ограничение, потому что сообщение PostgreSQL может цитировать значения строк. Само значение записи не хранится. Валидное событие и так лежит в `outbox_events` под своим `event_id`, это же источник повторного запуска, поэтому вторая копия лишь дублировала бы данные, которые события могут нести позже, и таблица dead letters хранила бы их без правила хранения. Невалидная запись пришла не от relay; пока топик ее хранит, оператор может прочитать ее по топику, партиции и offset, а SHA-256 подтверждает, что это то же значение. Порядок повторного запуска описан в [DEPLOY.md](DEPLOY.md#dead-letters-и-повторный-запуск). + +Жизненный цикл. При старте выполняются миграции, затем wire собирает обработчики: один пул PostgreSQL на всех с одним соединением на обработчик (обработчик держит одну транзакцию за раз и пишет dead letter только после ее завершения) и по одному клиенту franz-go на обработчик. В этот момент ничего не подключается, поэтому недоступные Kafka или база не блокируют запуск. Приложение открывает listeners, запускает relay и каждый обработчик рядом с HTTP-серверами и начинает обслуживать запросы. По SIGTERM HTTP-серверы, relay и обработчики останавливаются одновременно; ни один не зависит от другого. Обработчик не начинает новую запись и сразу прерывает ожидание backoff. Попытка в процессе получает `CONSUMER_SHUTDOWN_GRACE` на commit; после этого она отменяется, и ее транзакция откатывается. Завершенные записи фиксируются за `CONSUMER_COMMIT_TIMEOUT`; незавершенные не фиксируются никогда, поэтому их обработает следующий участник группы. Bootstrap ждет все workers до cleanup, в котором участники выходят из групп параллельно, каждый за `CONSUMER_COMMIT_TIMEOUT` плюс 2 секунды (финальный отзыв фиксирует только завершенные позиции), а затем закрывается пул. Полный бюджет остановки описан в [DEPLOY.md](DEPLOY.md#обработчики-событий). + +Компромиссы: один обработчик обрабатывает одну запись за раз на одном соединении. Параллельность дают дополнительные экземпляры backend в той же группе, но не больше числа партиций топика (по умолчанию 3). Маркеры хранятся бессрочно; их очистка запланирована и должна покрывать горизонт повторного запуска, потому что удаленный маркер позволит повторному запуску применить событие еще раз. Задача очистки добавит и нужный ей индекс по `processed_at`; до нее каждое примененное событие платило бы за индекс, который никто не читает. + +Метрика `lincodex_event_consumer_records_total{consumer,outcome}` считает завершенные записи по `applied`, `duplicate`, `ignored` или `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` считает каждую неудачную операцию, включая последнюю попытку обработчика перед dead letter, по `handler`, `store`, `poll` (неудачное чтение шины событий) или `commit` (неудачный commit offset). Метка consumer берется из зарегистрированных в коде имен, поэтому число рядов ограничено. Все ряды обработчика существуют с его запуска со значением 0. Журналы содержат обработчик, группу, топик, партицию, offset, ID и тип события, но никогда не значение или payload. + ### Почтовый транспорт Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий; слой доставки запланирован. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). @@ -233,11 +273,11 @@ backend/ internal/ domain/ плоский пакет; DomainEvent, типы identity, продуктовая политика usecase/health/ operational readiness usecase - port/inbound/ inbound граница readiness + port/inbound/ inbound границы readiness и обработчиков событий usecase/identity/ проверка пароля до хеширования (Credentials) usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем для usecase identity и доставки (пока не подключен) - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации событий, identity, политики, хеширования паролей и почты + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, политики, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -246,18 +286,20 @@ backend/ router.go сборка chi router adapter/secondary/ argon2id/ hasher паролей Argon2id с бюджетом памяти - kafka/ publisher событий на franz-go: конверт записи и создание топика событий + kafka/ publisher событий и участник consumer group на franz-go: конверт записи, его декодирование и создание топика событий mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend ml/api/ generated client из backend/codegen/ogen-ml.yml - postgres/ pool, migrator, transactor, запись outbox и хранилище relay, репозитории 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 и остановка + worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка + worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers bootstrap/ конфигурация, wiring, lifecycle, shutdown - db/ встроенные миграции и SQL-запросы; таблицы outbox, identity и политики + db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики и обработчиков событий codegen/ конфигурация ogen и sqlc pkg/ резерв для обоснованных общих технических helpers ``` @@ -266,7 +308,7 @@ backend/ `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, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, репозитории 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, runtime обработчиков событий без зарегистрированных продуктовых обработчиков, репозитории 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/`. @@ -410,7 +452,7 @@ contact_grant относится к паре кандидат-компания ## Будущее расширение -Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox и ее транзакционная запись реализованы (см. "Transactional outbox" выше); relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. +Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox, ее транзакционная запись, relay и runtime обработчиков реализованы (см. "Transactional outbox", "Relay outbox" и "Обработчики событий" выше); продуктовые обработчики и дополнительные топики запланированы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера. k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 55f99d7..71d0b5c 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -87,7 +87,7 @@ Backend запускает relay outbox в своем процессе рядо | `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`. +`SHUTDOWN_TIMEOUT` ограничивает и relay: проход, который идет в момент остановки, получает это время, чтобы закончить, иначе он откатывается, и его события остаются в ожидании. Compose задает backend `stop_grace_period: 30s`, что покрывает весь бюджет остановки из раздела [Обработчики событий](#обработчики-событий), чтобы 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 реплик, поэтому с этими значениями подтвержденное событие переживает потерю одного брокера, а при недоступности двух брокеров из трех запись останавливается, а не попадает на единственную реплику. @@ -97,6 +97,73 @@ Relay создает отсутствующий топик и никогда н Очередь неопубликованных событий видна на внутреннем 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 запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: продуктовых обработчиков нет, поэтому backend пишет в журнал `no event consumer is registered`, не запускает ни одного обработчика и не открывает consumer group; настройки ниже начнут действовать, когда появится обработчик. Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены. + +| Переменная | По умолчанию | Назначение | +| --- | --- | --- | +| `CONSUMER_ENABLED` | `true` | `true` или `false`. При `false` или без `DATABASE_URL` обработчики не работают, и события ждут в Kafka, пока их хранит топик. | +| `CONSUMER_GROUP_PREFIX` | `lincodex` | Префикс ID каждой consumer group, до 128 латинских букв, цифр, точек, подчеркиваний или дефисов. Смена префикса создает новые группы, которые читают топик с самой ранней хранимой записи; маркеры дедупликации превращают уже примененные события в дубликаты. | +| `CONSUMER_MAX_ATTEMPTS` | `5` | Попытки обработчика для одного события до перевода в dead letters, от 1 до 20. Сбои базы вне обработчика не считаются. Должно укладываться в бюджет ребалансировки ниже. | +| `CONSUMER_BACKOFF_INITIAL` | `500ms` | Пауза после первой неудачной попытки; удваивается после каждой следующей неудачи. | +| `CONSUMER_BACKOFF_MAX` | `10s` | Наибольшая пауза между попытками, от `CONSUMER_BACKOFF_INITIAL` до 5m. | +| `CONSUMER_HANDLER_TIMEOUT` | `5s` | Предел одной попытки и одной записи dead letter, от 100ms до 5m. Это же значение задает `statement_timeout` и `idle_in_transaction_session_timeout` транзакции обработчика на стороне сервера. | +| `CONSUMER_MAX_POLL_RECORDS` | `100` | Записей за одно чтение, от 1 до 10000. Обработчик обрабатывает их, удерживая ребалансировку группы, поэтому меньшее значение сокращает это удержание. | +| `CONSUMER_COMMIT_TIMEOUT` | `5s` | Предел одного commit offset, от 100ms до 1m. | +| `CONSUMER_SHUTDOWN_GRACE` | `5s` | Время, за которое запись в процессе должна зафиксироваться после начала остановки; не больше `SHUTDOWN_TIMEOUT`. После него транзакция откатывается, offset не фиксируется, и запись обработает следующий участник. | +| `CONSUMER_REBALANCE_TIMEOUT` | `60s` | Rebalance timeout Kafka для каждого участника consumer group, от 10s до 30m. Старт не проходит, если он не больше самой медленной записи хотя бы на 5 секунд. | + +Бюджет ребалансировки. Обработчик удерживает ребалансировку группы, пока обрабатывает прочитанную пачку, а участника, который держит ее дольше `CONSUMER_REBALANCE_TIMEOUT`, исключают из группы, и его записи заново обрабатывает следующий владелец. Самая медленная запись без отказа базы занимает (`CONSUMER_MAX_ATTEMPTS` + 1) раз по `CONSUMER_HANDLER_TIMEOUT` (попытки и запись dead letter), наибольший backoff перед каждым повтором и один `CONSUMER_COMMIT_TIMEOUT`. Со значениями по умолчанию это 6 x 5s + (0.5 + 1 + 2 + 4)s + 5s = 42.5s, меньше 60s - 5s. Конфигурация, которая не помещается, не проходит старт, а ошибка называет вычисленное значение; уменьшите попытки или таймауты либо увеличьте `CONSUMER_REBALANCE_TIMEOUT`, но тогда группа дольше ждет участника, который перестал отвечать. После каждой записи, которой понадобился повтор или dead letter, обработчик сразу фиксирует offsets, поэтому в бюджет должна помещаться одна медленная запись, а не вся пачка. + +Бюджет остановки со значениями по умолчанию: + +1. Параллельно: HTTP-серверы завершаются за `SHUTDOWN_TIMEOUT` (10s); проход relay получает те же 10s и до 5s на откат; каждый обработчик получает `CONSUMER_SHUTDOWN_GRACE` (5s) на запись в процессе, до 5s на откат отмененной транзакции и `CONSUMER_COMMIT_TIMEOUT` (5s) на offsets. Эта фаза заканчивается не позже чем через 15s. +2. Затем все обработчики параллельно выходят из своих групп, каждый за `CONSUMER_COMMIT_TIMEOUT` плюс 2s (7s), а клиенты и пулы закрываются примерно за 1s. + +Это около 23s при любом числе обработчиков. Compose задает backend `stop_grace_period: 30s`, чтобы Docker не убил процесс во время фиксации транзакции; увеличивайте его, когда увеличиваете `SHUTDOWN_TIMEOUT`, `CONSUMER_SHUTDOWN_GRACE` или `CONSUMER_COMMIT_TIMEOUT`. + +Обработчику нужно одно соединение с PostgreSQL; все обработчики процесса делят один пул такого же размера. Несколько экземпляров backend делят партиции группы, поэтому события одного обработчика одновременно обрабатывают не больше `KAFKA_EVENTS_TOPIC_PARTITIONS` экземпляров; остальные остаются простаивающими участниками. + +Оператор следит за двумя счетчиками на внутреннем endpoint /metrics. `lincodex_event_consumer_records_total{consumer,outcome}` считает завершенные записи: `applied`, `duplicate` (ожидаемо после повторной доставки), `ignored` (другой тип события) и `dead_lettered`. Alert ставится на любой рост `dead_lettered`; все ряды существуют со значением 0 с запуска обработчика, поэтому `increase(...[15m]) > 0` срабатывает на первый dead letter. `lincodex_event_consumer_failures_total{consumer,stage}` считает каждую неудачную операцию, включая последнюю попытку обработчика перед dead letter: растущий `store` при неподвижном `applied` значит, что обработчик не может достучаться до PostgreSQL и его партиция ждет; растущий `handler` значит, что события продолжают падать; растущий `poll` значит, что обработчик не может читать Kafka (брокер недоступен, топика нет или ошибка группы); растущий `commit` значит, что offsets не сохраняются, и после перезапуска или ребалансировки записи придут снова. Alert ставится на сбои `poll` или `commit`, которые продолжаются несколько минут, например `increase(...{stage=~"poll|commit"}[5m]) > 0` в течение 10 минут. Журналы обработчиков помечены компонентом `event_consumer` и содержат группу, топик, партицию, offset, ID и тип события, но никогда не значение записи. Dead letter пишется в журнал на уровне error сообщением `event dead-lettered; the offset is committed and the record needs an operator` с классом и причиной. + +#### Dead letters и повторный запуск + +Dead letter - запись, от которой обработчик отказался, чтобы партиция могла идти дальше. `error_class` объясняет причину: + +- `invalid_record`: значение не является валидным конвертом события. Оно пришло не от relay; найдите producer, который пишет в топик. Повторно запустить такую запись как есть нельзя. +- `handler_rejected`: обработчик сообщил, что событие нельзя применить никогда, например из-за неизвестной `schema_version`. +- `handler_panic`: обработчик упал с panic; стек есть в строке журнала `event handler panicked` с тем же ID события. +- `retries_exhausted`: обработчик упал `CONSUMER_MAX_ATTEMPTS` раз, например из-за ошибки в коде или в вызываемой зависимости. + +Список выводится через psql в контейнере базы (проект `app` по умолчанию): + + docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ + exec postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"' + + SELECT id, consumer_name, error_class, event_id, event_type, topic, + kafka_partition, kafka_offset, attempts, reason, dead_lettered_at + FROM consumer_dead_letters ORDER BY id; + +Таблица не хранит значение записи; `value_size` и `value_sha256` его идентифицируют. Повторно запускайте dead letter только после устранения причины, обычно после выкладки исправленного обработчика: + +1. Повторно опубликуйте одно событие из outbox. Для dead letter с `event_id` и классом, отличным от `invalid_record`: + + UPDATE outbox_events SET published_at = NULL WHERE event_id = ''; + + Relay публикует событие снова с тем же `event_id` по новому offset. Его получают все обработчики: те, кто уже применил его, находят свой маркер и считают `duplicate`, а упавший обработчик применяет событие, потому что dead letter не пишет маркер. Это работает, пока строка outbox существует (опубликованные строки пока не удаляются), в том числе после того, как Kafka удалила исходную запись. Событие может прийти после более поздних версий своего агрегата; обработчики пропускают уже пройденные версии. +2. Или перемотайте группу, пока Kafka еще хранит запись. Kafka сбрасывает offsets только у пустой группы, поэтому сначала остановите всех участников (экземпляры backend или `CONSUMER_ENABLED=false`). Участник, которого убили, а не остановили, остается в группе до истечения своего session timeout (по умолчанию 45 секунд); выполните команду ниже с `--describe` вместо параметров перемотки и дождитесь, пока она не покажет ни одного активного участника. Затем: + + docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ + exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-consumer-groups.sh \ + --bootstrap-server localhost:9092 --group lincodex. \ + --topic lincodex.domain.events: --reset-offsets --to-offset --execute + + После этого группа заново читает партицию с этого offset. Уже примененные записи становятся дубликатами; другие dead letters в диапазоне пробуются снова, и повторно упавшая запись обновляет свою строку новыми классом, причиной и числом попыток, а не добавляет еще одну. `--describe` показывает и offsets, и отставание группы. +3. Проверьте результат и закройте dead letter: событие применено, если `SELECT 1 FROM consumer_processed_events WHERE consumer_name = '' AND event_id = ''` возвращает строку. Затем удалите строку через `DELETE FROM consumer_dead_letters WHERE id = ` или оставьте ее как запись об инциденте. + +Чтобы посмотреть `invalid_record`, пока топик ее хранит, прочитайте ровно эту запись через `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic --partition --offset --max-messages 1` и сравните ее SHA-256 с `value_sha256`. Значение может содержать персональные данные, поэтому не вставляйте его в задачи и чаты. + ## Почта 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 17b716a..c59f828 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; producer relay outbox и integration tests | backend/go.mod | +| franz-go (`kgo`, `kadm`) | v1.22.1, kadm v1.19.0; producer relay outbox, участники consumer group обработчиков событий и 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 запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka, и события пока никто не читает. +- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий есть, но продуктовые обработчики не зарегистрированы, поэтому события пока никто не читает; см. [Обработчики событий](#обработчики-событий). - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 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). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, продуктовые обработчики событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` и таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -181,10 +181,18 @@ goose выполняет каждую миграцию в отдельной т ### 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()` в своей бизнес-транзакции. +Relay переносит зафиксированные строки `outbox_events` в Kafka. Цикл находится в `backend/internal/worker/outboxrelay/`, а его backoff - в `backend/internal/worker/retry/`; он зависит от портов `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). +### Обработчики событий + +Runtime обработчиков применяет события из Kafka к собственному состоянию сервиса, по одному разу на обработчик. Цикл находится в `backend/internal/worker/eventconsumer/`; он зависит от порта `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`) и портов `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` - участник группы на franz-go, который декодирует конверт и фиксирует offsets, а `postgres.EventConsumerStore` выполняет транзакцию дедупликации запросами из `backend/db/queries/event_consumer.sql`. Backoff общий с relay и находится в `backend/internal/worker/retry/`. + +Продуктовых обработчиков пока нет. Чтобы добавить обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`. + +Backend, запущенный напрямую с зарегистрированным обработчиком и `DATABASE_URL`, читает события из `KAFKA_BROKERS`; задайте `CONSUMER_ENABLED=false`, если это не нужно. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий); настройки, метрики и порядок работы с dead letters - в [DEPLOY.md](DEPLOY.md#обработчики-событий); тесты - в [TESTING.md](TESTING.md#тесты-обработчиков-событий). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index d4b30c3..ab28e88 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -38,7 +38,7 @@ 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 (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых событий и их потребителей в 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)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых событий и продуктовых обработчиков в Kafka и нет реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. @@ -74,7 +74,7 @@ Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx ## Тесты 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/`). +Unit-тесты (`make -C backend test`) покрывают конверт записи, ключ и заголовки, а также ошибку для некорректного payload без его цитирования (`internal/adapter/secondary/kafka/`), публикацию и создание топика, которые завершаются ошибкой в пределах таймаута публикации плюс 2 секунды запаса на планирование, когда брокер недоступен (тесты проверяют затраченное время), преобразование неизвестного топика в `ErrEventDestinationMissing`, сравнение существующего топика с настроенной раскладкой, общее расписание backoff с jitter и без него (`internal/worker/retry/`), проходы 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 с тестовым агрегатом и последовательно выполняет случаи, у каждого свой топик: @@ -88,7 +88,28 @@ Unit-тесты (`make -C backend test`) покрывают конверт за - `Backlog` возвращает ноль для пустого outbox и два ожидающих события с положительным возрастом после двух записей. - `Prepare` создает топик с настроенным числом партиций, фактором репликации брокера по умолчанию и `min.insync.replicas` на уровне топика и повторно принимает существующий топик. -Набор работает с одним брокером и одним PostgreSQL. Он не измеряет пропускную способность и задержку, не покрывает переключение брокеров и репликацию и не тестирует потребителей; удаление дубликатов у потребителя относится к TASK-010. +Набор работает с одним брокером и одним PostgreSQL. Он не измеряет пропускную способность и задержку, и не покрывает переключение брокеров и репликацию. Обработчики событий описаны в разделе [Тесты обработчиков событий](#тесты-обработчиков-событий). + +## Тесты обработчиков событий + +Unit-тесты (`make -C backend test`) покрывают runtime обработчиков с поддельными источником, хранилищем и обработчиком (`internal/worker/eventconsumer/`): записи `applied`, `duplicate` и `ignored`, зафиксированные в порядке получения; сбои хранилища, которые повторяются сверх лимита попыток без dead letter, а offset фиксируется только после успеха хранилища; обработчик, который все время падает, повторяется ровно `MaxAttempts` раз не чаще минимального backoff, а затем уходит в dead letters с ID и типом события, размером значения и SHA-256, пока следующая запись применяется; `ErrEventRejected` и panic, которые уходят в dead letters после одной попытки без цитирования значения panic; невалидную запись, которая уходит в dead letters без вызова обработчика, причем commit ждет, пока две неудачные записи dead letter не пройдут; остановку, которая бросает зависший обработчик после grace без фиксации его и всего после него; запись, которая завершается в пределах grace и фиксируется, тогда как следующая не начинается; отсутствие повторов и dead letters во время остановки; backoff после неудачных чтений; commit, который PostgreSQL отвергает после того, как обработчик проглотил ошибку, считается попыткой и заканчивается `retries_exhausted`; конфликт сериализации при commit повторяется как попытка; panic в `Handles` уходит в dead letters без цитирования значения; начало пачки фиксируется сразу после dead letter, до начала следующей записи; счетчики сбоев `poll` и `commit`; очистку причины. Тесты адаптера PostgreSQL проверяют классификацию отвергнутого, конфликтного и сетевого сбоя commit и то, что ошибки обработчика сохраняют идентичность без сообщения PostgreSQL. Они же покрывают декодирование конверта и его согласованность с producer, каждое отвергнутое правило конверта без цитирования значения и учет commit участника группы, включая отказ для завершенных записей, которые не являются для каждой партиции началом последнего чтения без пропусков (`internal/adapter/secondary/kafka/`), настройки обработчиков и бюджет ребалансировки, включая описанное в документации значение по умолчанию 42,5 секунды (`config/`), счетчики обработчиков (`internal/adapter/secondary/prometheus/`), а в `internal/bootstrap/` - случаи пропуска, один обработчик на handler, отказ для повторяющихся и недопустимых имен, пустой список обработчиков, значения меток, совпадающие с подготовленными метриками, и приложение, которое запускает обработчик вместе с серверами и возвращается только после того, как он перестал читать. + +`TestEventConsumer` в `backend/integration_test/event_consumer_test.go` использует `bootstrap(t, postgresService, kafkaService)`. Его обработчик существует только в тесте: он пишет одну строку на примененное событие в `consumer_test.effects`, таблицу без уникального ключа, которую создает тест, поэтому второй эффект остался бы виден. Последовательные случаи, каждый со своими топиком и группой: + +- Один ID события доставлен трижды, дважды в партицию 0 и один раз в партицию 1, рядом с другим событием: группа фиксирует обе партиции, у каждого события ровно одна строка эффекта и один маркер, а счетчики показывают 2 `applied` и 2 `duplicate`. +- Два обработчика соревнуются за одно событие без Kafka: каждый читает одну и ту же запись из источника в памяти. Первый держит незафиксированный маркер внутри обработчика, пока тест не увидит в `pg_stat_activity`, что вставка маркера второго ждет блокировку; затем первый фиксируется. Итог: один эффект, `applied` у первого и `duplicate` у второго, причем второй не вызывает обработчик. +- Та же гонка, в которой обработчик первого падает после того, как второй начал ждать: первый откатывается, второй применяет событие, а повтор первого находит маркер. Одна строка эффекта. +- Перезапуск до commit: обработчик пишет эффект и блокируется дольше grace остановки в 300 ms, как процесс, убитый до commit. После остановки нет ни строки эффекта, ни маркера, ни зафиксированного offset группы. Новый обработчик в той же группе получает запись, применяет ее один раз и фиксирует offset 1. +- Падение после commit в базе, но до commit offset: эффект и маркер фиксируются напрямую, затем запись читается. Она становится `duplicate`, обработчик не вызывается, offset фиксируется. +- Невалидная запись, за которой в той же партиции идет валидная: одна строка dead letter с offset 0, ID события из заголовка, классом `invalid_record`, нулем попыток, размером значения и SHA-256 и причиной, которая не цитирует значение; валидное событие применяется; фиксируется offset 2; счетчик `dead_lettered` равен 1; за 500 ms новых dead letters не появляется. +- Обработчик, который всегда падает на одном событии, с 3 попытками и backoff 200 ms: ровно 3 попытки не чаще чем через 100 ms и в пределах 5 секунд, dead letter `retries_exhausted` с ID и типом события и ошибкой обработчика, ни одной строки эффекта этого события, потому что каждая попытка откатилась, следующее событие применяется, фиксируется offset 2, счетчик сбоев обработчика равен 3, и за 500 ms новых попыток нет. +- Жесткое падение до commit: обработчик пишет эффект, читает PID своего backend и завершает его через `pg_terminate_backend`, как это сделали бы упавший процесс или оборванное соединение. Backend исчезает из `pg_stat_activity`, не остается ни строки эффекта, ни маркера, ни зафиксированного offset, а новый участник группы применяет событие один раз. +- Обработчик, который выполняет `SELECT 1 / 0`, игнорирует ошибку и возвращает nil: PostgreSQL отвергает каждый commit, обработчик насчитывает 3 попытки обработчика и ни одного сбоя хранилища, пишет dead letter `retries_exhausted`, фиксирует offset 1 и не оставляет ни эффекта, ни маркера. +- Повторная запись dead letter: одна и та же запись, записанная дважды, оставляет одну строку со вторым исходом; другое значение на той же позиции получает свою строку. +- Передача партиции между двумя участниками одной группы: commit первого участника всегда падает, и он держит запись, пока присоединяется второй; тест ждет состояния группы `PreparingRebalance`, отпускает запись и ждет, пока группа не станет стабильной с одной партицией у каждого участника. У каждого из четырех событий ровно один эффект, первый участник обработал оба события первого раунда до ребалансировки, второй не получил ничего из первого раунда переданной партиции (ее позиция зафиксирована при отзыве, единственным оставшимся путем commit) и не насчитал дубликатов, первый участник после потери партиции не пытался ни фиксировать, ни обрабатывать ее записи, а после выхода первого участника offsets группы равны 2 в обеих партициях, то есть переданная партиция не перемотана назад. +- Событие, добавленное в outbox через transactor, опубликованное relay и прочитанное обработчиком: декодированное событие совпадает со строкой outbox, значит producer и consumer одинаково понимают конверт. + +`TestPostgresMigrations` дополнительно проверяет, что миграция 00005 создает и удаляет обе таблицы обработчиков. Набор использует один брокер, один PostgreSQL и тестовые обработчики. Он не измеряет пропускную способность, не покрывает ребалансировку под нагрузкой или с более чем двумя участниками, переключение брокеров, исключение участника после rebalance timeout и реальный продуктовый обработчик и не проверяет доставку alerts. ## Шардирование интеграционных тестов