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