feat(notifications): send product notifications with a rights check right before each send

This commit is contained in:
shira committed 2026-10-09 20:38:39 +03:00
1 parent a856066316
commit 623d41b969
59 files changed
+4125 -1126

No files matched your search

+37 -15
View File
@@ -196,7 +196,7 @@ Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `d
### Mail transport
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The only caller is the sending worker for service identity mail (see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until product notification sending is implemented. Settings are described in [DEPLOY.md](DEPLOY.md#mail).
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The callers are the sending workers: the service worker for identity mail (see [Sending service mail](#sending-service-mail)) and the notification worker (see [Sending product notifications](#sending-product-notifications)). Settings are described in [DEPLOY.md](DEPLOY.md#mail).
`Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of:
@@ -234,7 +234,7 @@ Every `rejected` or `unknown` answer with a known error name sets `ProviderCode`
### Mail deliveries
Implemented: 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; see [Mail quotas](#mail-quotas). Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications with the permission check before a send is not implemented. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). Product flows do not call `MailRequester` yet, so notification requests remain queued. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented.
Implemented: 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; see [Mail quotas](#mail-quotas). Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications, with the rights check before each send, is implemented; see [Sending product notifications](#sending-product-notifications). The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). The invitation send is the first product caller of `MailRequester`. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented.
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
@@ -247,7 +247,7 @@ A delivery is the durable state of sending one message to one recipient. A `deli
Creation path:
1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": <id>, "kind": "notification"}` and nothing else.
1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, the subject the notice concerns (for an invitation, the invitation and its organization), and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": <id>, "kind": "notification"}` and nothing else.
2. The relay publishes the event, and the consumer `notification_delivery` applies it in the transaction of its dedup marker. It checks the envelope and that `mail_request_id` equals the aggregate ID, refuses trailing data after the payload object, and locks the request row (`FOR UPDATE`). It reads the account, renders the notification once with the current template version, inserts the delivery under the request ID with `source_event_id` set, and deletes the request row, all in that transaction.
3. A redelivered event is a `duplicate` of the consumer marker. A replay under another consumer name, a replayed dead letter after success, or a concurrent second consumer finds the request row gone (the second consumer waits on its lock) and skips. When an insert finds a delivery under the request ID already, the handler accepts it only for the same recipient and kind, and rejects the event otherwise.
4. Skips: a request that no longer exists, because it was handled or its account was deleted, and a notification to an account whose address is not verified (`email_verified_at` NULL). The unverified case deletes the request; notifications go only to confirmed addresses. Skips are logged at info level with the delivery and event IDs only. An unknown schema version, a payload that breaks the contract, or text that the template refuses is rejected for good and becomes a `handler_rejected` dead letter; storage errors are retried. An account deleted after the handler read it makes the insert fail on the foreign key; the transaction is aborted, so the error is retried, and the retry finds the request deleted with the account and skips.
@@ -273,14 +273,14 @@ Statuses. The values follow the `MailSender` outcomes:
| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal |
| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal |
| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body | Optional; none means operator review is required |
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, a notification's rights no longer hold, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides |
Transitions:
- `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted`, `rejected`, and `cancelled` refuse any further attempt with `domain.ErrDeliveryTransition`.
- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where the local mail quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it.
- `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it.
- `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, `processing_failed`, `rights_revoked`, `recipient_ineligible`, or `source_closed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it.
- `Delivery.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it.
Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`.
@@ -293,11 +293,11 @@ Provider account. Each delivery is pinned to the transport and account configure
Migration `00012_add_delivery_sending.sql` is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission.
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending workers `ClaimDue` (one statement per lane, selected by `ClaimScope`), `ReleaseClaim`, and `ServiceMailState`. The notification rights reader is `UnitOfWork.NotificationRights()`. Migrations `00044_add_notification_subject.sql` and `00045_send_product_notifications.sql` add the subject columns, the product due index `deliveries_product_due_idx`, and the cancel reasons of the rights checks. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
### Mail quotas
Implemented: quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota until product notification sending is implemented.
Implemented: quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Both lanes count against the quota: a product notification is admitted only while the windows keep the service reserve free (see [Sending product notifications](#sending-product-notifications)).
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.
@@ -342,9 +342,9 @@ Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quot
### Sending service mail
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented.
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. The password reset flow is not implemented.
Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
Scope. The service worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state; the notification lane is described in [Sending product notifications](#sending-product-notifications). Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was.
@@ -408,7 +408,29 @@ Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used
Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint.
Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
Open points. Notifications are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`); the notification lane has no overdue alert yet. Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
### Sending product notifications
Implemented: the notification lane of the sending loop. `usecase/notification.NewNotificationSender` (`notification_sender.go`) builds a `DeliverySender` (`delivery_sender.go`) for the notification kind. It claims with `ClaimDueProductDelivery` through the partial index `deliveries_product_due_idx` and uses the same transport, quota gate, and settlement as the service lane. A `SubjectRights` implementation decides, per subject kind, whether a notice may still go out. The invitation notice is `invitationNoticeRights` (`invitation_rights.go`), and its rule is `Delivery.CheckInvitationNotice` (`backend/internal/domain/invitation_notice.go`). `bootstrap/notification_sender.go` builds the loop with the service timing and `EMAIL_PROVIDER`.
Subject. A notification names the record whose rights it depends on: `domain.MailSubject`, stored with the request and copied to the delivery. The invitation send names the invitation and its organization. The subject is fixed with the delivery, and the content trigger refuses to change it (migration `00044_add_notification_subject.sql`).
Rights check. Before the transport is called, the lane's eligibility runs twice: once in the claim transaction, and again in the check transaction that holds the delivery lock, so a change after the claim is honored. The invitation rule checks, in this order: the recipient account exists and its address is verified; the address of the delivery is still the address of the account; the invitation exists in the organization of the subject; the invitation still awaits an answer (delivered or viewed) and its response deadline has not passed; the candidate has not hidden the organization; and the candidate's publication (C2) is current. The notice declares no allowed fields: its body is fixed text that names neither the organization nor the terms, and it carries no contact, so no field consent (C4) applies. The content was rendered once when the request was handled, so the check is the only work before the transport call. Like the check of service mail, the rights read is a snapshot taken in the sending transaction.
Contacts. Mail never carries a contact. Contact reads are pull-only, and each read re-checks the consent and the grant, so a contact copied into mail would outlive its grant. A future notice that carries a candidate field or a contact adds its consent check to `SubjectRights` before it can be sent.
Cancel reasons. A failed check cancels the delivery with no attempt, no provider call, and no change of the provider account, and clears its bodies (`deliveries_body_present` allows the clearing of a cancelled notification). `rights_revoked` covers a hidden organization, a withdrawn publication, and an invitation that was answered, expired, or passed its deadline. `recipient_ineligible` covers a missing account or an unverified address, and `recipient_mismatch` a changed address. `source_closed` covers a notice that names no subject, or an invitation that no longer exists. A subject kind that this build cannot check is neither sent nor cancelled: the claim returns `ErrNoSubjectRights` and the row waits for a build that can check it. None of these reasons counts as a broken cancellation for `LincodexMailCancelledBroken`.
Reserve. The notification lane's quota gate admits a send only while, after it, each window keeps at least `EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY` recipients free (`QuotaGate.WithReserve`). The defaults are a fifth of each quota limit: 20 a day and 600 a month on the Resend Free plan. The service lane keeps the full limits, so service mail always has its share of the same windows. A notification that the reserve refuses is parked in `waiting_quota` until the reset, and an idle pass does not claim it again, so the loop does not spin. A provider answer that its quota is used up marks the full window, not the reserve.
Retention. Every due notice is checked when it is claimed, including one whose invitation ended long ago, so no cancellable row stays due. A cancelled notice loses its bodies. An accepted notice keeps its neutral body, which is an open point.
Loop and disabled transport. The loop has its own gauge, `lincodex_notification_sender_running`, and its cancellations count in `lincodex_mail_sender_cancelled_total` by reason. With `EMAIL_PROVIDER=disabled` or without a database no loop starts, and a stored notice waits pinned to the transport it was created under, as service mail does. Once a transport runs, the loop rebinds the notice and sends it, if its rights still hold.
Privacy. Logs name a notice only by its delivery ID, kind, and closed values (the outcome and the cancel reason). The subject, the address, the candidate, and the body never appear in a log line, an error, or a metric label.
Open points. The invitation notice requires the candidate's publication, so a withdrawn publication cancels a pending notice; the product owner should confirm that choice. Accepted notices keep their neutral bodies, and no retention rule clears them yet. The notification lane has no overdue alert; the `lincodex_mail_deliveries{kind="notification",status="pending"}` gauge shows its backlog.
### Internal notifications
@@ -541,7 +563,7 @@ backend/
usecase/policy/ publication of policy versions and the demo policy seed
usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), and the sender of service mail (`ServiceMailSender`)
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), the senders of service mail (`ServiceMailSender`) and of product notifications (`NewNotificationSender`), and their rights checks
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
adapter/primary/http/
@@ -566,7 +588,7 @@ backend/
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
worker/mailsender/ sending loop of service identity mail: repeats passes, waits when idle, backs off on failures, reports lincodex_mail_sender_running
worker/mailsender/ sending loop of the mail lanes (service identity mail and product notifications): repeats passes, waits when idle, backs off on failures, reports its running gauge
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics
bootstrap/ configuration, wiring, lifecycle, shutdown
@@ -579,7 +601,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
@@ -1106,7 +1128,7 @@ The Go service exports standard Go/process metrics and the product metrics on an
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged.
- Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`.
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_notification_sender_running` reports the same for the notification loop; `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
@@ -1115,7 +1137,7 @@ Planned observability work includes bounded measurements for queued jobs, oldest
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action; the rights reasons of notifications (`rights_revoked`, `recipient_ineligible`, `source_closed`) are normal and do not fire it. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
## Requirements coverage