feat(mail): send service identity mail through a leased worker
This commit is contained in:
1 parent
204c6bae62
commit
d21fd49a42
58 files changed
+7577
-164
No files matched your search
+91
-20
@@ -190,7 +190,7 @@ Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `d
|
||||
|
||||
### 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).
|
||||
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. The only caller is the sending worker for service identity mail (TASK-016, see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until TASK-462. Settings are described in [DEPLOY.md](DEPLOY.md#mail).
|
||||
|
||||
`Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of:
|
||||
|
||||
@@ -224,11 +224,11 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt
|
||||
| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend |
|
||||
| The caller's context ended before the request was written | the context error; nothing was sent |
|
||||
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy (TASK-017), the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Planned: the worker that claims due deliveries, passes them through the quota gate, and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), and the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and nothing sends a stored delivery.
|
||||
Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Implemented (TASK-016): the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy (TASK-017), and sending product notifications with the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests.
|
||||
|
||||
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
|
||||
|
||||
@@ -248,7 +248,7 @@ Creation path:
|
||||
|
||||
Why the event carries only a reference. Events stay in `outbox_events` and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in `mail_requests`, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation.
|
||||
|
||||
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are to be created by the identity flows directly in the transaction that issues the token, through the same `domain.NewDelivery` and `DeliveryRepository.Create`; that wiring is planned with TASK-016 and the registration and reset tasks.
|
||||
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer` (TASK-016), which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks.
|
||||
|
||||
Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with `domain.ErrMailContentIntegrity` on a mismatch. The trigger `deliveries_refuse_content_change` refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint `deliveries_content_immutable`, mapped to `outbound.ErrDeliveryContentImmutable`). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery.
|
||||
|
||||
@@ -256,7 +256,7 @@ Personal data at rest. A delivery row holds the recipient address and the bodies
|
||||
|
||||
- Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see [DEPLOY.md](DEPLOY.md#mail-deliveries).
|
||||
- Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row.
|
||||
- A retention rule that deletes or clears terminal deliveries after a bounded period is not implemented yet; until it exists, rows stay. Encryption of the bodies at rest is not implemented either.
|
||||
- The bodies of a token mail are cleared when the delivery reaches `accepted`, `rejected`, or `cancelled` (`body_redacted_at`, see [Sending service mail](#sending-service-mail)), so a database dump or backup holds no token of a finished mail; a retention rule that deletes other terminal deliveries after a bounded period is not implemented yet, and until it exists those rows stay. Encryption of the bodies at rest is not implemented either.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics (TASK-022) carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject.
|
||||
|
||||
Statuses. The values follow the `MailSender` outcomes:
|
||||
@@ -264,15 +264,17 @@ Statuses. The values follow the `MailSender` outcomes:
|
||||
| Status | Meaning | `next_attempt_at` |
|
||||
| --- | --- | --- |
|
||||
| `pending` | Waits for its first attempt, or for a retry after a `temporary` or `rate_limited` rejection | Required: when it is due |
|
||||
| `accepted` | The provider accepted the message and returned `provider_message_id`; not delivery to or reading by a person | None; terminal |
|
||||
| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal |
|
||||
| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal |
|
||||
| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": a retry reuses the key and the stored body | Optional; none means no automatic retry |
|
||||
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
|
||||
| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides |
|
||||
|
||||
Transitions:
|
||||
|
||||
- `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted` and `rejected` refuse any further attempt with `domain.ErrDeliveryTransition`.
|
||||
- `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted`, `rejected`, and `cancelled` refuse any further attempt with `domain.ErrDeliveryTransition`.
|
||||
- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where TASK-018's local quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it.
|
||||
- `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it.
|
||||
- `Delivery.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it.
|
||||
|
||||
Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy (TASK-017) and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`.
|
||||
@@ -283,17 +285,13 @@ Quota accounting is not derived from this history: the cascade from an account d
|
||||
|
||||
Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. `EMAIL_ACCOUNT` names the account (`default` unless set); change it whenever `RESEND_API_KEY` moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: `Delivery.Rebind` refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint `deliveries_provider_pinned`, mapped to `outbound.ErrDeliveryProviderPinned`). TASK-016 uses it for deliveries created while `EMAIL_PROVIDER=disabled` once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision.
|
||||
|
||||
Planned additive changes for later tasks. Each is a new column, index, or CHECK value in a later migration; existing rows stay valid:
|
||||
Migration `00012_add_delivery_sending.sql` (TASK-016) is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission (TASK-462).
|
||||
|
||||
- A terminal cancelled status for a delivery that must not be sent anymore: a token or account invalidated before the send (TASK-016) or a revoked permission (TASK-462).
|
||||
- A nullable reference from a token mail delivery to `email_tokens.id`, so the worker can check that the token is still the active one for its purpose before it sends (TASK-016).
|
||||
- For the sending worker (TASK-016): lease columns (for example a claim owner and `claimed_until`) and a partial index on `next_attempt_at` for the statuses that are picked up again, so several processes claim due deliveries with `FOR UPDATE SKIP LOCKED` and an attempt whose process stopped after the request becomes `unknown`.
|
||||
|
||||
The store already provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, and `Rebind`.
|
||||
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`.
|
||||
|
||||
### Mail quotas
|
||||
|
||||
Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). Planned: the sending worker that calls the gate around `MailSender.Send` and builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP (TASK-016) and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing.
|
||||
Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker (TASK-016) calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota while TASK-462 is open.
|
||||
|
||||
Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets.
|
||||
|
||||
@@ -330,11 +328,82 @@ What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID
|
||||
| `waiting_quota` with `WaitingUntil` | Your email is waiting until `<WaitingUntil>` |
|
||||
| `waiting_quota` without `WaitingUntil` | Your email is waiting; the time is not known yet |
|
||||
| `pending`, `unknown` | Your email is being sent. `unknown` is not shown as a failure: the message may have been accepted |
|
||||
| `accepted` | Your email was sent. It means that the provider accepted it, not that it reached the inbox |
|
||||
| `accepted` | Your email was handed to the email provider, which accepted it. We cannot confirm that it reached your inbox |
|
||||
| `rejected` | Your email could not be sent |
|
||||
| `cancelled` | Your email was not sent because the link in it is no longer valid; request a new one |
|
||||
|
||||
Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges (TASK-022) come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts).
|
||||
|
||||
### Sending service mail
|
||||
|
||||
Implemented (TASK-016): the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications (TASK-462), the retry and unknown outcome policy (TASK-017), and the identity flows that call `ServiceMailer`.
|
||||
|
||||
Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
|
||||
|
||||
Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was.
|
||||
|
||||
Links. The token travels only in the URL fragment: `<APP_PUBLIC_URL>/verify-email#token=<token>` and `<APP_PUBLIC_URL>/reset-password#token=<token>`, built by `mailtemplate` (`tokenLink`). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records `$uri`, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend route reads the fragment and sends the token in the body of an API request. A query would be needed only if a frontend route could not read the fragment, and then the page would have to send the token onward and the access log would see it, so the fragment is the choice. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no `?token=`. The body in `deliveries` holds the live token until the mail is sent or cancelled; see Personal data at rest.
|
||||
|
||||
One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps:
|
||||
|
||||
1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending` or `waiting_quota`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. A delivery in `unknown`, or in `waiting_quota` without a time, has no due time and waits for an operator. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows.
|
||||
2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and notes `first_send_started_at` the first time. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/<id>`. The sender never retries. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace.
|
||||
3. Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then `QuotaGate.SettleSend` and `DeliveryRepository.RecordClaimedAttempt` commit together, and the lease ends with the attempt. `RecordClaimedAttempt` applies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reports `lease_lost`. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored.
|
||||
|
||||
Time budget. The lease is `EMAIL_TIMEOUT` plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and `SHUTDOWN_TIMEOUT` minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below.
|
||||
|
||||
Lock order. Every path locks the delivery row first and the quota rows second: the claim locks the row with `FOR UPDATE SKIP LOCKED`, and the check and the settlement start with `LockClaimed` (`SELECT ... FOR UPDATE` of the row of the lease holder), so no two paths can wait for each other in opposite directions.
|
||||
|
||||
Check before sending. In the claim transaction, `Delivery.CheckServiceMail` compares the delivery with a snapshot read in one statement (`ServiceMailState`: the token and the account, no lock, only the address comparison key). The first failure cancels the delivery with `cancelled` and that reason; nothing is reserved and nothing is sent:
|
||||
|
||||
| Order | Rule | Reason |
|
||||
| --- | --- | --- |
|
||||
| 1 | A token is bound and its row exists | `token_missing` |
|
||||
| 2 | Its purpose is the one the mail kind carries (`email_verification` for verification, `password_reset` for reset) | `token_purpose_mismatch` |
|
||||
| 3 | It belongs to the recipient account | `token_owner_mismatch` |
|
||||
| 4 | It is not consumed | `token_consumed` |
|
||||
| 5 | It is not revoked (`invalidated_at`, by a resend or a re-registration) | `token_revoked` |
|
||||
| 6 | It has not expired | `token_expired` |
|
||||
| 7 | The account still has the registration version the token was issued for, and a verification mail does not go to an address that is verified already | `account_not_current` |
|
||||
| 8 | The address in the delivery is still the account's address | `recipient_mismatch` |
|
||||
|
||||
A claimed row whose content no longer matches its hash (only a manual edit can cause that) is cancelled by the claim itself with `content_invalid`, with the bodies cleared like any cancelled token mail, and logged at error level with the delivery ID. Any other failure to restore a row may be transient, so it is not cancelled for good: it is a failing row, below.
|
||||
|
||||
There is no deactivated flag on an account. "Current" is rule 7 and the token rules: a re-registration moves the version and revokes the token, and a deleted account takes its deliveries with it by cascade, so nothing is left to send. A reset mail has no verification-state rule: that the reset applies only to verified accounts is a product decision for the reset flow. The check is a snapshot: a token consumed or revoked after it, before the provider call, still lets the mail go. That is harmless, because the link is checked again when it is used.
|
||||
|
||||
What a provider answer becomes. The delivery state machine of `domain.Delivery` decides; the worker only fills the attempt:
|
||||
|
||||
| Result | Delivery | Next attempt | Quota |
|
||||
| --- | --- | --- | --- |
|
||||
| `accepted` | `accepted`, provider message ID stored | none | counted |
|
||||
| `rejected` `permanent` or `invalid_request` | `rejected` | none | released |
|
||||
| `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released |
|
||||
| `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full |
|
||||
| `unknown` | `unknown` | none: no automatic retry (TASK-017) | counted |
|
||||
| `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released |
|
||||
| `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released |
|
||||
| `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released |
|
||||
|
||||
The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. `unknown` is never read as not sent and is never repeated by the worker; an operator decides, and the alert `LincodexMailDeliveryUnknownOutcome` fires.
|
||||
|
||||
A worker lost after the call. If a worker stops after it called the provider but before it stored the answer, its lease expires and another worker claims the delivery on the same attempt and repeats the request with the same idempotency key. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt.
|
||||
|
||||
Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (`ErrInvalidDelivery`, `ErrDeliveryTransition`, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, `outbound.ErrRowFault`). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (`RecordFailure`): `failure_count` is incremented, the lease ends, and the row is due again by `RetryPolicy` (outcome `row_failed`; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a `row_failed` pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason `processing_failed`, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires.
|
||||
|
||||
`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins.
|
||||
|
||||
Loop and shutdown. `worker/mailsender` repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota.
|
||||
|
||||
Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` is not terminal and keeps its body, because a retry resends it; an operator who resolves it must clear it. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies.
|
||||
|
||||
Privacy. Logs name a delivery only by `delivery_id`, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. `ServiceMailSender` builds the outgoing message from the stored content and never logs it; `OutgoingMail` and `Delivery` redact themselves.
|
||||
|
||||
Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used by production code: `backend/.golangci.yml` forbids importing the fixture and calling the constructor outside `_test.go` files (depguard and forbidigo), and `bootstrap` binds the real transport with `resend.NewSender`.
|
||||
|
||||
Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint.
|
||||
|
||||
Open points. `unknown` has no automatic retry or escalation until TASK-017. Sending notifications, and the permission check they need, belong to TASK-462; until then they wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
|
||||
|
||||
### Product policy versions
|
||||
|
||||
Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented.
|
||||
@@ -423,7 +492,7 @@ backend/
|
||||
usecase/policy/ publication of policy versions and the demo policy seed
|
||||
usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check
|
||||
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
|
||||
usecase/notification/ mail requests and the consumer that stores them as deliveries
|
||||
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), and the sender of service mail (`ServiceMailSender`)
|
||||
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
|
||||
adapter/primary/http/
|
||||
@@ -438,6 +507,7 @@ backend/
|
||||
kafka/ franz-go event publisher and consumer group member: record envelope, its decoding, and events topic provisioning
|
||||
mail/disabled/ mail transport that sends nothing and reports the channel unavailable
|
||||
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
|
||||
mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it
|
||||
ml/api/ generated client from backend/codegen/ogen-ml.yml
|
||||
postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
@@ -447,6 +517,7 @@ backend/
|
||||
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/mailsender/ sending loop of service identity mail: repeats passes, waits when idle, backs off on failures, reports lincodex_mail_sender_running
|
||||
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
|
||||
worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics
|
||||
bootstrap/ configuration, wiring, lifecycle, shutdown
|
||||
@@ -459,9 +530,9 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
|
||||
|
||||
Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, 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.
|
||||
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, the mail template renderer, and the sending worker of service identity mail, which no account flow feeds yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, 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. `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, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. 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/`.
|
||||
`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, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. 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; `ServiceMailer` renders verification and password reset mail with it when the identity usecases issue a token, and those usecases (registration, resend, reset) are separate tasks. 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.
|
||||
|
||||
@@ -719,7 +790,7 @@ The Go service exports standard Go/process metrics and the product metrics of TA
|
||||
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged.
|
||||
- Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, and `rejected`, zero included; `lincodex_mail_delivery_oldest_due_pending_age_seconds`; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet, because the sending worker (TASK-016) does not exist.
|
||||
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
|
||||
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
|
||||
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
|
||||
@@ -728,7 +799,7 @@ Planned observability work includes bounded measurements for queued jobs, oldest
|
||||
|
||||
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
|
||||
|
||||
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running`, which the sending worker of TASK-016 must export, so it stays inert until then. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
|
||||
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
|
||||
|
||||
## Requirements coverage
|
||||
|
||||
|
||||
+23
-7
@@ -218,7 +218,7 @@ A worker claims it within one poll interval and runs it with fresh attempts. To
|
||||
|
||||
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.
|
||||
|
||||
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. No flow sends mail yet: mail requests are stored as deliveries (see [Mail deliveries](#mail-deliveries)), and the worker that calls the transport is planned.
|
||||
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until TASK-462, so a production stand sends no message today.
|
||||
|
||||
`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
|
||||
|
||||
@@ -243,18 +243,18 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. The deliveries are only stored for now: the worker that sends them is planned, so no row leaves `pending`. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
||||
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until TASK-462 connects product notifications. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
||||
|
||||
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Deliveries created while `EMAIL_PROVIDER=disabled` stay pinned to `disabled` until the sending worker (TASK-016) moves them with `Rebind`, which is allowed only before the first attempt.
|
||||
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand.
|
||||
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
|
||||
- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats.
|
||||
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Until the sending worker exists (TASK-016), every stored delivery stays `pending` and its due age only grows. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1; that gauge belongs to the sending worker of TASK-016, which must export it while its loop runs, so the alert stays silent while no sender exists, with `EMAIL_PROVIDER=disabled`, and without traffic.
|
||||
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until TASK-462; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until TASK-462, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider.
|
||||
- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision.
|
||||
- Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request.
|
||||
|
||||
### Mail quotas
|
||||
|
||||
Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The quota gate is implemented, but the sending worker that calls it is planned (TASK-016), so the current build counts nothing yet. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
||||
Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until TASK-462. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
||||
|
||||
- Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart.
|
||||
- Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month.
|
||||
@@ -266,12 +266,28 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo
|
||||
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017).
|
||||
- Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit.
|
||||
|
||||
### Sending service mail
|
||||
|
||||
The backend process runs one sending loop for service identity mail (email verification and password reset). It starts with the backend when `EMAIL_PROVIDER` is `resend` and `DATABASE_URL` is set, shares the database with the other workers on a pool of two connections, and needs no setting of its own: the poll interval (5 seconds), the lease on a claimed delivery (`EMAIL_TIMEOUT` plus one minute), the shutdown grace (5 seconds), the retry schedule (1 minute doubling to 30 minutes), and the failure backoff (5 seconds doubling to 2 minutes) are constants in `backend/internal/bootstrap/mail_sender.go`. Migration 00012 adds its columns; the model, the checks, and the outcomes are in [ARCHITECTURE.md](ARCHITECTURE.md#sending-service-mail).
|
||||
|
||||
- Several backend instances may run at once. Each claims a delivery with `FOR UPDATE SKIP LOCKED` and a lease, so one delivery is sent by one instance, and the provider call carries the stable idempotency key `delivery/<id>`. During a rolling deployment the instance that stops finishes its send within 5 seconds, stores the result, and exits.
|
||||
- With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off.
|
||||
- Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one".
|
||||
- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A refusal for now (`temporary`, `rate_limited`) leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the same key and body; it repeats until it succeeds, is refused for good, or the token expires and the delivery is cancelled. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas).
|
||||
- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy (TASK-017).
|
||||
- A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand.
|
||||
- `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled.
|
||||
- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. Do not copy bodies of waiting mail anywhere.
|
||||
- The lease is measured by the database clock, so clock differences between instances do not matter; only the database's clock does. The call to the provider is bounded by what is left of the lease; with `SHUTDOWN_TIMEOUT` at its default of 10 seconds a stopping instance finishes within 3 seconds of grace plus 5 seconds to store the answer. Lowering `SHUTDOWN_TIMEOUT` shortens the second part (at least 1 second); a result that cannot be stored in time is covered by the takeover.
|
||||
- Logs name a delivery only by `delivery_id`, its kind, and the outcome or cancel reason, for example `service mail was not sent because it is no longer valid`; never an address, a token, a link, or a body. If a token or link appears in a log, treat it as a defect.
|
||||
- The internal /metrics endpoint shows `lincodex_mail_sender_running` (1 while this instance's loop runs, 0 otherwise; no labels) and `lincodex_mail_sender_cancelled_total{reason}` (a counter per cancel reason, zero included) next to the delivery gauges, which also have the status `cancelled`.
|
||||
|
||||
### Mail templates
|
||||
|
||||
Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications with it when it stores a delivery; registration, verification, password reset, and sending are planned, so the current build sends no message.
|
||||
Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications with it when it stores a delivery, and `ServiceMailer` renders verification and password reset mail when an identity flow issues a token; the flows themselves (registration, verification, password reset) are planned, so no account triggers a message yet.
|
||||
|
||||
- Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl`, and `<kind>.v<N>.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address.
|
||||
- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `<APP_PUBLIC_URL>/verify-email#token=<token>`; password reset: `<APP_PUBLIC_URL>/reset-password#token=<token>` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the query. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected.
|
||||
- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `<APP_PUBLIC_URL>/verify-email#token=<token>`; password reset: `<APP_PUBLIC_URL>/reset-password#token=<token>` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it, and the frontend route reads it in the browser and sends it in an API request body. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected.
|
||||
- Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000.
|
||||
- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery.
|
||||
- The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed.
|
||||
|
||||
@@ -50,7 +50,7 @@ What exists now:
|
||||
|
||||
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
|
||||
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap.
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends them yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends notifications yet (TASK-462). With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
|
||||
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers).
|
||||
|
||||
+41
-1
@@ -199,7 +199,47 @@ Unit tests (`make -C backend test`) cover the quota rules without a database:
|
||||
- Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`.
|
||||
- The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome.
|
||||
|
||||
`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.
|
||||
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence (TASK-016) is covered by the service mail sending tests below.
|
||||
|
||||
## Service mail sending tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover:
|
||||
|
||||
- `domain`: `Delivery.CheckServiceMail` names the first failed rule (missing token, purpose, owner, consumed, revoked, expired exactly at its deadline, registration moved, verified address, changed address) and leaves a current verification or reset mail sendable; `Delivery.Cancel` works from `pending` and `waiting_quota`, refuses `unknown` and the terminal statuses, leaves no attempt, and survives a restore; a notification cannot carry a token ID; the status names contain no claim of delivery to a person.
|
||||
- `usecase/notification`: `ServiceMailSender` against in-memory stores with the version rule and the lease of the PostgreSQL store, the in-memory quota of the gate, and a scripted transport. Every transport result becomes the right delivery state, due time, and quota effect (accepted, permanent and invalid-request refusal, temporary refusal after the first backoff, a provider wait hint longer than the backoff, the provider's daily quota answer until midnight UTC, a quota answer without a reset, unknown, a transport that answers without an outcome, no transport, an interrupted call, an invalid message); every cancel reason is reached without a transport call or a reservation; a full local quota parks the delivery without a call and sends it at the reset; a result that cannot be stored keeps the lease, is repeated three times, and is then covered by a replacement under the same key without counting twice; an attempt lost beyond the idempotency window, or with a transport without deduplication, is recorded as unknown and not repeated; a delivery whose content hash does not match is cancelled as `content_invalid` and reported without calling the transport; a row that fails by its own fault (unreadable for a reason other than a hash mismatch, a domain rule broken while reading its state) is counted, moved back by the retry schedule so the delivery behind it is sent, and cancelled as `processing_failed` after three failures; transient errors (deadline, cancellation, deadlock, network, EOF, missing quota configuration) are reported to the worker and never counted or cancelled however often they repeat; a `Send` error without an answer moves the row back without counting it; paused counting moves rows back without counting; a successful pass clears the count; a failure is not recorded for a row another worker holds; the idempotency window is counted from the first request across repeated lost workers and with the one-hour margin; a revocation between the claim and the call is honored; a result is dropped when the lease was lost during the call; the call is bounded by the lease minus the settle budget; jitter is bounded and injectable; mail stored while no transport ran is rebound to the configured account and a delivery of another account is left alone; logs never hold the address, the token, or the link. `ServiceMailer` stores a token-bound delivery under the token ID with the token in the fragment of the link and no `?token=`, repeats harmlessly, and refuses a token of the wrong purpose before rendering. `RetryPolicy` doubles to its maximum and honors a longer hint.
|
||||
- `worker/mailsender`: cancelled deliveries are counted by reason; the breaker pauses failure counting after three different rows fail in a row and resumes after a success, and one row failing again does not trip it; a failing row makes the loop wait by the backoff; the gauge is true only while the loop runs, an idle pass waits for the poll interval, a handled delivery is followed at once by the next pass, and a missing transport, an interrupted call, or a database failure back off instead of spinning.
|
||||
- `adapter/secondary/postgres`: only SQLSTATE classes 22 and 23 match `ErrRowFault`; deadlock, serialization, connection, resource, shutdown, and internal errors do not.
|
||||
- `adapter/secondary/prometheus`: `lincodex_mail_sender_cancelled_total` has every reason at zero and refuses an arbitrary label; `lincodex_mail_sender_running` exists at 0 and follows `SetMailSenderRunning`; every delivery status including `cancelled` exists at zero.
|
||||
- `adapter/secondary/mail/resend`: the loopback constructor accepts only an http URL on a loopback host, so the key and the messages of a deployment cannot be pointed at another host through it; `resendfixture` answers like Resend (accepts, replays a repeated key and body with the original message, refuses another body under the key, plays scripted errors).
|
||||
- `bootstrap`: no worker without a transport or a database; the loop starts and stops with the application and the gauge follows.
|
||||
- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` stays silent without the gauge, while it is 0, and for a notification-only backlog (age 0), and fires while some instance reports 1; `LincodexMailCancelledBroken` fires on `content_invalid` and `processing_failed` and stays silent on user-caused reasons (`make -C observability check`).
|
||||
|
||||
`TestServiceMailSending` in `backend/integration_test/mail_sender_test.go` uses `bootstrap(t, postgresService)`, the real transactor, stores, quota gate, and sending usecase, the real Resend transport pointed at the local fixture, and a fake clock. Subtests share the database and start from empty tables:
|
||||
|
||||
- A service email for a synthetic account with no consent record of any purpose is enqueued with its token in one transaction and accepted by the fixture: one provider call with the key `delivery/<id>`, the address, and the link with the token in the fragment; the delivery is `accepted` with the provider message ID, one accepted attempt, one counted recipient, no lease left, the account's status is `accepted`, and a second pass does nothing. Logs hold neither the address nor the token.
|
||||
- A worker that holds a delivery keeps another off it: the fixture answers slowly, the second worker's pass is idle while the first one's request is in flight, and the fixture gets exactly one call and the database one attempt.
|
||||
- Four workers drain a queue of eight deliveries at once: eight provider calls under eight distinct keys, none replayed, eight accepted deliveries with one attempt each, eight counted recipients.
|
||||
- A worker that stopped after sending (the database fails when it stores the answer) is replaced after its lease expires: two calls under the same key, the second a replay, one message at the provider, one attempt, and the open reservation reused, so the recipient counts once. Beyond the 24-hour window the replacement records an unknown attempt and does not call the provider.
|
||||
- A delivery whose content hash was broken by a manual edit is cancelled as `content_invalid` at version 2 without a provider call, and the delivery behind it is sent in the next pass.
|
||||
- A row that fails for a reason of its own (a subject that breaks the domain rules, so the row cannot be restored although its hash is intact) is counted and moved back by a minute while the delivery behind it is sent, fails again at each due time, and is cancelled as `processing_failed` on the third failure with its bodies cleared; a transport error without an answer moves the row back by a minute without counting it, with the reservation given back and the delivery pending.
|
||||
- A failure recorded by a worker whose claim rolled back leaves a row alone that another worker holds, and an uncounted failure leaves `failure_count` at 0.
|
||||
- Three workers lost in turn do not hide the age of the first request: the delivery becomes `unknown` once `first_send_started_at` is 24 hours old, and the provider is not called a fourth time.
|
||||
- The lease is a few seconds by the database clock; a stranger cannot record an attempt or lock the row; `RecordClaimedAttempt` succeeds for the holder.
|
||||
- Over 5000 due notification rows the claim plan uses `deliveries_due_idx` and no sequential scan (`EXPLAIN`).
|
||||
- A notification-only backlog does not make the earliest pending age appear; a service mail does.
|
||||
- A token mail's bodies are cleared when it is accepted or cancelled and the token no longer appears in any row; a waiting mail cannot be cleared by hand; a cleared row cannot get a body back or lose its mark; the account still sees its status.
|
||||
- A token revoked by a resend, a token already used, an expired token, an account registered again, an address already verified, a changed address, and a token of another purpose each end the delivery as `cancelled` with the matching reason, no attempt, no lease, no next attempt, no reservation, and no provider call; the account sees `cancelled`; a further pass is idle. A deleted account takes its delivery with it.
|
||||
- Provider answers: a 503 `service_unavailable` leaves the delivery `pending` due one minute later, a pass before that is idle, the retry at the due time repeats the key and is accepted; a 500 is `unknown` with no next attempt and no retry a day later; a 403 `validation_error` is `rejected`.
|
||||
- Quota: a local limit of one per day parks the second delivery in `waiting_quota` until midnight UTC without a provider call, the account sees the wait and its end, and the delivery is sent at the reset; the provider's `daily_quota_exceeded` answer parks the delivery until the next midnight.
|
||||
- A product notification is never claimed.
|
||||
- `EMAIL_PROVIDER=disabled`: with the disabled transport the pass reports the channel unavailable, the delivery stays untouched at version 1, the lease and the reservation are released, nothing reaches the fixture, a loop run against it makes at most four passes in under a second, and the gauge is 1 while it runs and 0 after; with a transport the same mail is rebound to the configured account and accepted.
|
||||
- The schema refuses a cancelled delivery without a reason, a reason on another status, a half lease, a lease on a terminal delivery, a notification bound to a token, a change of the token binding, and the deletion of a token that a delivery references; deleting the account removes both.
|
||||
|
||||
`TestDeliverySendingMigration` rolls back and applies migration 00012 over a cancelled and redacted reset delivery: the earlier schema keeps it as `rejected` with a placeholder body, drops reset tokens and the new columns, and the migration applies again. `TestPostgresMigrations` covers the generic up, down, and up path.
|
||||
|
||||
`make -C backend lint` also forbids importing `resendfixture` and calling `resend.NewLoopbackSender` outside `_test.go` files (depguard and forbidigo in `backend/.golangci.yml`).
|
||||
|
||||
No check calls the real Resend API: the fixture is the only provider, so these tests prove the protocol the transport speaks and the delivery rules, not Resend's behavior, deliverability, or the account's real quota.
|
||||
|
||||
## Scheduled job tests
|
||||
|
||||
|
||||
+91
-20
@@ -190,7 +190,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Почтовый транспорт
|
||||
|
||||
Реализовано: 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#почта).
|
||||
Реализовано: 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 отправки служебной почты identity (TASK-016, см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
|
||||
|
||||
`Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из:
|
||||
|
||||
@@ -224,11 +224,11 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| Сбой до записи запроса: DNS, соединение, TLS или таймаут попытки | `rejected`, `temporary`: полный запрос до Resend не дошел |
|
||||
| Контекст вызывающего завершился до записи запроса | ошибка контекста; ничего не отправлено |
|
||||
|
||||
Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit, предел числа попыток и остановка по окончании 24-часового окна ключа относятся к запланированному слою доставки; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты).
|
||||
Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit и предел числа попыток относятся к политике повторов (TASK-017), worker отправки применяет только минимальное расписание из раздела [Отправка служебной почты](#отправка-служебной-почты), а остановка по окончании 24-часового окна ключа - его правило для попытки, чей worker потерян; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты).
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Запланировано: worker, который берет доставки к отправке, пропускает их через шлюз квот и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017) и проверка разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет.
|
||||
Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Реализовано (TASK-016): worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода (TASK-017) и отправка продуктовых уведомлений с проверкой разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет.
|
||||
|
||||
Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит:
|
||||
|
||||
@@ -248,7 +248,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Почему событие несет только ссылку. События хранятся в `outbox_events` и в Kafka в пределах retention топика, а правило доменных событий разрешает только идентификаторы и минимальные факты. FR19 также требует, чтобы очередь не сохраняла доступ к отозванным данным. Поэтому текст лежит в `mail_requests`, которые удаление аккаунта убирает каскадно, и только пока он нужен: обработчик удаляет строку в той же транзакции, где сохраняет сформированную доставку. После этого текст есть только в доставке, с ее правилами хранения и доступа. Адрес обработчик читает из аккаунта в своей транзакции, поэтому это адрес, актуальный на момент создания.
|
||||
|
||||
Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном должны создавать сценарии identity прямо в транзакции, которая выпускает токен, через те же `domain.NewDelivery` и `DeliveryRepository.Create`; это подключение запланировано вместе с TASK-016 и задачами регистрации и сброса пароля.
|
||||
Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer` (TASK-016): он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи.
|
||||
|
||||
Неизменяемое содержимое. Доставка хранит отрендеренное тело и никогда не рендерит его заново. Для рендеринга во время отправки нужен исходный токен, который существует только в памяти в момент выпуска, а повтор под тем же ключом идемпотентности должен повторить ровно то же тело: Resend считает измененное тело под старым ключом конфликтом. Domain пересчитывает hash содержимого при каждом чтении и при несовпадении возвращает `domain.ErrMailContentIntegrity`. Trigger `deliveries_refuse_content_change` отклоняет UPDATE, меняющий получателя, содержимое, ключ идемпотентности, исходное событие или время создания (SQLSTATE 23000, ограничение `deliveries_content_immutable`, адаптер переводит его в `outbound.ErrDeliveryContentImmutable`). Поэтому новая версия шаблона применяется только к новым доставкам, а для отправки сохраненной доставки старые файлы шаблона не нужны.
|
||||
|
||||
@@ -256,7 +256,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
- Запросы для эксплуатации выбирают столбцы метаданных (ID, вид, статус, попытки, время, провайдер) и никогда не выбирают тела, текст запроса и адрес; см. [DEPLOY.md](DEPLOY.md#доставки-писем).
|
||||
- Удаление аккаунта каскадно удаляет его запросы писем, доставки и их попытки. Очистка неподтвержденных аккаунтов блокирует их через `FOR UPDATE SKIP LOCKED`, как токены и сессии, поэтому никогда не ждет обработчик доставки или worker, который держит строку.
|
||||
- Правило хранения, которое удаляет или очищает завершенные доставки через ограниченный срок, еще не реализовано; пока его нет, строки остаются. Шифрование тел в хранилище тоже не реализовано.
|
||||
- Тела письма с токеном очищаются, когда доставка достигает `accepted`, `rejected` или `cancelled` (`body_redacted_at`, см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому дамп или резервная копия базы не содержат токена завершенного письма; правило хранения, которое удаляет остальные завершенные доставки через ограниченный срок, еще не реализовано, и пока его нет, эти строки остаются. Шифрование тел в хранилище тоже не реализовано.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки (TASK-022) несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы.
|
||||
|
||||
Статусы. Значения следуют исходам `MailSender`:
|
||||
@@ -264,15 +264,17 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| Статус | Значение | `next_attempt_at` |
|
||||
| --- | --- | --- |
|
||||
| `pending` | Ждет первую попытку или повтор после отказа `temporary` или `rate_limited` | Обязательно: когда доставка должна быть отправлена |
|
||||
| `accepted` | Провайдер принял письмо и вернул `provider_message_id`; это не доставка человеку и не прочтение | Нет; конечный |
|
||||
| `accepted` | Провайдер принял письмо и вернул `provider_message_id`: "принято провайдером". Это не доставка человеку и не прочтение; ни один статус этого не утверждает | Нет; конечный |
|
||||
| `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный |
|
||||
| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет |
|
||||
| `cancelled` | Письмо намеренно не отправлено и не будет: токен или аккаунт перестали соответствовать доставке, или сохраненное письмо нельзя отправить. `cancel_reason` говорит почему; попытка не записывается | Нет; конечный |
|
||||
| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс (см. [Квоты почты](#квоты-почты)); отсутствует, когда момент сброса неизвестен, например после ответа провайдера о квоте без окна и без паузы, и решение принимает оператор |
|
||||
|
||||
Переходы:
|
||||
|
||||
- `Delivery.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted` и `rejected` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`.
|
||||
- `Delivery.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted`, `rejected` и `cancelled` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`.
|
||||
- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная квота TASK-018 откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`.
|
||||
- `Delivery.Cancel(at, reason)` завершает доставку из `pending` или `waiting_quota` в `cancelled` без попытки; причина - одна из `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Переход отклоняет `unknown`, как `WaitForQuota`: прошлая попытка могла быть принята, поэтому письмо никогда не объявляется неотправленным. Сохраняет его `DeliveryRepository.Cancel`.
|
||||
- `Delivery.Rebind(at, account)` переносит доставку без единой попытки на другой аккаунт провайдера; см. ниже. Сохраняет его `DeliveryRepository.Rebind`.
|
||||
|
||||
Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода (TASK-017), и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`.
|
||||
@@ -283,17 +285,13 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). TASK-016 использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача.
|
||||
|
||||
Запланированные аддитивные изменения для следующих задач. Каждое - новый столбец, индекс или значение CHECK в следующей миграции; существующие строки остаются корректными:
|
||||
Миграция `00012_add_delivery_sending.sql` (TASK-016) аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению (TASK-462).
|
||||
|
||||
- Конечный статус отмены для доставки, которую больше нельзя отправлять: токен или аккаунт аннулирован до отправки (TASK-016) или отозвано разрешение (TASK-462).
|
||||
- Необязательная ссылка доставки письма с токеном на `email_tokens.id`, чтобы worker перед отправкой проверил, что токен все еще действующий для своего назначения (TASK-016).
|
||||
- Для worker отправки (TASK-016): столбцы lease (например, владелец захвата и `claimed_until`) и частичный индекс по `next_attempt_at` для статусов, которые берутся снова, чтобы несколько процессов захватывали доставки через `FOR UPDATE SKIP LOCKED`, а попытка, процесс которой остановился после отправки запроса, становилась `unknown`.
|
||||
|
||||
Хранилище уже дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota` и `Rebind`.
|
||||
Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Запланировано: worker отправки, который вызывает шлюз вокруг `MailSender.Send` и собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP (TASK-016) и API или сценарий identity, который показывает результат чтения статуса. Пока ничего не отправляется, поэтому текущая сборка ничего не считает.
|
||||
Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки (TASK-016) вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока открыта TASK-462, в квоту считается только служебная почта identity.
|
||||
|
||||
Лимиты. `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают число получателей, отправленных через настроенный аккаунт провайдера (`EMAIL_PROVIDER` и `EMAIL_ACCOUNT`), за UTC-сутки, с 00:00 до 00:00 UTC, и за календарный месяц UTC. Считается каждый получатель, как считает Resend; у доставки один получатель. Значения по умолчанию - лимиты Resend Free, проверенные 05.10.2026: 100 и 3000; они действуют для `resend` и для `disabled`, который ничего не отправляет. У `smtp` значений по умолчанию нет, и без обоих значений он не запускается: лимиты relay не совпадают с лимитами Resend. Допустимы значения от 1 до 1000000000, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна.
|
||||
|
||||
@@ -330,11 +328,82 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| `waiting_quota` с `WaitingUntil` | Ваше письмо ожидает отправки до `<WaitingUntil>` |
|
||||
| `waiting_quota` без `WaitingUntil` | Ваше письмо ожидает отправки; время пока неизвестно |
|
||||
| `pending`, `unknown` | Ваше письмо отправляется. `unknown` не показывается как сбой: письмо могло быть принято |
|
||||
| `accepted` | Ваше письмо отправлено. Это значит, что провайдер его принял, а не что оно дошло до ящика |
|
||||
| `accepted` | Ваше письмо передано почтовому провайдеру, и он его принял. Подтвердить, что оно дошло до вашего ящика, мы не можем |
|
||||
| `rejected` | Ваше письмо не удалось отправить |
|
||||
| `cancelled` | Ваше письмо не отправлено, потому что ссылка в нем больше не действует; запросите новое |
|
||||
|
||||
Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот (TASK-022) читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts).
|
||||
|
||||
### Отправка служебной почты
|
||||
|
||||
Реализовано (TASK-016): usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений (TASK-462), политика повторов и неизвестного исхода (TASK-017) и сценарии identity, которые вызывают `ServiceMailer`.
|
||||
|
||||
Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было. Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие.
|
||||
|
||||
Постановка. `ServiceMailer.EnqueueVerification` и `EnqueuePasswordReset` выполняются в транзакции, которая вставляет токен, и получают запись токена, исходный токен, адрес получателя и срок действия в часах. Они проверяют, что назначение токена подходит письму, один раз рендерят письмо текущей версией шаблона и сохраняют доставку `pending`, привязанную к токену (`email_token_id`), с ID токена в роли ID доставки. Повторный вызов для того же токена ничего нового не сохраняет, а сохраненное тело остается прежним.
|
||||
|
||||
Ссылки. Токен передается только во фрагменте URL: `<APP_PUBLIC_URL>/verify-email#token=<token>` и `<APP_PUBLIC_URL>/reset-password#token=<token>`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Маршрут frontend читает фрагмент и отправляет токен в теле запроса API. Query понадобился бы, только если бы маршрут frontend не мог прочитать фрагмент, но тогда страница отправляла бы токен дальше, а access log его видел бы, поэтому выбран фрагмент. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище".
|
||||
|
||||
Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага:
|
||||
|
||||
1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending` или `waiting_quota`, `next_attempt_at` наступил, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Он записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов никогда не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения, поэтому экземпляры с разными часами не могут перехватить живой lease или держать мертвый; сроки доставок остаются на часах приложения, которые их записали. У доставки в `unknown` или в `waiting_quota` без времени нет срока, и она ждет оператора. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки".
|
||||
2. Проверка прямо перед отправкой, одна короткая транзакция: она блокирует строку доставки (только для владельца lease), заново читает токен и аккаунт через `ServiceMailState`, поэтому отзыв после фиксации захвата учитывается, и в первый раз записывает `first_send_started_at`. Письмо, которое больше нельзя отправлять, отменяется, а резервирование возвращается. Затем один вызов `MailSender.Send` с сохраненным содержимым и стабильным ключом идемпотентности `delivery/<id>`. Отправитель никогда не повторяет вызов. Вызов ограничен тем, что осталось от lease после захвата и бюджета расчета, и льготным периодом остановки.
|
||||
3. Транзакция расчета. Она сначала блокирует строку доставки (только пока этот worker держит lease), затем `QuotaGate.SettleSend` и `DeliveryRepository.RecordClaimedAttempt` фиксируются вместе, а lease заканчивается вместе с попыткой. `RecordClaimedAttempt` применяется только поверх версии доставки и только для владельца lease, поэтому worker, чей lease перехвачен, записать не может, а если два worker дошли до этого шага для одной доставки, сохраняется только первая; вторая откатывается вместе с расчетом квоты и сообщает `lease_lost`. Сбой базы при сохранении ответа повторяется до трех раз в пределах бюджета расчета, потому что ответ до сохранения существует только в памяти.
|
||||
|
||||
Бюджет времени. Lease равен `EMAIL_TIMEOUT` плюс одна минута. Сначала идут захват и проверка; вызов получает остаток lease за вычетом бюджета расчета (20 секунд), поэтому захват, вызов и весь расчет умещаются в lease. Когда остановка началась, бюджет расчета - меньшее из 5 секунд и `SHUTDOWN_TIMEOUT` за вычетом 3 секунд льготного периода остановки (не меньше 1 секунды), поэтому процесс останавливается в пределах своего тайм-аута остановки, по умолчанию 10 секунд (период остановки в Compose - 30 секунд). Результат, который не удалось сохранить вовремя, покрывает перехват ниже.
|
||||
|
||||
Порядок блокировок. Каждый путь блокирует сначала строку доставки, затем строки квоты: захват блокирует строку через `FOR UPDATE SKIP LOCKED`, а проверка и расчет начинаются с `LockClaimed` (`SELECT ... FOR UPDATE` строки владельца lease), поэтому две транзакции не могут ждать друг друга в противоположных направлениях.
|
||||
|
||||
Проверка перед отправкой. В транзакции захвата `Delivery.CheckServiceMail` сравнивает доставку со снимком, прочитанным одним запросом (`ServiceMailState`: токен и аккаунт, без блокировок, из адреса - только ключ сравнения). Первая неудача отменяет доставку статусом `cancelled` с этой причиной; ничего не резервируется и не отправляется:
|
||||
|
||||
| Порядок | Правило | Причина |
|
||||
| --- | --- | --- |
|
||||
| 1 | Токен привязан, и его строка существует | `token_missing` |
|
||||
| 2 | Его назначение совпадает с тем, которое несет вид письма (`email_verification` для подтверждения, `password_reset` для сброса) | `token_purpose_mismatch` |
|
||||
| 3 | Он принадлежит аккаунту получателя | `token_owner_mismatch` |
|
||||
| 4 | Он не использован | `token_consumed` |
|
||||
| 5 | Он не отозван (`invalidated_at`, повторной отправкой или повторной регистрацией) | `token_revoked` |
|
||||
| 6 | Его срок не истек | `token_expired` |
|
||||
| 7 | У аккаунта все еще та версия регистрации, для которой выпущен токен, а письмо подтверждения не идет на уже подтвержденный адрес | `account_not_current` |
|
||||
| 8 | Адрес в доставке все еще адрес аккаунта | `recipient_mismatch` |
|
||||
|
||||
Захваченная строка, чье содержимое больше не совпадает с хешем (это может вызвать только ручная правка), отменяется самим захватом с причиной `content_invalid`, тела очищаются, как у любого отмененного письма с токеном, а в журнал на уровне error пишется ID доставки. Любой другой сбой восстановления строки может быть временным, поэтому навсегда она не отменяется: это сбойная строка, см. ниже.
|
||||
|
||||
Признака деактивированного аккаунта нет. "Актуален" - это правило 7 и правила токена: повторная регистрация сдвигает версию и отзывает токен, а удаленный аккаунт уносит свои доставки каскадом, так что отправлять нечего. У письма сброса нет правила про состояние подтверждения: что сброс применяется только к подтвержденным аккаунтам, решает сценарий сброса. Проверка - снимок: токен, использованный или отозванный после нее и до вызова провайдера, не остановит письмо. Это безвредно, потому что ссылка проверяется снова при использовании.
|
||||
|
||||
Во что превращается ответ провайдера. Решает конечный автомат `domain.Delivery`; worker лишь заполняет попытку:
|
||||
|
||||
| Результат | Доставка | Следующая попытка | Квота |
|
||||
| --- | --- | --- | --- |
|
||||
| `accepted` | `accepted`, ID сообщения провайдера сохранен | нет | считается |
|
||||
| `rejected` `permanent` или `invalid_request` | `rejected` | нет | возвращается |
|
||||
| `rejected` `temporary` или `rate_limited` | `pending` | сейчас плюс `RetryPolicy`: 1 минута, удвоение до 30 минут, не меньше `Retry-After` провайдера | возвращается |
|
||||
| `rejected` `quota_exhausted` | `waiting_quota` | сброс, который вернул шлюз (ближайшие 00:00 UTC для суток, первое число следующего месяца для месяца); нет, если провайдер не назвал окно | окно отмечено заполненным |
|
||||
| `unknown` | `unknown` | нет: автоматического повтора нет (TASK-017) | считается |
|
||||
| Ошибка `Send`: нет транспорта (`ErrMailChannelUnavailable`) или context завершился | без изменений, lease освобожден | остается срок | возвращается |
|
||||
| Ошибка `Send`: неверное сообщение (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | нет | возвращается |
|
||||
| Ошибка `Send`: любая другая без ответа | не считается против строки; она отодвигается по `RetryPolicy`, а worker делает паузу | сейчас плюс `RetryPolicy` | возвращается |
|
||||
|
||||
В расписании повторов нет предела числа попыток намеренно: токен истекает, и тогда проверка отменяет доставку с `token_expired`. К каждой паузе добавляется ограниченный jitter, до пятой части сверх расписания, из подменяемого источника (в тестах nil, поэтому время точное), чтобы доставки, отклоненные вместе, не возвращались вместе. `unknown` никогда не читается как неотправленное и никогда не повторяется worker; решает оператор, и срабатывает alert `LincodexMailDeliveryUnknownOutcome`.
|
||||
|
||||
Worker потерян после вызова. Если worker остановился после вызова провайдера, но до сохранения ответа, его lease истекает, и другой worker берет доставку на той же попытке и повторяет запрос с тем же ключом идемпотентности. Resend отвечает на повторный ключ и тело исходным результатом, а шлюз квот повторно использует открытое резервирование, поэтому письмо существует одно и считается один раз. Провайдер хранит ключ 24 часа от первого запроса, поэтому возраст считается от `first_send_started_at` (его по часам базы записывает проверка прямо перед первым запросом), а не от последнего lease: сколько бы worker ни потерялось подряд и какой бы длины ни был lease, когда этот возраст достигает 23 часов (окно за вычетом часового запаса), прежний запрос может быть забыт, и повтор способен отправить письмо дважды, поэтому вместо этого доставка записывается как попытка `unknown` без следующей попытки. То же применяется сразу для транспорта без дедупликации на стороне провайдера (окно ноль, SMTP). Lease, не дошедший до первого запроса, ничего не оставляет под сомнением.
|
||||
|
||||
Сбойные строки. Сбой одной строки не должен занимать начало очереди. Когда транзакция захвата падает после того, как взяла строку, ее lease откатывается вместе с ней, и та же строка тут же была бы взята снова, а все доставки за ней ждали бы. Против строки считается только сбой, который вызывает сама строка: нарушаемое ею правило домена (`ErrInvalidDelivery`, `ErrDeliveryTransition`, неверное содержимое или адрес), строку нельзя восстановить по причине, отличной от несовпадения хеша, или отказ ограничения данных или целостности (классы SQLSTATE 22 и 23, `outbound.ErrRowFault`). Все остальное о строке ничего не говорит и никогда не считается: завершившийся context, тайм-аут, deadlock, потеря соединения (SQLSTATE 08, 40, 53, 57, XX), ошибка ввода-вывода, отсутствие настройки квоты. Такая ошибка возвращается worker, который делает паузу, как при любом глобальном сбое, а lease истекает или откатывается. Для считаемого сбоя отправитель записывает его короткой отдельной транзакцией (`RecordFailure`): `failure_count` растет, lease заканчивается, и строка снова должна быть отправлена по `RetryPolicy` (исход `row_failed`; следующий проход берет доставку за ней). Запрос не трогает строку, которую другой worker держит под живым lease, поэтому откатившийся захват не может помешать строке, которую кто-то только что взял. Счетчик означает сбои подряд: успешный захват и подготовка (проверка перед отправкой) его очищают, как и записанная попытка. Предохранитель в worker останавливает счет, когда сбои попадают на разные строки проход за проходом: три прохода подряд, упавших на трех разных строках, читаются как глобальный сбой, worker ждет с растущей паузой (проход `row_failed` никогда не крутится сразу), а сбои отодвигаются, но не считаются и ни одна строка не отменяется, пока проход не завершится успешно. После 3 считаемых сбоев подряд строка отменяется с причиной `processing_failed`: это существующий конечный статус, который подходит, оператор его видит, и срабатывает alert ниже, поэтому новый статус не понадобился. Если сбой базы мешает и этой записи, строка остается под своим lease, который истекает.
|
||||
|
||||
`EMAIL_PROVIDER=disabled`. Bootstrap не запускает цикл: `newMailSenderWorker` не возвращает worker и пишет `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, поэтому `lincodex_mail_sender_running` остается 0, а `LincodexMailDeliveriesOverdue` молчит. Сохраненные письма ждут, закрепленные за `disabled`; после перезапуска стенда с транспортом worker переносит их и отправляет, если токен и аккаунт проходят проверку. Worker, который все же запущен с транспортом disabled (в тестах), получает `ErrMailChannelUnavailable` на каждую отправку, ничего не записывает, освобождает lease и резервирование и делает паузу (5 секунд с удвоением до 2 минут) вместо немедленного нового захвата, так что он никогда не крутится вхолостую.
|
||||
|
||||
Цикл и остановка. `worker/mailsender` повторяет проходы: после прохода, обработавшего доставку, сразу идет следующий, после холостого прохода worker ждет 5 секунд, а после сбоя базы, отсутствия транспорта или прерванного вызова ждет с растущей паузой. Когда context завершается, worker больше ничего не захватывает, дает выполняющейся отправке продолжиться 5 секунд, сохраняет ее результат и возвращается; после этого gauge равен 0. Цикл - горутина процесса backend на собственном pool из двух соединений, как у других worker; больший объем дают дополнительные экземпляры, а каждый обрабатывает одну доставку за раз, что подходит для служебной почты при квоте Resend Free.
|
||||
|
||||
Токен в хранилище. Тело письма с токеном содержит одноразовый токен, а токен сброса - примитив захвата аккаунта для любого, кто может читать базу или резервную копию. Когда письмо с токеном достигает `accepted`, `rejected` или `cancelled` (любым путем: попыткой, отменой, отменой испорченной строки или `processing_failed`), тот же запрос делает `text_body` и `html_body` пустыми и ставит `body_redacted_at`; тема, хеш содержимого и версия шаблона остаются. Trigger разрешает ровно это изменение один раз для конечной строки и отклоняет любое другое изменение тел или метки; CHECK `deliveries_body_present` принимает пустое тело только с меткой; домен восстанавливает такую строку как очищенное содержимое (`RestoreRedactedMailContent`), которое отправить нельзя. `unknown` не конечный и сохраняет тело, потому что повтор отправляет его снова; оператор, который его разрешает, должен очистить его. Уведомления не очищаются. Откат миграции 00012 подставляет заглушку в очищенные тела.
|
||||
|
||||
Приватность. Журнал называет доставку только по `delivery_id`, ее виду и закрытым значениям (исход и причина отмены); адрес, токен, ссылка, тема и тело не попадают ни в строку журнала, ни в ошибку, ни в label метрики, а у метрики вообще нет labels. `ServiceMailSender` строит исходящее письмо из сохраненного содержимого и никогда его не логирует; `OutgoingMail` и `Delivery` скрывают себя сами.
|
||||
|
||||
Только тестовая подмена. `resendfixture` и `resend.NewLoopbackSender` никогда не используются production-кодом: `backend/.golangci.yml` запрещает импорт подмены и вызов конструктора вне файлов `_test.go` (depguard и forbidigo), а `bootstrap` связывает настоящий транспорт через `resend.NewSender`.
|
||||
|
||||
Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint.
|
||||
|
||||
Открытые вопросы. У `unknown` нет автоматического повтора и эскалации до TASK-017. Отправка уведомлений и нужная ей проверка разрешений относятся к TASK-462; до нее они ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
|
||||
|
||||
### Версии продуктовой политики
|
||||
|
||||
Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач.
|
||||
@@ -423,7 +492,7 @@ backend/
|
||||
usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики
|
||||
usecase/consent/ выдача согласий C1-C3 и C5 и C4 со scope с проверкой актуального текста
|
||||
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
|
||||
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки
|
||||
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки, шлюз квот, постановка служебной почты (`ServiceMailer`) и отправитель служебной почты (`ServiceMailSender`)
|
||||
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
|
||||
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты
|
||||
adapter/primary/http/
|
||||
@@ -438,6 +507,7 @@ backend/
|
||||
kafka/ publisher событий и участник consumer group на franz-go: конверт записи, его декодирование и создание топика событий
|
||||
mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала
|
||||
mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend
|
||||
mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует
|
||||
ml/api/ generated client из backend/codegen/ogen-ml.yml
|
||||
postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
@@ -447,6 +517,7 @@ backend/
|
||||
worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка
|
||||
worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка
|
||||
worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка
|
||||
worker/mailsender/ цикл отправки служебной почты identity: повторяет проходы, ждет без работы, откатывается при сбоях, сообщает lincodex_mail_sender_running
|
||||
worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers
|
||||
worker/deliverymetrics/ периодическое чтение агрегатов доставок и квот почты в метрики
|
||||
bootstrap/ конфигурация, wiring, lifecycle, shutdown
|
||||
@@ -459,9 +530,9 @@ backend/
|
||||
|
||||
`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
|
||||
|
||||
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка почты, транспорт 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 шаблонов писем и worker отправки служебной почты identity, который пока не питает ни один сценарий аккаунта. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
|
||||
|
||||
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `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`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` рендерит им письма подтверждения и сброса пароля, когда usecase identity выпускают токен, а сами эти usecase (регистрация, повторная отправка, сброс) - отдельные задачи. Шаблоны, версии и формат ссылок описаны в [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.
|
||||
|
||||
@@ -719,7 +790,7 @@ Go экспортирует стандартные Go/process метрики и
|
||||
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются.
|
||||
- Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted` и `rejected`, включая нулевые; `lincodex_mail_delivery_oldest_due_pending_age_seconds`; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет, потому что worker отправки (TASK-016) еще не существует.
|
||||
- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected` и `cancelled`, включая нулевые; `lincodex_mail_sender_running` - 1, пока цикл отправки почты этого процесса работает, и 0 иначе (по процессу, поэтому агрегируйте через `max`; при `EMAIL_PROVIDER=disabled` остается 0, цикл не запускается); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, который считает только служебную почту (`domain.ServiceMailKinds`), поэтому очередь уведомлений никогда не выглядит просроченной; `lincodex_mail_sender_cancelled_total{reason}` - доставки, которые worker отправки завершил без отправки, по закрытому набору причин отмены, включая нулевые; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет; исходы показывают состояния доставок, журнал worker отправки и история `delivery_attempts`.
|
||||
- Ответы теста: `lincodex_assessment_answer_saves_total{format,outcome}` с исходами `stored`, `unchanged`, `rejected` и `failed`. PRD 6.6 требует наблюдать сохранение ответов; это понимается как команда ответа теста `SubmitMyAssessmentAnswer`. Команда не реализована, поэтому есть только hook `Metrics.ObserveAssessmentAnswerSave`, и серии не появятся, пока usecase не начнет вызывать его один раз на команду. Значение вне закрытых наборов превращается в `other`. Задержка и ошибки HTTP этой команды уже видны под маршрутом `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
|
||||
В labels нельзя помещать ID пользователя, кандидата, доставки или запроса, полный URL или query string, адреса и содержимое резюме. Unit-тесты прогоняют настоящий router и каждый hook метрик с fixture email и UUID и падают, если в выдаче есть значение, похожее на email или UUID. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS, Linux и продуктовый Lincodex поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики inference пока не реализованы.
|
||||
@@ -728,7 +799,7 @@ Go экспортирует стандартные Go/process метрики и
|
||||
|
||||
План браузерного пути: Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. React SDK пока не подключен. Собирать очищенные Web Vitals, JS errors, release и нормализованный маршрут; исключить console logs, формы, текст резюме и session replay. Удалять query string, fragment и ID из URL. Ограничить размер, частоту и origin приемника. Request/trace IDs остаются полями логов, не labels; хранение spans требует отдельного backend, например Tempo, и пока не поддерживается.
|
||||
|
||||
Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще `lincodex_mail_sender_running`, который должен экспортировать worker отправки из TASK-016, поэтому до него оно не срабатывает. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
|
||||
Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре, поэтому там, где цикл отправки не работает, например при `EMAIL_PROVIDER=disabled`, оно молчит. Оно считает только служебную почту, виды, которые отправляет worker, поэтому просроченное уведомление его не включает. `LincodexMailCancelledBroken` срабатывает при росте `lincodex_mail_sender_cancelled_total` с причиной `content_invalid` или `processing_failed`, то есть для отмен, означающих испорченную строку или дефект, а не действие пользователя. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
|
||||
|
||||
## Покрытие требований ТЗ
|
||||
|
||||
|
||||
+23
-7
@@ -220,7 +220,7 @@ Worker захватит его в течение одного интервала
|
||||
|
||||
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
|
||||
|
||||
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Пока ни один сценарий не отправляет почту: запросы писем сохраняются как доставки (см. [Доставки писем](#доставки-писем)), а worker, который вызывает транспорт, запланирован.
|
||||
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462, так что боевой стенд сегодня не отправляет ни одного письма.
|
||||
|
||||
`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов относятся к запланированному слою доставки, а ожидание сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
|
||||
|
||||
@@ -245,18 +245,18 @@ Compose передает эти переменные из корневого `.e
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Пока доставки только сохраняются: worker, который их отправляет, запланирован, поэтому ни одна строка не выходит из `pending`. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
|
||||
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока TASK-462 не подключит продуктовые уведомления. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
|
||||
|
||||
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Доставки, созданные при `EMAIL_PROVIDER=disabled`, остаются закрепленными за `disabled`, пока worker отправки (TASK-016) не перенесет их через `Rebind`, что разрешено только до первой попытки.
|
||||
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `Rebind` (разрешено только до первой попытки) и отправляет, если ее токен и аккаунт все еще проходят проверку. Не переносите вручную.
|
||||
- Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован.
|
||||
- Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты.
|
||||
- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Пока нет worker отправки (TASK-016), каждая сохраненная доставка остается в `pending`, а ее просрочка только растет. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще `lincodex_mail_sender_running`, равный 1; этот gauge принадлежит worker отправки из TASK-016, который должен экспортировать его, пока работает его цикл, поэтому alert молчит, пока отправителя нет, при `EMAIL_PROVIDER=disabled` и без трафика.
|
||||
- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до TASK-462; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до TASK-462, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером.
|
||||
- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` ждет сброса квоты в `next_attempt_at`; см. [Квоты почты](#квоты-почты). Без `next_attempt_at` момент сброса неизвестен, и нужно решение оператора.
|
||||
- Логи называют доставку только по `delivery_id` (вместе с ID события), никогда по адресу или теме. Пропущенные запросы пишутся на уровне info: `mail request skipped because it was already handled or its account was deleted` и `notification skipped because the recipient address is not verified`. Запрос, нарушающий контракт события, становится dead letter класса `handler_rejected` обработчика `notification_delivery`; см. [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск). Повторять его безопасно: ID доставки сохраняет одну доставку на запрос.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Шлюз квот реализован, но worker отправки, который его вызывает, запланирован (TASK-016), поэтому текущая сборка пока ничего не считает. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
|
||||
Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до TASK-462. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
|
||||
|
||||
- Задайте `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по тарифу аккаунта провайдера, который назван в `EMAIL_ACCOUNT`. Значения по умолчанию соответствуют Resend Free: 100 получателей за UTC-сутки и 3000 за месяц по проверке 05.10.2026. Сверьте текущую квоту аккаунта в панели Resend до запуска стенда и после любой смены тарифа. Для `smtp` задайте оба значения по лимитам relay; без них запуск завершается ошибкой. Измененное значение действует после перезапуска.
|
||||
- Меняйте `EMAIL_ACCOUNT` только вместе с настоящей сменой аккаунта провайдера, то есть с ключом другого аккаунта. Локальный счет ведется по метке аккаунта, поэтому переименование метки для того же аккаунта начинает счет с нуля, а у провайдера остается прежний. При запуске backend пишет в журнал `mail quota usage` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце.
|
||||
@@ -268,12 +268,28 @@ Compose передает эти переменные из корневого `.e
|
||||
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017).
|
||||
- Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита.
|
||||
|
||||
### Отправка служебной почты
|
||||
|
||||
Процесс backend запускает один цикл отправки служебной почты identity (подтверждение почты и сброс пароля). Он стартует вместе с backend, когда `EMAIL_PROVIDER` равен `resend` и задан `DATABASE_URL`, использует ту же базу, что и другие worker, через pool из двух соединений и не требует собственных настроек: интервал опроса (5 секунд), lease на захваченную доставку (`EMAIL_TIMEOUT` плюс одна минута), льготный период остановки (5 секунд), расписание повторов (1 минута с удвоением до 30 минут) и пауза после сбоя (5 секунд с удвоением до 2 минут) - константы в `backend/internal/bootstrap/mail_sender.go`. Миграция 00012 добавляет его столбцы; модель, проверки и исходы описаны в [ARCHITECTURE.md](ARCHITECTURE.md#отправка-служебной-почты).
|
||||
|
||||
- Одновременно может работать несколько экземпляров backend. Каждый захватывает доставку через `FOR UPDATE SKIP LOCKED` и lease, поэтому одну доставку отправляет один экземпляр, а вызов провайдера несет стабильный ключ идемпотентности `delivery/<id>`. При поэтапном обновлении останавливающийся экземпляр завершает отправку в течение 5 секунд, сохраняет результат и выходит.
|
||||
- При `EMAIL_PROVIDER=disabled` цикл не запускается, а в журнале пишется `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` равен 0, ничего не отправляется, а сохраненная служебная почта ждет следующего запуска с транспортом. Worker никогда не крутится вхолостую: после прохода, который ничего не смог отправить, он делает паузу.
|
||||
- Перед отправкой worker проверяет токен и аккаунт. Доставка, которую нельзя отправлять, завершается как `cancelled` с `cancel_reason`, без попытки и без расхода квоты: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Причины, вызванные пользователем, нормальны: пользователь запросил новую ссылку, подтвердил адрес, зарегистрировался заново или слишком долго ждал. Причины можно посмотреть так: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. Пользователь видит отмененное письмо как "не отправлено, запросите новое".
|
||||
- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Отказ "пока" (`temporary`, `rate_limited`) оставляет доставку в `pending` с более поздним `next_attempt_at`, а повтор использует тот же ключ и тело; он повторяется, пока не удастся, пока не будет отказа навсегда или пока токен не истечет и доставка не будет отменена. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты).
|
||||
- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов (TASK-017).
|
||||
- Захваченная доставка держит lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. Строка с давно прошедшим `claimed_until` значит, что ее worker умер; другой экземпляр подхватит ее сам. Не сбрасывайте lease вручную.
|
||||
- `content_invalid` и `processing_failed` - не действия пользователя: первое значит, что сохраненная строка не совпадает со своим хешем содержимого (ручная правка) или содержит сообщение, которое не принимает ни один транспорт, второе - что worker трижды подряд потерпел сбой на строке (повторы разнесены расписанием). Alert `LincodexMailCancelledBroken` срабатывает при росте; прочитайте журнал worker по `delivery_id` и осмотрите метаданные строки. Строка, которая сбоит постоянно, не блокирует остальные: она повторяется позже (`failure_count`, `next_attempt_at`), а затем отменяется.
|
||||
- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Не копируйте тела ожидающих писем никуда.
|
||||
- Lease измеряется часами базы, поэтому различие часов экземпляров не важно, важны только часы базы. Вызов провайдера ограничен остатком lease; при `SHUTDOWN_TIMEOUT` по умолчанию 10 секунд останавливающийся экземпляр укладывается в 3 секунды льготного периода плюс 5 секунд на сохранение ответа. Снижение `SHUTDOWN_TIMEOUT` укорачивает вторую часть (не меньше 1 секунды); результат, не сохраненный вовремя, покрывает перехват.
|
||||
- Журнал называет доставку только по `delivery_id`, ее виду и исходу или причине отмены, например `service mail was not sent because it is no longer valid`; никогда не по адресу, токену, ссылке или телу. Если токен или ссылка появились в журнале, считайте это дефектом.
|
||||
- Внутренний endpoint /metrics показывает `lincodex_mail_sender_running` (1, пока цикл этого экземпляра работает, иначе 0; без labels) и `lincodex_mail_sender_cancelled_total{reason}` (счетчик по причине отмены, включая нулевые) рядом с gauges доставок, у которых теперь есть и статус `cancelled`.
|
||||
|
||||
### Шаблоны писем
|
||||
|
||||
Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку; регистрация, подтверждение, сброс пароля и отправка запланированы, поэтому текущая сборка не отправляет писем.
|
||||
Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку, а `ServiceMailer` рендерит письма подтверждения и сброса пароля, когда сценарий identity выпускает токен; сами сценарии (регистрация, подтверждение, сброс пароля) запланированы, поэтому ни один аккаунт пока не вызывает письмо.
|
||||
|
||||
- Шаблоны встроены в бинарник через `go:embed` и разбираются один раз при создании renderer; сломанный шаблон останавливает создание. У каждой версии три файла: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl` и `<kind>.v<N>.html.tmpl`. HTML часть использует `html/template`, текстовая часть и тема используют `text/template`. Любой транспорт отправляет один и тот же результат; в шаблонах нет настроек провайдера, ключей и адреса отправителя.
|
||||
- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `<APP_PUBLIC_URL>/verify-email#token=<token>`; сброс пароля: `<APP_PUBLIC_URL>/reset-password#token=<token>` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда в query. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются.
|
||||
- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `<APP_PUBLIC_URL>/verify-email#token=<token>`; сброс пароля: `<APP_PUBLIC_URL>/reset-password#token=<token>` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда ни в пути, ни в query: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат, а маршрут frontend читает его в браузере и отправляет в теле запроса API. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются.
|
||||
- В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000.
|
||||
- Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Доставка хранит сформированное тело вместе с hash, а повтор отправляет сохраненное тело, а не формирует его заново, поэтому новая версия применяется только к новым доставкам, а файлы старой версии для отправки сохраненной доставки не нужны.
|
||||
- Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются.
|
||||
|
||||
@@ -50,7 +50,7 @@ Frontend зависимости выбираются из актуальных s
|
||||
|
||||
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
|
||||
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен.
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто их не отправляет. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления (TASK-462). С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers.
|
||||
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий).
|
||||
|
||||
+41
-1
@@ -199,7 +199,47 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
|
||||
- Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`.
|
||||
- База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход.
|
||||
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор не вызывает транспорт: worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, - это TASK-016.
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend` (TASK-016), покрыт тестами отправки служебной почты ниже.
|
||||
|
||||
## Тесты отправки служебной почты
|
||||
|
||||
Модульные тесты (`make -C backend test`) покрывают:
|
||||
|
||||
- `domain`: `Delivery.CheckServiceMail` называет первое нарушенное правило (нет токена, назначение, владелец, использован, отозван, истек ровно в свой срок, регистрация сдвинулась, адрес подтвержден, адрес изменен) и оставляет актуальное письмо подтверждения или сброса отправляемым; `Delivery.Cancel` работает из `pending` и `waiting_quota`, отклоняет `unknown` и конечные статусы, не оставляет попытки и переживает восстановление; уведомление не может нести ID токена; названия статусов не содержат утверждения о доставке человеку.
|
||||
- `usecase/notification`: `ServiceMailSender` против хранилищ в памяти с правилом версии и lease хранилища PostgreSQL, квоты шлюза в памяти и транспорта по сценарию. Каждый результат транспорта дает правильное состояние доставки, срок и эффект на квоту (принято, постоянный отказ и отказ запроса, временный отказ после первой паузы, более длинная подсказка провайдера, ответ провайдера о дневной квоте до полуночи UTC, ответ о квоте без сброса, unknown, транспорт, ответивший без исхода, нет транспорта, прерванный вызов, неверное сообщение); каждая причина отмены достигается без вызова транспорта и резервирования; заполненная локальная квота откладывает доставку без вызова и отправляет ее при сбросе; результат, который не удалось сохранить, сохраняет lease, повторяется три раза, а затем его подхватывает замена с тем же ключом без двойного подсчета; попытка, потерянная за пределами окна идемпотентности или у транспорта без дедупликации, записывается как unknown и не повторяется; доставка, чей хеш содержимого не совпадает, отменяется как `content_invalid` и сообщается без вызова транспорта; строка, которая сбоит по собственной вине (нечитаемая по причине, отличной от несовпадения хеша, нарушенное правило домена при чтении состояния), считается, отодвигается расписанием повторов, чтобы доставка за ней отправилась, и после трех сбоев отменяется как `processing_failed`; временные ошибки (тайм-аут, отмена, deadlock, сеть, EOF, отсутствие настройки квоты) возвращаются worker и никогда не считаются и не отменяют строку, сколько бы ни повторялись; ошибка `Send` без ответа отодвигает строку без счета; приостановленный счет отодвигает строки без счета; успешный проход очищает счетчик; сбой не записывается для строки, которую держит другой worker; окно идемпотентности считается от первого запроса при повторных потерях worker и с часовым запасом; отзыв между захватом и вызовом учитывается; результат отбрасывается, если lease потерян во время вызова; вызов ограничен lease за вычетом бюджета расчета; jitter ограничен и подменяем; письма, сохраненные, пока транспорта не было, переносятся на настроенный аккаунт, а доставка другого аккаунта остается нетронутой; журнал никогда не содержит адрес, токен или ссылку. `ServiceMailer` сохраняет доставку, привязанную к токену, с ID токена, токеном во fragment ссылки и без `?token=`, безвредно повторяется и отклоняет токен не того назначения до рендеринга. `RetryPolicy` удваивает паузу до максимума и учитывает более длинную подсказку.
|
||||
- `worker/mailsender`: отмененные доставки считаются по причине; предохранитель приостанавливает счет сбоев, когда подряд падают три разные строки, и возобновляет после успеха, а повторный сбой одной строки его не включает; сбойная строка заставляет цикл ждать по backoff; gauge равен true только пока работает цикл, холостой проход ждет интервал опроса, за обработанной доставкой сразу идет следующий проход, а отсутствие транспорта, прерванный вызов и сбой базы вызывают паузу вместо вращения вхолостую.
|
||||
- `adapter/secondary/postgres`: только классы SQLSTATE 22 и 23 совпадают с `ErrRowFault`; deadlock, serialization, соединение, ресурсы, остановка и внутренние ошибки - нет.
|
||||
- `adapter/secondary/prometheus`: у `lincodex_mail_sender_cancelled_total` каждая причина существует с нулем, а произвольный label отклоняется; `lincodex_mail_sender_running` существует со значением 0 и следует за `SetMailSenderRunning`; каждый статус доставки, включая `cancelled`, существует с нулем.
|
||||
- `adapter/secondary/mail/resend`: loopback-конструктор принимает только http URL на loopback-хосте, поэтому ключ и письма развертывания нельзя направить через него на другой хост; `resendfixture` отвечает как Resend (принимает, повторяет исходное сообщение для повторного ключа и тела, отклоняет другое тело под тем же ключом, проигрывает заданные ошибки).
|
||||
- `bootstrap`: нет worker без транспорта или базы; цикл запускается и останавливается вместе с приложением, а gauge следует за ним.
|
||||
- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` молчит без gauge, пока он равен 0 и для очереди из одних уведомлений (возраст 0), и срабатывает, пока какой-либо экземпляр сообщает 1; `LincodexMailCancelledBroken` срабатывает на `content_invalid` и `processing_failed` и молчит для причин от действий пользователя (`make -C observability check`).
|
||||
|
||||
`TestServiceMailSending` в `backend/integration_test/mail_sender_test.go` использует `bootstrap(t, postgresService)`, настоящие транзакционный слой, хранилища, шлюз квот и usecase отправки, настоящий транспорт Resend, направленный на локальную имитацию, и фиктивные часы. Подтесты делят базу и начинают с пустых таблиц:
|
||||
|
||||
- Служебное письмо для синтетического аккаунта без записи согласия любого назначения ставится вместе с токеном в одной транзакции и принимается имитацией: один вызов провайдера с ключом `delivery/<id>`, адресом и ссылкой с токеном во fragment; доставка `accepted` с ID сообщения провайдера, одной принятой попыткой, одним посчитанным получателем и без оставшегося lease, аккаунт видит статус `accepted`, а второй проход ничего не делает. Журнал не содержит ни адреса, ни токена.
|
||||
- Worker, который держит доставку, не пускает к ней другого: имитация отвечает медленно, проход второго worker холостой, пока запрос первого в пути, и имитация получает ровно один вызов, а база - одну попытку.
|
||||
- Четыре worker одновременно разбирают очередь из восьми доставок: восемь вызовов провайдера под восемью разными ключами, ни один не повторен, восемь принятых доставок по одной попытке, восемь посчитанных получателей.
|
||||
- Worker, остановившийся после отправки (база отказывает при сохранении ответа), заменяется после истечения его lease: два вызова под одним ключом, второй - повтор, одно сообщение у провайдера, одна попытка, открытое резервирование использовано повторно, поэтому получатель считается один раз. За пределами 24-часового окна замена записывает попытку unknown и не вызывает провайдера.
|
||||
- Доставка с хешем содержимого, испорченным ручной правкой, отменяется как `content_invalid` на версии 2 без вызова провайдера, а следующая за ней доставка отправляется в следующем проходе.
|
||||
- Строка, которая сбоит по своей причине (тема с переводом строки нарушает правила домена, поэтому строку нельзя восстановить, хотя хеш цел), считается и отодвигается на минуту, пока доставка за ней отправляется, сбоит снова в каждый срок и отменяется как `processing_failed` на третьем сбое с очищенными телами; ошибка транспорта без ответа отодвигает строку на минуту без счета, с возвращенным резервированием и доставкой в `pending`.
|
||||
- Сбой, записанный worker, чей захват откатился, не трогает строку, которую держит другой worker, а несчитаемый сбой оставляет `failure_count` равным 0.
|
||||
- Три потерянных подряд worker не скрывают возраст первого запроса: доставка становится `unknown`, когда `first_send_started_at` старше 24 часов, и провайдер в четвертый раз не вызывается.
|
||||
- Lease - несколько секунд по часам базы; чужой worker не может записать попытку или заблокировать строку; `RecordClaimedAttempt` проходит для владельца.
|
||||
- При 5000 просроченных строк уведомлений план захвата использует `deliveries_due_idx` и не использует последовательное сканирование (`EXPLAIN`).
|
||||
- Очередь из одних уведомлений не создает возраст самой ранней ожидающей доставки; служебное письмо создает.
|
||||
- Тела письма с токеном очищаются, когда оно принято или отменено, и токен больше не встречается ни в одной строке; ожидающее письмо вручную очистить нельзя; очищенная строка не может получить тело обратно или потерять метку; аккаунт по-прежнему видит свой статус.
|
||||
- Токен, отозванный повторной отправкой, уже использованный токен, истекший токен, повторно зарегистрированный аккаунт, уже подтвержденный адрес, измененный адрес и токен другого назначения завершают доставку как `cancelled` с соответствующей причиной, без попытки, без lease, без следующей попытки, без резервирования и без вызова провайдера; аккаунт видит `cancelled`; следующий проход холостой. Удаленный аккаунт уносит свою доставку.
|
||||
- Ответы провайдера: 503 `service_unavailable` оставляет доставку в `pending` со сроком через минуту, проход до срока холостой, повтор в срок использует тот же ключ и принимается; 500 дает `unknown` без следующей попытки и без повтора через сутки; 403 `validation_error` дает `rejected`.
|
||||
- Квота: локальный лимит один в сутки переводит вторую доставку в `waiting_quota` до полуночи UTC без вызова провайдера, аккаунт видит ожидание и его конец, а доставка отправляется при сбросе; ответ провайдера `daily_quota_exceeded` откладывает доставку до следующей полуночи.
|
||||
- Продуктовое уведомление не берется никогда.
|
||||
- `EMAIL_PROVIDER=disabled`: с транспортом disabled проход сообщает, что канал недоступен, доставка остается нетронутой на версии 1, lease и резервирование освобождены, до имитации ничего не доходит, цикл с ним делает не больше четырех проходов меньше чем за секунду, а gauge равен 1, пока он работает, и 0 после; с транспортом то же письмо переносится на настроенный аккаунт и принимается.
|
||||
- Схема отклоняет отмененную доставку без причины, причину у другого статуса, половину lease, lease у конечной доставки, уведомление, привязанное к токену, смену привязки токена и удаление токена, на который ссылается доставка; удаление аккаунта убирает оба.
|
||||
|
||||
`TestDeliverySendingMigration` откатывает и заново применяет миграцию 00012 поверх отмененной и очищенной доставки сброса пароля: прежняя схема хранит ее как `rejected` с заглушкой в теле, удаляет токены сброса и новые столбцы, а миграция применяется снова. `TestPostgresMigrations` покрывает общий путь вверх, вниз и снова вверх.
|
||||
|
||||
`make -C backend lint` также запрещает импорт `resendfixture` и вызов `resend.NewLoopbackSender` вне файлов `_test.go` (depguard и forbidigo в `backend/.golangci.yml`).
|
||||
|
||||
Ни одна проверка не вызывает настоящий API Resend: единственный провайдер - имитация, поэтому эти тесты доказывают протокол, на котором говорит транспорт, и правила доставки, но не поведение Resend, доставляемость и реальную квоту аккаунта.
|
||||
|
||||
## Тесты заданий по сроку
|
||||
|
||||
|
||||
Reference in new issue
Block a user