feat(notification): add Resend quota gate and waiting-for-reset state

This commit is contained in:
shira committed 2026-10-06 11:50:38 +03:00
1 parent 3b917befa9
commit b856d4ff54
40 files changed
+4116 -48

No files matched your search

+51 -8
View File
@@ -162,7 +162,7 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai
- `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`.
- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator.
`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store.
`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A `quota_exhausted` rejection also names the exhausted window in `QuotaPeriod` (`day` or `month`) when the provider said which; it is empty otherwise. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store.
A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
@@ -180,19 +180,19 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt
| 409 `invalid_idempotent_request` | `unknown`: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates |
| 409 without a known name | `unknown` |
| 429 `rate_limit_exceeded` or unnamed | `rejected`, `rate_limited`, `RetryAfter` from `Retry-After` (seconds or a future HTTP date), otherwise from `ratelimit-reset` |
| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` until the next 00:00 UTC |
| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, no `RetryAfter`: the reset follows the billing cycle |
| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `day`, `RetryAfter` until the next 00:00 UTC |
| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `month`, no `RetryAfter`: the reset follows the billing cycle |
| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` |
| Other 5xx, including 500 `application_error` and `internal_server_error`, a truncated body, or a proxy or gateway answer | `unknown`: the API may have accepted the message before it failed |
| No answer after the request was written: timeout, reset, or closed connection | `unknown` |
| 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, waiting for a quota reset or an operator decision, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer.
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).
### 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`. Planned: the worker that claims due deliveries and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), quotas (TASK-018), delivery metrics (TASK-022), and the permission check before a send (TASK-462). 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). 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), delivery metrics (TASK-022), and the permission check before a send (TASK-462). No product flow calls `MailRequester` yet, and nothing sends a stored delivery.
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
@@ -231,7 +231,7 @@ Statuses. The values follow the `MailSender` outcomes:
| `accepted` | The provider accepted the message and returned `provider_message_id`; not delivery to or reading by a person | 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 |
| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset; none when the reset is unknown, for example Resend's monthly quota, and an operator or the quota rule decides |
| `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:
@@ -243,7 +243,7 @@ Every change advances `version`, and the store applies it only over the previous
Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt.
Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. TASK-018 needs its own counter that does not cascade, keyed by provider, provider account, and UTC day or month, and incremented atomically when a send is admitted.
Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see [Mail quotas](#mail-quotas).
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.
@@ -252,10 +252,53 @@ Planned additive changes for later tasks. Each is a new column, index, or CHECK
- 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 non-cascading quota counter of TASK-018 described above.
The store already provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, and `Rebind`.
### 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), quota metrics (TASK-022), and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing.
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.
Tables. Neither table has a foreign key to users or deliveries: deleting an account deletes its deliveries and attempts by cascade, but the provider has already counted those messages, so the usage stays. Neither holds personal data; `delivery_id` is an opaque ID.
- `mail_quota_usage`: one row per provider, provider account, period kind (`day` or `month`), and period start (a UTC date; the first day for a month), with `used_recipients`, `provider_exhausted_at`, and `updated_at`. An account accrues about 400 rows a year.
- `mail_quota_reservations`: a journal with one row per admitted send: the delivery, the account, the day and month windows it was counted in, the recipients, `reserved_at`, `released_at` (set once), and the last `settled_outcome` (`accepted`, `unknown`, `rejected`, or `not_sent`) with `settled_at`. A row without an outcome is a send in flight, or one whose process stopped before settling. A partial index serves the lookup of a delivery's open reservations. There is no retention rule for either table yet; journal rows are needed only within the reuse window and for the audit of a month.
Lock order. Every write first creates and locks all the usage rows it will touch with one statement, sorted by `(period_kind, period_start)`, and only then updates them or the journal; later `UPDATE` statements find their rows locked already. The order therefore never depends on the query plan. An `UPDATE ... WHERE (day) OR (month)` alone locks rows in scan order, which with a bitmap or sequential scan is heap order, and deadlocked against a reservation that locked the day first; the integration test reproduces that interleaving and checks that it no longer deadlocks. A settlement that releases yesterday's windows and marks today's locks all three rows in the same sorted statement. The guarantee covers the quota rows only: a caller that also locks other rows in the same transaction, such as the delivery, keeps its own consistent order for them.
Reservation. `QuotaGate.PrepareSend(ctx, unit, delivery)` runs in the caller's transaction:
1. A delivery pinned to a provider account other than the configured one fails with `notification.ErrQuotaNotConfigured`: no limits are known for it, and an account without a quota is never "unlimited". An `accepted` or `rejected` delivery fails with `domain.ErrDeliveryTransition`.
2. A retry inside the provider's idempotency window reuses an open reservation of the same delivery (the earlier attempt was `unknown`, or its process stopped before settling) and proceeds without counting again: the provider answers a repeated key with the original result instead of sending twice. The window is a gate parameter: `resend.IdempotencyWindow`, 24 hours per the Resend API documentation, or zero for SMTP, which has no provider-side deduplication, so every SMTP retry counts again. After the window a retry counts again; whether it may run at all is the retry policy's decision (TASK-017).
3. Otherwise the repository locks the day and month rows, adds one recipient to both only when it fits both limits, and journals the reservation. If it does not fit, nothing changes and the result says which limit would be exceeded. The reservation is all-or-nothing across both windows.
4. When the send is admitted, the decision carries a permit and the delivery is unchanged. Otherwise the delivery waits for the reset of the full window: the next 00:00 UTC for the day, the first day of the next month for the month; when both are full, the month reset wins. A `pending` or `waiting_quota` delivery is stored as `waiting_quota` with `next_attempt_at` at that time through `Delivery.WaitForQuota`. The change time is the later of the clock and the delivery's last change, and the reset is not earlier than that, so an instance whose clock runs a few milliseconds behind the one that last wrote the delivery can still park it. An `unknown` delivery is returned unchanged with the reset time: its retry belongs to the retry policy (TASK-017), and parking it would hide that an earlier attempt may have been accepted.
The row locks last until the caller's transaction ends, so the worker must commit before it calls the transport; the cost is that sends of one account reserve one after another.
Settlement. `QuotaGate.SettleSend(ctx, unit, permit, result, sendErr)` runs in the transaction that stores the attempt or, after a `Send` error, the delivery's next state. It always journals the outcome, and:
- `accepted` and `unknown` keep the reservation. An unknown attempt may have been sent, and counting it errs on the safe side.
- A `Send` error, where nothing left the process, and every `rejected` outcome release a new reservation: the provider did not take the message, so it did not count it. Without the release, a provider outage would use up the daily quota with failed retries. The journal sets `released_at` only on an open row, so a repeated settlement, for example after a commit whose answer was lost, releases nothing a second time, independently of the delivery's version. A reused reservation is never released: the earlier attempt under it may have been sent. A reservation that is never settled, for example after a crash between the two transactions, stays counted, which only over-counts.
- `rejected` with `quota_exhausted` also refines the count from the provider's answer. The window comes from `SendResult.QuotaPeriod`, which the transport fills from the provider's own error name (Resend `daily_quota_exceeded` gives `day`, `monthly_quota_exceeded` gives `month`), not from the wait hint. The window is the one current at settlement, because the provider answered about it, even when the reservation was made before midnight. The day mark raises that day's usage to the daily limit and the delivery waits for the next 00:00 UTC; the month mark raises the month's usage to the monthly limit and the delivery waits for the next UTC month start. A daily refusal on the last day of a month marks only the day. Resend's monthly quota follows the account's billing cycle; if that cycle resets later than the calendar month, the retry at the month start is refused again and waits another month unless an operator decides otherwise. Without a named window nothing is marked: the delivery waits for the provider's hint, or, without one, for an operator. A marked row records `provider_exhausted_at`, and a release no longer lowers it, so the local count stays at the provider's answer until the window resets. Raising the limit reopens the window; that is the operator's decision. `SettleSend` returns the time to store as the attempt's `next_attempt_at`.
No purchase, plan switch, or transport change. The gate only defers. Nothing buys a plan, moves the account to a paid tier, or sends a waiting delivery through another transport, provider, or account; the delivery stays pinned (see [Mail deliveries](#mail-deliveries)). Switching `EMAIL_PROVIDER` is an operator decision, and the gate applies to the new transport too: it runs in the usecase before any transport is called, `smtp` needs stated limits, and deliveries pinned to the old account are refused instead of being sent without a limit. Counters are kept per provider and account label, so a new transport or a new `EMAIL_ACCOUNT` label starts with its own count. A transport that reaches the same provider account by another route, for example Resend's own SMTP endpoint, shares the provider's quota but not the local count, and so does a relabeled account: the provider's refusal then refines the count as above, the startup report warns about other labels with usage this month, and the operator should set the limits to what the account has left.
Startup report. After the startup migrations, unless `EMAIL_PROVIDER=disabled`, bootstrap logs `mail quota usage` with the provider, account, and the day and month usage and limits, and warns `other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count` when other account labels of the same provider have usage this month. A failed read is a warning and never stops startup.
What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind)` returns the status of the newest delivery of a kind addressed to the account: the kind, the status, `WaitingUntil` for `waiting_quota` (the stored `next_attempt_at`), and the time of the last change. It returns no address, subject, body, provider, or delivery ID, and false when there is none. The query is scoped to deliveries addressed to the given account, so the caller must pass the authenticated account's own ID, never an ID from request input. No HTTP route calls it yet; the identity flows and a later API show it. A user interface maps the statuses as follows:
| Status | What the user is told |
| --- | --- |
| `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 |
| `rejected` | Your email could not be sent |
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. There is no quota metric yet; `MailQuotaRepository.Usage` is the read that TASK-022 can expose with the labels provider and period.
### 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.
+19 -4
View File
@@ -168,7 +168,7 @@ The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects e
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.
`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, waiting for a daily or monthly quota reset, and outcome records belong to the planned delivery layer. 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).
`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).
`disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning.
@@ -176,8 +176,10 @@ Current state: this build contains the `disabled` and `resend` transports. With
| --- | --- | --- |
| `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive |
| `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex <no-reply@example.com>`. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. |
| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. |
| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to and that the quota is counted under: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. Change it only with a real account change; renaming it resets the local quota count. |
| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt |
| `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. |
| `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. |
| `APP_PUBLIC_URL` | none, required | Public origin for links in mail: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. |
| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. |
| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. |
@@ -185,7 +187,7 @@ Current state: this build contains the `disabled` and `resend` transports. With
| `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. |
| `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. |
Compose passes these variables from the root `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
Compose passes these variables from the root `.env`; it passes an unset `EMAIL_QUOTA_DAILY` or `EMAIL_QUOTA_MONTHLY` as an empty value, which the backend reads as unset. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
### Mail deliveries
@@ -194,9 +196,22 @@ A notification request is a row in `mail_requests` until the consumer `notificat
- 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.
- 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.
- 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` without `next_attempt_at` waits for a quota reset that is not known, such as Resend's monthly quota, and needs an operator decision.
- 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).
- 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.
- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet.
- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`.
- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused.
- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.
- 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.
### 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.
+3 -1
View File
@@ -57,7 +57,7 @@ What exists now:
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), and the mail delivery tables (`deliveries`, `delivery_attempts`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), and the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
## Install and work loop
@@ -197,6 +197,8 @@ A directly launched backend with a registered handler and `DATABASE_URL` set con
To send a notification from a usecase, call `notification.MailRequester.RequestNotification(ctx, unit, request)` with the usecase's `UnitOfWork`, the recipient account ID, and `mailtemplate.NotificationData`; it returns the delivery ID. It stores the text in `mail_requests` and appends an event that carries only the request ID and kind, both in the usecase's transaction. The consumer `notification_delivery` then stores the delivery with the address read from the account and the rendered content, and deletes the request; it skips accounts whose address is not verified. Never put an email address, a token, notification text, or another person's contact into any event payload, and never put a token or another person's contact into a request. Verification and password reset mail carry a token and cannot use the event: the identity flows create those deliveries with `domain.NewDelivery` and `UnitOfWork.Deliveries().Create` in the transaction that issues the token. A new template version changes new deliveries only; never update a stored delivery's content. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries), operations in [DEPLOY.md](DEPLOY.md#mail-deliveries), and tests in [TESTING.md](TESTING.md#mail-delivery-tests).
Every send must pass `notification.QuotaGate`: build it with the configured account and limits and the transport's idempotency window (`resend.IdempotencyWindow`, or zero for SMTP); call `PrepareSend` in the transaction that claims the delivery and commit before calling `MailSender.Send`; then call `SettleSend` in the transaction that records the attempt, and use the time it returns as the attempt's `next_attempt_at` for a `quota_exhausted` rejection. A transport sets `SendResult.QuotaPeriod` from the provider's own error name for a quota rejection. Never call a transport without a permit, and never fall back to another transport or account when the quota is used up. To show an account its own mail status, call `notification.DeliveryStatusReader.LatestForUser` with the authenticated account's ID only. The rules are in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
## Go readability
- Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call.
+37 -1
View File
@@ -131,7 +131,43 @@ Unit tests (`make -C backend test`) cover the delivery model and its creation pa
- A request whose account is deleted loses its request row with the account; the handler then stores no delivery and logs the delivery ID.
- The unverified account cleanup skips an account whose delivery row another transaction holds, deletes it once the lock is gone, and its pending request and its delivery, created directly through the repository as token mail will be, go with it.
Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. The suite does not send mail: the sending worker, retries, quotas, and the permission check are later tasks, and there is no test of a verification or password reset delivery, which the identity flows will create.
Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. The suite does not send mail: the sending worker, retries, and the permission check are later tasks, quotas have their own [Mail quota tests](#mail-quota-tests), and there is no test of a verification or password reset delivery, which the identity flows will create.
## Mail quota tests
Unit tests (`make -C backend test`) cover the quota rules without a database:
- `internal/domain/`: the day and month windows of an instant are UTC calendar periods whatever its location: midnight UTC belongs to the new day and one nanosecond before it to the old one, a local time after local midnight can still be the previous UTC day, the day reset of February 28 in a common year and of February 29 in a leap year is March 1, and December resets into January of the next year; limits refuse zero, negative, and a daily limit above the monthly one.
- `config/` and `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` default to 100 and 3000 for `resend` and `disabled`; `smtp` refuses to start without either and takes stated values; a lowered value is taken as configured for every provider; an empty value counts as unset; zero, negative, non-integer, out-of-range values and a daily limit above the monthly one are refused without echoing secrets; bootstrap refuses to start with a quota of zero.
- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` gives `QuotaPeriod` `day` with the wait until midnight, and `monthly_quota_exceeded` gives `month` without a wait.
- `internal/usecase/notification/`, with an in-memory counter and journal and a fake clock:
- `QuotaGate.PrepareSend` admits sends up to the daily limit and parks the next one in `waiting_quota` until 00:00 UTC without counting it, then admits it after midnight. It waits for the month start when the month is full (December 31 to January 1) and also when both windows are full.
- It parks a delivery last changed by an instance whose clock is 5 ms ahead, past midnight, at that change time without an error.
- It applies a lowered limit to `smtp` like any other transport, and refuses a delivery pinned to an account without a quota, reserving nothing for it.
- It returns an `unknown` delivery unchanged with the reset time and refuses a terminal one.
- A retry within 24 hours reuses the open reservation even with the day otherwise full; a rejection of that retry keeps it; after the window the retry counts again. An `smtp` gate, without provider deduplication, counts every retry.
- `SettleSend` keeps the reservation for `accepted` and `unknown`, and releases it for a `Send` error and every `rejected` outcome. A repeated settlement releases once.
- A daily quota answer marks the day and returns midnight, a monthly one marks the month and returns its end, an answer without a window parks only the delivery for its hint or without a time, and a window the provider reported full is not reopened by a release.
- The window marked is the one current at settlement: a daily refusal on October 31 marks only the day and leaves November open, a reservation at 23:59:59 settled 5 ms after midnight marks the new day, and a hint computed by a provider clock 5 ms ahead still gives exactly midnight.
- `ReportQuotaUsage` logs the usage and limits and warns with the other account labels.
- `DeliveryStatusReader.LatestForUser` returns the kind, status, and change time, and `WaitingUntil` only for `waiting_quota`. It asks only for the given account, returns nothing without a delivery, and refuses a nil account and an unknown kind.
- Logs hold no address, subject, or body.
`TestMailQuota` in `backend/integration_test/mail_quota_test.go` uses `bootstrap(t, postgresService)`, the real transactor, delivery store, and quota repository, and a fake clock. Each case starts from empty tables:
- Concurrency: 12 senders, each with its own connection and transaction, call `PrepareSend` at once. On windows without rows (the row creation races too) and a daily limit of 10 exactly 10 get a permit; after 7 sequential sends exactly 3 of the next 12 get one. Every other delivery is stored as `waiting_quota` with `next_attempt_at` at the next 00:00 UTC, and both counters end at 10. Without the row lock the case fails with all 12 admitted.
- Midnight and month boundary: with limits of 2 per day and 3 per month starting October 30 at 22:00 UTC, the third send waits until October 31 00:00 UTC, still waits one second before it, and goes at midnight; the fourth waits for November 1 because the month is full, and goes then. The day and month rows hold 2, 1, 1 and 3, 1.
- Lowered limit and SMTP: gates are built from `config.LoadFromEnv`. After 4 Resend sends with the default limit, a limit lowered to 3 parks the next send until midnight. `smtp` without quota settings fails to load; with 2 and 2 it admits two relay sends and parks the third until the month start, and a Resend delivery under the `smtp` gate fails with `ErrQuotaNotConfigured` and changes no counter.
- Provider refinement: a `temporary` rejection gives its reservation back. A `daily_quota_exceeded` refusal while the local count is 1 of 100 stores the delivery as `waiting_quota` until midnight with one attempt, raises the day row to 100 with `provider_exhausted_at`, and the gate then parks the next delivery itself. After midnight a `monthly_quota_exceeded` refusal raises the month row to 3000 and parks the deliveries until November 1.
- Account deletion: three accepted sends count 3 of 3; deleting the account deletes its deliveries and attempts by cascade, the counters keep 3, and a delivery for another account the same day waits until midnight.
- Lock order, deterministic: the month row lies before the day row in the heap, and the writers run on sessions with `enable_indexscan=off`, so scans follow heap order as in the reproduced deadlock. A third transaction holds the day row; a reservation and a release queue on it in both orders, and the blocker is released. Neither gets a deadlock error, and the usage ends consistent. With the ordered lock removed from `Settle`, the case fails with SQLSTATE 40P01.
- Lock order, bounded stress: 60 rounds, each starting at once a release of day two, a release of day one that marks day two across midnight, and two reservations of day two, on heap-order sessions. No round returns an error.
- Journal: a transport error settled twice releases once. An unknown attempt's reservation is reused by a retry an hour later and not after the 24-hour window. The journal ends with 2 open rows, 1 released, and 2 with an outcome.
- User status: an account without mail gets nothing; after one admitted and one parked notification it sees `waiting_quota` until midnight; another account and another kind get nothing.
- 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.
## Integration test sharding
+51 -8
View File
@@ -162,7 +162,7 @@ Offsets и партиции. Каждый обработчик - один уча
- `rejected`: провайдер не принял письмо. Либо он ответил отказом, либо транспорт сломался до полной записи запроса (DNS, соединение или TLS), и полный запрос до провайдера не дошел; второй случай всегда `temporary`, и повтор не может продублировать письмо. `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`.
- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Дедупликация у провайдера ограничена окном (24 часа у Resend); после него повтор может отправить письмо дважды, поэтому слой доставки обязан прекратить повторы и передать случай оператору.
`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить.
`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Отказ `quota_exhausted` еще и называет исчерпанное окно в `QuotaPeriod` (`day` или `month`), если провайдер это сообщил; иначе поле пустое. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить.
Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера.
@@ -180,19 +180,19 @@ Offsets и партиции. Каждый обработчик - один уча
| 409 `invalid_idempotent_request` | `unknown`: ключ уже использован с другим телом, поэтому более ранний запрос мог быть принят; повтор не поможет, и слой доставки останавливается и передает случай оператору |
| 409 без известного имени | `unknown` |
| 429 `rate_limit_exceeded` или без имени | `rejected`, `rate_limited`, `RetryAfter` из `Retry-After` (секунды или будущая HTTP-дата), иначе из `ratelimit-reset` |
| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` до ближайших 00:00 UTC |
| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, без `RetryAfter`: сброс зависит от платежного цикла |
| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `day`, `RetryAfter` до ближайших 00:00 UTC |
| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, `QuotaPeriod` `month`, без `RetryAfter`: сброс зависит от платежного цикла |
| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` из `Retry-After` |
| Прочие 5xx, включая 500 `application_error` и `internal_server_error`, обрезанное тело или ответ прокси или шлюза | `unknown`: API мог принять письмо до сбоя |
| Нет ответа после записи запроса: таймаут, сброс или закрытие соединения | `unknown` |
| Сбой до записи запроса: 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, предел числа попыток и остановка по окончании 24-часового окна ключа относятся к запланированному слою доставки; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты).
### Доставки писем
Реализовано (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`. Запланировано: worker, который берет доставки к отправке и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017), квоты (TASK-018), метрики доставки (TASK-022) и проверка разрешений перед отправкой (TASK-462). Ни один продуктовый сценарий пока не вызывает `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; см. [Квоты почты](#квоты-почты). Запланировано: worker, который берет доставки к отправке, пропускает их через шлюз квот и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017), метрики доставки (TASK-022) и проверка разрешений перед отправкой (TASK-462). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет.
Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит:
@@ -231,7 +231,7 @@ Offsets и партиции. Каждый обработчик - один уча
| `accepted` | Провайдер принял письмо и вернул `provider_message_id`; это не доставка человеку и не прочтение | Нет; конечный |
| `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный |
| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет |
| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс; отсутствует, когда момент сброса неизвестен, например для месячной квоты Resend, и решение принимает оператор или правило квот |
| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс (см. [Квоты почты](#квоты-почты)); отсутствует, когда момент сброса неизвестен, например после ответа провайдера о квоте без окна и без паузы, и решение принимает оператор |
Переходы:
@@ -243,7 +243,7 @@ Offsets и партиции. Каждый обработчик - один уча
Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки.
Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. TASK-018 нужен собственный счетчик без каскада, с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца, который атомарно увеличивается при допуске отправки.
Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. Поэтому у квоты собственный счетчик без каскада с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца; см. [Квоты почты](#квоты-почты).
Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). TASK-016 использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача.
@@ -252,10 +252,53 @@ Offsets и партиции. Каждый обработчик - один уча
- Конечный статус отмены для доставки, которую больше нельзя отправлять: токен или аккаунт аннулирован до отправки (TASK-016) или отозвано разрешение (TASK-462).
- Необязательная ссылка доставки письма с токеном на `email_tokens.id`, чтобы worker перед отправкой проверил, что токен все еще действующий для своего назначения (TASK-016).
- Для worker отправки (TASK-016): столбцы lease (например, владелец захвата и `claimed_until`) и частичный индекс по `next_attempt_at` для статусов, которые берутся снова, чтобы несколько процессов захватывали доставки через `FOR UPDATE SKIP LOCKED`, а попытка, процесс которой остановился после отправки запроса, становилась `unknown`.
- Описанный выше счетчик квот TASK-018 без каскада.
Хранилище уже дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota` и `Rebind`.
### Квоты почты
Реализовано (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), метрики квот (TASK-022) и API или сценарий 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, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна.
Таблицы. Внешних ключей на пользователей или доставки нет ни у одной: удаление аккаунта каскадно удаляет его доставки и попытки, но провайдер эти письма уже посчитал, поэтому расход остается. Персональных данных нет ни в одной; `delivery_id` - непрозрачный ID.
- `mail_quota_usage`: одна строка на провайдер, аккаунт провайдера, вид периода (`day` или `month`) и начало периода (дата UTC; для месяца первое число) с полями `used_recipients`, `provider_exhausted_at` и `updated_at`. На один аккаунт набирается около 400 строк в год.
- `mail_quota_reservations`: журнал с одной строкой на допущенную отправку: доставка, аккаунт, окна суток и месяца, в которых она посчитана, число получателей, `reserved_at`, `released_at` (ставится один раз) и последний `settled_outcome` (`accepted`, `unknown`, `rejected` или `not_sent`) с `settled_at`. Строка без исхода - отправка в процессе или такая, чей процесс остановился до расчета. Частичный индекс обслуживает поиск открытых резервирований доставки. Правила хранения пока нет ни для одной таблицы; строки журнала нужны только в окне повторного использования и для аудита месяца.
Порядок блокировок. Каждая запись сначала одним запросом создает и блокирует все строки расхода, которые она затронет, в порядке `(period_kind, period_start)`, и только потом обновляет их или журнал; следующие `UPDATE` находят свои строки уже заблокированными. Поэтому порядок никогда не зависит от плана запроса. Одиночный `UPDATE ... WHERE (day) OR (month)` блокирует строки в порядке сканирования, а при bitmap или последовательном сканировании это порядок в heap, и такой запрос попадал во взаимоблокировку с резервированием, которое блокировало сначала сутки; интеграционный тест воспроизводит это чередование и проверяет, что взаимоблокировки больше нет. Расчет, который возвращает вчерашние окна и отмечает сегодняшние, блокирует все три строки тем же отсортированным запросом. Гарантия касается только строк квот: вызывающий, который в той же транзакции блокирует другие строки, например доставку, сам соблюдает для них единый порядок.
Резервирование. `QuotaGate.PrepareSend(ctx, unit, delivery)` выполняется в транзакции вызывающего:
1. Доставка, закрепленная за другим аккаунтом провайдера, чем настроенный, завершается ошибкой `notification.ErrQuotaNotConfigured`: лимиты для нее неизвестны, а аккаунт без квоты никогда не считается "безлимитным". Доставка в `accepted` или `rejected` завершается ошибкой `domain.ErrDeliveryTransition`.
2. Повтор внутри окна идемпотентности провайдера повторно использует открытое резервирование той же доставки (прошлая попытка закончилась `unknown` или ее процесс остановился до расчета) и проходит без нового учета: на повтор с тем же ключом провайдер отвечает исходным результатом, а не отправляет письмо второй раз. Окно - параметр шлюза: `resend.IdempotencyWindow`, 24 часа по документации API Resend, или ноль для SMTP, у которого нет дедупликации на стороне провайдера, поэтому каждый повтор через SMTP считается заново. После окна повтор считается заново; допустим ли он вообще, решает политика повторов (TASK-017).
3. Иначе репозиторий блокирует строки суток и месяца, добавляет одного получателя в обе, только если он укладывается в оба лимита, и записывает резервирование в журнал. Если не укладывается, ничего не меняется, а результат сообщает, какой лимит был бы превышен. Резервирование выполняется по обоим окнам целиком или не выполняется вовсе.
4. Если отправка допущена, решение содержит разрешение, а доставка не меняется. Иначе доставка ждет сброса заполненного окна: ближайших 00:00 UTC для суток и первого числа следующего месяца для месяца; если заполнены оба, побеждает сброс месяца. Доставка в `pending` или `waiting_quota` сохраняется в `waiting_quota` с `next_attempt_at` на этот момент через `Delivery.WaitForQuota`. Временем изменения берется более позднее из показаний часов и последнего изменения доставки, а сброс не раньше него, поэтому экземпляр, чьи часы отстают на несколько миллисекунд от того, кто последним записал доставку, все равно может ее отложить. Доставка в `unknown` возвращается без изменений вместе с моментом сброса: ее повтор решает политика повторов (TASK-017), а перевод в ожидание скрыл бы, что прошлая попытка могла быть принята.
Блокировки строк держатся до конца транзакции вызывающего, поэтому worker обязан зафиксировать транзакцию до вызова транспорта; цена - отправки одного аккаунта резервируются по очереди.
Расчет. `QuotaGate.SettleSend(ctx, unit, permit, result, sendErr)` выполняется в транзакции, которая сохраняет попытку, а после ошибки `Send` - следующее состояние доставки. Он всегда записывает исход в журнал, а кроме того:
- `accepted` и `unknown` оставляют резервирование. Неизвестная попытка могла быть отправлена, и учет ее в расходе ошибается в безопасную сторону.
- Ошибка `Send`, когда ничего не покинуло процесс, и любой исход `rejected` возвращают новое резервирование: провайдер письмо не взял и не посчитал. Без возврата сбой провайдера израсходовал бы суточную квоту на неудачные повторы. Журнал ставит `released_at` только в открытой строке, поэтому повторный расчет, например после commit, ответ на который потерялся, второй раз ничего не возвращает, и это не зависит от версии доставки. Повторно использованное резервирование не возвращается никогда: прошлая попытка под ним могла быть отправлена. Резервирование, которое так и не рассчитано, например после падения между двумя транзакциями, остается в расходе; это дает только завышенный счет.
- `rejected` с `quota_exhausted` еще и уточняет счет по ответу провайдера. Окно берется из `SendResult.QuotaPeriod`, которое транспорт заполняет по собственному имени ошибки провайдера (Resend `daily_quota_exceeded` дает `day`, `monthly_quota_exceeded` - `month`), а не из подсказки ожидания. Окно берется текущее на момент расчета, потому что провайдер ответил именно о нем, даже если резервирование было сделано до полуночи. Отметка суток поднимает расход этих суток до суточного лимита, и доставка ждет ближайших 00:00 UTC; отметка месяца поднимает расход месяца до месячного лимита, и доставка ждет начала следующего месяца UTC. Суточный отказ в последний день месяца отмечает только сутки. Месячная квота Resend следует платежному циклу аккаунта; если цикл сбрасывается позже календарного месяца, повтор в начале месяца снова получит отказ и будет ждать еще месяц, если оператор не решит иначе. Без названного окна ничего не отмечается: доставка ждет по подсказке провайдера, а без нее - решения оператора. В отмеченной строке фиксируется `provider_exhausted_at`, и возврат больше не уменьшает ее, поэтому локальный счет остается на значении из ответа провайдера до сброса окна. Повышение лимита снова открывает окно; это решение оператора. `SettleSend` возвращает момент, который нужно сохранить как `next_attempt_at` попытки.
Без покупки, смены тарифа и транспорта. Шлюз только откладывает. Ничто не покупает тариф, не переводит аккаунт на платный план и не отправляет ожидающую доставку через другой транспорт, провайдера или аккаунт; доставка остается закрепленной (см. [Доставки писем](#доставки-писем)). Смена `EMAIL_PROVIDER` - решение оператора, и шлюз действует и для нового транспорта: он работает в usecase до вызова любого транспорта, `smtp` требует явно заданных лимитов, а доставки, закрепленные за прежним аккаунтом, отклоняются, а не отправляются без лимита. Счетчики ведутся по провайдеру и метке аккаунта, поэтому новый транспорт или новая метка `EMAIL_ACCOUNT` начинают со своего счета. Транспорт, который другим путем ведет в тот же аккаунт провайдера, например собственный SMTP-адрес Resend, делит квоту провайдера, но не локальный счет, и так же ведет себя переименованная метка аккаунта: отказ провайдера тогда уточняет счет, как описано выше, отчет при запуске предупреждает о других метках с расходом в этом месяце, а оператору стоит задать лимиты по остатку аккаунта.
Отчет при запуске. После миграций при запуске, кроме `EMAIL_PROVIDER=disabled`, bootstrap пишет в журнал `mail quota usage` с провайдером, аккаунтом, расходом и лимитами суток и месяца и предупреждает `other accounts of this mail provider have quota usage this month; renaming EMAIL_ACCOUNT without changing the provider account resets the local count`, если у других меток аккаунта того же провайдера есть расход в этом месяце. Неудачное чтение дает предупреждение и никогда не останавливает запуск.
Что видит пользователь. `notification.DeliveryStatusReader.LatestForUser(ctx, userID, kind)` возвращает статус новейшей доставки вида, адресованной аккаунту: вид, статус, `WaitingUntil` для `waiting_quota` (сохраненный `next_attempt_at`) и время последнего изменения. Адрес, тему, тело, провайдера и ID доставки он не возвращает, а если доставки нет, возвращает false. Запрос ограничен доставками указанному аккаунту, поэтому вызывающий обязан передавать ID самого аутентифицированного аккаунта и никогда не брать его из входных данных запроса. HTTP-маршрута, который его вызывает, пока нет; результат покажут сценарии identity и следующее API. Интерфейс показывает статусы так:
| Статус | Что видит пользователь |
| --- | --- |
| `waiting_quota` с `WaitingUntil` | Ваше письмо ожидает отправки до `<WaitingUntil>` |
| `waiting_quota` без `WaitingUntil` | Ваше письмо ожидает отправки; время пока неизвестно |
| `pending`, `unknown` | Ваше письмо отправляется. `unknown` не показывается как сбой: письмо могло быть принято |
| `accepted` | Ваше письмо отправлено. Это значит, что провайдер его принял, а не что оно дошло до ящика |
| `rejected` | Ваше письмо не удалось отправить |
Операторы читают те же строки запросами из [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 доставки, провайдером, периодом и моментом сброса. Метрик квот пока нет; `MailQuotaRepository.Usage` - чтение, которое TASK-022 может отдать с метками provider и period.
### Версии продуктовой политики
Реализованы хранение, публикация и начальное заполнение при старте (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/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач.
+19 -4
View File
@@ -170,7 +170,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
Текущее состояние: в этой сборке есть транспорты `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, который вызывает транспорт, запланирован.
`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#почтовый-транспорт).
`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#почтовый-транспорт).
`disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`.
@@ -178,8 +178,10 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
| --- | --- | --- |
| `EMAIL_PROVIDER` | нет, обязательна | `resend`, `smtp` или `disabled`, без учета регистра |
| `EMAIL_FROM` | нет, обязательна | Один mailbox: `no-reply@example.com` или `Lincodex <no-reply@example.com>`. Только печатные ASCII символы. Адрес подчиняется правилам адресов аккаунтов: local part без кавычек и DNS-домен минимум из двух меток, без IP literal. |
| `EMAIL_ACCOUNT` | `default` | Метка аккаунта провайдера, за которым закрепляются новые доставки: от 1 до 64 строчных букв, цифр, `.`, `_` или `-`, начиная с буквы или цифры. Никогда не ключ. |
| `EMAIL_ACCOUNT` | `default` | Метка аккаунта провайдера, за которым закрепляются новые доставки и под которой ведется счет квоты: от 1 до 64 строчных букв, цифр, `.`, `_` или `-`, начиная с буквы или цифры. Никогда не ключ. Меняйте ее только при настоящей смене аккаунта; переименование сбрасывает локальный счет квоты. |
| `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта |
| `EMAIL_QUOTA_DAILY` | `100` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за UTC-сутки через настроенный аккаунт провайдера: целое от 1 до 1000000000. Пустое значение считается незаданным. Значения, которое отключает квоту, нет. |
| `EMAIL_QUOTA_MONTHLY` | `3000` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за календарный месяц UTC: целое от 1 до 1000000000, не меньше `EMAIL_QUOTA_DAILY`. Пустое значение считается незаданным. |
| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. |
| `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. |
| `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. |
@@ -187,7 +189,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
| `SMTP_USERNAME`, `SMTP_PASSWORD` | пусто | Обязательны для `smtp`; анонимный relay не поддерживается. |
| `SMTP_TLS_MODE` | пусто | Обязательна для `smtp`. `starttls` (переход на TLS через STARTTLS, обычно порт 587) или `tls` (TLS с начала соединения, обычно порт 465). SMTP без шифрования не поддерживается. |
Compose передает эти переменные из корневого `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера.
Compose передает эти переменные из корневого `.env`; незаданные `EMAIL_QUOTA_DAILY` или `EMAIL_QUOTA_MONTHLY` он передает пустыми, и backend читает их как незаданные. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера.
### Доставки писем
@@ -196,9 +198,22 @@ Compose передает эти переменные из корневого `.e
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Доставки, созданные при `EMAIL_PROVIDER=disabled`, остаются закрепленными за `disabled`, пока worker отправки (TASK-016) не перенесет их через `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` и никогда не вставляйте их в задачи и чаты.
- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` без `next_attempt_at` ждет сброса квоты, момент которого неизвестен, например месячной квоты Resend, и требует решения оператора.
- Не правьте сохраненную доставку вручную: 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#квоты-почты).
- Задайте `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` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце.
- Когда квота исчерпана, доставки ждут в `waiting_quota` до `next_attempt_at`: ближайших 00:00 UTC для суток и первого числа следующего месяца в 00:00 UTC для месяца. Ничто не покупает тариф, не переводит аккаунт на платный план и не переносит почту на другой транспорт или аккаунт. Сам аккаунт может узнать, что его письмо ждет и до какого времени, через чтение статуса, описанное в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты); HTTP-маршрута для этого пока нет.
- Чтобы увидеть состояние, выбирайте только счетчики и метаданные, например `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'` и для отправок, которые посчитаны, но так и не рассчитаны, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. В журнале видны `mail quota is used up; the delivery waits for the reset` и, если отказал сам провайдер, `the mail provider reported its quota used up; local sending stops until the reset`.
- Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит.
- `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом.
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017).
- Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита.
### Шаблоны писем
Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку; регистрация, подтверждение, сброс пароля и отправка запланированы, поэтому текущая сборка не отправляет писем.
+3 -1
View File
@@ -57,7 +57,7 @@ Frontend зависимости выбираются из актуальных s
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) и таблицы доставок писем (`deliveries`, `delivery_attempts`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
## Установка и цикл работы
@@ -197,6 +197,8 @@ Backend, запущенный напрямую с зарегистрирован
Чтобы отправить уведомление из usecase, вызовите `notification.MailRequester.RequestNotification(ctx, unit, request)` с `UnitOfWork` usecase, ID аккаунта получателя и `mailtemplate.NotificationData`; вызов возвращает ID доставки. Он сохраняет текст в `mail_requests` и добавляет событие, которое несет только ID запроса и вид, оба действия - в транзакции usecase. Затем обработчик `notification_delivery` сохраняет доставку с адресом, прочитанным из аккаунта, и сформированным содержимым и удаляет запрос; аккаунты с неподтвержденным адресом он пропускает. Никогда не кладите email, токен, текст уведомления или контакт другого человека в payload любого события и никогда не кладите токен или контакт другого человека в запрос. Письма подтверждения почты и сброса пароля содержат токен и не могут идти через событие: сценарии identity создают такие доставки через `domain.NewDelivery` и `UnitOfWork.Deliveries().Create` в транзакции, которая выпускает токен. Новая версия шаблона меняет только новые доставки; никогда не обновляйте содержимое сохраненной доставки. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем), эксплуатация - в [DEPLOY.md](DEPLOY.md#доставки-писем), тесты - в [TESTING.md](TESTING.md#тесты-доставки-писем).
Каждая отправка обязана пройти `notification.QuotaGate`: соберите его с настроенными аккаунтом и лимитами и окном идемпотентности транспорта (`resend.IdempotencyWindow` или ноль для SMTP); вызовите `PrepareSend` в транзакции, которая захватывает доставку, и зафиксируйте ее до вызова `MailSender.Send`; затем вызовите `SettleSend` в транзакции, которая записывает попытку, и для отказа `quota_exhausted` используйте возвращенный момент как `next_attempt_at` попытки. Для отказа по квоте транспорт заполняет `SendResult.QuotaPeriod` по собственному имени ошибки провайдера. Никогда не вызывайте транспорт без разрешения и не переключайтесь на другой транспорт или аккаунт, когда квота исчерпана. Чтобы показать аккаунту статус его писем, вызывайте `notification.DeliveryStatusReader.LatestForUser` только с ID аутентифицированного аккаунта. Правила описаны в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
## Читаемость Go-кода
- Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.
+37 -1
View File
@@ -131,7 +131,43 @@ Unit-тесты (`make -C backend test`) покрывают модель дос
- Запрос, аккаунт которого удален, теряет строку запроса вместе с аккаунтом; затем обработчик не сохраняет доставку и записывает в лог ID доставки.
- Очистка неподтвержденных аккаунтов пропускает аккаунт, строку доставки которого держит другая транзакция, удаляет его после снятия блокировки, и вместе с ним удаляются его ожидающий запрос и доставка, созданная прямо через репозиторий, как будут создаваться письма с токеном.
Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. Набор не отправляет писем: worker отправки, повторы, квоты и проверка разрешений относятся к следующим задачам, и нет теста доставки подтверждения почты или сброса пароля, которые создадут сценарии identity.
Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. Набор не отправляет писем: worker отправки, повторы и проверка разрешений относятся к следующим задачам, у квот свои [тесты квот почты](#тесты-квот-почты), и нет теста доставки подтверждения почты или сброса пароля, которые создадут сценарии identity.
## Тесты квот почты
Unit-тесты (`make -C backend test`) проверяют правила квот без базы:
- `internal/domain/`: окна суток и месяца для момента времени - календарные периоды UTC независимо от его часового пояса: полночь UTC относится к новым суткам, а наносекунда до нее - к старым, местное время после местной полуночи может еще относиться к предыдущим UTC-суткам, сброс суток 28 февраля обычного года и 29 февраля високосного приходится на 1 марта, а декабрь сбрасывается в январь следующего года; лимиты отклоняют ноль, отрицательные значения и суточный лимит больше месячного.
- `config/` и `internal/bootstrap/`: `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по умолчанию равны 100 и 3000 для `resend` и `disabled`; `smtp` без любого из них не запускается и принимает явно заданные значения; сниженное значение принимается как настроено для любого провайдера; пустое значение считается незаданным; ноль, отрицательные, нецелые значения, значения вне диапазона и суточный лимит больше месячного отклоняются без вывода секретов; bootstrap не запускается с нулевой квотой.
- `internal/adapter/secondary/mail/resend/`: 429 `daily_quota_exceeded` дает `QuotaPeriod` `day` с ожиданием до полуночи, а `monthly_quota_exceeded` дает `month` без ожидания.
- `internal/usecase/notification/`, со счетчиком и журналом в памяти и поддельными часами:
- `QuotaGate.PrepareSend` допускает отправки до суточного лимита, а следующую переводит в `waiting_quota` до 00:00 UTC и не считает ее; после полуночи допускает ее. При заполненном месяце (с 31 декабря на 1 января) и при заполнении обоих окон ждет начала месяца.
- Доставку, которую последним изменил экземпляр с часами на 5 мс впереди, уже после полуночи, откладывает с этим временем изменения и без ошибки.
- Применяет сниженный лимит к `smtp` так же, как к любому транспорту; отклоняет доставку, закрепленную за аккаунтом без квоты, и ничего для нее не резервирует.
- Возвращает доставку `unknown` без изменений с моментом сброса и отклоняет конечную доставку.
- Повтор в пределах 24 часов повторно использует открытое резервирование, даже когда сутки иначе заполнены; отказ этого повтора резервирование сохраняет; после окна повтор считается заново. Шлюз `smtp`, у которого нет дедупликации провайдера, считает каждый повтор.
- `SettleSend` оставляет резервирование для `accepted` и `unknown` и возвращает его при ошибке `Send` и любом исходе `rejected`. Повторный расчет возвращает резервирование один раз.
- Ответ о суточной квоте отмечает сутки и возвращает полночь, о месячной - отмечает месяц и возвращает его конец. Ответ без окна откладывает только доставку по подсказке или без времени, а окно, которое провайдер назвал заполненным, возврат не открывает.
- Отмечается окно, текущее на момент расчета: суточный отказ 31 октября отмечает только сутки и оставляет ноябрь открытым; резервирование в 23:59:59, рассчитанное через 5 мс после полуночи, отмечает новые сутки; подсказка, вычисленная по часам провайдера на 5 мс впереди, все равно дает ровно полночь.
- `ReportQuotaUsage` пишет расход и лимиты и предупреждает о других метках аккаунта.
- `DeliveryStatusReader.LatestForUser` возвращает вид, статус и время изменения, а `WaitingUntil` только для `waiting_quota`. Он спрашивает только про указанный аккаунт, без доставки ничего не возвращает и отклоняет нулевой аккаунт и неизвестный вид.
- Журналы не содержат адреса, темы или тела.
`TestMailQuota` в `backend/integration_test/mail_quota_test.go` использует `bootstrap(t, postgresService)`, настоящие transactor, хранилище доставок и репозиторий квот и поддельные часы. Каждый случай начинается с пустых таблиц:
- Конкурентность: 12 отправителей, каждый со своим соединением и транзакцией, одновременно вызывают `PrepareSend`. На окнах без строк (создание строк тоже конкурирует) при суточном лимите 10 разрешение получают ровно 10; после 7 последовательных отправок из следующих 12 разрешение получают ровно 3. Каждая остальная доставка сохраняется в `waiting_quota` с `next_attempt_at` на ближайшие 00:00 UTC, а оба счетчика заканчивают на 10. Без блокировки строк случай падает: допускаются все 12.
- Полночь и граница месяца: при лимитах 2 в сутки и 3 в месяц с 30 октября 22:00 UTC третья отправка ждет до 31 октября 00:00 UTC, за секунду до этого все еще ждет, а в полночь проходит; четвертая ждет 1 ноября, потому что месяц заполнен, и тогда проходит. Строки суток и месяца содержат 2, 1, 1 и 3, 1.
- Сниженный лимит и SMTP: шлюзы собираются из `config.LoadFromEnv`. После 4 отправок через Resend с лимитом по умолчанию лимит, сниженный до 3, откладывает следующую отправку до полуночи. `smtp` без настроек квот не загружается; с 2 и 2 он допускает две отправки через relay и откладывает третью до начала месяца, а доставка Resend под шлюзом `smtp` завершается ошибкой `ErrQuotaNotConfigured` и не меняет счетчиков.
- Уточнение по провайдеру: отказ `temporary` возвращает свое резервирование. Отказ `daily_quota_exceeded` при локальном счете 1 из 100 сохраняет доставку в `waiting_quota` до полуночи с одной попыткой, поднимает строку суток до 100 с `provider_exhausted_at`, после чего шлюз сам откладывает следующую доставку. После полуночи отказ `monthly_quota_exceeded` поднимает строку месяца до 3000 и откладывает доставки до 1 ноября.
- Удаление аккаунта: три принятые отправки дают 3 из 3; удаление аккаунта каскадно удаляет его доставки и попытки, счетчики сохраняют 3, а доставка другому аккаунту в тот же день ждет до полуночи.
- Порядок блокировок, детерминированно: строка месяца лежит в heap раньше строки суток, а запись идет в сессиях с `enable_indexscan=off`, поэтому сканирование следует порядку heap, как в воспроизведенной взаимоблокировке. Третья транзакция держит строку суток; резервирование и возврат встают за ней в очередь в обоих порядках, затем блокировка снимается. Ни один не получает ошибку взаимоблокировки, а расход сходится. Если убрать упорядоченную блокировку из `Settle`, случай падает с SQLSTATE 40P01.
- Порядок блокировок, ограниченная нагрузка: 60 раундов, в каждом одновременно стартуют возврат вторых суток, возврат первых суток с отметкой вторых через полночь и два резервирования вторых суток в сессиях с порядком heap. Ни один раунд не возвращает ошибку.
- Журнал: ошибка транспорта, рассчитанная дважды, возвращается один раз. Резервирование неизвестной попытки повторно используется повтором через час и не используется после 24-часового окна. В журнале остаются 2 открытые строки, 1 возвращенная и 2 с исходом.
- Статус для пользователя: аккаунт без писем ничего не получает; после одного допущенного и одного отложенного уведомления он видит `waiting_quota` до полуночи; другой аккаунт и другой вид ничего не получают.
- Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`.
- База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход.
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор не вызывает транспорт: worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, - это TASK-016.
## Шардирование интеграционных тестов