feat(mail): add Resend API transport
This commit is contained in:
1 parent
1aa7a9feaf
commit
c85b642d32
13 files changed
+1387
-63
No files matched your search
+33
-6
@@ -79,15 +79,41 @@ Planned relay contract (TASK-009): the relay selects unpublished rows (`publishe
|
||||
|
||||
### Mail transport
|
||||
|
||||
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), 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: the Resend transport (`mail/resend/`, the primary provider for the working stand, TASK-013) and an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP). Until they exist, `resend` and `smtp` fail startup after their settings are validated. Settings are described in [DEPLOY.md](DEPLOY.md#mail).
|
||||
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet; the delivery layer is planned. 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:
|
||||
|
||||
- `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading.
|
||||
- `rejected`: the provider answered and refused; `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`, with an optional `RetryAfter`.
|
||||
- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`). It is not a failure; a retry reuses the idempotency key.
|
||||
- `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`.
|
||||
- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator.
|
||||
|
||||
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. 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.
|
||||
`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
| Resend answer | Result |
|
||||
| --- | --- |
|
||||
| 2xx with an `id` of up to 128 letters, digits, `-`, or `_` | `accepted` with `ProviderMessageID` |
|
||||
| 2xx without a valid `id`, truncated, or over 64 KiB | `unknown`: the request may have been accepted |
|
||||
| 3xx, not followed | `rejected`, `invalid_request`: the API documents no redirect, and a repeat gets the same one |
|
||||
| 403 `validation_error` (unverified sender domain: without one Resend sends only testing emails to the account's own address) | `rejected`, `permanent` |
|
||||
| Other 4xx: 400, 422, key and permission errors (401, 403), 404, 405 | `rejected`, `invalid_request` |
|
||||
| 408; 409 `resource_locked` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` |
|
||||
| 409 `concurrent_idempotent_requests` | `unknown`: another request with the same key is in progress and may be accepted; retry later with the same key |
|
||||
| 409 `invalid_idempotent_request` | `unknown`: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates |
|
||||
| 409 without a known name | `unknown` |
|
||||
| 429 `rate_limit_exceeded` or unnamed | `rejected`, `rate_limited`, `RetryAfter` from `Retry-After` (seconds or a future HTTP date), otherwise from `ratelimit-reset` |
|
||||
| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` until the next 00:00 UTC |
|
||||
| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, no `RetryAfter`: the reset follows the billing cycle |
|
||||
| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` |
|
||||
| Other 5xx, including 500 `application_error` and `internal_server_error`, a truncated body, or a proxy or gateway answer | `unknown`: the API may have accepted the message before it failed |
|
||||
| No answer after the request was written: timeout, reset, or closed connection | `unknown` |
|
||||
| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend |
|
||||
| The caller's context ended before the request was written | the context error; nothing was sent |
|
||||
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing, waiting for a quota reset or an operator decision, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer.
|
||||
|
||||
### Product policy versions
|
||||
|
||||
@@ -200,9 +226,9 @@ backend/
|
||||
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
||||
|
||||
Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
Product domain types and usecase modules, the SMTP and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` transport, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
|
||||
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging; the identity usecases (verification and password reset) and the planned delivery usecase are expected to call it, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
|
||||
|
||||
@@ -218,6 +244,7 @@ This is a compact map, not a claim that every planned product package exists. Cu
|
||||
| assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history |
|
||||
| matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items |
|
||||
| invitation | Offer and contact permission | invitations, invitation_events, contact_grants |
|
||||
mail/resend/ mail transport that sends one request to the Resend HTTP API per message
|
||||
| document | Files, resume analysis, standard PDF | files, analysis_results, document_jobs |
|
||||
| achievement | FSP link and achievement provenance | fsp_links, achievements, sync_runs |
|
||||
| vacancy, later | Vacancies and voluntary applications | vacancies, applications |
|
||||
|
||||
Reference in new issue
Block a user