feat(backend): add transactional outbox and embedded goose migrations

This commit is contained in:
shira committed 2026-10-05 23:32:43 +03:00
1 parent 653f3775f8
commit 15e2e50561
40 files changed
+2471 -67

No files matched your search

+36 -9
View File
@@ -44,13 +44,38 @@ The planned backend boundaries are:
Shared Go configuration belongs in backend/config/ outside internal. wahrwelt-kit logkit 0.6.0, httpkit 0.7.0, and cachekit 0.7.0 currently provide technical functions. Metrics use bounded custom collector/middleware code, and pgxpool collection must not block startup. pgkit and httpkit/metrics are not currently used. Technical libraries do not own product rules. Do not add unselected JWT or WebSocket dependencies for hypothetical features.
PostgreSQL with pgx, sqlc, and goose remains the planned database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment.
PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL; sqlc generates typed adapters. goose manages versioned migrations: the SQL files are embedded in the binary, and the backend applies them at startup under a PostgreSQL advisory lock before it opens its listeners. wire provides compile-time dependency construction in bootstrap, with no runtime DI container. API and worker share the database pool in the planned single-process deployment.
Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet.
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, while the Go client, outbox, and 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 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.
### Transactional outbox
Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns:
- `position`: a bigint identity, unique and monotonic in insertion order; the relay scans by it.
- `event_id`: uuid primary key, a UUIDv7 generated in Go.
- `event_type`: a lowercase dotted name of at most 128 bytes.
- `schema_version`: an integer above zero.
- `aggregate_type`: snake_case, at most 64 bytes.
- `aggregate_id`: a uuid.
- `aggregate_version`: a bigint above zero.
- `payload`: a jsonb object.
- `occurred_at`: `clock_timestamp()` at insert. It is informational only and does not define order.
- `published_at`: null until the relay publishes the row.
A unique key on aggregate type, aggregate ID, aggregate version, and event type rejects a second event of the same type for the same aggregate version. A partial index on `position` where `published_at` is null serves the relay scan. CHECK constraints repeat the domain rules for versions, names, and the object payload as a backstop. The payload size limit lives only in Go, because the jsonb text and binary sizes differ from the compact input and a database length check could reject an event the domain accepted.
A usecase writes through outbound ports. `Transactor.WithinTransaction(ctx, fn)` opens one READ COMMITTED transaction and passes a `UnitOfWork`; every repository it returns, including `Outbox().Append(ctx, events...)`, uses that transaction. The transaction commits when fn returns nil and rolls back when fn returns an error, panics, or its context is canceled. Calling `WithinTransaction` again with the callback context returns `outbound.ErrNestedTransaction` instead of opening a second connection. A conflict on the event ID or the unique key returns an error that wraps `outbound.ErrOutboxEventConflict` and names the constraint. A network error during commit leaves the outcome unknown, so callers that retry must be idempotent.
The outbox uniqueness rule is a backstop, not concurrency control. Aggregate updates still check the expected version (`UPDATE ... WHERE version = $n`), so a stale writer fails before it records an event.
`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.
## Repository map and package purpose
@@ -58,13 +83,14 @@ The MVP does not add a separate vector database, Kubernetes, or a search microse
api/core/ public browser-to-Go contract and bundle
api/ml/ internal Go-to-ML contract and bundle
backend/cmd/app/main.go calls bootstrap.Run and reports errors
backend/cmd/migrate/ local migration status, up, and down-one
backend/config/ shared runtime configuration
backend/internal/domain/ product invariants, planned modules
backend/internal/usecase/ application operations and orchestration
backend/internal/port/ inbound and outbound interfaces
backend/internal/adapter/ primary HTTP and secondary integrations
backend/internal/bootstrap/ dependency wiring and process lifecycle
backend/db/ migrations and SQL queries
backend/db/ migrations, SQL queries, and the embedded migration set
backend/codegen/ ogen server and ML-client configs, sqlc
frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ Orval configuration
@@ -81,10 +107,10 @@ backend/
cmd/app/main.go calls bootstrap.Run and reports errors
config/ shared runtime configuration
internal/
domain/ flat package; currently only .gitkeep
domain/ flat package; DomainEvent for the outbox
usecase/health/ operational readiness usecase
port/inbound/ readiness input boundary
port/outbound/ readiness, cache, and object storage boundaries
port/outbound/ readiness, cache, object storage, transaction, and outbox boundaries
adapter/primary/http/
api/ generated ogen handler
middleware/ request metrics
@@ -93,21 +119,22 @@ backend/
router.go chi composition
adapter/secondary/
ml/api/ generated client from backend/codegen/ogen-ml.yml
postgres/ pool, migrator, transactor, outbox writer, 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
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ migrations and SQL queries; no product schema yet
db/ embedded migrations and SQL queries; outbox table, no product schema yet
codegen/ ogen and sqlc configs
pkg/ reserved for justified shared technical helpers
```
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. Until the types are defined, the directory contains only `.gitkeep`.
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.
Product domain types and usecase modules, mail/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.
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, a PostgreSQL health query, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, 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, a Redis cache adapter, and a SeaweedFS S3 adapter. Accounts, resumes, assessments, invitations, worker jobs, file workflows, mail, 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 `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
@@ -210,7 +237,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo
## Future extensions
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node; the outbox, relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table and its transactional writer are implemented (see "Transactional outbox" above); the relay, topics, and consumers are planned and not implemented. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy.
+2
View File
@@ -11,6 +11,8 @@ Install Docker Engine and the Docker Compose plugin. At the repository root, cop
deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Kafka, Go, and Nginx communicate on the Compose network.
Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass `DATABASE_MIGRATE_ON_START`, so the deployed backend always migrates at startup, and the PostgreSQL role in `DATABASE_URL` needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. See [DEVELOPMENT.md](DEVELOPMENT.md#database-migrations).
The backend build context is `backend/`, so Docker applies `backend/.dockerignore`. Local tools, caches, environment files, and build outputs are excluded from that context.
The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data.
+21 -3
View File
@@ -40,7 +40,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` and `tool`) |
| mockery | v3.8.0 | backend/go.mod (`tool`) |
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
| goose | v3.28.0 | backend/go.mod (`tool`) |
| goose | v3.28.0 | backend/go.mod (`require` and `tool`) |
| 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 |
@@ -48,14 +48,14 @@ The repository contains a verifiable technical scaffold, not a product. Values b
What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, and a 404 for an unknown API route; it does not start ML.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, and a transactor with the transactional outbox writer; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap.
- 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 a home page, 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 backend has no Go Kafka client, topics, or readiness check for Kafka.
- 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, mail delivery, the Go Kafka client, the transactional outbox and its relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ has no business schema, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. 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, mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains only the outbox table and no business schema, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
## Install and work loop
@@ -141,6 +141,24 @@ ML runs as a separate FastAPI process. It currently provides operational health/
Write all source comments and docstrings in English. Keep canonical agent instructions in one English version; maintain user documentation in Russian and English.
### Database migrations
Migrations are goose SQL files in `backend/db/migrations/` named `NNNNN_description.sql` with sequential five-digit versions. Each file has a `-- +goose Up` section and a working `-- +goose Down` section. sqlc reads the same directory as its schema, and `make -C backend lint-sql` lints it. `backend/db/migrations.go` embeds the files, so the binary applies exactly the schema it was built with. `make -C backend check` loads the embedded set without a database and fails on a malformed name, a missing Down section, or a duplicate version. A deployed migration is immutable; change the schema with a new file. Two branches that add the same version must renumber before merging. To create a file with the next sequential number, run `go tool goose -dir db/migrations -s create <name> sql` in `backend/`.
goose runs each migration in its own transaction. A statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`, needs a file of its own with the `-- +goose NO TRANSACTION` annotation. Every migration connection sets `lock_timeout` to 10 seconds, so DDL fails instead of queueing behind long transactions and blocking later queries on the table, and `statement_timeout` to 4 minutes.
At startup bootstrap applies pending migrations after configuration validation and before the HTTP and metrics listeners open. The runner in `backend/internal/adapter/secondary/postgres/migrator.go` uses the goose v3 Provider API with the pgx database/sql driver and a PostgreSQL session advisory lock, so instances that start together apply migrations one at a time. Lock waiting and migration work are limited to five minutes. A migration error stops startup; the error omits the connection string and the password. Without `DATABASE_URL` the step is skipped with a warning, and readiness stays `not_ready` as before.
`DATABASE_MIGRATE_ON_START` accepts only `true` or `false` (case-insensitive, surrounding spaces ignored); the default is `true`. It is a local and development option, for example to start the service against a database that a developer migrates by hand. The Compose stack does not pass it, and the backend image contains no separate migration command, so a deployed backend always migrates at startup and its database role needs DDL rights on the application schema. A separate migration role and job with a least-privilege runtime role is future work.
For a local database, export `DATABASE_URL` in your shell and use these targets:
- `make -C backend migrate-status` lists each embedded migration as applied, with its time, or pending.
- `make -C backend migrate-up` applies pending migrations.
- `make -C backend migrate-down-one` rolls back the latest applied migration.
The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts as startup. The Makefile contains no connection strings; keep credentials out of committed files. Integration tests apply all migrations to the PostgreSQL container from the shared bootstrap; see [TESTING.md](TESTING.md).
## 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.
+2 -2
View File
@@ -36,7 +36,7 @@ Security checks run separately: `make -C security check` scans source/dependenci
## Current scaffold coverage
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or 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), cache operations and TTL, S3 operations and object persistence, metrics, the API client, ML schemas, and current endpoint availability. There are no accounts, assessments, search results, invitations, file workflows, or 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.
@@ -48,7 +48,7 @@ The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable.
Bootstrap starts infrastructure and clients. The application HTTP server, business-schema migrations, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
## Integration test sharding
+36 -9
View File
@@ -44,13 +44,38 @@ Go владеет авторизацией, подтвержденными ка
Общие настройки Go принадлежат backend/config/ вне internal. Сейчас logkit 0.6.0, httpkit 0.7.0 и cachekit 0.7.0 из wahrwelt-kit используются для технических функций. Метрики реализованы ограниченным собственным collector/middleware, а pgxpool state не должен блокировать startup. pgkit и httpkit/metrics пока не используются; технические библиотеки не владеют бизнес-логикой. Не добавлять невыбранные JWT или WebSocket зависимости ради предполагаемых будущих сценариев.
PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте.
PostgreSQL с pgx, sqlc и goose остается основной базой. SQL написан вручную, sqlc генерирует типизированный адаптер. goose управляет версионными миграциями: SQL-файлы встроены в бинарник, и backend применяет их при старте под advisory lock PostgreSQL до открытия своих listeners. wire в bootstrap - compile-time сборка зависимостей; во время выполнения DI-контейнера нет. Worker и API используют один пул БД в целевом однопроцессном варианте.
Redis входит в основной Compose и подключен через `backend/internal/adapter/secondary/redis/` к outbound-порту кеша. Адаптер предоставляет Get/Set/Del с TTL, а bootstrap управляет подключением и закрытием клиента. Внутренний /readyz требует доступности PostgreSQL, Redis и bucket SeaweedFS. Кеш не является источником истины: вытеснение ключей и перезапуск Redis должны быть допустимы для будущих потребителей. Кеширование профилей, поиска, резюме и другие продуктовые правила еще не реализованы.
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, а Go клиент, outbox и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, таблица `outbox_events` и ее транзакционная запись уже есть, а Go клиент Kafka и relay пока не реализованы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
### Transactional outbox
Реализовано: миграция `backend/db/migrations/00001_create_outbox_events.sql` создает `outbox_events`. Колонки:
- `position`: bigint identity, уникальный и монотонный в порядке вставки; relay читает по нему.
- `event_id`: uuid primary key, UUIDv7 создается в Go.
- `event_type`: имя в нижнем регистре через точку, не длиннее 128 байт.
- `schema_version`: integer больше нуля.
- `aggregate_type`: snake_case, не длиннее 64 байт.
- `aggregate_id`: uuid.
- `aggregate_version`: bigint больше нуля.
- `payload`: jsonb-объект.
- `occurred_at`: `clock_timestamp()` в момент вставки. Только для информации, порядок он не задает.
- `published_at`: null, пока relay не опубликует строку.
Уникальный ключ по типу агрегата, ID агрегата, версии агрегата и типу события отклоняет второе событие того же типа для той же версии агрегата. Частичный индекс по `position` при `published_at IS NULL` обслуживает выборку relay. CHECK-ограничения повторяют доменные правила для версий, имен и payload-объекта как последнюю защиту. Ограничение размера payload есть только в Go: текстовый и бинарный размер jsonb отличаются от компактного входа, и проверка длины в БД могла бы отклонить событие, принятое доменом.
Usecase пишет через outbound-порты. `Transactor.WithinTransaction(ctx, fn)` открывает одну транзакцию READ COMMITTED и передает `UnitOfWork`; все репозитории из него, включая `Outbox().Append(ctx, events...)`, работают в этой транзакции. Транзакция фиксируется, если fn вернула nil, и откатывается, если fn вернула ошибку, вызвала panic или ее контекст отменен. Повторный вызов `WithinTransaction` с контекстом callback возвращает `outbound.ErrNestedTransaction` и не открывает второе соединение. Конфликт по ID события или уникальному ключу возвращает ошибку, которая оборачивает `outbound.ErrOutboxEventConflict` и называет ограничение. Сетевая ошибка во время commit оставляет результат неизвестным, поэтому вызывающий код с повторами должен быть идемпотентным.
Правило уникальности outbox - последняя защита, а не управление конкурентностью. Обновления агрегата по-прежнему проверяют ожидаемую версию (`UPDATE ... WHERE version = $n`), чтобы устаревший writer упал до записи события.
`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; первая бизнес-транзакция подключит его вместе с общим пулом.
## Структура репозитория и назначение пакетов
@@ -58,13 +83,14 @@ SeaweedFS работает отдельным сервером в основно
api/core/ публичный контракт браузер-Go и bundle
api/ml/ внутренний контракт Go-ML и bundle
backend/cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
backend/cmd/migrate/ локальные status, up и down-one для миграций
backend/config/ общая конфигурация runtime
backend/internal/domain/ продуктовые правила, планируемые модули
backend/internal/usecase/ операции приложения и orchestration
backend/internal/port/ inbound и outbound интерфейсы
backend/internal/adapter/ primary HTTP и secondary интеграции
backend/internal/bootstrap/ wiring зависимостей и lifecycle процесса
backend/db/ миграции и SQL-запросы
backend/db/ миграции, SQL-запросы и встроенный набор миграций
backend/codegen/ конфигурация ogen для сервера и ML-клиента, sqlc
frontend/src/ app, pages, widgets, features, entities, shared
frontend/codegen/ конфигурация Orval
@@ -81,10 +107,10 @@ backend/
cmd/app/main.go вызывает bootstrap.Run и обрабатывает ошибку
config/ общая конфигурация runtime
internal/
domain/ плоский пакет; пока только .gitkeep
domain/ плоский пакет; DomainEvent для outbox
usecase/health/ operational readiness usecase
port/inbound/ inbound граница readiness
port/outbound/ границы readiness, кеша и объектного хранилища
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции и outbox
adapter/primary/http/
api/ generated ogen handler
middleware/ метрики запросов
@@ -93,21 +119,22 @@ backend/
router.go сборка chi router
adapter/secondary/
ml/api/ generated client из backend/codegen/ogen-ml.yml
postgres/ pool, migrator, transactor, запись outbox, health check
postgres/sqlc/ generated SQL adapter
redis/ адаптер кеша и проверка Redis
seaweedfs/ S3-адаптер и проверка bucket
prometheus/ ограниченные Go/process и request metrics
bootstrap/ конфигурация, wiring, lifecycle, shutdown
db/ миграции и SQL-запросы; продуктовой схемы пока нет
db/ встроенные миграции и SQL-запросы; таблица outbox, продуктовой схемы пока нет
codegen/ конфигурация ogen и sqlc
pkg/ резерв для обоснованных общих технических helpers
```
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Пока типы не определены, каталог содержит только `.gitkeep`.
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox.
`domain/`, продуктовые `usecase/`, адаптеры почты и 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, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, Redis cache adapter и S3-адаптер SeaweedFS. Аккаунты, резюме, оценивание, приглашения, worker jobs, файловые сценарии, mail и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
@@ -210,7 +237,7 @@ contact_grant относится к паре кандидат-компания
## Будущее расширение
Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka; outbox, relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox и ее транзакционная запись реализованы (см. "Transactional outbox" выше); relay, топики и потребители запланированы и не реализованы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy.
+2
View File
@@ -13,6 +13,8 @@
Основной файл deploy/docker/docker-compose.yml запускает PostgreSQL, Redis, SeaweedFS, Kafka, Go backend и frontend контейнер. Frontend контейнер раздает статические файлы через Nginx и проксирует /api в backend. PostgreSQL, Redis, SeaweedFS, Kafka, backend и Nginx общаются по выделенной Compose сети.
До открытия listeners backend применяет встроенные в бинарник миграции базы данных; ошибка миграции останавливает контейнер. Compose не передает `DATABASE_MIGRATE_ON_START`, поэтому развернутый backend всегда мигрирует при старте, и роли PostgreSQL из `DATABASE_URL` нужны права DDL на схему приложения. Этот флаг - опция локальной разработки; отдельная роль миграций с минимальными правами - будущая работа. См. [DEVELOPMENT.md](DEVELOPMENT.md#миграции-базы-данных).
Контекст сборки backend - каталог `backend/`, поэтому Docker применяет `backend/.dockerignore`. Локальные инструменты, кеши, файлы окружения и результаты сборки не отправляются в этот build context.
Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные.
+21 -3
View File
@@ -40,7 +40,7 @@ Frontend зависимости выбираются из актуальных s
| wire (`github.com/goforj/wire`) | v1.2.0 | backend/go.mod (`require` и `tool`) |
| mockery | v3.8.0 | backend/go.mod (`tool`) |
| golangci-lint | v2.14.0 | backend/go.mod (`tool`) |
| goose | v3.28.0 | backend/go.mod (`tool`) |
| goose | v3.28.0 | backend/go.mod (`require` и `tool`) |
| chi | v5.3.2 | backend/go.mod |
| pgx | v5.11.0 | backend/go.mod |
| testcontainers-go | v0.44.0, включая modules/postgres | backend/go.mod |
@@ -48,14 +48,14 @@ Frontend зависимости выбираются из актуальных s
Что есть сейчас:
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose и 404 для неизвестного API маршрута; ML он не запускает.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, и transactor с записью transactional outbox; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- 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`, но в backend нет Go клиента Kafka, топиков и проверки Kafka в readiness.
- 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), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, transactional outbox и его relay, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть только таблица outbox и нет бизнес-схемы, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
## Установка и цикл работы
@@ -141,6 +141,24 @@ ML - отдельный FastAPI процесс. Сейчас он предост
Все комментарии и docstrings в коде пишутся на английском. Инструкции для агентов в корне и .agents также ведутся в единой английской версии; документация команды поддерживается на русском и английском.
### Миграции базы данных
Миграции - SQL-файлы goose в `backend/db/migrations/` с именами `NNNNN_description.sql` и последовательными пятизначными версиями. В каждом файле есть секция `-- +goose Up` и работающая секция `-- +goose Down`. sqlc читает этот же каталог как схему, а `make -C backend lint-sql` проверяет его линтером. `backend/db/migrations.go` встраивает файлы в бинарник, поэтому он применяет ровно ту схему, с которой собран. `make -C backend check` загружает встроенный набор без базы данных и падает на неверном имени, отсутствующей секции Down или дублирующейся версии. Примененная на стенде миграция неизменна; схема меняется новым файлом. Две ветки с одинаковой версией должны перенумеровать файл перед слиянием. Чтобы создать файл со следующим номером, выполните `go tool goose -dir db/migrations -s create <name> sql` в `backend/`.
goose выполняет каждую миграцию в отдельной транзакции. Команде, которая не работает внутри транзакции, например `CREATE INDEX CONCURRENTLY`, нужен отдельный файл с аннотацией `-- +goose NO TRANSACTION`. Каждое соединение миграций устанавливает `lock_timeout` в 10 секунд, чтобы DDL падал, а не ждал за длинными транзакциями и не блокировал последующие запросы к таблице, и `statement_timeout` в 4 минуты.
При старте bootstrap применяет ожидающие миграции после проверки конфигурации и до открытия HTTP и metrics listeners. Runner в `backend/internal/adapter/secondary/postgres/migrator.go` использует Provider API goose v3 с драйвером pgx для database/sql и сессионный advisory lock PostgreSQL, поэтому одновременно стартующие экземпляры применяют миграции по очереди. Ожидание блокировки и сами миграции ограничены пятью минутами. Ошибка миграции останавливает запуск; текст ошибки не содержит строку подключения и пароль. Без `DATABASE_URL` шаг пропускается с предупреждением, а readiness, как и раньше, остается `not_ready`.
`DATABASE_MIGRATE_ON_START` принимает только `true` или `false` (без учета регистра, пробелы по краям игнорируются); по умолчанию `true`. Это опция для локальной разработки, например чтобы запустить сервис с базой, которую разработчик мигрирует вручную. Compose ее не передает, а в образе backend нет отдельной команды миграций, поэтому развернутый backend всегда мигрирует при старте, и его роли БД нужны права DDL на схему приложения. Отдельная роль и job миграций с минимальными правами runtime-роли - будущая работа.
Для локальной базы экспортируйте `DATABASE_URL` в shell и используйте цели:
- `make -C backend migrate-status` показывает каждую встроенную миграцию как примененную, со временем, или ожидающую.
- `make -C backend migrate-up` применяет ожидающие миграции.
- `make -C backend migrate-down-one` откатывает последнюю примененную миграцию.
Цели запускают `backend/cmd/migrate` с тем же runner, блокировкой и таймаутами, что и старт сервиса. Makefile не содержит строк подключения; не храните учетные данные в коммитах. Интеграционные тесты применяют все миграции к контейнеру PostgreSQL из общего bootstrap; см. [TESTING.md](TESTING.md).
## Читаемость Go-кода
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
+2 -2
View File
@@ -36,7 +36,7 @@ make -C ml check-generated использует datamodel-code-generator --check
## Что покрывает текущий каркас
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат.
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет пользователей, тестовых заданий, поисковой выдачи, приглашений, файлового workflow или реального model inference, которые можно было бы проверить как бизнес-результат.
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
@@ -48,7 +48,7 @@ Deployment smoke проверяет инфраструктурные маршр
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой.
Bootstrap поднимает инфраструктуру и клиенты. HTTP-сервер приложения, миграции бизнес-схемы, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
## Шардирование интеграционных тестов