feat(events): add idempotent Kafka event consumer runtime

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

No files matched your search

+51 -9
View File
@@ -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 `<CONSUMER_GROUP_PREFIX>.<name>` 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.
+68 -1
View File
@@ -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 `<CONSUMER_GROUP_PREFIX>.<consumer name>`, 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 = '<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.<consumer> \
--topic lincodex.domain.events:<partition> --reset-offsets --to-offset <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 = '<consumer>' AND event_id = '<event_id>'` returns a row. Then delete the row with `DELETE FROM consumer_dead_letters WHERE id = <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 <topic> --partition <partition> --offset <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.
+12 -4
View File
@@ -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.
+24 -3
View File
@@ -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
+51 -9
View File
@@ -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 `<CONSUMER_GROUP_PREFIX>.<name>` и область дедупликации, поэтому переименованный обработчик заново обрабатывает все события, которые еще хранит топик.
- `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.
+68 -1
View File
@@ -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` как участник группы `<CONSUMER_GROUP_PREFIX>.<имя обработчика>`, применяет каждое событие один раз и фиксирует 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 = '<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.<consumer> \
--topic lincodex.domain.events:<partition> --reset-offsets --to-offset <offset> --execute
После этого группа заново читает партицию с этого offset. Уже примененные записи становятся дубликатами; другие dead letters в диапазоне пробуются снова, и повторно упавшая запись обновляет свою строку новыми классом, причиной и числом попыток, а не добавляет еще одну. `--describe` показывает и offsets, и отставание группы.
3. Проверьте результат и закройте dead letter: событие применено, если `SELECT 1 FROM consumer_processed_events WHERE consumer_name = '<consumer>' AND event_id = '<event_id>'` возвращает строку. Затем удалите строку через `DELETE FROM consumer_dead_letters WHERE id = <id>` или оставьте ее как запись об инциденте.
Чтобы посмотреть `invalid_record`, пока топик ее хранит, прочитайте ровно эту запись через `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1` и сравните ее SHA-256 с `value_sha256`. Значение может содержать персональные данные, поэтому не вставляйте его в задачи и чаты.
## Почта
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
+12 -4
View File
@@ -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/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
+24 -3
View File
@@ -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.
## Шардирование интеграционных тестов