chore: remove backlog references from code and documentation
This commit is contained in:
1 parent
0529601021
commit
8e7ce8d71c
129 files changed
+699
-701
No files matched your search
+66
-66
@@ -54,7 +54,7 @@ The MVP does not add a separate vector database, Kubernetes, or a search microse
|
||||
|
||||
### HTTP perimeter and client address
|
||||
|
||||
Implemented (TASK-042). The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address).
|
||||
Implemented. The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address).
|
||||
|
||||
The client address is derived only through trusted proxies. The edge replaces `X-Forwarded-For`; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS` (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with `middleware.ClientAddr(ctx)` and key the limiter with `middleware.LimiterKey` (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. The first consumer is the registration and resend limits (see Registration and verification resend); the router mounts `ClientIP`.
|
||||
|
||||
@@ -64,7 +64,7 @@ The client address is derived only through trusted proxies. The edge replaces `X
|
||||
|
||||
- Keys have the form `<namespace>/<32 hex characters>` from 128 random bits. Only the validated policy namespace comes from code; file names and other client input never become part of a key. `Open` and `Delete` accept only keys of their policy's namespace and format, so a client-shaped key, a traversal path, or another feature's key is rejected before storage is called.
|
||||
- Writes take the exact size. A declared size above the policy limit is rejected before any request. The stream passes through an `io.LimitReader` guard that withholds the last chunk until the source has ended, so a longer or shorter source aborts the request before storage receives a complete body. Any failure after the write started deletes the key, also after caller cancellation. Sources of unknown length are not buffered; a feature that needs them must spool to a bounded temporary file or add multipart upload. The source needs its own deadline, such as `http.ResponseController.SetReadDeadline` on a request body: `Put` waits for a blocked read, and canceling the context does not interrupt it.
|
||||
- `Put` returns a `Record`: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order: `Put`, then persist the record with their ownership data in a database transaction, then `Delete` the key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanup `Delete` returned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports (TASK-030, TASK-458) and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser.
|
||||
- `Put` returns a `Record`: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order: `Put`, then persist the record with their ownership data in a database transaction, then `Delete` the key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanup `Delete` returned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser.
|
||||
- `Open` checks that the stored object still fits the policy and closes the response on every rejection. The caller closes the returned `File`; reading fails when the body differs from the stored size. The adapter's `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, and the wait for response headers, not the body transfer of `Put` and `Get`, so the caller's context is the only bound on a long or slow stream. `Delete` is idempotent, and absence maps to `files.ErrNotFound`.
|
||||
- There are no public URLs. The layer creates no public, permanent, or presigned URLs, and the bucket has no public policy or anonymous ACL. A browser download must go through an authenticated backend endpoint that checks current access and streams `File` with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, so a stored file is never rendered as a page of the application origin. The key, bucket, and storage URL never reach clients.
|
||||
|
||||
@@ -99,7 +99,7 @@ The relay that publishes these rows is described in [Outbox relay](#outbox-relay
|
||||
|
||||
### Outbox relay
|
||||
|
||||
Implemented (TASK-009): the relay loop in `backend/internal/worker/outboxrelay/`, the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports (`backend/internal/port/outbound/outbox_relay.go`), the PostgreSQL store (`adapter/secondary/postgres/outbox_relay.go`), and the franz-go producer (`adapter/secondary/kafka/`). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when `RELAY_ENABLED=false` or `DATABASE_URL` is unset; the outbox then keeps the events. Settings are listed in [DEPLOY.md](DEPLOY.md#outbox-relay).
|
||||
Implemented: the relay loop in `backend/internal/worker/outboxrelay/`, the `outbound.OutboxRelayStore` and `outbound.EventPublisher` ports (`backend/internal/port/outbound/outbox_relay.go`), the PostgreSQL store (`adapter/secondary/postgres/outbox_relay.go`), and the franz-go producer (`adapter/secondary/kafka/`). Bootstrap starts the relay together with the HTTP servers in the same process and stops it on shutdown. The relay has its own PostgreSQL pool of at most two connections, one for the claim transaction and one for the backlog read, so it never takes connections from request handling. It does not run when `RELAY_ENABLED=false` or `DATABASE_URL` is unset; the outbox then keeps the events. Settings are listed in [DEPLOY.md](DEPLOY.md#outbox-relay).
|
||||
|
||||
One pass is one READ COMMITTED transaction:
|
||||
|
||||
@@ -134,7 +134,7 @@ The metric `lincodex_outbox_relay_events_total{outcome}` counts published and fa
|
||||
|
||||
### Event consumers
|
||||
|
||||
Implemented (TASK-010): the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered (TASK-015): `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `<CONSUMER_GROUP_PREFIX>.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers).
|
||||
Implemented: the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `<CONSUMER_GROUP_PREFIX>.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers).
|
||||
|
||||
A handler implements three methods:
|
||||
|
||||
@@ -174,7 +174,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
Implemented (TASK-035): durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline (TASK-205). Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
|
||||
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
|
||||
|
||||
Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `<id>:<version>`.
|
||||
|
||||
@@ -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/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The only caller is the sending worker for service identity mail (TASK-016, see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until TASK-462. Settings are described in [DEPLOY.md](DEPLOY.md#mail).
|
||||
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).
|
||||
|
||||
`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:
|
||||
|
||||
@@ -206,7 +206,7 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai
|
||||
|
||||
`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.
|
||||
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 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.
|
||||
|
||||
The Resend transport uses `net/http` without an SDK. One `Send` is one `POST https://api.resend.com/emails` with `from` (`EMAIL_FROM`), `to` (one recipient), `subject`, `text`, and `html` (a blank part is omitted), an `Authorization: Bearer` key, a `User-Agent`, and `Idempotency-Key` set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. `EMAIL_TIMEOUT` bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false `unknown`. The request also has no `GetBody`, because `net/http` treats a POST with `Idempotency-Key` as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error `name` are parsed, and the provider's message and body are not kept.
|
||||
|
||||
@@ -230,11 +230,11 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt
|
||||
| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend |
|
||||
| The caller's context ended before the request was written | the context error; nothing was sent |
|
||||
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy (TASK-017), the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Implemented (TASK-016): the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy (TASK-017), and sending product notifications with the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests.
|
||||
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 worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy, and sending product notifications with the permission check before a send. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests.
|
||||
|
||||
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
|
||||
|
||||
@@ -254,7 +254,7 @@ Creation path:
|
||||
|
||||
Why the event carries only a reference. Events stay in `outbox_events` and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in `mail_requests`, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation.
|
||||
|
||||
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer` (TASK-016), which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks.
|
||||
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer`, which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks.
|
||||
|
||||
Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with `domain.ErrMailContentIntegrity` on a mismatch. The trigger `deliveries_refuse_content_change` refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint `deliveries_content_immutable`, mapped to `outbound.ErrDeliveryContentImmutable`). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery.
|
||||
|
||||
@@ -263,7 +263,7 @@ Personal data at rest. A delivery row holds the recipient address and the bodies
|
||||
- Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see [DEPLOY.md](DEPLOY.md#mail-deliveries).
|
||||
- Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row.
|
||||
- The bodies of a token mail are cleared when the delivery reaches `accepted`, `rejected`, or `cancelled` (`body_redacted_at`, see [Sending service mail](#sending-service-mail)), so a database dump or backup holds no token of a finished mail; a retention rule that deletes other terminal deliveries after a bounded period is not implemented yet, and until it exists those rows stay. Encryption of the bodies at rest is not implemented either.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics (TASK-022) carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject.
|
||||
|
||||
Statuses. The values follow the `MailSender` outcomes:
|
||||
|
||||
@@ -279,25 +279,25 @@ Statuses. The values follow the `MailSender` outcomes:
|
||||
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 TASK-018's local quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it.
|
||||
- `Delivery.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.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it.
|
||||
|
||||
Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy (TASK-017) and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`.
|
||||
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`.
|
||||
|
||||
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. 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.
|
||||
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`). The service mail worker 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.
|
||||
|
||||
Migration `00012_add_delivery_sending.sql` (TASK-016) is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission (TASK-462).
|
||||
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`.
|
||||
|
||||
### 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`). The sending worker (TASK-016) calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota while TASK-462 is open.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -311,9 +311,9 @@ Lock order. Every write first creates and locks all the usage rows it will touch
|
||||
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).
|
||||
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.
|
||||
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.
|
||||
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, 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.
|
||||
|
||||
@@ -338,11 +338,11 @@ What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID
|
||||
| `rejected` | Your email could not be sent |
|
||||
| `cancelled` | Your email was not sent because the link in it is no longer valid; request a new one |
|
||||
|
||||
Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges (TASK-022) come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts).
|
||||
Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts).
|
||||
|
||||
### Sending service mail
|
||||
|
||||
Implemented (TASK-016): the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications (TASK-462), the retry and unknown outcome policy (TASK-017), and the identity flows that call `ServiceMailer`.
|
||||
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications, the retry and unknown outcome policy, and the identity flows that call `ServiceMailer`.
|
||||
|
||||
Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
|
||||
|
||||
@@ -385,7 +385,7 @@ What a provider answer becomes. The delivery state machine of `domain.Delivery`
|
||||
| `rejected` `permanent` or `invalid_request` | `rejected` | none | released |
|
||||
| `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released |
|
||||
| `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full |
|
||||
| `unknown` | `unknown` | none: no automatic retry (TASK-017) | counted |
|
||||
| `unknown` | `unknown` | none: no automatic retry | counted |
|
||||
| `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released |
|
||||
| `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released |
|
||||
| `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released |
|
||||
@@ -408,11 +408,11 @@ 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. `unknown` has no automatic retry or escalation until TASK-017. Sending notifications, and the permission check they need, belong to TASK-462; until then they wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
|
||||
Open points. Automatic retry or escalation for `unknown` is not implemented. 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.
|
||||
|
||||
### 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.
|
||||
Implemented as storage, a publisher, and a startup seed: 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.
|
||||
|
||||
`policy_versions` columns:
|
||||
|
||||
@@ -426,9 +426,9 @@ Implemented as storage, a publisher, and a startup seed (TASK-005): migration `b
|
||||
|
||||
The database enforces immutability. The trigger function `policy_versions_refuse_change` refuses every UPDATE and DELETE (row trigger) and TRUNCATE (statement trigger) with SQLSTATE 23000 and the constraint name `policy_versions_immutable`; the adapter maps exactly that pair to `outbound.ErrPolicyVersionImmutable`, never the message. The port has no update or delete method, so a change is always a new version. The guarantee covers application statements and manual SQL; a role that owns the table can still disable the trigger or drop the table, so a least-privilege runtime role remains future work.
|
||||
|
||||
Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for TASK-087); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.
|
||||
Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for organization quota enforcement); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.
|
||||
|
||||
Open question for the attempt tasks (TASK-157 and TASK-158): `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided.
|
||||
Open question for the attempt tasks: `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided.
|
||||
|
||||
The document has `schema_version` 1 and the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`; field names carry their unit (`_days`, `_business_days`, `_hours`, `_bp`). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so `domain.RestorePolicyVersion` decodes the stored document, validates it, encodes it again, and compares its SHA-256 with `document_sha256`; a mismatch returns `domain.ErrPolicyDocumentIntegrity`. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder.
|
||||
|
||||
@@ -591,7 +591,7 @@ These intervals are the accepted initial policy, stored as demo version 1 of the
|
||||
|
||||
### Assessment bank
|
||||
|
||||
Implemented as storage and a loader (TASK-154), not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open.
|
||||
Implemented as storage and a loader, not as a candidate-facing feature: migration `backend/db/migrations/00011_create_assessment_bank.sql`, queries in `backend/db/queries/assessment_bank.sql`, the domain types in `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), the `outbound.AssessmentBankRepository` port (`port/outbound/assessment_bank.go`, reachable through `UnitOfWork.AssessmentBank()`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/assessment_bank.go`, and the loader in `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Nothing in bootstrap or the HTTP API calls it yet, and no category is open.
|
||||
|
||||
- Family version. One `assessment_families` row is one version of one family (`family_key`, `version`): category, specialization (the domain inside the category), title, author (`ai:<name>` or `operator:<handle>`), reviewer (`operator:<handle>` or NULL), `review_status` (`pending`, `approved`, `rejected`), the seed generator, the answer key, the rubric, a content hash with its `hash_scheme`, a lifecycle (`draft`, `published`, `retired`), and the operators and times of publication and retirement. The reviewer is never the author, and a review is pending exactly while there is no reviewer (CHECK constraints; the domain applies the same rules). The reviewer in a bundle and the operator of a publication are declared values, not authenticated identities, until reviewer and operator accounts exist.
|
||||
- Immutability. The content of a stored version never changes: the trigger `assessment_families_guard_update` refuses every UPDATE that changes a column other than the lifecycle columns (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), and `assessment_families_refuse_removal` refuses DELETE and TRUNCATE, all with SQLSTATE 23000 and the constraint name `assessment_families_immutable`, which the adapter maps to `outbound.ErrAssessmentFamilyImmutable`. The lifecycle moves only forward (draft, published, retired), the trigger sets the times and keeps the publisher through a retirement, and a version is published only with an approved review by a reviewer (`assessment_families_published_requires_review`). A change is a new version with the next number; the loader accepts only version 1 for a new family and the successor of the latest version otherwise. A pending draft is never approved in place: its review is recorded by importing a new version of the family that carries the review, and the pending version stays an unpublished draft. The domain recomputes the content hash when it reads a row and returns `ErrAssessmentFamilyIntegrity` for a row changed outside the application. The hash is the SHA-256 of a canonical JSON document that holds the content without the bundle name, ID, lifecycle, and publication fields. The `hash_scheme` column (a smallint with a CHECK of the known values, one of the immutable columns) names the layout: the domain verifies a row with the hash function of the scheme the row was stored with, so a later scheme (a new function and a new CHECK value, never an edit of scheme 1) verifies new rows without invalidating old ones, and a row with an unknown scheme is refused; tests verify a row with its own scheme and pin the scheme 1 hash of a fixed input. As for `policy_versions`, a role that owns the table can still disable the triggers.
|
||||
@@ -646,7 +646,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep
|
||||
|
||||
### Identity storage
|
||||
|
||||
Implemented as storage only (TASK-051): migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned (TASK-053 to TASK-056); no usecase or handler uses this storage yet.
|
||||
Implemented as storage only: migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned; no usecase or handler uses this storage yet.
|
||||
|
||||
- `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case.
|
||||
- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists the allowed purposes, so a password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. A CHECK allows at most one of consumed and invalidated.
|
||||
@@ -659,13 +659,13 @@ Decisions:
|
||||
- The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values.
|
||||
- Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it.
|
||||
- Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time.
|
||||
- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. TASK-056 can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration.
|
||||
- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. Session authentication can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration.
|
||||
|
||||
What the ports guarantee:
|
||||
|
||||
- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see [Consent ledger](#consent-ledger)). `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise.
|
||||
- `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose.
|
||||
- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase (TASK-054) maps that outcome to `verification_token_invalid`.
|
||||
- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase maps that outcome to `verification_token_invalid`.
|
||||
- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`.
|
||||
- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement.
|
||||
- `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection.
|
||||
@@ -674,20 +674,20 @@ What the ports guarantee:
|
||||
|
||||
### Password hashing
|
||||
|
||||
Implemented (TASK-052) and tested: registration (TASK-053) creates the hasher from configuration and calls it; login (TASK-055) will do the same.
|
||||
Implemented and tested: registration creates the hasher from configuration and calls it; login will do the same.
|
||||
|
||||
- `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check.
|
||||
- The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure.
|
||||
- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; request rate limiting comes with the HTTP operations.
|
||||
- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones, so a login can store a new hash.
|
||||
- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike.
|
||||
- Login (TASK-055) must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it.
|
||||
- Login must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it.
|
||||
- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration will call it on every branch before it looks up the email.
|
||||
- Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address.
|
||||
|
||||
### Consent ledger
|
||||
|
||||
Implemented as storage, ports, and a read contract (TASK-062): migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check is implemented as the usecase `consent.Service` (TASK-063, see [Consent usecase](#consent-usecase)). Revocation with its downstream effects and the HTTP handler (TASK-064), C1 in the registration transaction (TASK-053), and C4 in the invitation acceptance (TASK-201) are planned; no product flow calls the usecase yet.
|
||||
Implemented as storage, ports, and a read contract: migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check is implemented as the usecase `consent.Service` (see [Consent usecase](#consent-usecase)). Revocation with its downstream effects and the HTTP handler, C1 in the registration transaction, and C4 in the invitation acceptance are planned; no product flow calls the usecase yet.
|
||||
|
||||
The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another.
|
||||
|
||||
@@ -698,12 +698,12 @@ The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation
|
||||
Decisions:
|
||||
|
||||
- Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes, and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`.
|
||||
- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` (TASK-063) checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back.
|
||||
- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented.
|
||||
- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration.
|
||||
- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)).
|
||||
- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the history of TASK-088 (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change.
|
||||
- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance (TASK-201) calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`.
|
||||
- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back.
|
||||
- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to consent revocation and are not implemented.
|
||||
- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration.
|
||||
- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for registration: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)).
|
||||
- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the candidate visibility history (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change.
|
||||
- C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`.
|
||||
- Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent.
|
||||
- Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output.
|
||||
|
||||
@@ -717,31 +717,31 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo
|
||||
|
||||
### Consent usecase
|
||||
|
||||
Implemented (TASK-063): `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant.
|
||||
Implemented: `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant.
|
||||
|
||||
- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration (TASK-053) creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled.
|
||||
- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled.
|
||||
- Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it with `Created` false, and leave the account without any C1 once it is deleted. The integration test shows both orders.
|
||||
- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration (TASK-053) must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist.
|
||||
- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist.
|
||||
- Current text only. A grant reads `ConsentTexts().Current` at the application time and refuses any other version with `*StaleConsentTextError`, which matches `ErrStaleConsentText` and carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid.
|
||||
- Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time.
|
||||
- Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with `Created` false, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. A repeat that names an older version after a newer text was published is stale, not a repeat: the subject has to see the new text, and the ledger keeps its one record.
|
||||
- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance (TASK-201): the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls.
|
||||
- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request of TASK-315, the revocation of TASK-064) treats a missing record as "not given" and keeps the manual path open.
|
||||
- No revocation here. `Revoke` stays on the ledger port, and TASK-064 calls it with the downstream effects and the outbox events in one transaction.
|
||||
- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers (TASK-064, TASK-053, TASK-201).
|
||||
- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or TASK-064, and neither exists yet.
|
||||
- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance: the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls.
|
||||
- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request, consent revocation) treats a missing record as "not given" and keeps the manual path open.
|
||||
- No revocation here. `Revoke` stays on the ledger port, and consent revocation must call it with the downstream effects and the outbox events in one transaction.
|
||||
- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers.
|
||||
- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or consent revocation, and neither exists yet.
|
||||
|
||||
### Registration and verification resend
|
||||
|
||||
Implemented (TASK-053): `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/identity.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`.
|
||||
Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/identity.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`.
|
||||
|
||||
One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
|
||||
|
||||
Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing. Requirements for the hand-off:
|
||||
|
||||
- TASK-054 (`ConfirmEmail`): confirming a token applies the pending credentials of the clicked token, and only those, to the account row in the confirmation transaction (password hash, scenario, onboarding step), and must require the password of that registration to confirm a token that carries pending credentials, verified against the token's pending hash. Then a victim who clicks an attacker's link cannot adopt the attacker's password, and an attacker cannot confirm the victim's token. `EmailVerificationRequest` has no password field today; adding it is a contract change of TASK-054, not made here. The description of `RegisterAccount` in the contract still says a repeat registration replaces the password hash on the account; TASK-054 corrects it with that change.
|
||||
- TASK-054 also: test both orderings (the attacker registers first and the victim second, and the reverse) and show that the owner never ends up with a password they did not choose; require that a C1 record exists and belongs to the registration version of the confirmed token; refuse a token that carries no pending credentials, with no legacy path that skips the password; null the `pending_*` columns of the token when it is consumed.
|
||||
- TASK-055 (login): an unverified account never signs in. Login answers as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials.
|
||||
- Email confirmation (`ConfirmEmail`): confirming a token applies the pending credentials of the clicked token, and only those, to the account row in the confirmation transaction (password hash, scenario, onboarding step), and must require the password of that registration to confirm a token that carries pending credentials, verified against the token's pending hash. Then a victim who clicks an attacker's link cannot adopt the attacker's password, and an attacker cannot confirm the victim's token. `EmailVerificationRequest` has no password field today; adding it is an email confirmation contract change, not made here. The description of `RegisterAccount` in the contract still says a repeat registration replaces the password hash on the account; email confirmation must correct it with that change.
|
||||
- Email confirmation also requires: test both orderings (the attacker registers first and the victim second, and the reverse) and show that the owner never ends up with a password they did not choose; require that a C1 record exists and belongs to the registration version of the confirmed token; refuse a token that carries no pending credentials, with no legacy path that skips the password; null the `pending_*` columns of the token when it is consumed.
|
||||
- Login: an unverified account never signs in. Login answers as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials.
|
||||
|
||||
Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit.
|
||||
|
||||
@@ -759,7 +759,7 @@ Known limits. A resend for an unknown or verified address skips the token and me
|
||||
|
||||
### Organizations and memberships
|
||||
|
||||
Implemented as storage, ports, and a source contract (TASK-077): migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers (TASK-078) and the server-side context and membership checks of every tenant operation (TASK-079) are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints.
|
||||
Implemented as storage, ports, and a source contract: migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers and the server-side context and membership checks of every tenant operation are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints.
|
||||
|
||||
Tables:
|
||||
|
||||
@@ -769,13 +769,13 @@ Tables:
|
||||
|
||||
Decisions:
|
||||
|
||||
- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The decision follows TASK-079 (the context comes only from the caller's active memberships, and a terminated membership closes reads at once) and TASK-085 (a switch clears the client's tenant queries).
|
||||
- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it (TASK-081, TASK-082). `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing (TASK-083, TASK-463).
|
||||
- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; TASK-086 adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (TASK-087 reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier).
|
||||
- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management (TASK-084), not of this constraint, which would otherwise block a platform decision about an abusive organization.
|
||||
- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management of TASK-084, which changes a membership and the organization together, and the tenant repository of TASK-079 must take the locks in that order, or two transactions can deadlock.
|
||||
- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the ledger tests of TASK-062 and TASK-063 to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records (TASK-198), together with the keys of needs (TASK-179). All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3).
|
||||
- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` (TASK-078) keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and delete it at the end of the replay window; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (TASK-078 and TASK-087 need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations).
|
||||
- Active context. It is not a server-side session attribute. The organization is the `org_id` in the path, and the server derives the right from the active membership on every request, so a removal, a suspension, or a leave closes the next read with nothing to invalidate. `ListMyOrganizations` is the directory a client picks from; remembering the last choice is a browser convenience. The context comes only from the caller's active memberships, and a terminated membership closes reads at once. A switch clears the client's tenant queries.
|
||||
- Role and state in the membership only. `OrganizationRole` is `owner`, `recruiter`, `hiring_manager`, or `technical_expert` (PRD 2.2, Q3, and the FR07 matrix), and `MembershipState` is `active`, `suspended`, `removed`, or `left`, each a CHECK constraint, not a PostgreSQL enum, so a later value is a constraint change in a migration. There is no `invited` state: PRD 6.4 lists `MemberInvite` as its own entity, an invitation to an email address that may have no account yet, and a membership row appears when its owner accepts it. `organizations` has no role, owner, or member column (an integration test reads the catalog to prove it), and `Organization`, `OrganizationCreate`, and `OrganizationUpdate` have no such field. Only the owner manages the company (`OrganizationRole.CanManageOrganization`); the rest of the matrix is applied by the operations it governs, and in the MVP the other roles grant nothing.
|
||||
- Verification level. `verification_level` is `e0` to `e3` with `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), and one CHECK ties each level to its own bases. The columns are separate from the profile: `UpdateOrganizationProfile` never names them, `domain.NewOrganization` cannot choose a level and starts every organization at `e0` on `confirmed_email`, `Organization.ApplyProfile` keeps the verification, and the contract has no operation or request field that sets it. A test updates a profile after a process moved the level and checks that it stays. E1 to E3 are set by the verification processes that do not exist yet; the planned verification flow adds E0/E1 with evidence, a scope, and an append-only history, and it will update these columns together with its history row and must first write a history record from the current row of every existing organization (level, basis, and time as stored), so the history has no gap before its first process. `OrganizationVerificationLevel.QuotaTier` maps `e0` to `e2` to the quota tiers of the product policy and has none for `e3`, which the PRD gives a separate policy (quota enforcement reads the tier and must fail closed on an `e3` organization: no quota granted, the action refused, never a fallback to another tier).
|
||||
- An organization has an owner. A deferred constraint trigger (`organizations_owner_required`, SQLSTATE 23514) refuses at commit an organization with no `owner` membership in the `active` state, so creating an organization without its owner fails whichever code inserted it, and `CreateWithOwner` stores the organization, its representatives, and the owner in one transaction. Removing or demoting the last owner later is a rule of the member management, not of this constraint, which would otherwise block a platform decision about an abusive organization.
|
||||
- Update. `UpdateProfile` is one statement that applies only when the stored version equals the version the caller read, and advances it by one. The same statement requires an active membership of the actor with a manager role (the roles come from `domain.ManagerRoles`, not from SQL), so a membership that ended after the caller's read still stops the write. When the statement matches nothing, the adapter reads the membership to answer `ErrOrganizationNotFound` (unknown organization or no active membership), `ErrOrganizationManagerRequired`, or `ErrOrganizationVersionConflict`, in that order, so a stale version never tells an outsider anything. The representative list is then replaced in the same transaction under the row lock of the update. The statement locks the organization row (`FOR UPDATE`) and then the actor's membership row `FOR SHARE`, so a revocation that commits while the statement waits for the membership lock is re-evaluated and stops the write (an integration test holds a revocation open, queues the update behind it, and commits it). The lock order of every writer is organizations, then memberships: the member management, which changes a membership and the organization together, and the tenant repository must take the locks in that order, or two transactions can deadlock.
|
||||
- Foreign keys and deletion. `memberships` restricts the deletion of an organization and of an account, so an account with memberships cannot be deleted until a procedure ends them, in the same way as the consent ledger restricts the account. The application never deletes an organization. The consent ledger does not reference `organizations` yet: `consent_records.organization_id` is still a plain column with the snapshot name beside it. Adding the foreign key now would force the consent ledger tests to create real organizations, and the same migration has to add the `invitation_id` key, which needs the invitation table; both arrive with the migration that creates the invitation records, together with the keys of needs. All of them are `ON DELETE RESTRICT`, so an organization with consent history, needs, or invitations stays undeletable, which is the intended protection of consent evidence (PRD 7.3).
|
||||
- Privacy. Contacts are public company channels; the contract and the domain accept no personal contact of an employee, and the owner answers for the content. Representative names are personal data of employees: `OrganizationRepresentative` hides its fields behind a pointer and redacts itself in `fmt` and `slog` output, `Organization` logs only its identifier, version, and level, and adapter errors keep the SQLSTATE and the constraint name without the failing row. The website is only stored: the server never fetches it, and a later feature that does must resolve the address and refuse private ranges itself. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput`, and the generated sqlc parameter structs of this repository hold names and must never be logged. The idempotency store of `CreateOrganization` keeps the stored 201 for 24 hours, and that response holds the representatives' names: the store must keep it out of logs and metrics, protect it like the other personal data, and delete it at the end of the replay window; its request fingerprint must be a hash, not the body. The candidate card is shown only to a candidate who received an invitation from the organization, and its `representatives` may be absent. The open questions (the publication of representative names, a sphere taxonomy) and the blocking one, a limit of organizations per account, which the PRD does not set and without which an account can multiply quotas by creating organizations (organization creation and quota enforcement need the owner's decision, and the prepared mechanism is a 409 `state_conflict` on create), are in [api/README.en.md](../../api/README.en.md#organizations).
|
||||
|
||||
What the ports guarantee (`outbound.OrganizationRepositories`, available on `UnitOfWork` only, because a write needs the transaction):
|
||||
|
||||
@@ -785,7 +785,7 @@ What the ports guarantee (`outbound.OrganizationRepositories`, available on `Uni
|
||||
|
||||
### Candidate profile
|
||||
|
||||
Implemented as storage, domain, and the source contract (TASK-066): the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test.
|
||||
Implemented as storage, domain, and the source contract: the migration `backend/db/migrations/00013_create_candidate_profiles.sql`, the queries in `backend/db/queries/candidate.sql`, the domain types in `backend/internal/domain/candidate.go`, the schemas in `api/core/components/schemas/candidate_schemas.yml`, and the operations `GetMyProfile` and `SaveMyProfile` in `api/core/routes/candidate_profile.yml`. There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter will come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`StoredClaims`, `RestoreCandidateProfile`) are ready and covered by an integration test.
|
||||
|
||||
Tables:
|
||||
|
||||
@@ -804,7 +804,7 @@ Decisions:
|
||||
|
||||
### Candidate visibility
|
||||
|
||||
Implemented as storage, domain, and the source contract (TASK-088): the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test.
|
||||
Implemented as storage, domain, and the source contract: the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test.
|
||||
|
||||
Four independent pieces of state, each with its own table and its own version. No statement of one table writes another, and the consent C2 is neither copied nor replaced:
|
||||
|
||||
@@ -825,20 +825,20 @@ Decisions:
|
||||
- History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger).
|
||||
- Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do.
|
||||
|
||||
- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read: TASK-185, TASK-089, TASK-090) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table.
|
||||
- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path (TASK-064) must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants.
|
||||
- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table.
|
||||
- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants.
|
||||
- Publish and revoke race. The publish transaction takes the current C2 with `LockCurrentC2Record` (`SELECT ... FOR SHARE`) and writes the publication under that lock, then re-reads the effective state with `ReadCandidatePublication` in the same transaction to build its response. The revocation stamp is an UPDATE of the same row, so it either commits first (the lock returns no row and the publication is refused with 409) or waits until the publication commits and closes the card right after; an integration test holds the lock and proves both orders.
|
||||
- Verified email. Publishing, hiding, and the history exist only for accounts with a verified email (a usecase requirement). The unverified account cleanup (`DeleteUnverifiedUsersRegisteredBefore`) deletes its consent records explicitly and would meet the restricting reference of a publication to its C2 record, so that no unconfirmed account holds a publication is a usecase requirement, not a physical impossibility: the cleanup also works over an unverified account that does hold a C2, a publication, and history, and over a C2 revoked and granted again (an integration scenario verifies it, and it depends on the order in which the data-modifying statements of the cleanup apply). Hiding records and history cascade.
|
||||
- Two kinds of 409 `state_conflict` are told apart by `errors[]`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. The hiding limit is enforced by the trigger under a lock on the account row; when an insertion fails with SQLSTATE 23514 and `candidate_hidden_organizations_limit`, the adapter must re-read the pair before answering 409, because a concurrent PUT of the same pair at 999 records can have created it, and the idempotent answer is 200; an integration test fires eight concurrent insertions at 999 records and expects exactly one success.
|
||||
- A new card field is a contract change and a migration. The codes are listed in the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables, as well as in the `CardField` enum, `domain.CardField`, and the card builder.
|
||||
|
||||
Content of the card (hard requirements for TASK-089, which builds it):
|
||||
Content of the card (hard requirements for its builder):
|
||||
|
||||
- Only values that the candidate confirmed ever reach the card; an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.
|
||||
- A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped, never published. `domain.CardTextLooksLikeContact` is the check the builder must apply to every free text; it errs on the side of dropping.
|
||||
- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion of TASK-089, not decided here (see the open question in the API README).
|
||||
- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion for the card builder, not decided here (see the open question in the API README).
|
||||
|
||||
The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result (TASK-185) must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks.
|
||||
The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks.
|
||||
|
||||
## Frontend
|
||||
|
||||
@@ -875,7 +875,7 @@ Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amo
|
||||
|
||||
## Metrics, telemetry, and alerts
|
||||
|
||||
The Go service exports standard Go/process metrics and the product metrics of TASK-022 on an internal `/metrics` listener outside `/api/v1`:
|
||||
The Go service exports standard Go/process metrics and the product metrics on an internal `/metrics` listener outside `/api/v1`:
|
||||
|
||||
- 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`.
|
||||
|
||||
+6
-6
@@ -233,7 +233,7 @@ A worker claims it within one poll interval and runs it with fresh attempts. To
|
||||
|
||||
The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read.
|
||||
|
||||
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until TASK-462, so a production stand sends no message today.
|
||||
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until product notification sending is implemented, so a production stand sends no message today.
|
||||
|
||||
`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
|
||||
|
||||
@@ -258,18 +258,18 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until TASK-462 connects product notifications. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
||||
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
||||
|
||||
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand.
|
||||
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
|
||||
- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats.
|
||||
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until TASK-462; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until TASK-462, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider.
|
||||
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until product notification sending is implemented; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until product notification sending is implemented, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider.
|
||||
- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision.
|
||||
- Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request.
|
||||
|
||||
### Mail quotas
|
||||
|
||||
Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until TASK-462. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
|
||||
Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until product notification sending is implemented. 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.
|
||||
@@ -278,7 +278,7 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo
|
||||
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up.
|
||||
- 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).
|
||||
- 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.
|
||||
- Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit.
|
||||
|
||||
### Sending service mail
|
||||
@@ -289,7 +289,7 @@ The backend process runs one sending loop for service identity mail (email verif
|
||||
- With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off.
|
||||
- Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one".
|
||||
- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A refusal for now (`temporary`, `rate_limited`) leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the same key and body; it repeats until it succeeds, is refused for good, or the token expires and the delivery is cancelled. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas).
|
||||
- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy (TASK-017).
|
||||
- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy.
|
||||
- A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand.
|
||||
- `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled.
|
||||
- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. Do not copy bodies of waiting mail anywhere.
|
||||
|
||||
@@ -50,7 +50,7 @@ What exists now:
|
||||
|
||||
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
|
||||
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap.
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends notifications yet (TASK-462). With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends notifications yet. With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
|
||||
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
|
||||
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers).
|
||||
@@ -88,7 +88,7 @@ Security tools have a separate install and work loop: `make -C security install`
|
||||
|
||||
The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production.
|
||||
|
||||
Planned Origin rule (TASK-056): every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an `Origin` from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare `Origin` with `Host`. An unsafe request without `Origin` or with another value answers 403 `csrf_check_failed`.
|
||||
Planned Origin rule: every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an `Origin` from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare `Origin` with `Host`. An unsafe request without `Origin` or with another value answers 403 `csrf_check_failed`.
|
||||
|
||||
## Layout
|
||||
|
||||
|
||||
+2
-2
@@ -199,7 +199,7 @@ Unit tests (`make -C backend test`) cover the quota rules without a database:
|
||||
- Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`.
|
||||
- The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome.
|
||||
|
||||
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence (TASK-016) is covered by the service mail sending tests below.
|
||||
`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is covered by the service mail sending tests below.
|
||||
|
||||
## Service mail sending tests
|
||||
|
||||
@@ -264,7 +264,7 @@ Unit tests (`make -C backend test`) cover the job runtime with an in-memory stor
|
||||
|
||||
## Product metrics tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the product metrics (TASK-022). In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself.
|
||||
Unit tests (`make -C backend test`) cover the product metrics. In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself.
|
||||
|
||||
`TestDeliveryStatistics` in `backend/integration_test/delivery_statistics_test.go` checks the sqlc query `GetDeliveryStatistics` on PostgreSQL: an empty table, then deliveries of three kinds in all five statuses, set within the table constraints, give exact counts per kind and status, and the earliest due time comes only from deliveries that are still pending.
|
||||
|
||||
|
||||
+66
-66
@@ -54,7 +54,7 @@ SeaweedFS работает отдельным сервером в основно
|
||||
|
||||
### HTTP-периметр и адрес клиента
|
||||
|
||||
Реализовано (TASK-042). Frontend Nginx - единственная публичная HTTP-точка входа. Он отдает SPA, проксирует `/api/v1/` в Go и ограниченный `/telemetry`; любой другой путь, включая `/metrics`, `/readyz` и административные пути других сервисов, отклоняется с 404. Там же заданы заголовки безопасности, строгий CSP только для того же origin, лимит тела по умолчанию 1 МБ с ответом 413 в формате problem из контракта и грубые `limit_req`/`limit_conn` на клиента (429 с `Retry-After`); значения намного выше обычного использования и не заменяют доменные квоты, которые остаются в backend. Подробности и проверки - в [DEPLOY.md](DEPLOY.md#публичный-периметр-и-адрес-клиента).
|
||||
Реализовано. Frontend Nginx - единственная публичная HTTP-точка входа. Он отдает SPA, проксирует `/api/v1/` в Go и ограниченный `/telemetry`; любой другой путь, включая `/metrics`, `/readyz` и административные пути других сервисов, отклоняется с 404. Там же заданы заголовки безопасности, строгий CSP только для того же origin, лимит тела по умолчанию 1 МБ с ответом 413 в формате problem из контракта и грубые `limit_req`/`limit_conn` на клиента (429 с `Retry-After`); значения намного выше обычного использования и не заменяют доменные квоты, которые остаются в backend. Подробности и проверки - в [DEPLOY.md](DEPLOY.md#публичный-периметр-и-адрес-клиента).
|
||||
|
||||
Адрес клиента определяется только через доверенные прокси. Edge заменяет `X-Forwarded-For`; app Nginx доверяет адресу туннеля edge и передает backend одну найденную запись; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) доверяет `X-Forwarded-For` только от `TRUSTED_PROXY_CIDRS` (по умолчанию только закрепленный адрес frontend контейнера) и читает его справа, поэтому запись, которую клиент поставил слева от первого недоверенного узла, не учитывается. Сценарии и обработчики, которым нужен адрес для лимитера, читают его через `middleware.ClientAddr(ctx)` и строят ключ лимитера через `middleware.LimiterKey` (IPv6 сводится к /64). Адрес не логируется и не хранится дольше окна лимитера; в журнале запросов и метриках для него нет поля. Первый потребитель - лимиты регистрации и повторной отправки (см. раздел о регистрации); роутер подключает `ClientIP`.
|
||||
|
||||
@@ -64,7 +64,7 @@ SeaweedFS работает отдельным сервером в основно
|
||||
|
||||
- Ключ имеет вид `<namespace>/<32 hex-символа>` из 128 случайных бит. Из кода приходит только проверенный namespace политики; имена файлов и другой ввод клиента никогда не попадают в ключ. `Open` и `Delete` принимают только ключи namespace и формата своей политики, поэтому ключ, сформированный клиентом, путь с обходом каталогов или ключ другого сценария отклоняется до обращения к хранилищу.
|
||||
- Запись требует точный размер. Заявленный размер больше лимита политики отклоняется до запроса. Поток проходит через ограничитель на основе `io.LimitReader`, который придерживает последний фрагмент, пока источник не закончился, поэтому более длинный или более короткий источник прерывает запрос раньше, чем хранилище получит полное тело. Любая ошибка после начала записи удаляет ключ, в том числе после отмены контекста вызывающим. Источники неизвестной длины не буферизуются; сценарию, которому они нужны, придется сохранять их в ограниченный временный файл или добавить multipart upload. Источнику нужен собственный дедлайн, например `http.ResponseController.SetReadDeadline` для тела запроса: `Put` ждет заблокированное чтение, и отмена контекста его не прерывает.
|
||||
- `Put` возвращает `Record`: ключ, media type без параметров, размер, SHA-256, посчитанный во время потока, и очищенное исходное имя файла. Слой не ведет индекс и не добавляет таблиц. Вызывающий соблюдает один порядок: `Put`, затем сохранение записи вместе с данными о владельце в транзакции БД, затем `Delete` ключа, если транзакция не удалась. Остается одна гонка: если тело целиком ушло до отмены вызывающим, сервер может зафиксировать объект уже после завершения очищающего `Delete`. У таких сирот нет записи, и ни один запрос до них не доходит; sweeper по namespace, который удаляет ключи без записи, запланирован вместе с резервным копированием и выгрузками (TASK-030, TASK-458) и пока не существует. Исходное имя - только метаданные для отображения: оно не сохраняется в SeaweedFS и не используется в ключах и логах, но может содержать персональные данные. Очистка удаляет элементы пути, управляющие символы, символы форматирования, разделители строк и абзацев и символы частного использования и не нормализует Unicode. Content type заявляет вызывающий; определение типа по содержимому относится к разбору документов.
|
||||
- `Put` возвращает `Record`: ключ, media type без параметров, размер, SHA-256, посчитанный во время потока, и очищенное исходное имя файла. Слой не ведет индекс и не добавляет таблиц. Вызывающий соблюдает один порядок: `Put`, затем сохранение записи вместе с данными о владельце в транзакции БД, затем `Delete` ключа, если транзакция не удалась. Остается одна гонка: если тело целиком ушло до отмены вызывающим, сервер может зафиксировать объект уже после завершения очищающего `Delete`. У таких сирот нет записи, и ни один запрос до них не доходит; sweeper по namespace, который удаляет ключи без записи, запланирован вместе с резервным копированием и выгрузками и пока не существует. Исходное имя - только метаданные для отображения: оно не сохраняется в SeaweedFS и не используется в ключах и логах, но может содержать персональные данные. Очистка удаляет элементы пути, управляющие символы, символы форматирования, разделители строк и абзацев и символы частного использования и не нормализует Unicode. Content type заявляет вызывающий; определение типа по содержимому относится к разбору документов.
|
||||
- `Open` проверяет, что сохраненный объект по-прежнему соответствует политике, и закрывает ответ при каждом отказе. Возвращенный `File` закрывает вызывающий; чтение завершается ошибкой, если тело отличается от сохраненного размера. `SEAWEEDFS_TIMEOUT` адаптера ограничивает установку соединения, TLS handshake и ожидание заголовков ответа, но не передачу тела в `Put` и `Get`, поэтому длинный или медленный поток ограничивает только контекст вызывающего. `Delete` идемпотентен, отсутствие объекта отображается в `files.ErrNotFound`.
|
||||
- Публичных URL нет. Слой не создает публичных, постоянных или presigned URL, у bucket нет публичной политики и анонимного ACL. Скачивание в браузере должно идти через аутентифицированный endpoint backend, который проверяет текущие права и передает `File` потоком с `Content-Disposition: attachment` и `X-Content-Type-Options: nosniff`, чтобы сохраненный файл никогда не отображался как страница origin приложения. Ключ, bucket и URL хранилища не попадают к клиентам.
|
||||
|
||||
@@ -99,7 +99,7 @@ Relay, который публикует эти строки, описан в р
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Реализовано (TASK-009): цикл relay в `backend/internal/worker/outboxrelay/`, порты `outbound.OutboxRelayStore` и `outbound.EventPublisher` (`backend/internal/port/outbound/outbox_relay.go`), хранилище PostgreSQL (`adapter/secondary/postgres/outbox_relay.go`) и producer на franz-go (`adapter/secondary/kafka/`). Bootstrap запускает relay вместе с HTTP-серверами в том же процессе и останавливает его при завершении. У relay свой пул PostgreSQL не больше чем на два соединения: одно для транзакции захвата и одно для чтения размера очереди, поэтому он не забирает соединения у обработки запросов. Relay не запускается при `RELAY_ENABLED=false` или без `DATABASE_URL`; тогда события остаются в outbox. Настройки перечислены в [DEPLOY.md](DEPLOY.md#relay-outbox).
|
||||
Реализовано: цикл relay в `backend/internal/worker/outboxrelay/`, порты `outbound.OutboxRelayStore` и `outbound.EventPublisher` (`backend/internal/port/outbound/outbox_relay.go`), хранилище PostgreSQL (`adapter/secondary/postgres/outbox_relay.go`) и producer на franz-go (`adapter/secondary/kafka/`). Bootstrap запускает relay вместе с HTTP-серверами в том же процессе и останавливает его при завершении. У relay свой пул PostgreSQL не больше чем на два соединения: одно для транзакции захвата и одно для чтения размера очереди, поэтому он не забирает соединения у обработки запросов. Relay не запускается при `RELAY_ENABLED=false` или без `DATABASE_URL`; тогда события остаются в outbox. Настройки перечислены в [DEPLOY.md](DEPLOY.md#relay-outbox).
|
||||
|
||||
Один проход - одна транзакция READ COMMITTED:
|
||||
|
||||
@@ -134,7 +134,7 @@ Producer требует подтверждения от всех in-sync реп
|
||||
|
||||
### Обработчики событий
|
||||
|
||||
Реализовано (TASK-010): runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик (TASK-015): `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `<CONSUMER_GROUP_PREFIX>.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий).
|
||||
Реализовано: runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `<CONSUMER_GROUP_PREFIX>.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий).
|
||||
|
||||
Обработчик реализует три метода:
|
||||
|
||||
@@ -174,7 +174,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Реализовано (TASK-035): устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение (TASK-205). Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
|
||||
Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
|
||||
|
||||
Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `<id>:<version>`.
|
||||
|
||||
@@ -196,7 +196,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Почтовый транспорт
|
||||
|
||||
Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Единственный вызывающий - worker отправки служебной почты identity (TASK-016, см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
|
||||
Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Единственный вызывающий - worker отправки служебной почты identity (см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до реализации отправки продуктовых уведомлений. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
|
||||
|
||||
`Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из:
|
||||
|
||||
@@ -206,7 +206,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Отказ `quota_exhausted` еще и называет исчерпанное окно в `QuotaPeriod` (`day` или `month`), если провайдер это сообщил; иначе поле пустое. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить.
|
||||
|
||||
Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера.
|
||||
Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера.
|
||||
|
||||
Транспорт Resend использует `net/http` без SDK. Один `Send` - это один `POST https://api.resend.com/emails` с полями `from` (`EMAIL_FROM`), `to` (один получатель), `subject`, `text` и `html` (пустая или пробельная часть не передается), ключом в `Authorization: Bearer`, заголовком `User-Agent` и `Idempotency-Key`, равным ключу письма. Resend хранит ключ 24 часа и на тот же ключ с тем же телом возвращает исходный результат без повторной отправки, поэтому повтор обязан передать сохраненное тело под тем же ключом; измененное тело под старым ключом - это конфликт, а не повод создать новый ключ. `EMAIL_TIMEOUT` ограничивает всю попытку. Клиент не следует редиректам, использует HTTP/1.1 и открывает новое соединение для каждой отправки: keep-alive соединение, которое сервер закрыл по простою, сломалось бы уже после передачи запроса и превратило бы письмо, которого Resend не видел, в ложный `unknown`. У запроса также нет `GetBody`, потому что `net/http` считает POST с `Idempotency-Key` повторяемым после обрыва переиспользованного соединения. В адаптере нет цикла повторов, и он ничего не логирует. Ответ читается не больше 64 KiB; разбираются только идентификатор письма и `name` ошибки, а сообщение провайдера и тело ответа не сохраняются.
|
||||
|
||||
@@ -230,11 +230,11 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| Сбой до записи запроса: DNS, соединение, TLS или таймаут попытки | `rejected`, `temporary`: полный запрос до Resend не дошел |
|
||||
| Контекст вызывающего завершился до записи запроса | ошибка контекста; ничего не отправлено |
|
||||
|
||||
Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit и предел числа попыток относятся к политике повторов (TASK-017), worker отправки применяет только минимальное расписание из раздела [Отправка служебной почты](#отправка-служебной-почты), а остановка по окончании 24-часового окна ключа - его правило для попытки, чей worker потерян; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты).
|
||||
Каждый ответ `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 и предел числа попыток относятся к политике повторов, worker отправки применяет только минимальное расписание из раздела [Отправка служебной почты](#отправка-служебной-почты), а остановка по окончании 24-часового окна ключа - его правило для попытки, чей worker потерян; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты).
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Реализовано (TASK-016): worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода (TASK-017) и отправка продуктовых уведомлений с проверкой разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет.
|
||||
Реализовано: агрегат `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`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода и отправка продуктовых уведомлений с проверкой разрешений перед отправкой. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет.
|
||||
|
||||
Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит:
|
||||
|
||||
@@ -254,7 +254,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Почему событие несет только ссылку. События хранятся в `outbox_events` и в Kafka в пределах retention топика, а правило доменных событий разрешает только идентификаторы и минимальные факты. FR19 также требует, чтобы очередь не сохраняла доступ к отозванным данным. Поэтому текст лежит в `mail_requests`, которые удаление аккаунта убирает каскадно, и только пока он нужен: обработчик удаляет строку в той же транзакции, где сохраняет сформированную доставку. После этого текст есть только в доставке, с ее правилами хранения и доступа. Адрес обработчик читает из аккаунта в своей транзакции, поэтому это адрес, актуальный на момент создания.
|
||||
|
||||
Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer` (TASK-016): он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи.
|
||||
Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer`: он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи.
|
||||
|
||||
Неизменяемое содержимое. Доставка хранит отрендеренное тело и никогда не рендерит его заново. Для рендеринга во время отправки нужен исходный токен, который существует только в памяти в момент выпуска, а повтор под тем же ключом идемпотентности должен повторить ровно то же тело: Resend считает измененное тело под старым ключом конфликтом. Domain пересчитывает hash содержимого при каждом чтении и при несовпадении возвращает `domain.ErrMailContentIntegrity`. Trigger `deliveries_refuse_content_change` отклоняет UPDATE, меняющий получателя, содержимое, ключ идемпотентности, исходное событие или время создания (SQLSTATE 23000, ограничение `deliveries_content_immutable`, адаптер переводит его в `outbound.ErrDeliveryContentImmutable`). Поэтому новая версия шаблона применяется только к новым доставкам, а для отправки сохраненной доставки старые файлы шаблона не нужны.
|
||||
|
||||
@@ -263,7 +263,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
- Запросы для эксплуатации выбирают столбцы метаданных (ID, вид, статус, попытки, время, провайдер) и никогда не выбирают тела, текст запроса и адрес; см. [DEPLOY.md](DEPLOY.md#доставки-писем).
|
||||
- Удаление аккаунта каскадно удаляет его запросы писем, доставки и их попытки. Очистка неподтвержденных аккаунтов блокирует их через `FOR UPDATE SKIP LOCKED`, как токены и сессии, поэтому никогда не ждет обработчик доставки или worker, который держит строку.
|
||||
- Тела письма с токеном очищаются, когда доставка достигает `accepted`, `rejected` или `cancelled` (`body_redacted_at`, см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому дамп или резервная копия базы не содержат токена завершенного письма; правило хранения, которое удаляет остальные завершенные доставки через ограниченный срок, еще не реализовано, и пока его нет, эти строки остаются. Шифрование тел в хранилище тоже не реализовано.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки (TASK-022) несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы.
|
||||
|
||||
Статусы. Значения следуют исходам `MailSender`:
|
||||
|
||||
@@ -279,25 +279,25 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
Переходы:
|
||||
|
||||
- `Delivery.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted`, `rejected` и `cancelled` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`.
|
||||
- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная квота TASK-018 откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`.
|
||||
- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная почтовая квота откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`.
|
||||
- `Delivery.Cancel(at, reason)` завершает доставку из `pending` или `waiting_quota` в `cancelled` без попытки; причина - одна из `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Переход отклоняет `unknown`, как `WaitForQuota`: прошлая попытка могла быть принята, поэтому письмо никогда не объявляется неотправленным. Сохраняет его `DeliveryRepository.Cancel`.
|
||||
- `Delivery.Rebind(at, account)` переносит доставку без единой попытки на другой аккаунт провайдера; см. ниже. Сохраняет его `DeliveryRepository.Rebind`.
|
||||
|
||||
Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода (TASK-017), и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`.
|
||||
Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода, и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`.
|
||||
|
||||
Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки.
|
||||
|
||||
Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `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`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача.
|
||||
Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). Worker служебной почты использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача.
|
||||
|
||||
Миграция `00012_add_delivery_sending.sql` (TASK-016) аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению (TASK-462).
|
||||
Миграция `00012_add_delivery_sending.sql` аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению.
|
||||
|
||||
Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки (TASK-016) вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока открыта TASK-462, в квоту считается только служебная почта identity.
|
||||
Реализовано: окна и лимиты квот в `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`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока отправка продуктовых уведомлений не реализована, в квоту считается только служебная почта 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, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна.
|
||||
|
||||
@@ -311,9 +311,9 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
Резервирование. `QuotaGate.PrepareSend(ctx, unit, delivery)` выполняется в транзакции вызывающего:
|
||||
|
||||
1. Доставка, закрепленная за другим аккаунтом провайдера, чем настроенный, завершается ошибкой `notification.ErrQuotaNotConfigured`: лимиты для нее неизвестны, а аккаунт без квоты никогда не считается "безлимитным". Доставка в `accepted` или `rejected` завершается ошибкой `domain.ErrDeliveryTransition`.
|
||||
2. Повтор внутри окна идемпотентности провайдера повторно использует открытое резервирование той же доставки (прошлая попытка закончилась `unknown` или ее процесс остановился до расчета) и проходит без нового учета: на повтор с тем же ключом провайдер отвечает исходным результатом, а не отправляет письмо второй раз. Окно - параметр шлюза: `resend.IdempotencyWindow`, 24 часа по документации API Resend, или ноль для SMTP, у которого нет дедупликации на стороне провайдера, поэтому каждый повтор через SMTP считается заново. После окна повтор считается заново; допустим ли он вообще, решает политика повторов (TASK-017).
|
||||
2. Повтор внутри окна идемпотентности провайдера повторно использует открытое резервирование той же доставки (прошлая попытка закончилась `unknown` или ее процесс остановился до расчета) и проходит без нового учета: на повтор с тем же ключом провайдер отвечает исходным результатом, а не отправляет письмо второй раз. Окно - параметр шлюза: `resend.IdempotencyWindow`, 24 часа по документации API Resend, или ноль для SMTP, у которого нет дедупликации на стороне провайдера, поэтому каждый повтор через SMTP считается заново. После окна повтор считается заново; допустим ли он вообще, решает политика повторов.
|
||||
3. Иначе репозиторий блокирует строки суток и месяца, добавляет одного получателя в обе, только если он укладывается в оба лимита, и записывает резервирование в журнал. Если не укладывается, ничего не меняется, а результат сообщает, какой лимит был бы превышен. Резервирование выполняется по обоим окнам целиком или не выполняется вовсе.
|
||||
4. Если отправка допущена, решение содержит разрешение, а доставка не меняется. Иначе доставка ждет сброса заполненного окна: ближайших 00:00 UTC для суток и первого числа следующего месяца для месяца; если заполнены оба, побеждает сброс месяца. Доставка в `pending` или `waiting_quota` сохраняется в `waiting_quota` с `next_attempt_at` на этот момент через `Delivery.WaitForQuota`. Временем изменения берется более позднее из показаний часов и последнего изменения доставки, а сброс не раньше него, поэтому экземпляр, чьи часы отстают на несколько миллисекунд от того, кто последним записал доставку, все равно может ее отложить. Доставка в `unknown` возвращается без изменений вместе с моментом сброса: ее повтор решает политика повторов (TASK-017), а перевод в ожидание скрыл бы, что прошлая попытка могла быть принята.
|
||||
4. Если отправка допущена, решение содержит разрешение, а доставка не меняется. Иначе доставка ждет сброса заполненного окна: ближайших 00:00 UTC для суток и первого числа следующего месяца для месяца; если заполнены оба, побеждает сброс месяца. Доставка в `pending` или `waiting_quota` сохраняется в `waiting_quota` с `next_attempt_at` на этот момент через `Delivery.WaitForQuota`. Временем изменения берется более позднее из показаний часов и последнего изменения доставки, а сброс не раньше него, поэтому экземпляр, чьи часы отстают на несколько миллисекунд от того, кто последним записал доставку, все равно может ее отложить. Доставка в `unknown` возвращается без изменений вместе с моментом сброса: ее повтор решает политика повторов, а перевод в ожидание скрыл бы, что прошлая попытка могла быть принята.
|
||||
|
||||
Блокировки строк держатся до конца транзакции вызывающего, поэтому worker обязан зафиксировать транзакцию до вызова транспорта; цена - отправки одного аккаунта резервируются по очереди.
|
||||
|
||||
@@ -338,11 +338,11 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| `rejected` | Ваше письмо не удалось отправить |
|
||||
| `cancelled` | Ваше письмо не отправлено, потому что ссылка в нем больше не действует; запросите новое |
|
||||
|
||||
Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот (TASK-022) читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts).
|
||||
Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts).
|
||||
|
||||
### Отправка служебной почты
|
||||
|
||||
Реализовано (TASK-016): usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений (TASK-462), политика повторов и неизвестного исхода (TASK-017) и сценарии identity, которые вызывают `ServiceMailer`.
|
||||
Реализовано: usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений, политика повторов и неизвестного исхода и сценарии identity, которые вызывают `ServiceMailer`.
|
||||
|
||||
Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было. Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие.
|
||||
|
||||
@@ -385,7 +385,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| `rejected` `permanent` или `invalid_request` | `rejected` | нет | возвращается |
|
||||
| `rejected` `temporary` или `rate_limited` | `pending` | сейчас плюс `RetryPolicy`: 1 минута, удвоение до 30 минут, не меньше `Retry-After` провайдера | возвращается |
|
||||
| `rejected` `quota_exhausted` | `waiting_quota` | сброс, который вернул шлюз (ближайшие 00:00 UTC для суток, первое число следующего месяца для месяца); нет, если провайдер не назвал окно | окно отмечено заполненным |
|
||||
| `unknown` | `unknown` | нет: автоматического повтора нет (TASK-017) | считается |
|
||||
| `unknown` | `unknown` | нет: автоматического повтора нет | считается |
|
||||
| Ошибка `Send`: нет транспорта (`ErrMailChannelUnavailable`) или context завершился | без изменений, lease освобожден | остается срок | возвращается |
|
||||
| Ошибка `Send`: неверное сообщение (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | нет | возвращается |
|
||||
| Ошибка `Send`: любая другая без ответа | не считается против строки; она отодвигается по `RetryPolicy`, а worker делает паузу | сейчас плюс `RetryPolicy` | возвращается |
|
||||
@@ -408,11 +408,11 @@ Worker потерян после вызова. Если worker останови
|
||||
|
||||
Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint.
|
||||
|
||||
Открытые вопросы. У `unknown` нет автоматического повтора и эскалации до TASK-017. Отправка уведомлений и нужная ей проверка разрешений относятся к TASK-462; до нее они ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
|
||||
Открытые вопросы. Автоматический повтор и эскалация для `unknown` пока не реализованы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
|
||||
|
||||
### Версии продуктовой политики
|
||||
|
||||
Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач.
|
||||
Реализованы хранение, публикация и начальное заполнение при старте: миграция `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/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач.
|
||||
|
||||
Колонки `policy_versions`:
|
||||
|
||||
@@ -426,9 +426,9 @@ Worker потерян после вызова. Если worker останови
|
||||
|
||||
Неизменяемость обеспечивает база данных. Функция триггера `policy_versions_refuse_change` отклоняет каждый UPDATE и DELETE (строчный триггер) и TRUNCATE (триггер на оператор) с SQLSTATE 23000 и именем ограничения `policy_versions_immutable`; адаптер сопоставляет с `outbound.ErrPolicyVersionImmutable` именно эту пару, а не текст сообщения. В порту нет методов изменения и удаления, поэтому изменение - всегда новая версия. Гарантия покрывает запросы приложения и ручной SQL; роль-владелец таблицы все еще может отключить триггер или удалить таблицу, поэтому runtime-роль с минимальными правами остается будущей работой.
|
||||
|
||||
Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для TASK-087); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот.
|
||||
Типизированная политика `domain.ProductPolicy`: каждое значение - именованное поле, тип которого несет единицу измерения: `CalendarDays`, `BusinessDays` (без перевода в длительность; производственный календарь задает использующая функция), `Hours` и `BasisPoints` для вероятностей и стандартной ошибки - целое число долей 0.0001 (0.80 - это 8000). Базисные пункты сравниваются точно, без погрешности чисел с плавающей точкой, и оставляют в документе целые числа. Метод `Validate` каждого раздела отклоняет нулевые, отсутствующие и выходящие за диапазон значения и несогласованные сочетания, например срок по умолчанию вне списка вариантов, более высокий уровень квоты с меньшим лимитом, неактивный E0, активный уровень над неактивным или вероятности остановки, которые не охватывают порог подтверждения. Диапазоны - защита от ошибок в единицах, а не продуктовые решения. Уровни квот E0 < E1 < E2 доступны через `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (для применения квот организации); каждая организация начинает с E0, а правила перехода между уровнями относятся к функции квот.
|
||||
|
||||
Открытый вопрос для задач попыток (TASK-157 и TASK-158): `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено.
|
||||
Открытый вопрос для задач попыток: `MaxAttemptsPerWindow` хранит только число. Считается ли лимит по грейду, по специальности или по всем оцениваниям кандидата, не решено.
|
||||
|
||||
У документа `schema_version` 1 и разделы `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`; имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_bp`). Разбор строгий: отклоняются неизвестные поля, отсутствующие поля и null, неверные типы, дробные числа, значения вне int32, неизвестная версия схемы, данные после объекта и документы больше 64 KiB. Каноническая форма - компактная кодировка Go в порядке объявления полей. jsonb нормализует порядок ключей, поэтому `domain.RestorePolicyVersion` разбирает сохраненный документ, проверяет его, кодирует заново и сравнивает SHA-256 с `document_sha256`; при расхождении возвращается `domain.ErrPolicyDocumentIntegrity`. Golden-тест фиксирует каноническую форму, потому что ее изменение сломало бы проверку всех сохраненных версий; новой структуре нужны новая версия схемы и свой декодер.
|
||||
|
||||
@@ -591,7 +591,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Банк заданий оценки
|
||||
|
||||
Реализованы хранилище и загрузчик (TASK-154), а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap и HTTP API его пока не вызывают, и ни одна категория не открыта.
|
||||
Реализованы хранилище и загрузчик, а не функция для кандидата: миграция `backend/db/migrations/00011_create_assessment_bank.sql`, запросы в `backend/db/queries/assessment_bank.sql`, доменные типы в `backend/internal/domain/` (`assessment_family.go`, `assessment_generator.go`, `assessment_algorithms.go`), порт `outbound.AssessmentBankRepository` (`port/outbound/assessment_bank.go`, доступен через `UnitOfWork.AssessmentBank()`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/assessment_bank.go` и загрузчик в `backend/internal/usecase/assessment/` (`Bank`, `Bundle`). Bootstrap и HTTP API его пока не вызывают, и ни одна категория не открыта.
|
||||
|
||||
- Версия семейства. Одна строка `assessment_families` - одна версия одного семейства (`family_key`, `version`): категория, специализация (область внутри категории), название, автор (`ai:<name>` или `operator:<handle>`), рецензент (`operator:<handle>` или NULL), `review_status` (`pending`, `approved`, `rejected`), генератор по seed, ключ ответа, рубрика, хеш содержимого с его `hash_scheme`, жизненный цикл (`draft`, `published`, `retired`) и операторы и время публикации и вывода из обращения. Рецензент не бывает автором, а рецензия остается `pending`, пока рецензента нет (CHECK-ограничения; домен применяет те же правила). Рецензент в пакете и оператор публикации - заявленные значения, а не аутентифицированные личности, пока нет учетных записей рецензентов и операторов.
|
||||
- Неизменяемость. Содержимое сохраненной версии не меняется: триггер `assessment_families_guard_update` отклоняет любой UPDATE, который меняет колонки кроме колонок жизненного цикла (`lifecycle`, `published_at`, `published_by`, `retired_at`, `retired_by`), а `assessment_families_refuse_removal` отклоняет DELETE и TRUNCATE, все с SQLSTATE 23000 и именем ограничения `assessment_families_immutable`, которое адаптер преобразует в `outbound.ErrAssessmentFamilyImmutable`. Жизненный цикл идет только вперед (draft, published, retired), время ставит триггер и он же сохраняет публикатора при выводе из обращения, а версия публикуется только с одобренной рецензией рецензента (`assessment_families_published_requires_review`). Изменение - это новая версия со следующим номером: загрузчик принимает версию 1 для нового семейства и преемника последней версии для существующего. Черновик с рецензией `pending` никогда не одобряется на месте: рецензия записывается импортом новой версии семейства, которая ее несет, а версия `pending` остается неопубликованным черновиком. Домен пересчитывает хеш содержимого при чтении строки и возвращает `ErrAssessmentFamilyIntegrity`, если строку изменили вне приложения. Хеш - это SHA-256 канонического JSON-документа, который содержит содержимое без имени пакета, ID, жизненного цикла и полей публикации. Колонка `hash_scheme` (smallint с CHECK известных значений, одна из неизменяемых колонок) называет формат: домен проверяет строку хеш-функцией той схемы, с которой строка сохранена, поэтому следующая схема (новая функция и новое значение CHECK, а не правка схемы 1) проверяет новые строки и не ломает старые, а строка с неизвестной схемой отклоняется; тесты проверяют строку ее собственной схемой и фиксируют хеш схемы 1 для заданного входа. Как и для `policy_versions`, роль-владелец таблицы все еще может отключить триггеры.
|
||||
@@ -646,7 +646,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Хранение identity
|
||||
|
||||
Реализовано только хранение (TASK-051): миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы (TASK-053 - TASK-056); ни один usecase или обработчик это хранение пока не использует.
|
||||
Реализовано только хранение: миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы; ни один usecase или обработчик это хранение пока не использует.
|
||||
|
||||
- `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр.
|
||||
- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. CHECK допускает не больше одного из consumed и invalidated.
|
||||
@@ -659,13 +659,13 @@ contact_grant относится к паре кандидат-компания
|
||||
- База хранит хеши, а не пароли и исходные токены. Токен несет 256 бит из crypto/rand, поэтому SHA-256 без соли нельзя обратить перебором, а поиск остается одним обращением к индексу; для паролей нужен медленный KDF Argon2id. `bytea` вдвое компактнее hex-текста, допускает точную проверку длины и не имеет вариантов регистра. `domain.SecretToken`, `domain.PasswordHash` и `domain.EmailAddress` скрывают значение в выводе `fmt` (для любого verb) и `slog`, поэтому при печати `domain.User` не видны ни адрес, ни хеш; настоящие значения возвращают явные методы доступа. Неотображенные ошибки PostgreSQL из репозиториев identity сохраняют только SQLSTATE и имя ограничения, потому что текст и detail ошибки могут содержать значения строки.
|
||||
- Колонки с перечислимыми значениями - text с CHECK, а не enum-типы PostgreSQL. Новый сценарий, шаг или назначение заменяет одно ограничение в обратимой миграции; значение enum нельзя удалить и нельзя использовать в транзакции, которая его добавила.
|
||||
- Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время.
|
||||
- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. TASK-056 может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией.
|
||||
- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. Аутентификация сессий может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией.
|
||||
|
||||
Что гарантируют порты:
|
||||
|
||||
- `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код, и удаляет регистрационное C1 прежнего регистранта (см. [Журнал согласий](#журнал-согласий)). `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`.
|
||||
- `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением.
|
||||
- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения (TASK-054) переводит этот исход в `verification_token_invalid`.
|
||||
- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения переводит этот исход в `verification_token_invalid`.
|
||||
- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`.
|
||||
- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем, доставки писем и записи согласий через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма, доставки или согласия заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно; записи согласий, которые запрещают удаление аккаунта, удаляются явно в том же запросе.
|
||||
- `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение.
|
||||
@@ -674,20 +674,20 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Хеширование паролей
|
||||
|
||||
Реализовано (TASK-052) и покрыто тестами: регистрация (TASK-053) создает hasher из конфигурации и вызывает его; вход (TASK-055) будет делать то же.
|
||||
Реализовано и покрыто тестами: регистрация создает hasher из конфигурации и вызывает его; вход будет делать то же.
|
||||
|
||||
- `domain.Password` хранит пароль, нормализованный в Unicode NFKC. `domain.NewPassword` применяет политику регистрации: от 15 до 128 кодовых точек после нормализации; `domain.ParseLoginPassword` принимает от 1 до 128. До нормализации оба отклоняют исходный ввод длиннее 512 байт (128 кодовых точек по 4 байта UTF-8 максимум, поэтому любое значение, принятое схемой контракта, помещается) и некорректный UTF-8. Эти проверки выполняются до любого хеширования и завершаются `domain.ErrInvalidPassword` с названием правила, но без значения. Blocklist распространенных и утекших паролей - отдельная запланированная проверка.
|
||||
- Порт `outbound.PasswordHasher` (`port/outbound/password.go`) содержит `Hash`, `Verify` и `VerifyDummy`; адаптер `adapter/secondary/argon2id` реализует его через `golang.org/x/crypto/argon2`. Новые хеши используют Argon2id v19 с m=65536 KiB, t=3, p=4 (второй рекомендованный вариант RFC 9106, выше базового уровня OWASP 19 MiB, t=2, p=1), соль 16 байт из crypto/rand и ключ 32 байта в формате `$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>` в base64 без дополнения - этот формат принимают `domain.NewPasswordHash` и CHECK `users_password_hash_format`. Один хеш занял примерно 26-33 ms на машине разработчика Apple M5 (`BenchmarkHashRecommendedParameters`, в том числе на одном CPU); это не измерение задержки в production.
|
||||
- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; ограничение частоты запросов появится вместе с HTTP-операциями.
|
||||
- `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих, и вход может сохранить новый хеш.
|
||||
- `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход будет вызывать его для неизвестного email, поэтому обе ветки одинаково разбирают хеш, ждут память, вычисляют и сравнивают.
|
||||
- Вход (TASK-055) должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует.
|
||||
- Вход должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует.
|
||||
- `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация будет вызывать его в каждой ветке до поиска email.
|
||||
- Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес.
|
||||
|
||||
### Журнал согласий
|
||||
|
||||
Реализованы хранение, порты и контракт чтения (TASK-062): миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии реализована как usecase `consent.Service` (TASK-063, см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик (TASK-064), C1 в транзакции регистрации (TASK-053) и C4 при принятии приглашения (TASK-201) запланированы; ни один продуктовый поток пока не вызывает usecase.
|
||||
Реализованы хранение, порты и контракт чтения: миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии реализована как usecase `consent.Service` (см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик, C1 в транзакции регистрации и C4 при принятии приглашения запланированы; ни один продуктовый поток пока не вызывает usecase.
|
||||
|
||||
Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую.
|
||||
|
||||
@@ -698,12 +698,12 @@ contact_grant относится к паре кандидат-компания
|
||||
Решения:
|
||||
|
||||
- Привязка к тексту. Внешний ключ на (`purpose`, `text_version`) отклоняет версию, которая для цели не публиковалась, а триггер BEFORE INSERT отклоняет версию, опубликованную позже времени выдачи (`consent_records_text_published`). Для C1-C3 и C5 второй внешний ключ через генерируемую колонку требует, чтобы `text_hash` совпадал с хэшем опубликованного текста. Для C4 тот же триггер требует, чтобы `text_hash` был SHA-256 опубликованного текста с подставленным `organization_name` (`consent_records_c4_text_hash`). Домен сам считает этот хэш в `domain.NewContactConsentGrant` из опубликованного `ConsentText` и названия, поэтому вызывающий код не передает байты хэша, а клиент не может придумать ни версию, ни хэш. Сохраненное название - снимок, который доказывает показанный текст; последующее переименование организации его не меняет, и модель чтения возвращает его как `ConsentOrganization.name`.
|
||||
- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` (TASK-063) проверяет, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается.
|
||||
- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к TASK-064 и не реализованы.
|
||||
- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 из TASK-064 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией.
|
||||
- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)).
|
||||
- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории TASK-088 (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта.
|
||||
- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения (TASK-201) вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`.
|
||||
- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` проверяет, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается.
|
||||
- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к отзыву согласий и не реализованы.
|
||||
- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией.
|
||||
- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для регистрации: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)).
|
||||
- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории видимости кандидата (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта.
|
||||
- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`.
|
||||
- Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие.
|
||||
- Ограничение субъектом. Каждое чтение и отзыв принимают субъекта, а операция контракта берет его из сессии, поэтому модель чтения возвращает только собственные записи вызывающего. Ошибки адаптера сохраняют только SQLSTATE и имя ограничения, а `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant` и `ConsentRevocation` не показывают в выводе `fmt` и `slog` субъекта, организацию, название или поля.
|
||||
|
||||
@@ -717,31 +717,31 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Usecase согласий
|
||||
|
||||
Реализовано (TASK-063): `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче.
|
||||
Реализовано: `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче.
|
||||
|
||||
- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация (TASK-053) создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста.
|
||||
- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста.
|
||||
- Порядок при повторной регистрации. Для неподтвержденного аккаунта, который регистрируется снова, вызывайте `GrantAtRegistration` строго после `UserRepository.UpdateRegistration` в той же транзакции. `UpdateRegistration` удаляет регистрационное C1 прежнего регистранта, а выдача, выполненная до него, нашла бы эту запись, вернула ее с `Created` false и после удаления оставила бы аккаунт без C1. Интеграционный тест показывает оба порядка.
|
||||
- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация (TASK-053) обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют.
|
||||
- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют.
|
||||
- Только актуальный текст. Выдача читает `ConsentTexts().Current` на время приложения и отклоняет любую другую версию ошибкой `*StaleConsentTextError`, которая совпадает с `ErrStaleConsentText` и содержит цель, запрошенную и актуальную версии, поэтому обработчик может сопоставить ее одному коду problem и показать новый текст. Устаревшая версия, версия, которая запланирована, но еще не опубликована, и версия, которой никогда не было, считаются устаревшими. Журнал принимает любую опубликованную версию, поэтому именно эта проверка не пускает выдачу устаревшего текста. Проверка и вставка не блокируются от публикации между ними: тексты публикуют миграции, а выдача, назвавшая актуальный текст на момент проверки, допустима.
|
||||
- Серверное время. Во входе нет поля времени. Выдача берет одно чтение внедренных часов для проверки и для времени записи; клиент не выбирает время. База по-прежнему отклоняет версию, опубликованную после этого времени.
|
||||
- Идемпотентность. Повтор того же субъекта, цели и актуальной версии возвращает существующую неотозванную запись с `Created` false, сохраняет ее первое время, ничего не записывает и не прерывает внешнюю транзакцию. Выдача после отзыва - новая запись. Повтор с более старой версией после публикации нового текста - не повтор, а устаревшая версия: субъект должен увидеть новый текст, а в журнале остается одна запись.
|
||||
- C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения (TASK-201): вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова.
|
||||
- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки TASK-315, отзыв TASK-064), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным.
|
||||
- Отзыва здесь нет. `Revoke` остается на порте журнала, а TASK-064 вызывает его вместе с последующими эффектами и событиями outbox в одной транзакции.
|
||||
- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков (TASK-064, TASK-053, TASK-201).
|
||||
- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или TASK-064, и ни той, ни другой пока нет.
|
||||
- C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения: вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова.
|
||||
- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки, отзыв согласия), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным.
|
||||
- Отзыва здесь нет. `Revoke` остается на порте журнала, а отзыв согласий должен вызывать его вместе с последующими эффектами и событиями outbox в одной транзакции.
|
||||
- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков.
|
||||
- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или отзыв согласий, и ни той, ни другой пока нет.
|
||||
|
||||
### Регистрация и повторная отправка подтверждения
|
||||
|
||||
Реализовано (TASK-053): `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/identity.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`.
|
||||
Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/identity.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`.
|
||||
|
||||
Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт.
|
||||
|
||||
Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает. Требования для передачи следующим задачам:
|
||||
|
||||
- TASK-054 (`ConfirmEmail`): подтверждение токена применяет отложенные данные нажатого токена, и только их, к строке аккаунта в транзакции подтверждения (хеш пароля, сценарий, шаг онбординга) и обязано требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными, проверяя его по отложенному хешу токена. Тогда жертва, перешедшая по ссылке злоумышленника, не может принять его пароль, а злоумышленник не может подтвердить токен жертвы. Поля пароля в `EmailVerificationRequest` сегодня нет; его добавление - изменение контракта в TASK-054, здесь не делается. Описание `RegisterAccount` в контракте по-прежнему говорит, что повторная регистрация заменяет хеш пароля аккаунта; TASK-054 исправляет его вместе с этим изменением.
|
||||
- TASK-054 дополнительно: тесты обоих порядков (злоумышленник регистрируется первым, жертва вторым, и наоборот), показывающие, что владелец никогда не получает пароль, который не выбирал; требовать, чтобы запись C1 существовала и относилась к версии регистрации подтверждаемого токена; отклонять токен без отложенных данных, без устаревшего пути в обход пароля; обнулять столбцы `pending_*` токена при его расходовании.
|
||||
- TASK-055 (вход): неподтвержденный аккаунт никогда не входит. Вход отвечает как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не сравнивает пароль со строкой неподтвержденного аккаунта или с отложенными данными.
|
||||
- Подтверждение почты (`ConfirmEmail`): подтверждение токена применяет отложенные данные нажатого токена, и только их, к строке аккаунта в транзакции подтверждения (хеш пароля, сценарий, шаг онбординга) и обязано требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными, проверяя его по отложенному хешу токена. Тогда жертва, перешедшая по ссылке злоумышленника, не может принять его пароль, а злоумышленник не может подтвердить токен жертвы. Поля пароля в `EmailVerificationRequest` сегодня нет; его добавление - изменение контракта подтверждения почты, здесь не делается. Описание `RegisterAccount` в контракте по-прежнему говорит, что повторная регистрация заменяет хеш пароля аккаунта; при реализации подтверждения почты нужно исправить его вместе с этим изменением.
|
||||
- Для подтверждения почты также нужны: тесты обоих порядков (злоумышленник регистрируется первым, жертва вторым, и наоборот), показывающие, что владелец никогда не получает пароль, который не выбирал; требовать, чтобы запись C1 существовала и относилась к версии регистрации подтверждаемого токена; отклонять токен без отложенных данных, без устаревшего пути в обход пароля; обнулять столбцы `pending_*` токена при его расходовании.
|
||||
- Вход: неподтвержденный аккаунт никогда не входит. Вход отвечает как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не сравнивает пароль со строкой неподтвержденного аккаунта или с отложенными данными.
|
||||
|
||||
Порядок проверок регистрации: валидация всего тела и версии текста C1, проверка воспроизведения, лимит, хеш пароля (в каждой ветке, до чтения аккаунта), транзакция. Ошибка валидации (400) не зависит от хранимых аккаунтов и не расходует лимит.
|
||||
|
||||
@@ -759,7 +759,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Организации и членства
|
||||
|
||||
Реализовано как хранение, порты и исходный контракт (TASK-077): миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками (TASK-078) и серверные проверки контекста и членства для каждой tenant-операции (TASK-079) запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения.
|
||||
Реализовано как хранение, порты и исходный контракт: миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками и серверные проверки контекста и членства для каждой tenant-операции запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения.
|
||||
|
||||
Таблицы:
|
||||
|
||||
@@ -769,13 +769,13 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
Решения:
|
||||
|
||||
- Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Решение следует TASK-079 (контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение) и TASK-085 (переключение очищает клиентские запросы с областью организации).
|
||||
- Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает (TASK-081, TASK-082). В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают (TASK-083, TASK-463).
|
||||
- Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; TASK-086 добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (ступень читает TASK-087 и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет).
|
||||
- У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками (TASK-084), а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации.
|
||||
- Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками TASK-084, которое меняет членство и организацию вместе, и tenant-репозиторий TASK-079 обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться.
|
||||
- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала TASK-062 и TASK-063 создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений (TASK-198), вместе с ключами потребностей (TASK-179). Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD).
|
||||
- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` (TASK-078) держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять по окончании окна повтора; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (TASK-078 и TASK-087 нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации).
|
||||
- Активный контекст. Это не атрибут серверной сессии. Организация - это `org_id` в пути, а сервер выводит право из активного членства на каждом запросе, поэтому удаление, приостановка или выход закрывают следующее чтение без чего-либо, что нужно сбрасывать. `ListMyOrganizations` - справочник, из которого клиент выбирает; запоминание последнего выбора - удобство браузера. Контекст берется только из активных членств вызывающего, а прекращенное членство сразу закрывает чтение. Переключение очищает клиентские запросы с областью организации.
|
||||
- Роль и состояние только в членстве. `OrganizationRole` - `owner`, `recruiter`, `hiring_manager` или `technical_expert` (2.2, Q3 и матрица FR07 в PRD), а `MembershipState` - `active`, `suspended`, `removed` или `left`; каждое задано CHECK, а не enum PostgreSQL, поэтому новое значение - изменение ограничения в миграции. Состояния `invited` нет: в 6.4 PRD `MemberInvite` - отдельная сущность, приглашение на email, у которого еще может не быть аккаунта, а строка членства появляется, когда владелец адреса его принимает. В `organizations` нет столбца роли, владельца или участника (интеграционный тест читает каталог, чтобы это доказать), а в `Organization`, `OrganizationCreate` и `OrganizationUpdate` нет такого поля. Компанией управляет только владелец (`OrganizationRole.CanManageOrganization`); остальная матрица применяется операциями, которыми она управляет, а в MVP остальные роли ничего не дают.
|
||||
- Уровень проверки. `verification_level` - от `e0` до `e3` с `verification_basis` (`confirmed_email`, `corporate_domain`, `requisites_and_authority`, `manual_review`, `partner_status`), а один CHECK связывает каждый уровень с его основаниями. Столбцы отделены от профиля: `UpdateOrganizationProfile` никогда их не называет, `domain.NewOrganization` не может выбрать уровень и начинает каждую организацию с `e0` на основании `confirmed_email`, `Organization.ApplyProfile` сохраняет проверку, а в контракте нет операции или поля запроса, которые ее задают. Тест обновляет профиль после того, как процесс сдвинул уровень, и проверяет, что он остается. E1-E3 задаются процессами проверки, которых еще нет; запланированный процесс проверки добавляет E0/E1 с доказательствами, областью действия и историей только на добавление и будет обновлять эти столбцы вместе со строкой истории, а сначала обязан записать историю из текущей строки каждой существующей организации (уровень, основание и время как сохранены), чтобы в истории не было разрыва до первого процесса. `OrganizationVerificationLevel.QuotaTier` сопоставляет `e0`-`e2` ступеням квот продуктовой политики и не имеет ступени для `e3`, которому PRD отводит отдельную политику (механизм квот читает ступень и обязан отказывать по умолчанию для организации с `e3`: квота не выдается, действие отклоняется, возврата на другую ступень нет).
|
||||
- У организации есть владелец. Отложенный constraint trigger (`organizations_owner_required`, SQLSTATE 23514) при фиксации отказывает организации без членства `owner` в состоянии `active`, поэтому создание организации без владельца падает, каким бы кодом ее ни вставили, а `CreateWithOwner` сохраняет организацию, представителей и владельца в одной транзакции. Удаление или понижение последнего владельца позже - правило управления участниками, а не этого ограничения, которое иначе блокировало бы решение платформы о недобросовестной организации.
|
||||
- Обновление. `UpdateProfile` - один оператор, который применяется только когда сохраненная версия равна версии, прочитанной вызывающим, и увеличивает ее на единицу. Тот же оператор требует активного членства исполнителя с управляющей ролью (роли берутся из `domain.ManagerRoles`, а не из SQL), поэтому членство, закончившееся после чтения вызывающего, все равно останавливает запись. Если оператор ничего не нашел, адаптер читает членство и отвечает `ErrOrganizationNotFound` (неизвестная организация или нет активного членства), `ErrOrganizationManagerRequired` или `ErrOrganizationVersionConflict` в этом порядке, поэтому устаревшая версия ничего не сообщает постороннему. Затем список представителей заменяется в той же транзакции под блокировкой строки обновления. Оператор блокирует строку организации (`FOR UPDATE`), а затем строку членства исполнителя `FOR SHARE`, поэтому отзыв, зафиксированный, пока оператор ждет блокировку членства, проверяется заново и останавливает запись (интеграционный тест держит отзыв открытым, ставит обновление за ним в очередь и фиксирует отзыв). Порядок блокировок у каждого писателя: сначала организации, затем членства; управление участниками, которое меняет членство и организацию вместе, и tenant-репозиторий обязаны брать блокировки в этом порядке, иначе две транзакции могут взаимно заблокироваться.
|
||||
- Внешние ключи и удаление. `memberships` ограничивает удаление организации и аккаунта, поэтому аккаунт с членствами нельзя удалить, пока процедура их не завершит, так же как журнал согласий ограничивает аккаунт. Приложение никогда не удаляет организацию. Журнал согласий пока не ссылается на `organizations`: `consent_records.organization_id` остается обычным столбцом со снимком названия рядом. Ключ сейчас заставил бы тесты журнала согласий создавать настоящие организации, а та же миграция должна добавить ключ `invitation_id`, которому нужна таблица приглашений; оба появятся с миграцией, создающей записи приглашений, вместе с ключами потребностей. Все они `ON DELETE RESTRICT`, поэтому организацию с историей согласий, потребностями или приглашениями нельзя удалить, что и является задуманной защитой доказательств согласия (7.3 в PRD).
|
||||
- Приватность. Контакты - публичные каналы компании; контракт и домен не принимают личных контактов сотрудника, а за содержимое отвечает владелец. Имена представителей - персональные данные сотрудников: `OrganizationRepresentative` прячет поля за указателем и скрывает себя в выводе `fmt` и `slog`, `Organization` логирует только идентификатор, версию и уровень, а ошибки адаптера хранят SQLSTATE и имя ограничения без строки с ошибкой. Сайт только хранится: сервер никогда не обращается по его адресу, а будущая функция, которая это делает, обязана сама разрешить адрес и отказать приватным диапазонам. `StoredRepresentative`, `OrganizationRepresentativeInput`, `OrganizationProfileInput` и сгенерированные sqlc-структуры параметров этого репозитория содержат имена и никогда не логируются. Хранилище идемпотентности `CreateOrganization` держит сохраненный ответ 201 24 часа, а в нем имена представителей: хранилище обязано не пускать его в логи и метрики, защищать как остальные персональные данные и удалять по окончании окна повтора; отпечаток запроса должен быть хешем, а не телом. Карточку кандидата видит только кандидат, получивший приглашение от организации, и ее `representatives` может отсутствовать. Открытые вопросы (публикация имен представителей, таксономия сферы) и блокирующий вопрос о лимите организаций на аккаунт, который PRD не задает и без которого аккаунт умножает квоты созданием организаций (для создания организаций и применения квот нужно решение владельца, а подготовленный механизм - 409 `state_conflict` при создании), в [api/README.md](../../api/README.md#организации).
|
||||
|
||||
Что гарантируют порты (`outbound.OrganizationRepositories`, доступны только через `UnitOfWork`, потому что запись требует транзакции):
|
||||
|
||||
@@ -785,7 +785,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Профиль кандидата
|
||||
|
||||
Реализовано как хранение, домен и исходный контракт (TASK-066): миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом.
|
||||
Реализовано как хранение, домен и исходный контракт: миграция `backend/db/migrations/00013_create_candidate_profiles.sql`, запросы в `backend/db/queries/candidate.sql`, доменные типы в `backend/internal/domain/candidate.go`, схемы в `api/core/components/schemas/candidate_schemas.yml` и операции `GetMyProfile` и `SaveMyProfile` в `api/core/routes/candidate_profile.yml`. Порта, адаптера и обработчиков пока нет: операции отвечают 401 `unauthenticated`, пока сессий нет, и 501 `not_implemented` после валидации. Порт и адаптер придут с обработчиками и должны войти в `UnitOfWork`; запросы и доменное преобразование строк (`StoredClaims`, `RestoreCandidateProfile`) уже готовы и проверены интеграционным тестом.
|
||||
|
||||
Таблицы:
|
||||
|
||||
@@ -804,7 +804,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Видимость кандидата
|
||||
|
||||
Реализовано как хранилище, домен и исходный контракт (TASK-088): миграция `backend/db/migrations/00015_create_candidate_privacy.sql` (номер 00014 занят записями идемпотентности задачи регистрации), запросы в `backend/db/queries/privacy.sql`, доменные типы в `backend/internal/domain/visibility.go`, схемы в `api/core/components/schemas/privacy_schemas.yml` и девять операций тега `privacy` в `api/core/routes/candidate_privacy*.yml` под `/api/v1/me/privacy` ([api/README.md](../../api/README.md#видимость-кандидата)). Порта, адаптера и обработчика еще нет: пока нет сессий, операции отвечают 401 `unauthenticated`, а после валидации - 501 `not_implemented`. Порт и адаптер появятся вместе с обработчиками и должны войти в `UnitOfWork`; запросы и доменное восстановление строк (`RestorePublication`, `RestoreSearchStatus`) готовы и покрыты интеграционным тестом.
|
||||
Реализовано как хранилище, домен и исходный контракт: миграция `backend/db/migrations/00015_create_candidate_privacy.sql` (номер 00014 занят записями идемпотентности задачи регистрации), запросы в `backend/db/queries/privacy.sql`, доменные типы в `backend/internal/domain/visibility.go`, схемы в `api/core/components/schemas/privacy_schemas.yml` и девять операций тега `privacy` в `api/core/routes/candidate_privacy*.yml` под `/api/v1/me/privacy` ([api/README.md](../../api/README.md#видимость-кандидата)). Порта, адаптера и обработчика еще нет: пока нет сессий, операции отвечают 401 `unauthenticated`, а после валидации - 501 `not_implemented`. Порт и адаптер появятся вместе с обработчиками и должны войти в `UnitOfWork`; запросы и доменное восстановление строк (`RestorePublication`, `RestoreSearchStatus`) готовы и покрыты интеграционным тестом.
|
||||
|
||||
Четыре независимых состояния, у каждого своя таблица и своя версия. Ни один оператор одной таблицы не пишет другую, а согласие C2 не копируется и не заменяется:
|
||||
|
||||
@@ -825,20 +825,20 @@ contact_grant относится к паре кандидат-компания
|
||||
- История вместо области полей. Запись C2 доказывает согласие с текстом публикации, а `candidate_privacy_events` хранит то, о чем просила заметка журнала согласий: набор опубликованных полей и его изменения с временами и записью C2 за каждым. Отзыв C2 и истечение статуса вычисляются и не являются событиями. Нужна ли C2 собственная область полей как согласию по статье 10.1 152-ФЗ - по-прежнему юридический вопрос (см. журнал согласий).
|
||||
- Приватность. Таблицы хранят идентификаторы, коды полей карточки и времена; значений профиля, имен, контактов и файлов нет (тест перечисляет столбцы). `Publication`, `SearchStatus`, `HiddenOrganization` и `PrivacyEvent` пишут в журналы только идентификаторы, версии и виды. Ни один запрос не выбирает строку чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер должен сообщать только SQLSTATE и имя ограничения, как остальные.
|
||||
|
||||
- Один структурный барьер для чтений со стороны организации. Представление `candidate_effective_publications` - опубликовано И держится на неотозванной записи C2. Каждое чтение от имени организации (поиск, карточка, чтение контактов: TASK-185, TASK-089, TASK-090) обязано выбирать из этого представления и добавлять `NOT EXISTS` по `candidate_hidden_organizations` для читающей организации, как это делает `ReadPublicationVisibleToOrganization`; отсутствие строки значит "читать нечего" по любой причине, поэтому организация не отличает скрывшего кандидата от неопубликованного. Прямое чтение `candidate_publications` оставлено только запросам настроек самого кандидата, а `backend/db/privacy_queries_test.go` падает, когда другой запрос в `db/queries` называет таблицу.
|
||||
- Закрытие поверх отозванной C2. Закрытие поверх сохраненной строки `published`, чья C2 отозвана, - настоящее изменение: строка нормализуется в `closed`, пишется `publication_closed`, а контактные разрешения отзываются с `visibility_closed`, как при любом закрытии. Повтором закрытия считается только сохраненное состояние `closed`. Путь отзыва C2 (TASK-064) сам обязан закрыть сохраненную публикацию и отозвать контактные разрешения аккаунта в своей транзакции; вычисляемое состояние закрывает карточку сразу, но разрешения не отзывает.
|
||||
- Один структурный барьер для чтений со стороны организации. Представление `candidate_effective_publications` - опубликовано И держится на неотозванной записи C2. Каждое чтение от имени организации (поиск, карточка, чтение контактов) обязано выбирать из этого представления и добавлять `NOT EXISTS` по `candidate_hidden_organizations` для читающей организации, как это делает `ReadPublicationVisibleToOrganization`; отсутствие строки значит "читать нечего" по любой причине, поэтому организация не отличает скрывшего кандидата от неопубликованного. Прямое чтение `candidate_publications` оставлено только запросам настроек самого кандидата, а `backend/db/privacy_queries_test.go` падает, когда другой запрос в `db/queries` называет таблицу.
|
||||
- Закрытие поверх отозванной C2. Закрытие поверх сохраненной строки `published`, чья C2 отозвана, - настоящее изменение: строка нормализуется в `closed`, пишется `publication_closed`, а контактные разрешения отзываются с `visibility_closed`, как при любом закрытии. Повтором закрытия считается только сохраненное состояние `closed`. Путь отзыва C2 сам обязан закрыть сохраненную публикацию и отозвать контактные разрешения аккаунта в своей транзакции; вычисляемое состояние закрывает карточку сразу, но разрешения не отзывает.
|
||||
- Гонка публикации и отзыва. Транзакция публикации берет текущую C2 через `LockCurrentC2Record` (`SELECT ... FOR SHARE`), пишет публикацию под этой блокировкой и затем перечитывает действующее состояние `ReadCandidatePublication` в той же транзакции, чтобы построить ответ. Отметка отзыва - UPDATE той же строки, поэтому он либо фиксируется раньше (блокировка не вернет строку, публикация отклонена с 409), либо ждет фиксации публикации и закрывает карточку сразу после; интеграционный тест удерживает блокировку и доказывает оба порядка.
|
||||
- Подтвержденный email. Публикация, скрытие и история существуют только у аккаунтов с подтвержденным email (требование юзкейса). Очистка неподтвержденных аккаунтов (`DeleteUnverifiedUsersRegisteredBefore`) удаляет их записи согласий явно и столкнулась бы с ограничивающей ссылкой публикации на запись C2, поэтому отсутствие публикации у неподтвержденного аккаунта - требование юзкейса, а не физическая невозможность: очистка работает и для неподтвержденного аккаунта, у которого есть C2, публикация и история, и для C2, отозванной и выданной снова (это проверяет интеграционный сценарий, и он зависит от порядка применения изменяющих операторов очистки). Записи скрытия и история удаляются каскадом.
|
||||
- Два вида 409 `state_conflict` различаются через `errors[]`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Предел скрытий обеспечивает триггер под блокировкой строки аккаунта; когда вставка падает с SQLSTATE 23514 и `candidate_hidden_organizations_limit`, адаптер обязан перечитать пару перед ответом 409, потому что параллельный PUT той же пары при 999 записях мог ее создать, а идемпотентный ответ - 200; интеграционный тест запускает восемь параллельных вставок при 999 записях и ожидает ровно один успех.
|
||||
- Новое поле карточки - это изменение контракта и миграция. Коды перечислены в функции `candidate_card_fields_are_canonical` и в CHECK таблиц публикации и событий, а также в enum `CardField`, `domain.CardField` и построителе карточки.
|
||||
|
||||
Содержимое карточки (жесткие требования к TASK-089, который ее строит):
|
||||
Содержимое карточки (жесткие требования к ее построителю):
|
||||
|
||||
- В карточку попадают только значения, которые кандидат подтвердил; неподтвержденное предложение (статус `extracted`) и неизвестное значение не попадают никогда, что бы ни говорил набор полей.
|
||||
- Свободный текст (тег стека, софт-скилл, место), похожий на контакт (адрес email, номер телефона, URL или домен, ссылка Telegram, @handle), отбрасывается и не публикуется. Проверка, которую построитель обязан применять к каждому свободному тексту, - `domain.CardTextLooksLikeContact`; она ошибается в сторону отбрасывания.
|
||||
- Квазиидентификаторы (редкое сочетание места, стека и опыта) и обобщение редких признаков - критерий приемки TASK-089, здесь не решаются (см. открытый вопрос в README API).
|
||||
- Квазиидентификаторы (редкое сочетание места, стека и опыта) и обобщение редких признаков - критерий приемки построителя карточки, здесь не решаются (см. открытый вопрос в README API).
|
||||
|
||||
Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации (TASK-185) нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами.
|
||||
Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами.
|
||||
|
||||
## Frontend
|
||||
|
||||
@@ -875,7 +875,7 @@ k3s не входит в критический путь. Его можно ра
|
||||
|
||||
## Метрики, телеметрия и alerts
|
||||
|
||||
Go экспортирует стандартные Go/process метрики и продуктовые метрики TASK-022 на внутреннем listener `/metrics`, вне `/api/v1`:
|
||||
Go экспортирует стандартные Go/process метрики и продуктовые метрики на внутреннем listener `/metrics`, вне `/api/v1`:
|
||||
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются.
|
||||
- Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
|
||||
+6
-6
@@ -235,7 +235,7 @@ Worker захватит его в течение одного интервала
|
||||
|
||||
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
|
||||
|
||||
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462, так что боевой стенд сегодня не отправляет ни одного письма.
|
||||
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации отправки продуктовых уведомлений, так что боевой стенд сегодня не отправляет ни одного письма.
|
||||
|
||||
`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#почтовый-транспорт).
|
||||
|
||||
@@ -260,18 +260,18 @@ Compose передает эти переменные из корневого `.e
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока TASK-462 не подключит продуктовые уведомления. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
|
||||
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока не реализована отправка продуктовых уведомлений. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
|
||||
|
||||
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `Rebind` (разрешено только до первой попытки) и отправляет, если ее токен и аккаунт все еще проходят проверку. Не переносите вручную.
|
||||
- Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован.
|
||||
- Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты.
|
||||
- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до TASK-462; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до TASK-462, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером.
|
||||
- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до реализации отправки продуктовых уведомлений; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до реализации отправки продуктовых уведомлений, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером.
|
||||
- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` ждет сброса квоты в `next_attempt_at`; см. [Квоты почты](#квоты-почты). Без `next_attempt_at` момент сброса неизвестен, и нужно решение оператора.
|
||||
- Логи называют доставку только по `delivery_id` (вместе с ID события), никогда по адресу или теме. Пропущенные запросы пишутся на уровне info: `mail request skipped because it was already handled or its account was deleted` и `notification skipped because the recipient address is not verified`. Запрос, нарушающий контракт события, становится dead letter класса `handler_rejected` обработчика `notification_delivery`; см. [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск). Повторять его безопасно: ID доставки сохраняет одну доставку на запрос.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до TASK-462. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
|
||||
Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до реализации отправки продуктовых уведомлений. Модель описана в [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` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце.
|
||||
@@ -280,7 +280,7 @@ Compose передает эти переменные из корневого `.e
|
||||
- Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано.
|
||||
- Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит.
|
||||
- `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом.
|
||||
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017).
|
||||
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов.
|
||||
- Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита.
|
||||
|
||||
### Отправка служебной почты
|
||||
@@ -291,7 +291,7 @@ Compose передает эти переменные из корневого `.e
|
||||
- При `EMAIL_PROVIDER=disabled` цикл не запускается, а в журнале пишется `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` равен 0, ничего не отправляется, а сохраненная служебная почта ждет следующего запуска с транспортом. Worker никогда не крутится вхолостую: после прохода, который ничего не смог отправить, он делает паузу.
|
||||
- Перед отправкой worker проверяет токен и аккаунт. Доставка, которую нельзя отправлять, завершается как `cancelled` с `cancel_reason`, без попытки и без расхода квоты: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Причины, вызванные пользователем, нормальны: пользователь запросил новую ссылку, подтвердил адрес, зарегистрировался заново или слишком долго ждал. Причины можно посмотреть так: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. Пользователь видит отмененное письмо как "не отправлено, запросите новое".
|
||||
- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Отказ "пока" (`temporary`, `rate_limited`) оставляет доставку в `pending` с более поздним `next_attempt_at`, а повтор использует тот же ключ и тело; он повторяется, пока не удастся, пока не будет отказа навсегда или пока токен не истечет и доставка не будет отменена. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты).
|
||||
- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов (TASK-017).
|
||||
- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов.
|
||||
- Захваченная доставка держит lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. Строка с давно прошедшим `claimed_until` значит, что ее worker умер; другой экземпляр подхватит ее сам. Не сбрасывайте lease вручную.
|
||||
- `content_invalid` и `processing_failed` - не действия пользователя: первое значит, что сохраненная строка не совпадает со своим хешем содержимого (ручная правка) или содержит сообщение, которое не принимает ни один транспорт, второе - что worker трижды подряд потерпел сбой на строке (повторы разнесены расписанием). Alert `LincodexMailCancelledBroken` срабатывает при росте; прочитайте журнал worker по `delivery_id` и осмотрите метаданные строки. Строка, которая сбоит постоянно, не блокирует остальные: она повторяется позже (`failure_count`, `next_attempt_at`), а затем отменяется.
|
||||
- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Не копируйте тела ожидающих писем никуда.
|
||||
|
||||
@@ -50,7 +50,7 @@ Frontend зависимости выбираются из актуальных s
|
||||
|
||||
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
|
||||
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен.
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления (TASK-462). С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления. С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
|
||||
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers.
|
||||
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
|
||||
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий).
|
||||
@@ -88,7 +88,7 @@ make check не является бизнес-E2E проверкой. make verif
|
||||
|
||||
Запланированная cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production.
|
||||
|
||||
Запланированное правило Origin (TASK-056): любой небезопасный запрос (POST, PUT, PATCH, DELETE), включая публичные, например вход, должен нести `Origin` из allowlist в конфигурации backend, например origin Nginx и origin dev-сервера Vite. Сервер не сравнивает `Origin` с `Host`. Небезопасный запрос без `Origin` или с другим значением получает 403 `csrf_check_failed`.
|
||||
Запланированное правило Origin: любой небезопасный запрос (POST, PUT, PATCH, DELETE), включая публичные, например вход, должен нести `Origin` из allowlist в конфигурации backend, например origin Nginx и origin dev-сервера Vite. Сервер не сравнивает `Origin` с `Host`. Небезопасный запрос без `Origin` или с другим значением получает 403 `csrf_check_failed`.
|
||||
|
||||
## Структура
|
||||
|
||||
|
||||
+2
-2
@@ -199,7 +199,7 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
|
||||
- Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`.
|
||||
- База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход.
|
||||
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend` (TASK-016), покрыт тестами отправки служебной почты ниже.
|
||||
`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, покрыт тестами отправки служебной почты ниже.
|
||||
|
||||
## Тесты отправки служебной почты
|
||||
|
||||
@@ -264,7 +264,7 @@ Unit-тесты (`make -C backend test`) проверяют runtime задани
|
||||
|
||||
## Тесты продуктовых метрик
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают продуктовые метрики (TASK-022). В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов.
|
||||
Unit-тесты (`make -C backend test`) покрывают продуктовые метрики. В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов.
|
||||
|
||||
`TestDeliveryStatistics` в `backend/integration_test/delivery_statistics_test.go` проверяет запрос sqlc `GetDeliveryStatistics` на PostgreSQL: пустая таблица, затем доставки трех видов во всех пяти статусах, выставленных в рамках ограничений таблицы, дают точные числа по виду и статусу, а самый ранний срок берется только из доставок, которые еще в `pending`.
|
||||
|
||||
|
||||
Reference in new issue
Block a user