feat(jobs): add durable due-time job runner with leases

This commit is contained in:
shira committed 2026-10-06 14:29:23 +03:00
1 parent 7e80c8ad2a
commit 008254e44a
39 files changed
+4909 -43

No files matched your search

+31 -8
View File
@@ -50,7 +50,7 @@ Redis is part of the core Compose project and connects through `backend/internal
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; no product consumer is registered yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; one product consumer is registered, `notification_delivery` for mail deliveries. 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.
### Private file storage
@@ -166,6 +166,28 @@ Trade-offs: one consumer processes one record at a time on one connection. Paral
The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts finished records by `applied`, `duplicate`, `ignored`, or `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` counts every failed operation, including the last handler attempt before a dead letter, by `handler`, `store`, `poll` (a failed poll of the event bus), or `commit` (a failed offset commit). The consumer label comes from the registered names in code, so the series are bounded. Every series of a consumer exists from its start at zero. Logs carry the consumer, group, topic, partition, offset, event ID, and event type, never the value or payload.
### Scheduled jobs
Implemented (TASK-035): durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline (TASK-205). Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `<id>:<version>`.
States. `due_at` is the deadline the job stands for and never changes; `available_at` is when a worker may claim the job next, `due_at` at first and the retry time after a failed attempt. `pending` waits for `available_at`; `failed` waits for its retry after a failed attempt; `running` is claimed under a lease; `done`, `dead`, and `cancelled` are final. Finished rows are kept, so their key stays reserved; their retention is not implemented yet.
Claim and lease. The worker claims up to `JOBS_BATCH_SIZE` jobs in one statement: a CTE selects waiting jobs whose `available_at` passed and running jobs whose `lease_expires_at` passed, of the kinds that have a handler in this process, in `available_at` order, with `FOR UPDATE SKIP LOCKED`, and the same statement sets `status = running`, `lease_owner` (a random ID per worker instance), and `lease_expires_at = now + JOBS_LEASE_DURATION`, and counts the attempt. Two partial indexes serve the claim, one on waiting rows and one on running rows; the kind filter applies after the index, so when many waiting jobs belong to kinds that the claiming process has no handler for, an index on `(kind, available_at, id)` is the next step. `now` is passed from the injected application clock; the database clock never decides whether a job is due or a lease expired, so tests move a fake clock instead of waiting days. Jobs of a kind without a handler stay untouched, so an older instance during a rolling deployment leaves them to the instances that have the handler. Right before its handler transaction, each job is started: a separately committed, guarded `UPDATE` renews its lease from now and sets `started_at`, but only while the lease of the claim has not expired. The attempt is counted at the claim, so a job that crashes its process while its handler runs cannot loop forever: when the lease of a started attempt expires on the last allowed attempt, the claim marks the job `dead` with `lease_expired` instead of running it again. A claim whose attempt never started (the worker stopped or was busy before the job's turn) is not the job's fault: the next claim reuses that attempt without counting another one and records no error class.
Run and completion. Each job runs in its own READ COMMITTED transaction: it sets `statement_timeout` and `idle_in_transaction_session_timeout` to the lease duration, locks the job row with a guard on `status = running`, the lease owner, and the attempt number, calls the handler with an `outbound.UnitOfWork` of the same transaction, marks the job `done` with the same guard, and commits. The handler effect and the completion therefore commit together: for an effect that stays in PostgreSQL a job is applied exactly once even when workers race, restart, or a lease expires. While the handler runs the row is locked, so another worker's claim skips it even after the lease expired by the clock; when the guard fails because the job was canceled or reclaimed, the handler is not called and nothing commits (`lease_lost`). A handler may cancel its own job through the unit, for example an expiry that also cancels the deadline job it stands for: the completion then finds the job `cancelled` in its own transaction, treats it as finished, and commits the effect, and the job stays `cancelled`. Any other change of its own job by the handler rolls back and makes the job `dead` with `completion_conflict`, because it would repeat on every attempt. A handler whose effect leaves the database, such as a call to another service, can repeat after a crash between that call and the commit and must be idempotent itself. The handler context ends with the renewed lease. A handler decides by `job.DueAt`, the deadline the job stands for, which a retry keeps, not by when it happens to run.
Lock order. The handler holds the job row lock and may then lock product rows. A business transaction that cancels a job, such as accepting an invitation at its deadline, should call `Cancel` before it locks those product rows. `Cancel` waits for a handler transaction in progress: after its commit the job is done and `Cancel` reports `false`, so the caller sees the expiry; otherwise the job is canceled and the worker finds its lease gone. The opposite order can deadlock, which PostgreSQL resolves by aborting one side with `ErrTransactionConflict`; the job side counts a failed attempt and retries.
Failures. A failed attempt rolls back its effect; a second statement, guarded the same way, records it. A handler error, a lease timeout, a deadlock or serialization failure (`conflict`), or a commit that PostgreSQL refuses (`effect_rejected`, for a handler that ignored a failed statement or a deferred constraint) moves the job to `failed` with `available_at = now + backoff`, where the backoff is the shared `worker/retry` delay from `JOBS_BACKOFF_INITIAL`, doubling up to `JOBS_BACKOFF_MAX`, with jitter. `inbound.ErrJobRejected`, a handler panic, and `completion_conflict` are final, also when they happen during shutdown. After the last allowed attempt (the job's own limit or `JOBS_MAX_ATTEMPTS`) the job is `dead`: it is logged at error level and counted as `dead`, and it needs an operator. `last_error_class` stores only a bounded class; a sanitized reason appears only in the log. A database failure outside the handler is not the job's fault: the worker releases its unfinished jobs without counting the attempt and backs off before the next claim, so an outage causes no hot loop. When the failure record itself cannot be written, the job keeps its started lease; a later claim then counts it as `lease_expired`, which on the last attempt makes it dead.
Shutdown. When the context ends, the worker claims nothing more. A job in progress has `JOBS_SHUTDOWN_GRACE` to commit; after that it is canceled and its transaction rolls back, so an unfinished job is never marked done. The worker then releases it, and the claimed jobs of the batch it did not start, explicitly: back to `pending` or `failed`, without counting the attempt, guarded by owner and attempt so a job that another worker reclaimed or a caller canceled meanwhile is left alone. Release makes the jobs claimable at once by another instance instead of after up to one lease, which matters during a rolling deployment; if the release cannot reach the database, the lease expires and a later claim takes the jobs, so the release is only a shortcut and never needed for correctness. Bootstrap starts the worker next to the HTTP servers, the relay, and the consumers, and runs the cleanup that closes its pool only after it stopped.
Trade-offs: one worker runs one job at a time on a pool of two connections; more throughput comes from more backend instances. The jobs of one batch are claimed together but each renews its lease when it starts, so a slow job ahead costs the next ones only waiting time: a job whose claim lease expired before its turn is not started and is released with its attempt intact, or, when another worker already took it over, that worker runs it on the same attempt. Due times are honored with a delay of up to `JOBS_POLL_INTERVAL` plus the batch ahead of it. There is no separate `cmd/worker`: the worker is a goroutine of the backend process, and migrations run as before.
Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `done`, `retry`, `dead`, `lease_lost`, or `released`; the kind label comes from the registered handlers, and every series exists at zero from the start. `lincodex_scheduled_jobs_due`, `lincodex_scheduled_jobs_oldest_due_age_seconds`, and `lincodex_scheduled_jobs_dead` describe all kinds at the last backlog read, at most every 15 seconds. Logs carry the job ID, kind, attempt, and error class, never the key or payload.
### Mail transport
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet: deliveries are stored (see [Mail deliveries](#mail-deliveries)), and the worker that sends them is planned (TASK-016). Settings are described in [DEPLOY.md](DEPLOY.md#mail).
@@ -422,20 +444,21 @@ backend/
prometheus/ bounded Go/process and request metrics
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
bootstrap/ configuration, wiring, lifecycle, shutdown
db/ embedded migrations and SQL queries; outbox, identity, policy, and event consumer tables
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, and scheduled job tables
codegen/ ogen and sqlc configs
pkg/ reserved for justified shared technical helpers
pkg/testutil/ fake application clock shared by tests
```
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 product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with no registered product handler, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, 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 with the shared private file layer over it, 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, product job kinds, 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 delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, 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/`.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock. A `mailer` package remains a candidate. 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 delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, 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/`.
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
@@ -514,7 +537,7 @@ Resume text is untrusted data, not an instruction to tools. ML does not follow a
A standardized PDF is required in the product even when profile entry is manual. PDFRenderer consumes structured profile data. The planned approach is controlled HTML and isolated headless Chromium with Cyrillic fonts, no external network fetches, and no user-supplied HTML.
Future jobs use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
Jobs that only need to run at a due time use the implemented runtime in [Scheduled jobs](#scheduled-jobs). Future ML and document jobs, which a user waits for, use queued, running, succeeded, failed, and cancelled states, an attempt limit, available_at, lease/heartbeat, and a safe error code. Claims are atomic. An expired lease permits retries; operation key, document version, and lease token prevent stale workers from overwriting newer results. Computation may repeat; a business effect must not. Retries are bounded and use backoff.
Long operations return 202 and a job ID. The UI polls with a widening interval and stops after completion or page exit. The browser never calls ML directly. Routine tests do not download a model or require GPU. Model, license, inference budget, and production latency are unselected.
@@ -577,7 +600,7 @@ The target screen stack is React Router, TanStack Query, React Hook Form, and Zo
## Future extensions
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); product consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
Apache Kafka in KRaft mode is the selected event bus for domain events, mail, ATS webhooks, recomputation, and FSP sync. PostgreSQL remains the source of truth: it keeps product facts and durable job and scheduling state. Events reach Kafka only through a transactional outbox written in the same PostgreSQL transaction as the fact; a relay publishes outbox rows, and consumers are idempotent and tolerate redelivery, reordering across partitions, and retries with deduplication. Redis is not a queue. The core Compose project already runs one internal Kafka node. The outbox table, its transactional writer, the relay, and the consumer runtime are implemented (see "Transactional outbox", "Outbox relay", and "Event consumers" above); one product consumer, `notification_delivery`, is registered; further consumers and additional topics are planned. Extract search, assessment, or notification only for an independent scale or lifecycle need. gRPC is useful when several internal services benefit from protobuf or streaming; it does not replace browser-facing OpenAPI.
k3s is outside the critical path. Consider it only with an operated cluster or measured multi-node need. A single-node cluster does not provide HA. A transition needs probes and resource limits, secrets, storage backup, ingress, and verified NetworkPolicy.
@@ -602,7 +625,7 @@ Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amo
## Metrics, telemetry, and alerts
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. Queue, inference, and product-event metrics are not implemented in the current scaffold.
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. The scheduled job counters and backlog gauges are described in [Scheduled jobs](#scheduled-jobs). Inference and product-event metrics are not implemented in the current scaffold.
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model.
+44
View File
@@ -168,6 +168,50 @@ The table holds no record value; `value_size` and `value_sha256` identify the va
To inspect an `invalid_record` while the topic retains it, read exactly that record with `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1` and compare its SHA-256 with `value_sha256`. The value can contain personal data, so do not paste it into tickets or chats.
### Scheduled jobs
The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: no product job kind is registered, so the backend logs `no scheduled job kind is registered` at startup and runs no worker; the settings below are still validated. With a registered kind, the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of the settings, 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, also with the worker disabled.
| Variable | Default | Meaning |
| --- | --- | --- |
| `JOBS_ENABLED` | `true` | `true` or `false`. With `false`, or without `DATABASE_URL`, no job runs; due jobs wait in `scheduled_jobs` and run after the worker starts again, with their original `due_at`. |
| `JOBS_POLL_INTERVAL` | `1s` | Wait after a pass that claimed less than a full batch, from 10ms to 5m. It is also the usual delay of a job after its due time. |
| `JOBS_BATCH_SIZE` | `10` | Jobs one claim leases, from 1 to 100. They run one after another under leases taken together, so a batch should finish well within one lease. |
| `JOBS_LEASE_DURATION` | `1m` | How long a claimed job belongs to one worker, from 1s to 1h. It bounds one handler attempt and is the server-side `statement_timeout` and `idle_in_transaction_session_timeout` of the job transaction. A worker that crashed delays its jobs by at most this long. |
| `JOBS_MAX_ATTEMPTS` | `5` | Attempts of a job scheduled without its own limit before it is dead, from 1 to 100. Database failures outside the handler and shutdown do not count. |
| `JOBS_BACKOFF_INITIAL` | `1s` | Delay before the first retry of a failed job; it doubles with each failed attempt. The same backoff spaces claims while the database fails. |
| `JOBS_BACKOFF_MAX` | `5m` | Longest delay before a retry, from `JOBS_BACKOFF_INITIAL` to 24h. |
| `JOBS_SHUTDOWN_GRACE` | `5s` | Time the job in progress has to commit after shutdown begins; at most `SHUTDOWN_TIMEOUT`. After it the transaction rolls back and the job is released unfinished. |
Due times and leases are compared with the backend clock, not the database clock, so keep the hosts of all backend instances synchronized with NTP. A clock ahead runs jobs early and takes over leases early; the row lock still prevents a second run while a handler is in progress.
Shutdown budget. The worker stops in parallel with the other workers: `JOBS_SHUTDOWN_GRACE` (5s) for the job in progress, up to 5s to roll back a canceled transaction, and up to 5s to release the unfinished jobs, 15s at most. This fits the first phase of the budget under [Event consumers](#event-consumers), so the total stays about 23s within `stop_grace_period: 30s`; raise that together with `JOBS_SHUTDOWN_GRACE`. If the backend is killed instead, its jobs stay `running` until their leases expire and then run on another instance or after the restart.
The worker uses its own PostgreSQL pool of at most two connections. Several backend instances share the jobs: each claim skips rows that another instance locks, and every instance can run every registered kind.
Operators watch `lincodex_scheduled_jobs_total{kind,outcome}` on the internal /metrics endpoint: `done`, `retry` (an attempt failed and the job waits for its backoff), `dead`, `lease_lost` (the job was canceled or reclaimed while this instance held it), and `released` (given back unfinished at shutdown or after a database failure). Every series exists at zero from the start, so alert on `increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0`. `lincodex_scheduled_jobs_due` and `lincodex_scheduled_jobs_oldest_due_age_seconds` describe due jobs that wait for a worker; an age that keeps growing beyond a few poll intervals means no instance claims them, for example because the worker is disabled, the database fails, or no running instance has the handler of their kind. `lincodex_scheduled_jobs_dead` counts dead jobs. Every instance reports the same database-wide gauges, so aggregate them with `max`. During a rolling deployment that adds a new kind, its jobs that already fell due wait until an instance with the handler runs, and the age can briefly look like a stuck worker; hold an age alert for longer than a deployment takes. Logs carry the `scheduled_jobs` component, the lease owner, job ID, kind, attempt, and error class, never the key or payload; a dead job is logged at error level as `scheduled job is dead; it needs an operator`.
#### Dead jobs
`last_error_class` says why a job is dead: `handler_rejected` (the handler can never run it), `handler_panic` (the log line `scheduled job handler panicked` with the same job ID holds the stack), `lease_expired` (its last started attempt stopped without finishing, usually a crash or a kill, or its failure could not be recorded because the database failed at that moment), or the class of the last failed attempt after the attempts ran out: `handler_failed`, `timeout`, `conflict`, or `effect_rejected`. `completion_conflict` means the handler changed its own job other than by canceling it. List dead jobs and jobs that are overdue with psql in the database container (see [Dead letters and replay](#dead-letters-and-replay) for the command that opens it):
SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class,
due_at, available_at, updated_at
FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at;
SELECT kind, status, count(*), min(available_at)
FROM scheduled_jobs
WHERE status IN ('pending', 'failed', 'running') AND available_at <= now()
GROUP BY kind, status;
The key identifies a product record, such as an invitation ID; the payload holds identifiers only. After the cause is fixed, usually by deploying a corrected handler, run a dead job again. Change only `available_at`, never `due_at`: the handler decides by the deadline in `due_at`.
UPDATE scheduled_jobs
SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp()
WHERE id = <id> AND status = 'dead';
A worker claims it within one poll interval and runs it with fresh attempts. To give a dead job up, set `status = 'cancelled'` with the same guard; its key stays reserved, so the product flow cannot schedule it again. Do not delete rows: a deleted key can be scheduled again and run a second time.
## 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.
+7 -1
View File
@@ -57,7 +57,7 @@ What exists now:
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), and the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`) 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 SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`), and the scheduled job table (`scheduled_jobs`, with no product job kind registered yet) 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
@@ -199,6 +199,12 @@ To send a notification from a usecase, call `notification.MailRequester.RequestN
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
### Scheduled jobs
To run something when it falls due, such as an expiry or a reminder, schedule a job in the usecase's own transaction: build it with `domain.NewScheduledJob` (a kind such as `invitation.response_deadline`, a key that identifies the logical job, for example the aggregate ID, the due time from the injected clock, and a payload of identifiers only) and call `unit.ScheduledJobs().Schedule(ctx, job)`. The first schedule of a kind and key wins and a repeat is ignored, so use a new key, for example `<id>:<version>`, for a new occurrence. Cancel with `unit.ScheduledJobs().Cancel(ctx, kind, key)` before locking the product rows that the handler touches.
Then implement `inbound.JobHandler` in the module's usecase package: return the kind from `JobKind()` and write the effect in `Handle` only through the `UnitOfWork` it receives, deciding by `job.DueAt` and the current product state, so the handler is a no-op when the state already moved on. A handler may cancel its own job through the unit, for example from a shared helper that cancels the deadline; the job then counts as finished. It must not change its own job in any other way. Return an error that wraps `inbound.ErrJobRejected` for a job that can never run; any other error is retried. Add the handler to `jobHandlers()` in `backend/internal/bootstrap/jobs.go`. Take the clock as a `func() time.Time` and test deadlines with `testutil.FakeClock` from `backend/pkg/testutil/` and `Worker.RunDue`, which runs the due jobs once without polling, as `TestScheduledJobs` does. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs); settings, metrics, and the dead job procedure are in [DEPLOY.md](DEPLOY.md#scheduled-jobs); tests are in [TESTING.md](TESTING.md#scheduled-job-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
View File
@@ -185,6 +185,27 @@ Unit tests (`make -C backend test`) cover the quota rules without a database:
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The suite does not call a transport: the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is TASK-016.
## Scheduled job tests
Unit tests (`make -C backend test`) cover the job runtime with an in-memory store that applies the claim, lease guard, and release rules of the PostgreSQL store and a fake clock from `backend/pkg/testutil/` (`internal/worker/jobrunner/`): only due jobs of registered kinds run, in due order, and a job due in two days runs exactly when the clock reaches it; a failing job is retried after the backoff by the clock, is not claimed again before it, and is dead after the last attempt with an error log and metrics; `ErrJobRejected` and a panic end a job after one attempt without logging the panic value; a handler that outlives its lease fails as `timeout`; a job reclaimed by another worker before it starts is skipped without calling the handler; a job whose last started lease expired becomes dead without running; a slow first job of a batch neither spends the next job's single attempt nor lets it die, and another worker runs a job that a busy worker claimed but did not start, on the same attempt; a database failure outside the handler releases the job and the rest of the batch without counting attempts; failed claims back off instead of looping; at shutdown the job in progress finishes within the grace, a job that outlasts it is canceled and released without an effect or a counted attempt, and claimed jobs that did not start are released; a panic during shutdown still makes the job dead; and the backlog of all kinds is reported. Further unit tests cover the job rules (`internal/domain/`: kind, key, flat payload, size limit, UTC microsecond due time), the settings (`config/`), the counters and gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), and in `internal/bootstrap/` the skip cases with their log lines, the empty kind registry, a duplicate kind, and an application that runs the worker against an unreachable database and still stops.
`TestScheduledJobs` in `backend/integration_test/scheduled_jobs_test.go` uses `bootstrap(t, postgresService)`. Its handler exists only in the test: it writes one row into `job_test.effects`, a table without a unique key, in the transaction that completes the job, so a second effect would stay visible. Each simulated process gets its own pool, store, and worker; building a new one is a restart. All due and lease decisions use one `FakeClock`. The sequential cases are:
- Jobs on different dates: two jobs scheduled through `UnitOfWork.ScheduledJobs()` for tomorrow and in three days, and a repeated schedule that is ignored and does not move the due time. Nothing runs at the start; after a restart and one day the first job runs; after another restart the second job does not run a microsecond early and runs at its due time; a month later nothing runs again. The effects are one per job, in due order.
- Two workers with their own pools run their loops against 40 due jobs at once: every job is done, and there are exactly 40 effects for 40 distinct jobs.
- A handler that outlives its lease by the clock still holds the job row lock, so another worker's claim skips the job; the first worker then completes it, with one effect.
- An expired lease: worker A claims and starts the job and stops inside it. Worker B cannot claim it a microsecond before the lease expires and runs it at expiry, with two counted attempts and `lease_expired` recorded. A's late start is refused, its late `Run` returns `ErrJobLeaseLost` without calling its handler, and its late failure record and release are refused; one effect remains.
- A started attempt with a limit of one attempt whose lease expired: the next claim makes the job dead with one attempt and `lease_expired`, without calling the handler.
- A claim that never started, with a limit of one attempt: after its lease expires another worker runs the job on the same attempt, with no error class.
- A slow first job of a batch runs past the claim lease: the next job, limited to one attempt, is released with its attempt intact and runs in the next pass. With two workers, while the slow job holds its row, the other worker claims only the waiting job and runs it on its single attempt; the busy worker then counts it as `lease_lost`.
- A handler that cancels its own job through the unit: its effect commits, the job stays `cancelled`, and the next job of the pass runs. A handler that changes its own job otherwise makes it dead with `completion_conflict` and leaves no effect.
- Graceful shutdown: a handler writes its effect and then outlasts a 200 ms grace. After the stop the effect is rolled back and the job is `pending` with no attempt and no lease, and a new process runs it at once without waiting for a lease.
- A failing job with its own limit of two attempts: the first attempt moves only `available_at` by the backoff and keeps `due_at`, the job is not claimed before the backoff, the second attempt makes it dead, the handler saw the original due time both times, no effect remains, the backlog reports one dead job, and the counters show one `retry` and one `dead`.
- Cancel: a canceled job is never claimed, a second cancel and a new schedule of the same key do nothing, and nothing is due.
- Cancel during a run: while a handler holds the job, a cancel in another transaction is observed waiting for the row lock in `pg_stat_activity`; after the handler commits, the job is done and the cancel reports false.
`TestPostgresMigrations` also checks that migration 00008 creates and drops `scheduled_jobs`. The suite uses one PostgreSQL and a test-only kind. It does not measure throughput, does not cover clock skew between instances, a database failover, or a product handler, and does not check alert delivery.
## Integration test sharding
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
+31 -8
View File
@@ -50,7 +50,7 @@ Redis входит в основной Compose и подключен через
SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Общий файловый слой и контроль доступа в контейнере SeaweedFS описаны в разделе [Закрытое файловое хранилище](#закрытое-файловое-хранилище). Загрузка резюме, проверка прав, продуктовые правила содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование.
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; продуктовые обработчики пока не зарегистрированы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрирован один продуктовый обработчик - `notification_delivery` для доставок писем. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
### Закрытое файловое хранилище
@@ -166,6 +166,28 @@ Offsets и партиции. Каждый обработчик - один уча
Метрика `lincodex_event_consumer_records_total{consumer,outcome}` считает завершенные записи по `applied`, `duplicate`, `ignored` или `dead_lettered`; `lincodex_event_consumer_failures_total{consumer,stage}` считает каждую неудачную операцию, включая последнюю попытку обработчика перед dead letter, по `handler`, `store`, `poll` (неудачное чтение шины событий) или `commit` (неудачный commit offset). Метка consumer берется из зарегистрированных в коде имен, поэтому число рядов ограничено. Все ряды обработчика существуют с его запуска со значением 0. Журналы содержат обработчик, группу, топик, партицию, offset, ID и тип события, но никогда не значение или payload.
### Задания по сроку
Реализовано (TASK-035): устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение (TASK-205). Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `<id>:<version>`.
Состояния. `due_at` - срок, который задание представляет, и он никогда не меняется; `available_at` - момент, когда worker может захватить задание в следующий раз: сначала `due_at`, после неудачной попытки - время повтора. `pending` ждет `available_at`; `failed` после неудачной попытки ждет повтора; `running` захвачено под lease; `done`, `dead` и `cancelled` - финальные. Завершенные строки сохраняются, поэтому их ключ остается занятым; срок их хранения пока не реализован.
Захват и lease. Worker захватывает до `JOBS_BATCH_SIZE` заданий одним оператором: CTE выбирает ожидающие задания с прошедшим `available_at` и выполняемые задания с прошедшим `lease_expires_at` тех видов, для которых в процессе есть обработчик, в порядке `available_at` с `FOR UPDATE SKIP LOCKED`, а тот же оператор ставит `status = running`, `lease_owner` (случайный ID экземпляра worker) и `lease_expires_at = now + JOBS_LEASE_DURATION` и учитывает попытку. Захват обслуживают два частичных индекса: по ожидающим и по выполняемым строкам; фильтр по виду применяется после индекса, поэтому, когда много ожидающих заданий относится к видам без обработчика в захватывающем процессе, следующим шагом нужен индекс `(kind, available_at, id)`. `now` передается из внедренных часов приложения; часы базы данных никогда не решают, наступил ли срок или истек ли lease, поэтому тесты сдвигают fake clock вместо ожидания в несколько дней. Задания вида без обработчика не трогаются, поэтому старый экземпляр во время поэтапного развертывания оставляет их экземплярам, у которых обработчик есть. Непосредственно перед транзакцией обработчика каждое задание запускается: отдельно зафиксированный `UPDATE` с проверкой продлевает его lease от текущего момента и ставит `started_at`, но только пока lease захвата не истек. Попытка учитывается при захвате, поэтому задание, которое роняет процесс во время работы обработчика, не может повторяться бесконечно: если lease начатой попытки истек на последней разрешенной попытке, захват переводит задание в `dead` с классом `lease_expired` вместо нового запуска. Захват, попытка которого так и не началась (worker остановился или был занят до очереди задания), не вина задания: следующий захват использует ту же попытку, не учитывая новую, и не записывает класс ошибки.
Выполнение и завершение. Каждое задание выполняется в собственной транзакции READ COMMITTED: она ставит `statement_timeout` и `idle_in_transaction_session_timeout` равными длительности lease, блокирует строку задания с проверкой `status = running`, владельца lease и номера попытки, вызывает обработчик с `outbound.UnitOfWork` той же транзакции, отмечает задание `done` с той же проверкой и фиксирует транзакцию. Эффект обработчика и завершение фиксируются вместе: для эффекта, который остается в PostgreSQL, задание применяется ровно один раз, даже когда workers конкурируют, перезапускаются или lease истекает. Пока обработчик работает, строка заблокирована, поэтому захват другого worker пропускает ее даже после истечения lease по часам; если проверка не прошла, потому что задание отменили или захватили заново, обработчик не вызывается и ничего не фиксируется (`lease_lost`). Обработчик может отменить собственное задание через unit, например истечение, которое заодно отменяет задание срока, которое оно представляет: тогда завершение находит задание `cancelled` в своей же транзакции, считает его выполненным и фиксирует эффект, а задание остается `cancelled`. Любое другое изменение собственного задания обработчиком откатывается и переводит задание в `dead` с классом `completion_conflict`, потому что оно повторялось бы на каждой попытке. Обработчик, эффект которого выходит за пределы базы данных, например вызов другого сервиса, может повториться после сбоя между этим вызовом и фиксацией и должен быть идемпотентным сам. Context обработчика заканчивается вместе с продленным lease. Обработчик принимает решение по `job.DueAt`, то есть по сроку, который задание представляет и который повтор сохраняет, а не по моменту, когда оно случайно выполнилось.
Порядок блокировок. Обработчик держит блокировку строки задания и затем может блокировать продуктовые строки. Бизнес-транзакция, которая отменяет задание, например принятие приглашения в момент срока, должна вызывать `Cancel` до блокировки этих продуктовых строк. `Cancel` ждет транзакцию обработчика, если она идет: после ее фиксации задание уже `done`, и `Cancel` возвращает `false`, поэтому вызывающий видит истечение; иначе задание отменяется, а worker обнаруживает, что его lease больше не действует. Обратный порядок может привести к deadlock, который PostgreSQL разрешает, прерывая одну сторону с `ErrTransactionConflict`; сторона задания засчитывает неудачную попытку и повторяет ее.
Сбои. Неудачная попытка откатывает свой эффект; второй оператор с той же проверкой записывает ее. Ошибка обработчика, истечение lease, deadlock или serialization failure (`conflict`) и фиксация, которую отверг PostgreSQL (`effect_rejected`, для обработчика, который проигнорировал упавший оператор, или для отложенного ограничения), переводят задание в `failed` с `available_at = now + backoff`, где backoff - общая задержка `worker/retry`: от `JOBS_BACKOFF_INITIAL`, удваивается до `JOBS_BACKOFF_MAX`, со случайным разбросом. `inbound.ErrJobRejected`, panic обработчика и `completion_conflict` финальны, в том числе во время остановки. После последней разрешенной попытки (собственный лимит задания или `JOBS_MAX_ATTEMPTS`) задание становится `dead`: это пишется в журнал на уровне error и считается как `dead`, такому заданию нужен оператор. `last_error_class` хранит только ограниченный класс; очищенная причина есть только в журнале. Сбой базы данных вне обработчика - не вина задания: worker освобождает незавершенные задания без учета попытки и ждет backoff перед следующим захватом, поэтому сбой не создает горячего цикла. Если не удалось записать сам сбой, задание сохраняет начатый lease; следующий захват учтет его как `lease_expired`, а на последней попытке это делает задание dead.
Остановка. Когда context заканчивается, worker больше ничего не захватывает. У задания в работе есть `JOBS_SHUTDOWN_GRACE` на фиксацию; после этого оно отменяется, его транзакция откатывается, поэтому незавершенное задание никогда не отмечается выполненным. Затем worker явно освобождает его и захваченные, но не начатые задания пачки: возвращает их в `pending` или `failed` без учета попытки с проверкой владельца и попытки, поэтому задание, которое тем временем захватил другой worker или отменил вызывающий, не трогается. Освобождение делает задания доступными другому экземпляру сразу, а не через время до одного lease, что важно при поэтапном развертывании; если освобождение не достучалось до базы, lease истекает, и задания берет следующий захват, поэтому освобождение только ускоряет и для корректности не требуется. Bootstrap запускает worker рядом с HTTP-серверами, relay и обработчиками событий и закрывает его пул только после его остановки.
Компромиссы: один worker выполняет одно задание за раз на пуле из двух соединений; большая пропускная способность достигается числом экземпляров backend. Задания одной пачки захватываются вместе, но каждое продлевает свой lease при запуске, поэтому медленное задание впереди стоит следующим только ожидания: задание, lease захвата которого истек до его очереди, не запускается и освобождается с сохраненной попыткой, а если его уже взял другой worker, тот выполняет его на той же попытке. Сроки соблюдаются с задержкой до `JOBS_POLL_INTERVAL` плюс время пачки перед заданием. Отдельного `cmd/worker` нет: worker - горутина процесса backend, миграции запускаются как раньше.
Метрики: `lincodex_scheduled_jobs_total{kind,outcome}` считает захваченные задания по исходам `done`, `retry`, `dead`, `lease_lost` и `released`; метка вида берется из зарегистрированных обработчиков, и каждый ряд существует с нулем с момента старта. `lincodex_scheduled_jobs_due`, `lincodex_scheduled_jobs_oldest_due_age_seconds` и `lincodex_scheduled_jobs_dead` описывают все виды на момент последнего чтения backlog, не чаще чем раз в 15 секунд. Журналы содержат ID задания, вид, номер попытки и класс ошибки, но никогда ключ или payload.
### Почтовый транспорт
Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий: доставки уже сохраняются (см. [Доставки писем](#доставки-писем)), а worker, который их отправляет, запланирован (TASK-016). Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
@@ -422,20 +444,21 @@ backend/
prometheus/ ограниченные Go/process и request metrics
worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка
worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка
worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка
worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers
bootstrap/ конфигурация, wiring, lifecycle, shutdown
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики и обработчиков событий
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты и заданий по сроку
codegen/ конфигурация ogen и sqlc
pkg/ резерв для обоснованных общих технических helpers
pkg/testutil/ fake clock приложения, общий для тестов
```
Доменные типы лежат непосредственно в `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. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий без зарегистрированных продуктовых обработчиков, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
@@ -514,7 +537,7 @@ contact_grant относится к паре кандидат-компания
Стандартизированный PDF обязателен в продуктовой версии, даже при ручном вводе. PDFRenderer получает структурированный профиль; предполагаемый подход - контролируемый HTML и изолированный headless Chromium с кириллическими шрифтами, без внешних сетевых загрузок и пользовательского HTML.
Будущие jobs имеют состояния queued, running, succeeded, failed, cancelled, лимит попыток, available_at, lease/heartbeat и безопасный код ошибки. Взятие атомарно. Истекший lease разрешает повтор; уникальный ключ операции, версия документа и lease token не дают старому worker перезаписать новый результат. Вычисление может повториться, бизнес-эффект - нет. Retry ограничен и использует backoff.
Задания, которым нужно только выполниться в срок, используют реализованный runtime из раздела [Задания по сроку](#задания-по-сроку). Будущие jobs ML и документов, результата которых ждет пользователь, имеют состояния queued, running, succeeded, failed, cancelled, лимит попыток, available_at, lease/heartbeat и безопасный код ошибки. Взятие атомарно. Истекший lease разрешает повтор; уникальный ключ операции, версия документа и lease token не дают старому worker перезаписать новый результат. Вычисление может повториться, бизнес-эффект - нет. Retry ограничен и использует backoff.
Для долгой обработки API возвращает 202 и job ID, интерфейс опрашивает статус с увеличивающимся интервалом и прекращает опрос после завершения или ухода со страницы. Браузер не обращается к ML напрямую. Обычные тесты не загружают модель и не требуют GPU. Модель, лицензия, бюджет inference и реальные сроки отклика пока не выбраны.
@@ -577,7 +600,7 @@ contact_grant относится к паре кандидат-компания
## Будущее расширение
Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox, ее транзакционная запись, relay и runtime обработчиков реализованы (см. "Transactional outbox", "Relay outbox" и "Обработчики событий" выше); продуктовые обработчики и дополнительные топики запланированы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
Шиной событий выбран Apache Kafka в режиме KRaft: доменные события, почта, вебхуки ATS, пересчеты и синхронизация с ФСП. PostgreSQL остается источником истины: в нем хранятся продуктовые факты и долговечное состояние заданий и расписаний. События попадают в Kafka только через transactional outbox, который записывается в той же транзакции PostgreSQL, что и факт; relay публикует строки outbox, а потребители идемпотентны и выдерживают повторную доставку, нарушение порядка между партициями и retry с дедупликацией. Redis не используется как очередь. Core Compose проект уже запускает один внутренний узел Kafka. Таблица outbox, ее транзакционная запись, relay и runtime обработчиков реализованы (см. "Transactional outbox", "Relay outbox" и "Обработчики событий" выше); зарегистрирован один продуктовый обработчик, `notification_delivery`; другие обработчики и дополнительные топики запланированы. Отдельный search, assessment или notification сервис выделяется только при собственном масштабе или lifecycle. gRPC нужен при нескольких внутренних сервисах и конкретной пользе protobuf/streaming; он не заменяет OpenAPI для браузера.
k3s не входит в критический путь. Его можно рассмотреть при готовом обслуживаемом кластере или измеренной потребности в нескольких узлах. Один узел k3s не дает HA. Переход требует probes/resources, секретов, storage backup, ingress и проверенных NetworkPolicy.
@@ -602,7 +625,7 @@ k3s не входит в критический путь. Его можно ра
## Метрики, телеметрия и alerts
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики очереди, inference и бизнес-событий пока не реализованы.
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Счетчики и gauges backlog заданий по сроку описаны в разделе [Задания по сроку](#задания-по-сроку). Метрики inference и бизнес-событий пока не реализованы.
План наблюдаемости включает метрики jobs: очередь, возраст старейшего готового задания, время ожидания и выполнения, retries и окончательные ошибки; состояние pgxpool должно собираться внутри Go ограниченными неблокирующими запросами. Nginx `stub_status` не дает latency по HTTP статусам; access logs могут измерять `request_time` и `upstream_response_time`. cAdvisor можно добавить при поддержке выбранного runtime. Redis exporter уже включен в отдельный monitoring Compose, Prometheus опрашивает его на внутреннем порту 9121. Метрики SeaweedFS опрашиваются напрямую на внутреннем порту 9327; сохраняются только выбранные агрегированные серии, без путей объектов. DCGM exporter понадобится только при локальной NVIDIA модели.
+44
View File
@@ -170,6 +170,50 @@ Dead letter - запись, от которой обработчик отказ
Чтобы посмотреть `invalid_record`, пока топик ее хранит, прочитайте ровно эту запись через `kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1` и сравните ее SHA-256 с `value_sha256`. Значение может содержать персональные данные, поэтому не вставляйте его в задачи и чаты.
### Задания по сроку
Backend запускает worker заданий по сроку как горутину процесса backend рядом с HTTP-серверами, relay и обработчиками событий. Он выполняет задания, которые usecase запланировали в своих транзакциях, когда наступает их срок; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку). Текущее состояние: продуктовый вид задания не зарегистрирован, поэтому backend при старте пишет в журнал `no scheduled job kind is registered` и не запускает worker; настройки ниже все равно проверяются. С зарегистрированным видом worker работает, когда `JOBS_ENABLED` равно true и задан `DATABASE_URL`. Compose не передает ни одну из этих настроек, поэтому стенд использует значения по умолчанию; чтобы изменить значение, добавьте его в `environment` backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает запуск, даже когда worker выключен.
| Переменная | По умолчанию | Значение |
| --- | --- | --- |
| `JOBS_ENABLED` | `true` | `true` или `false`. При `false` или без `DATABASE_URL` задания не выполняются; наступившие задания ждут в `scheduled_jobs` и выполнятся после нового запуска worker с исходным `due_at`. |
| `JOBS_POLL_INTERVAL` | `1s` | Пауза после прохода, который захватил меньше полной пачки, от 10ms до 5m. Это же обычное опоздание задания после его срока. |
| `JOBS_BATCH_SIZE` | `10` | Задания, которые берет один захват, от 1 до 100. Они выполняются друг за другом под lease, взятыми вместе, поэтому пачка должна укладываться в один lease с запасом. |
| `JOBS_LEASE_DURATION` | `1m` | Сколько захваченное задание принадлежит одному worker, от 1s до 1h. Ограничивает одну попытку обработчика и служит серверными `statement_timeout` и `idle_in_transaction_session_timeout` транзакции задания. Упавший worker задерживает свои задания не больше чем на это время. |
| `JOBS_MAX_ATTEMPTS` | `5` | Попытки задания без собственного лимита до перехода в dead, от 1 до 100. Сбои базы данных вне обработчика и остановка не учитываются. |
| `JOBS_BACKOFF_INITIAL` | `1s` | Задержка перед первым повтором неудачного задания; удваивается с каждой неудачной попыткой. Этот же backoff разносит захваты, пока база данных недоступна. |
| `JOBS_BACKOFF_MAX` | `5m` | Наибольшая задержка перед повтором, от `JOBS_BACKOFF_INITIAL` до 24h. |
| `JOBS_SHUTDOWN_GRACE` | `5s` | Время, за которое задание в работе может зафиксироваться после начала остановки; не больше `SHUTDOWN_TIMEOUT`. После него транзакция откатывается, а задание освобождается незавершенным. |
Сроки и lease сравниваются по часам backend, а не базы данных, поэтому держите часы всех хостов backend синхронизированными через NTP. Спешащие часы запускают задания раньше и раньше перехватывают lease; блокировка строки все равно не дает выполнить задание второй раз, пока работает обработчик.
Бюджет остановки. Worker останавливается параллельно с другими workers: `JOBS_SHUTDOWN_GRACE` (5s) на задание в работе, до 5s на откат отмененной транзакции и до 5s на освобождение незавершенных заданий, всего не больше 15s. Это укладывается в первую фазу бюджета из раздела [Обработчики событий](#обработчики-событий), поэтому общий бюджет остается около 23s внутри `stop_grace_period: 30s`; увеличивайте его вместе с `JOBS_SHUTDOWN_GRACE`. Если backend убит, его задания остаются `running` до истечения lease, а затем выполняются на другом экземпляре или после перезапуска.
У worker собственный пул PostgreSQL не больше чем на два соединения. Несколько экземпляров backend делят задания: каждый захват пропускает строки, заблокированные другим экземпляром, и каждый экземпляр может выполнять любой зарегистрированный вид.
Оператор следит за `lincodex_scheduled_jobs_total{kind,outcome}` на внутреннем endpoint /metrics: `done`, `retry` (попытка не удалась, задание ждет backoff), `dead`, `lease_lost` (задание отменили или захватили заново, пока его держал этот экземпляр) и `released` (возвращено незавершенным при остановке или после сбоя базы данных). Каждый ряд существует с нулем с момента старта, поэтому alert можно строить как `increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0`. `lincodex_scheduled_jobs_due` и `lincodex_scheduled_jobs_oldest_due_age_seconds` описывают наступившие задания, которые ждут worker; если возраст растет дольше нескольких интервалов опроса, их никто не захватывает, например потому что worker выключен, база данных недоступна или ни у одного работающего экземпляра нет обработчика их вида. `lincodex_scheduled_jobs_dead` считает dead задания. Каждый экземпляр сообщает одни и те же значения по всей базе, поэтому агрегируйте их через `max`. Во время поэтапного развертывания, которое добавляет новый вид, его уже наступившие задания ждут, пока заработает экземпляр с обработчиком, и возраст может ненадолго выглядеть как застрявший worker; держите alert по возрасту дольше, чем длится развертывание. Журналы содержат компонент `scheduled_jobs`, владельца lease, ID задания, вид, номер попытки и класс ошибки, но никогда ключ или payload; dead задание пишется на уровне error как `scheduled job is dead; it needs an operator`.
#### Dead задания
`last_error_class` объясняет, почему задание стало dead: `handler_rejected` (обработчик никогда не сможет его выполнить), `handler_panic` (строка журнала `scheduled job handler panicked` с тем же ID задания содержит стек), `lease_expired` (последняя начатая попытка остановилась незавершенной, обычно из-за падения или kill, или ее сбой не удалось записать, потому что в этот момент была недоступна база данных) или класс последней неудачной попытки после исчерпания попыток: `handler_failed`, `timeout`, `conflict` или `effect_rejected`, а также `completion_conflict` (обработчик изменил собственное задание иначе, чем отменой). Список dead и просроченных заданий можно получить через psql в контейнере базы данных (команда открытия описана в разделе [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск)):
SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class,
due_at, available_at, updated_at
FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at;
SELECT kind, status, count(*), min(available_at)
FROM scheduled_jobs
WHERE status IN ('pending', 'failed', 'running') AND available_at <= now()
GROUP BY kind, status;
Ключ указывает на продуктовую запись, например ID приглашения; payload содержит только идентификаторы. После устранения причины, обычно развертывания исправленного обработчика, запустите dead задание снова. Меняйте только `available_at` и никогда `due_at`: обработчик принимает решение по сроку в `due_at`.
UPDATE scheduled_jobs
SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp()
WHERE id = <id> AND status = 'dead';
Worker захватит его в течение одного интервала опроса и выполнит с новыми попытками. Чтобы отказаться от dead задания, задайте `status = 'cancelled'` с тем же условием; его ключ остается занятым, поэтому продуктовый сценарий не сможет запланировать его снова. Не удаляйте строки: удаленный ключ можно запланировать снова и выполнить второй раз.
## Почта
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
+7 -1
View File
@@ -57,7 +57,7 @@ Frontend зависимости выбираются из актуальных s
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`) и таблица заданий по сроку (`scheduled_jobs`, продуктовый вид задания пока не зарегистрирован), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
## Установка и цикл работы
@@ -199,6 +199,12 @@ Backend, запущенный напрямую с зарегистрирован
Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
### Задания по сроку
Чтобы выполнить что-то в срок, например истечение или напоминание, запланируйте задание в собственной транзакции usecase: соберите его через `domain.NewScheduledJob` (вид, например `invitation.response_deadline`, ключ логического задания, например ID агрегата, срок по внедренным часам и payload только из идентификаторов) и вызовите `unit.ScheduledJobs().Schedule(ctx, job)`. Побеждает первое планирование вида и ключа, повтор игнорируется, поэтому для нового повторения используйте новый ключ, например `<id>:<version>`. Отменяйте через `unit.ScheduledJobs().Cancel(ctx, kind, key)` до блокировки продуктовых строк, которые трогает обработчик.
Затем реализуйте `inbound.JobHandler` в пакете usecase модуля: верните вид из `JobKind()` и пишите эффект в `Handle` только через полученный `UnitOfWork`, принимая решение по `job.DueAt` и текущему продуктовому состоянию, чтобы обработчик ничего не делал, если состояние уже изменилось. Обработчик может отменить собственное задание через unit, например из общего helper, который отменяет срок; тогда задание считается выполненным. Иначе менять собственное задание нельзя. Для задания, которое нельзя выполнить никогда, верните ошибку, оборачивающую `inbound.ErrJobRejected`; любая другая ошибка повторяется. Добавьте обработчик в `jobHandlers()` в `backend/internal/bootstrap/jobs.go`. Принимайте часы как `func() time.Time` и проверяйте сроки через `testutil.FakeClock` из `backend/pkg/testutil/` и `Worker.RunDue`, который один раз выполняет наступившие задания без опроса, как это делает `TestScheduledJobs`. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку); настройки, метрики и порядок работы с dead заданиями - в [DEPLOY.md](DEPLOY.md#задания-по-сроку); тесты - в [TESTING.md](TESTING.md#тесты-заданий-по-сроку).
## Читаемость Go-кода
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
+21
View File
@@ -185,6 +185,27 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор не вызывает транспорт: worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, - это TASK-016.
## Тесты заданий по сроку
Unit-тесты (`make -C backend test`) проверяют runtime заданий с хранилищем в памяти, которое повторяет правила захвата, проверки lease и освобождения хранилища PostgreSQL, и с fake clock из `backend/pkg/testutil/` (`internal/worker/jobrunner/`): выполняются только наступившие задания зарегистрированных видов в порядке срока, а задание со сроком через два дня выполняется ровно тогда, когда часы его достигают; неудачное задание повторяется после backoff по часам, не захватывается раньше и после последней попытки становится dead с записью в журнал уровня error и метриками; `ErrJobRejected` и panic завершают задание после одной попытки, а значение panic не попадает в журнал; обработчик, переживший свой lease, падает как `timeout`; задание, которое другой worker захватил до начала, пропускается без вызова обработчика; задание с истекшим lease последней начатой попытки становится dead без выполнения; медленное первое задание пачки не тратит единственную попытку следующего и не убивает его, а другой worker выполняет задание, которое занятый worker захватил, но не начал, на той же попытке; сбой базы данных вне обработчика освобождает задание и остаток пачки без учета попыток; неудачные захваты ждут backoff, а не крутятся в цикле; при остановке задание в работе завершается внутри grace, задание, которое его переживает, отменяется и освобождается без эффекта и без учтенной попытки, а захваченные, но не начатые задания освобождаются; panic во время остановки все равно делает задание dead; backlog всех видов попадает в метрики. Остальные unit-тесты покрывают правила задания (`internal/domain/`: вид, ключ, плоский payload, лимит размера, срок в UTC с точностью до микросекунд), настройки (`config/`), счетчики и gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), а в `internal/bootstrap/` - случаи без запуска с их строками журнала, пустой реестр видов, повторный вид и приложение, которое запускает worker против недоступной базы и все равно останавливается.
`TestScheduledJobs` в `backend/integration_test/scheduled_jobs_test.go` использует `bootstrap(t, postgresService)`. Его обработчик существует только в тесте: он пишет одну строку в `job_test.effects`, таблицу без уникального ключа, в транзакции, которая завершает задание, поэтому второй эффект остался бы виден. У каждого имитируемого процесса свой пул, хранилище и worker; создание нового означает перезапуск. Все решения о сроках и lease принимаются по одному `FakeClock`. Последовательные случаи:
- Задания на разные даты: два задания запланированы через `UnitOfWork.ScheduledJobs()` на завтра и через три дня, а повторное планирование игнорируется и не сдвигает срок. В начале ничего не выполняется; после перезапуска и одного дня выполняется первое задание; после еще одного перезапуска второе не выполняется за микросекунду до срока и выполняется в свой срок; через месяц снова ничего не выполняется. Эффектов по одному на задание, в порядке сроков.
- Два worker с собственными пулами одновременно крутят свои циклы над 40 наступившими заданиями: все задания выполнены, эффектов ровно 40 для 40 разных заданий.
- Обработчик, переживший lease по часам, по-прежнему держит блокировку строки задания, поэтому захват другого worker пропускает задание; затем первый worker завершает его с одним эффектом.
- Истекший lease: worker A захватывает и запускает задание и останавливается внутри него. Worker B не может захватить его за микросекунду до истечения lease и выполняет его в момент истечения, с двумя учтенными попытками и записанным `lease_expired`. Поздний запуск worker A отклоняется, его поздний `Run` возвращает `ErrJobLeaseLost` без вызова обработчика, а поздняя запись сбоя и освобождение отклоняются; эффект остается один.
- Начатая попытка задания с лимитом в одну попытку, lease которой истек: следующий захват делает задание dead с одной попыткой и `lease_expired` без вызова обработчика.
- Захват, который так и не начался, с лимитом в одну попытку: после истечения lease другой worker выполняет задание на той же попытке без класса ошибки.
- Медленное первое задание пачки работает дольше lease захвата: следующее задание с лимитом в одну попытку освобождается с сохраненной попыткой и выполняется в следующем проходе. С двумя worker, пока медленное задание держит свою строку, другой worker захватывает только ожидающее задание и выполняет его на единственной попытке; занятый worker затем считает его `lease_lost`.
- Обработчик, который отменяет собственное задание через unit: его эффект фиксируется, задание остается `cancelled`, а следующее задание прохода выполняется. Обработчик, который меняет собственное задание иначе, переводит его в dead с `completion_conflict` и не оставляет эффекта.
- Корректная остановка: обработчик пишет эффект и переживает grace в 200 ms. После остановки эффект откачен, задание в `pending` без попыток и без lease, а новый процесс сразу выполняет его, не дожидаясь lease.
- Неудачное задание с собственным лимитом в две попытки: первая попытка сдвигает на backoff только `available_at` и сохраняет `due_at`, задание не захватывается до окончания backoff, вторая попытка делает его dead, обработчик оба раза видел исходный срок, эффектов нет, backlog показывает одно dead задание, а счетчики - один `retry` и один `dead`.
- Отмена: отмененное задание никогда не захватывается, повторная отмена и новое планирование того же ключа ничего не делают, наступивших заданий нет.
- Отмена во время выполнения: пока обработчик держит задание, отмена в другой транзакции видна в `pg_stat_activity` как ожидание блокировки строки; после фиксации обработчика задание выполнено, а отмена возвращает false.
`TestPostgresMigrations` также проверяет, что миграция 00008 создает и удаляет `scheduled_jobs`. Набор использует один PostgreSQL и тестовый вид задания. Он не измеряет пропускную способность, не покрывает расхождение часов между экземплярами, переключение базы данных и продуктовый обработчик и не проверяет доставку alerts.
## Шардирование интеграционных тестов
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.