From 32bb542e8ed56d56430e903300b4dd539b8228f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Wed, 25 Nov 2026 23:56:03 +0100 Subject: [PATCH 1/3] Postgres: many requests at once no longer stop the site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each Payload transaction holds a pool connection; code inside it that runs without its req needs a second one (Payload's own forgotPassword, the mail adapter's settings read and status write, payload.kv). With the default pool of 10, ten form submissions or ten "forgot password" requests at once held every connection and waited for good. - connectionReserve (default on): at most pool size − reserve transactions open at once; a waiter older than a second may use all but the last connection. Building blocks in modules/database/transactions.ts. - Form e-mails go out right after the submission's transaction commits, in the same request (forms.emailsInTransaction: true = the old way). - recordIntegrationStatus merges identical writes and does not hold its caller while the pool is busy. - SMTP time-outs: 10 s connect, 30 s greeting, 60 s silence (smtp.timeouts). Tests on Postgres 17: 30 submissions, 30 forgot-password, and both against an SMTP server that never answers, finish while a page answers. Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 25 ++ docs/agent/AGENT.md | 3 + docs/agent/skills/iapl-debug/SKILL.md | 3 + docs/agent/skills/iapl-form/SKILL.md | 6 + docs/agent/skills/iapl-upgrade/SKILL.md | 4 + docs/deployment.md | 39 +++ docs/email.md | 14 +- docs/forms.md | 29 +- docs/integrations.md | 4 +- reference/.agents/skills/iapl-debug/SKILL.md | 3 + reference/.agents/skills/iapl-form/SKILL.md | 6 + .../.agents/skills/iapl-upgrade/SKILL.md | 4 + src/index.ts | 7 +- src/modules/database/transactions.ts | 227 ++++++++++++++ src/modules/email/panelSmtpAdapter.ts | 17 +- src/modules/forms/afterCommit.ts | 48 +++ src/modules/forms/formsPluginConfig.ts | 10 +- src/modules/forms/types.ts | 10 + src/modules/integrations/status.ts | 48 ++- src/plugin.ts | 4 + src/types.ts | 12 + test/formAttachments.test.ts | 5 +- test/transactionPool.test.ts | 291 ++++++++++++++++++ test/transactionPoolInTx.test.ts | 31 ++ test/transactionPoolSite.ts | 89 ++++++ 25 files changed, 916 insertions(+), 23 deletions(-) create mode 100644 src/modules/database/transactions.ts create mode 100644 src/modules/forms/afterCommit.ts create mode 100644 test/transactionPool.test.ts create mode 100644 test/transactionPoolInTx.test.ts create mode 100644 test/transactionPoolSite.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 576b737..89d28ea 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -131,6 +131,31 @@ once there are more than 20. Not a switch for a live site: it would start visitors' histories and the running 2FA counts again. - `EnvRule.aliases` for `assertEnv`: older names of a variable, read when the main one is missing. +### Fixed — Postgres: many requests at once no longer stop the site (draft; release decided by the owner) +- **Ten or more form submissions at the same moment, or ten "forgot password" requests, stopped the whole site on + Postgres** — every request, also pages that only read, waited for good (older than 1.17.0; MongoDB sites were not + affected). Each transaction holds a pool connection, and code inside it that runs without its `req` (Payload's own + "forgot password", the e-mail adapter reading Site integrations and writing the send status, `payload.kv`) needs a + second one; the default pool has 10. Measured on Postgres 17: 12 submissions or 12 resets at once never finished; + now 30 of each, also against an SMTP server that never answers, finish while an ordinary request answers at once. +- **`connectionReserve`** (new plugin option, default on): a fifth of the pool, at least 2, stays free of + transactions; at most `pool size − reserve` transactions are open at once and the next one waits; one that has + waited a second may use all but the last connection. `false` = as before. Building blocks `reserveConnections`, + `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, + `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a). +- **Form e-mails go out after the submission's transaction commits** — same request, same answer to the visitor + (a file that could not be sent is still reported). A submission rolled back by a later hook now sends nothing; a + send that fails after the commit leaves the submission stored (as a failed e-mail always did). Sites without + transactions (MongoDB without a replica set, SQLite) send at once, as before. The old way: + `forms: { emailsInTransaction: true }`. Building blocks `sendAfterCommit`, `sendFormEmails` + ([forms.md](./forms.md) "When e-mails go out"). +- **The panel's send status** (`recordIntegrationStatus`): many sends failing at once write it once; while the pool + is busy the write is not waited for. +- **SMTP time-outs**: 10 s to connect (was nodemailer's 2 min), 30 s for the greeting, 60 s of silence (was 10 min); + `mailAdapter({ smtp: { timeouts } })` / `panelSmtpAdapter({ timeouts })`, `SMTP_TIMEOUT_DEFAULTS`, `SmtpTimeouts`. +- Not fixed here: Payload's own "forgot password" and "verify your e-mail" still send inside their transaction, so a + hanging mail server makes them hold a place until the SMTP time-out (others wait; nothing stops). + ### Deprecated - **Microsoft Graph as an e-mail transport** — `graphAdapter`, `GraphAdapterArgs`, `mailAdapter({ graph })`, `iaplEnvRules({ emailGraph })` and the four `GRAPH_*` variables. Nothing new is built on it; it gets fixes only and diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index a3963d3..505f0dc 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1246,6 +1246,9 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Account e-mails through the mail service: at most 5 to one address and 10 asked for by one visitor an hour | `mail: { relay: { accountMail: false } }` | `accountMail: { perAddress, perVisitor, windowMinutes }` | | Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` | | Microsoft Graph as transport: deprecated, one warning per start, removed in 2.0 | `mail: { graphDeprecationWarning: false }` (the warning only) | move off it: email.md "Moving off Microsoft Graph" | +| Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; one waiting a second may use all but the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: `; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) | +| Form e-mails go out right after the submission's transaction commits (same request, same answer); a rolled-back submission sends nothing; a send that fails after the commit leaves the submission stored. No transactions (MongoDB without a replica set, SQLite): at once, as before | `forms: { emailsInTransaction: true }` | `sendAfterCommit(prepare, deliver)`, `sendFormEmails(req, emails)`, `afterCommit(req, fn)` (forms.md "When e-mails go out") | +| SMTP time-outs: 10 s to connect, 30 s greeting, 60 s silence | — | `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })`, `panelSmtpAdapter({ timeouts })`; `SMTP_TIMEOUT_DEFAULTS`, type `SmtpTimeouts` (email.md "SMTP") | ### 7.2 E-mail — the mail service (default), SMTP (on request), Graph (deprecated) diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index 9933936..43f3a13 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -120,6 +120,9 @@ through this procedure. Ask only when you are missing something you cannot get y | replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) | | the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP | | start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` | +| Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) | +| Postgres: requests are slow while a mail server hangs (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) | +| a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" | | old email sender | mail client cache | check the raw headers | | form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts | | an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy | diff --git a/docs/agent/skills/iapl-form/SKILL.md b/docs/agent/skills/iapl-form/SKILL.md index 7827f0b..23562e3 100644 --- a/docs/agent/skills/iapl-form/SKILL.md +++ b/docs/agent/skills/iapl-form/SKILL.md @@ -120,6 +120,12 @@ Tell the client plainly: **there is no antivirus scan** (the e-mail says so), th files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**. +### E-mails go out after the save (1.17.0) +A form's e-mails are composed inside the submission's transaction and sent right after it commits, in the same +request (`submitForm` answers as before). A submission rolled back by a hook of yours sends nothing. Keep the old way +only on the owner's word: `forms: { emailsInTransaction: true }` (forms.md "When e-mails go out"). Check on Postgres: +a submission arrives; your own `afterChange` hooks on form-submissions pass `req` to every Local API call. + ## 4. Page — block data once (blocks do not import `lib/*`) From `createPageRoute` (PROGRAMISTA §2.8): ```tsx diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index 3beeb56..ff8f799 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -580,6 +580,10 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent". 5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's "forgot password" are marked by the plugin. +6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of + 10; `connectionReserve`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`), + SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the + reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out". **Check:** `pnpm exec iapl-doctor --deep --url ` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` / `mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending → **Send test e-mail** names the transport you expect; a form submission arrives. **The service has to be live for a site diff --git a/docs/deployment.md b/docs/deployment.md index 234b617..7708e27 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -351,6 +351,45 @@ with `NODE_ENV=production` — also during `next build` when the build reaches t schema: add columns/tables first, drop or rename in a later release (`iapl-migrate-fields` skill). Take a **Backup now** (§4.6) before a large migration. +### 4.3a Postgres: the connection pool + +Payload holds one pool connection for the whole of a transaction (a form submission, "forgot password", a save in +the panel). Code inside it that runs **without** the transaction's `req` needs a **second** connection: Payload's own +"forgot password" (it reserves the request interval outside the transaction), an e-mail adapter reading its settings, +`payload.kv`, a project hook that calls the Local API without `req`. With the default pool of 10, **ten such requests +at the same moment held all ten connections and each waited for an eleventh — the whole site stopped, for good** +(measured on 1.16.8 and the 1.17.0 branch: 12 form submissions or 12 "forgot password" requests at once, an ordinary +page got no answer). + +Since 1.17.0 the plugin keeps a few connections free of transactions (`connectionReserve`): + +- at most `pool size − reserve` transactions are open at once; the next one waits for a place — its request is + slower, nothing stops. Default reserve: a fifth of the pool, at least 2 (1 in a pool of fewer than 4): with the + default pool of 10, eight transactions at once and two connections for everything else; +- a transaction that has waited a second (`RESERVE_ESCAPE_MS`) may use the reserve too, all but one connection — so a + transaction begun inside another one (a hook without `req`) does not wait for ever on its caller, and one connection + is never held by a transaction; +- form e-mails go out **after** the submission's transaction commits ([forms.md](./forms.md) "When e-mails go out"), + so a slow mail server holds no connection; Payload's own account mail ("forgot password", "verify your e-mail") is + still sent inside its transaction — with a mail server that hangs, those requests hold a place until the SMTP + time-out ([email.md](./email.md) "SMTP": 10 s to connect, 30 s for the greeting by default). + +```ts +iapl({ connectionReserve: 3 }) // keep three connections free +iapl({ connectionReserve: false }) // no limit, as before 1.17.0 (not recommended) +``` + +MongoDB, SQLite and other adapters without a pool: no effect. A larger pool (`postgresAdapter({ pool: { max: 20 } })`) +moves the reserve with it; the Postgres server's own `max_connections` must allow every instance's pool. +Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnections(payload) }`. +Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction +commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route), +`poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`. + +**Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different +accounts) while loading a page — the page answers at once, every request finishes. `transactionWatchState(payload)` +shows `{ active, waiting, reserve }`. + ### 4.4 Health check and rolling updates Coolify → the application → **Health Checks**: HTTP, path `/api/health`, port 3000, a start period long enough diff --git a/docs/email.md b/docs/email.md index c2cb3ed..4514e3f 100644 --- a/docs/email.md +++ b/docs/email.md @@ -423,6 +423,11 @@ and password switches the site to the client's server. - Missing SMTP config or a send error → the adapter **does not throw**, it returns `{ sent: false, error }` and logs. - Port 465 → implicit TLS, others → STARTTLS. - The adapter reads the config on every send, so changing the mailbox in the panel works without a restart. +- **Time-outs** (since 1.17.0): 10 s to connect, 30 s for the server's greeting, 60 s of silence during the + dialogue (`SMTP_TIMEOUT_DEFAULTS`; nodemailer's own were 2 min and 10 min). A send inside a database transaction — + Payload's "forgot password" — holds a connection that long ([deployment.md](./deployment.md) §4.3a). Change them: + `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })` or `panelSmtpAdapter({ timeouts })` + (type `SmtpTimeouts`). SMTP only, without the dispatcher: @@ -438,7 +443,8 @@ export default buildConfig({ }) ``` -Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`). +Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`), `timeouts` +(`{ connectionMs: 10000, greetingMs: 30000, socketMs: 60000 }`). ## Dependency @@ -685,7 +691,8 @@ Save your changes before the test — the endpoint reads from the database, not ## Send status in the panel `mailAdapter()` stores the send result in Site integrations (at most once per 10 min -while an error persists, immediately when the state changes). When sending fails: +while an error persists, immediately when the state changes; many sends failing at once write it once, and while a +Postgres pool is busy the write goes on in the background — [integrations.md](./integrations.md)). When sending fails: - **Dashboard** — a red alert with the cause and a link to Site integrations, - **Site integrations → E-mail sending** — a banner with the error (e.g. `SMTP: connect ECONNREFUSED …`, `SMTP: Invalid login: 535 …`, `Microsoft Graph: Graph sendMail failed (403).`, or the text of a mail service @@ -724,7 +731,8 @@ SDK); you then skip the panel's SMTP fields, the mail service and the send statu integrations and the endpoint `POST /api/ipal/test-email` are always added. - **Choosing the transport:** `mailAdapter()` (decided per send) or a fixed `relayAdapter()` / `panelSmtpAdapter()` / `graphAdapter()`; any other Payload adapter also works. -- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` and `graph` +- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` (with + `smtp.timeouts`) and `graph` (`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments"); every option of the mail service ("Options"); panel texts through `i18n.translations` (keys `mailRelay…`, `statusEmailRelay…`); the tab's fields through `integrationsFields`. diff --git a/docs/forms.md b/docs/forms.md index 8a615f9..21787af 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -453,7 +453,8 @@ Limits are kept in memory by default, separately for each instance. Several inst `turnstile`, rejected **before** storing. Keys not set → the widget does not show, and the check is skipped. Details: [turnstile.md](./turnstile.md). 3. **Validation** against the form definition from the panel (+ enforced GDPR consent). -4. **Storing** the submission (form-submissions) → the form-builder sends the emails from the Emails tab. +4. **Storing** the submission (form-submissions) → the form-builder composes the emails from the Emails tab; + they go out right after the submission is saved ("When e-mails go out"). **A stored submission = success, even when the email fails** — Payload logs the sending error, the submission data is not lost (it is in Form Submissions). @@ -474,6 +475,29 @@ body (placeholders: `{{field}}`, `{{*}}`, `{{*:table}}`) without touching the co `submitForm` is responsible only for Turnstile verification and storing. It stores the submission in the page's language (`locale` from `createSubmitAction`), so the form-builder takes the email texts and labels in that language. +### When e-mails go out (`emailsInTransaction`) + +By default (since 1.17.0) a form's e-mails go out **right after the submission is saved**: they are composed inside +the submission's database transaction (layout, `forms.beforeEmail`, the kind marks, all with the transaction's +`req`), and handed to the mail server once that transaction has committed and given its connection back — still +within the same request, so `submitForm` answers as before (a file that could not be sent is still reported to the +visitor). What this changes: + +- a slow or hanging mail server holds **no database connection** — on Postgres, many submissions at once used to stop + the site ([deployment.md](./deployment.md) §4.3a); +- a submission whose transaction is **rolled back** (a later hook of yours throws) sends **nothing**; before, its + e-mails had already gone out; +- **a failure after the commit leaves a stored submission without its e-mail** (the mail server refused it, or the + process ended in between) — as an e-mail failure always did: the submission is in Form Submissions, the error in + the log and the panel status, a file marked **File delivery: Not sent**; +- `payload.create` of a submission inside **your own transaction** (`req` passed from a hook or a script): the e-mails + go out when that transaction commits, and not at all when it is rolled back; +- **MongoDB without a replica set, SQLite** (no transactions): sent at once, exactly as before. + +`forms: { emailsInTransaction: true }` sends them inside the transaction, as before 1.17.0 (not recommended on +Postgres). Building blocks: `sendAfterCommit(prepare, deliver)` (the `beforeEmail` that does this), +`sendFormEmails(req, emails)` (form-builder's own send loop), `afterCommit(req, fn)` (deployment.md §4.3a). + ### Nice emails (`emailLayout`) ```ts @@ -848,6 +872,7 @@ filter it out on the client. site-wide consent field name: `forms.consentFieldName`; shared limit store: `setRateLimitStore`; missing IP: `setUnknownIpFactor`. - **Check:** `POST /api/form-submissions` without a session = 403; a `user` account → `PATCH /api/forms/` = 403; submits without an IP header → past `maxPerMinute × 20` per minute (100 by default) you get `rate_limited`. -- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template. +- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template, + `emailsInTransaction: true` sends them inside the submission's transaction ("When e-mails go out"). - **Your own front end:** `BuilderForm` (`renderField`), `useBuilderForm`, pure logic (`splitSteps`, `visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, validators, `buildFormsPlugin` (root). diff --git a/docs/integrations.md b/docs/integrations.md index 88670cb..0d1ff2c 100644 --- a/docs/integrations.md +++ b/docs/integrations.md @@ -34,7 +34,9 @@ The state block above it reads `GET /api/iapl/mail-relay/status` and acts throug - **Write:** `mailAdapter()` on every send (`emailStatus`) and Turnstile verification on a form (`turnstileStatus`) call `recordIntegrationStatus`. It writes only when the state changes, - or at most every 10 min while an error lasts; it never throws. + or at most every 10 min while an error lasts; it never throws. The same change already being written (many sends + failing at once) is written once; while every transaction place of a Postgres pool is taken + ([deployment.md](./deployment.md) §4.3a) the write goes on in the background instead of holding the caller. - **Changing keys in the admin panel** (Turnstile, `emailTransport` / `smtp*`) clears that integration's old status. - **`emailStatus.code`** of a send through the Intecion mail service is one of the `relay-…` codes (`relay-pending`, `relay-quota`, `relay-unreachable`, …), each with a text in the editor's language — the list and what to do: diff --git a/reference/.agents/skills/iapl-debug/SKILL.md b/reference/.agents/skills/iapl-debug/SKILL.md index 9933936..43f3a13 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -120,6 +120,9 @@ through this procedure. Ask only when you are missing something you cannot get y | replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) | | the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP | | start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` | +| Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) | +| Postgres: requests are slow while a mail server hangs (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) | +| a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" | | old email sender | mail client cache | check the raw headers | | form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts | | an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy | diff --git a/reference/.agents/skills/iapl-form/SKILL.md b/reference/.agents/skills/iapl-form/SKILL.md index 7827f0b..23562e3 100644 --- a/reference/.agents/skills/iapl-form/SKILL.md +++ b/reference/.agents/skills/iapl-form/SKILL.md @@ -120,6 +120,12 @@ Tell the client plainly: **there is no antivirus scan** (the e-mail says so), th files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**. +### E-mails go out after the save (1.17.0) +A form's e-mails are composed inside the submission's transaction and sent right after it commits, in the same +request (`submitForm` answers as before). A submission rolled back by a hook of yours sends nothing. Keep the old way +only on the owner's word: `forms: { emailsInTransaction: true }` (forms.md "When e-mails go out"). Check on Postgres: +a submission arrives; your own `afterChange` hooks on form-submissions pass `req` to every Local API call. + ## 4. Page — block data once (blocks do not import `lib/*`) From `createPageRoute` (PROGRAMISTA §2.8): ```tsx diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index 3beeb56..ff8f799 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -580,6 +580,10 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent". 5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's "forgot password" are marked by the plugin. +6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of + 10; `connectionReserve`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`), + SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the + reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out". **Check:** `pnpm exec iapl-doctor --deep --url ` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` / `mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending → **Send test e-mail** names the transport you expect; a form submission arrives. **The service has to be live for a site diff --git a/src/index.ts b/src/index.ts index a2751ae..cea894f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -206,6 +206,8 @@ export { } from './modules/content/index.js' export type { ArchiveEntries } from './modules/content/index.js' export type { SearchResult } from './modules/content/index.js' +// Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool"). +export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js' // Files on panel forms (forms.attachments): checked, e-mailed, never stored. export { mailAttachmentLimit } from './modules/email/attachmentLimit.js' export { graphAdapter } from './modules/email/graphAdapter.js' @@ -215,8 +217,8 @@ export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter // Imported straight from the file, NOT from ./modules/email/index.js — that // barrel re-exports sendEmail, which imports 'server-only' and would crash when // Payload loads the config (or runs generate:importmap) as a plain Node script. -export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js' -export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js' +export { panelSmtpAdapter, SMTP_TIMEOUT_DEFAULTS } from './modules/email/panelSmtpAdapter.js' +export type { PanelSmtpAdapterArgs, SmtpTimeouts } from './modules/email/panelSmtpAdapter.js' // The Intecion Notifications Webservice (docs/email.md): the transport of a site with no SMTP server. // Every piece is exported, so a project can use the transport alone, enrol from a script, mark its own // mail, build its own panel, or test against the fake service. @@ -280,6 +282,7 @@ export type { MailPanelState } from './modules/email/relay/panel.js' // Boot-time environment validation (fail fast on misconfigured deploys). export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules, legacyEnvName, readEnv } from './modules/env/index.js' export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from './modules/env/index.js' +export { sendAfterCommit, sendFormEmails } from './modules/forms/afterCommit.js' export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js' export { buildFormMailKindHook } from './modules/forms/attachments/delivery.js' export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js' diff --git a/src/modules/database/transactions.ts b/src/modules/database/transactions.ts new file mode 100644 index 0000000..16eeac0 --- /dev/null +++ b/src/modules/database/transactions.ts @@ -0,0 +1,227 @@ +import type { BasePayload, PayloadRequest } from 'payload' + +/** + * Transactions and the Postgres pool. + * + * Payload holds one pool connection for the whole of a transaction. Code inside it that reads or writes + * WITHOUT the transaction's `req` needs a second connection: Payload's own "forgot password" (it reserves + * the request interval outside the transaction), an e-mail adapter reading its settings, the key-value + * store, a project's hook that forgot `req`. With the default pool of 10, ten such requests at the same + * moment hold all ten connections and each waits for an eleventh: the whole site stops, for good. + * + * `reserveConnections` keeps a few connections free of transactions: at most `pool size − reserve` + * transactions are open at once, the next one waits for a free place (its request is slower, nothing + * stops). A transaction that has waited a second (ESCAPE_MS) may use the reserve too, all but its last + * connection — so a transaction begun inside another one (a hook that calls the Local API without `req`) + * does not wait for ever on its own caller, and one connection is never held by a transaction. + * + * `afterCommit(req, fn)` runs `fn` right after the transaction of `req` commits, before the operation that + * began it returns — for work that must not hold a connection, such as sending e-mail. + */ + +type TransactionID = number | string +type Entry = { after: (() => Promise | void)[] } +type Waiter = { resolve: () => void; since: number } +type Watch = { + active: number + /** Open transactions begun through this watch, by id. */ + open: Map + queue: Waiter[] + /** Connections kept free; `null` = no limit (not Postgres, or switched off). */ + reserve: null | number + timer?: ReturnType +} +type WatchedDb = { + beginTransaction?: (...args: unknown[]) => Promise + commitTransaction?: (id: Promise | TransactionID) => Promise + pool?: { options?: { max?: number } } + rollbackTransaction?: (id: Promise | TransactionID) => Promise + [WATCH]?: Watch +} + +const WATCH = Symbol.for('iapl.transactionWatch') +/** After this long in the queue a transaction may use the reserve (all but one connection). */ +export const RESERVE_ESCAPE_MS = 1000 + +const dbOf = (payload: BasePayload) => ((payload as { db?: unknown } | undefined)?.db ?? {}) as WatchedDb + +/** The size of the adapter's pool (pg's default is 10), or null for an adapter without one. */ +export function poolSize(payload: BasePayload): null | number { + const pool = dbOf(payload).pool + if (!pool) {return null} + const max = pool.options?.max + return typeof max === 'number' && max > 0 ? max : 10 +} + +/** Connections kept free by default: a fifth of the pool, at least 2 (1 in a pool of fewer than 4). */ +export function defaultConnectionReserve(size: number): number { + return size < 4 ? 1 : Math.max(2, Math.ceil(size / 5)) +} + +function drain(payload: BasePayload, watch: Watch): void { + const size = poolSize(payload) ?? Infinity + const limit = watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve) + const escapeLimit = Math.max(limit, size - 1) + const now = Date.now() + // First come, first served; a waiter that has waited ESCAPE_MS may use the reserve but the last connection. + while (watch.queue.length) { + const waiter = watch.queue[0] + const room = now - waiter.since >= RESERVE_ESCAPE_MS ? escapeLimit : limit + if (watch.active >= room) {break} + watch.queue.shift() + watch.active += 1 + waiter.resolve() + } + if (watch.queue.length && !watch.timer) { + const wait = Math.max(1, watch.queue[0].since + RESERVE_ESCAPE_MS - now) + watch.timer = setTimeout(() => { + watch.timer = undefined + drain(payload, watch) + }, wait) + watch.timer.unref?.() + } +} + +function acquire(payload: BasePayload, watch: Watch): Promise | undefined { + let resolve = () => {} + const done = new Promise((r) => (resolve = r)) + const waiter: Waiter = { resolve: () => resolve(), since: Date.now() } + watch.queue.push(waiter) + drain(payload, watch) + return watch.queue.includes(waiter) ? done : undefined +} + +function release(payload: BasePayload, watch: Watch): void { + watch.active = Math.max(0, watch.active - 1) + drain(payload, watch) +} + +function finish(payload: BasePayload, watch: Watch, id: TransactionID): Entry | undefined { + const entry = watch.open.get(id) + if (!entry) {return undefined} + watch.open.delete(id) + release(payload, watch) + return entry +} + +/** + * Wraps the adapter's begin / commit / rollback once (idempotent). `reserve`: connections kept free of + * transactions (Postgres only), `false` = no limit; the watch for `afterCommit` is installed either way. + * Returns the watch, or null when the adapter has no transactions to watch. + */ +export function watchTransactions(payload: BasePayload, reserve: false | number = defaultConnectionReserve(poolSize(payload) ?? 10)): null | Watch { + const db = dbOf(payload) + if (typeof db.beginTransaction !== 'function' || typeof db.commitTransaction !== 'function' || typeof db.rollbackTransaction !== 'function') {return null} + const size = poolSize(payload) + const wanted = reserve === false || size === null ? null : Number.isFinite(reserve) ? Math.max(0, Math.floor(reserve)) : defaultConnectionReserve(size) + if (db[WATCH]) { + db[WATCH].reserve = wanted + drain(payload, db[WATCH]) + return db[WATCH] + } + const watch: Watch = { active: 0, open: new Map(), queue: [], reserve: wanted } + db[WATCH] = watch + + const begin = db.beginTransaction + const commit = db.commitTransaction + const rollback = db.rollbackTransaction + + db.beginTransaction = async function (this: unknown, ...args: unknown[]) { + const waiting = acquire(payload, watch) + if (waiting) {await waiting} + let id: null | TransactionID + try { + id = await begin.apply(this, args) + } catch (err) { + release(payload, watch) + throw err + } + if (id === null || id === undefined) { + release(payload, watch) + return id + } + watch.open.set(id, { after: [] }) + return id + } + + db.commitTransaction = async function (this: unknown, incoming) { + const id = incoming instanceof Promise ? await incoming : incoming + try { + await commit.call(this, id) + } catch (err) { + finish(payload, watch, id) + throw err + } + const entry = finish(payload, watch, id) + for (const fn of entry?.after ?? []) { + try { + await fn() + } catch (err) { + payload.logger.error({ err, msg: '[iapl] A step that runs after a transaction commits failed.' }) + } + } + } + + db.rollbackTransaction = async function (this: unknown, incoming) { + const id = incoming instanceof Promise ? await incoming : incoming + try { + await rollback.call(this, id) + } finally { + finish(payload, watch, id) + } + } + return watch +} + +/** + * Keeps `reserve` pool connections free of transactions (Postgres; does nothing on an adapter without a + * pool). `iapl()` calls it at start; a project that uses only the building blocks calls it in its own + * `onInit`: + * onInit: (payload) => { reserveConnections(payload) } + * `reserve`: a number, or the default (a fifth of the pool, at least 2). Calling it again changes the number. + */ +export function reserveConnections(payload: BasePayload, reserve?: number): void { + watchTransactions(payload, reserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)) +} + +/** + * Runs `fn` right after the transaction of `req` commits — still inside the operation that began it, so + * that operation returns only once `fn` is done — and drops it when the transaction is rolled back. + * Returns `false` when there is no transaction to wait for (none open, an adapter without transactions, + * one this watch did not see begin): then nothing is scheduled and the caller does the work at once. + * A caller's OUTER transaction counts: `fn` runs when that one commits. + * An error thrown by `fn` is logged; it does not undo the commit. + */ +export function afterCommit(req: Pick, fn: () => Promise | void): boolean { + const id = req.transactionID + if (id === undefined || id === null || id instanceof Promise) {return false} + const entry = dbOf(req.payload)[WATCH]?.open.get(id) + if (!entry) {return false} + entry.after.push(fn) + return true +} + +/** True when `req` is inside a transaction that `afterCommit` can wait for. */ +export function inWatchedTransaction(req: Pick): boolean { + const id = req.transactionID + return id !== undefined && id !== null && !(id instanceof Promise) && Boolean(dbOf(req.payload)[WATCH]?.open.has(id)) +} + +/** + * True while every place for a transaction is taken or a transaction waits for one (Postgres with the + * reserve on). Work that would open a transaction of its own and is not needed for the caller's answer — + * the panel status of an integration — runs in the background then instead of holding its caller, which + * may itself be inside a transaction. + */ +export function transactionsBusy(payload: BasePayload): boolean { + const watch = dbOf(payload)[WATCH] + if (!watch || watch.reserve === null) {return false} + const size = poolSize(payload) ?? Infinity + return watch.queue.length > 0 || watch.active >= Math.max(1, size - watch.reserve) +} + +/** For tests and diagnostics: open transactions, waiting ones and the reserve in force. */ +export function transactionWatchState(payload: BasePayload): { active: number; reserve: null | number; waiting: number } | null { + const watch = dbOf(payload)[WATCH] + return watch ? { active: watch.active, reserve: watch.reserve, waiting: watch.queue.length } : null +} diff --git a/src/modules/email/panelSmtpAdapter.ts b/src/modules/email/panelSmtpAdapter.ts index c20dfd8..4c75f8c 100644 --- a/src/modules/email/panelSmtpAdapter.ts +++ b/src/modules/email/panelSmtpAdapter.ts @@ -20,8 +20,19 @@ export type PanelSmtpAdapterArgs = { */ fallbackFromAddress?: string fallbackFromName?: string + /** + * How long a send waits for the SMTP server, in milliseconds: `connectionMs` to connect (default 10 000), + * `greetingMs` for its greeting (default 30 000), `socketMs` of silence during the dialogue (default 60 000). + * A send that runs inside a database transaction (Payload's "forgot password") holds a connection that long. + */ + timeouts?: SmtpTimeouts } +export type SmtpTimeouts = { connectionMs?: number; greetingMs?: number; socketMs?: number } + +/** nodemailer's own defaults are 2 minutes to connect and 10 minutes of silence. */ +export const SMTP_TIMEOUT_DEFAULTS: Required = { connectionMs: 10_000, greetingMs: 30_000, socketMs: 60_000 } + /** * Payload email adapter backed by the SMTP settings in the SiteIntegrations * global. @@ -83,11 +94,15 @@ export const panelSmtpAdapter = const { default: nodemailer } = await import('nodemailer') + const timeouts = { ...SMTP_TIMEOUT_DEFAULTS, ...args.timeouts } const transporter = nodemailer.createTransport({ auth: { pass, user }, + connectionTimeout: timeouts.connectionMs, + greetingTimeout: timeouts.greetingMs, host, port, - secure: port === 465, // implicit TLS on 465, STARTTLS otherwise + secure: port === 465, // implicit TLS on 465, STARTTLS otherwise + socketTimeout: timeouts.socketMs, }) try { diff --git a/src/modules/forms/afterCommit.ts b/src/modules/forms/afterCommit.ts new file mode 100644 index 0000000..6c05e37 --- /dev/null +++ b/src/modules/forms/afterCommit.ts @@ -0,0 +1,48 @@ +import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types' +import type { PayloadRequest } from 'payload' + +import { isolateObjectProperty } from 'payload' + +import { afterCommit } from '../database/transactions.js' + +type Emails = Parameters[0] +type HookArgs = Parameters[1] + +/** The same request outside its (committed) transaction: reads in the hooks take a connection of their own. */ +function outsideTransaction(req: PayloadRequest): PayloadRequest { + const own = isolateObjectProperty(req, 'transactionID') + own.transactionID = undefined + return own +} + +/** form-builder's own loop: every e-mail through the project's adapter, a failure logged, never thrown. */ +export async function sendFormEmails(req: PayloadRequest, emails: Emails): Promise { + const { payload } = req + await Promise.all( + emails.map(async (email) => { + try { + await payload.sendEmail(email as never) + } catch (err) { + payload.logger.error({ err, msg: `Error while sending email to address: ${String(email.to)}. Email not sent.` }) + } + }), + ) +} + +/** + * A form-builder `beforeEmail` that composes the e-mails at once (`prepare`: inside the submission's + * transaction, with its `req`) and hands them to the mail server right after that transaction commits + * (`deliver` — the file delivery — then the send). form-builder gets an empty list back and sends + * nothing itself. Inside a caller's outer transaction they go out when that one commits; with no + * transaction to wait for (MongoDB without a replica set, SQLite) everything happens at once, as before. + */ +export function sendAfterCommit(prepare: BeforeEmail, deliver: BeforeEmail): BeforeEmail { + return async (emails, args: HookArgs) => { + const prepared = await prepare(emails, args) + const later = afterCommit(args.req, async () => { + const req = outsideTransaction(args.req) + await sendFormEmails(req, await deliver(prepared, { ...args, req })) + }) + return later ? [] : deliver(prepared, args) + } +} diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 0fb6cbb..4b3021b 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -7,6 +7,7 @@ import type { AdminText } from '../admin-i18n/define.js' import type { FormsOption } from './types.js' import { userMeetsRole } from '../access/predicates.js' +import { sendAfterCommit } from './afterCommit.js' import { resolveFormAttachments } from './attachments/config.js' import { buildFileDeliveryHook, buildFileNoticeHook, buildFormMailKindHook } from './attachments/delivery.js' import { buildFormSubmitEndpoint } from './attachments/endpoint.js' @@ -221,13 +222,16 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { // Every e-mail of a form says what it is (notification to the addresses written in the panel, or // confirmation to an address the visitor typed): the Intecion mail service limits the two differently. const markKinds = buildFormMailKindHook({ formsSlug }) - const beforeEmail: BeforeEmail = async (emails, args) => { + const prepare: BeforeEmail = async (emails, args) => { const noticed = fileNotice ? await fileNotice(emails, args) : emails const laidOut = layout ? await layout(noticed, args) : noticed const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut - const marked = await markKinds(changed, args) - return fileDelivery ? fileDelivery(marked, args) : marked + return markKinds(changed, args) } + const deliver: BeforeEmail = (emails, args) => (fileDelivery ? fileDelivery(emails, args) : emails) + // Composed inside the transaction (the hooks read the form with its `req`); sent after it commits + // (forms.emailsInTransaction), so a slow mail server holds no database connection. + const beforeEmail: BeforeEmail = forms.emailsInTransaction ? async (emails, args) => deliver(await prepare(emails, args), args) : sendAfterCommit(prepare, deliver) const fileBlockOption = forms.fields?.file const formHooks = forms.formOverrides?.hooks const builder = formBuilderPlugin({ diff --git a/src/modules/forms/types.ts b/src/modules/forms/types.ts index 8e9b5da..7b14b1f 100644 --- a/src/modules/forms/types.ts +++ b/src/modules/forms/types.ts @@ -53,6 +53,16 @@ export type FormsOption = { * with the logo, accent colour and footer from Site Settings → Emails. Default false. */ emailLayout?: boolean + /** + * When a form's e-mails go out. Default (`false`): right AFTER the submission is saved — its database + * transaction has committed and given its connection back — still within the same request, so the + * visitor's answer (and a file that could not be sent) is reported as before. A mail server that is + * slow or hangs then holds no database connection, and nothing is sent for a submission that was not + * saved. A submission saved without its e-mail (the mail server refused it) stays stored, as it always + * did. `true` = inside the transaction, as before 1.17.0. Databases without transactions (MongoDB + * without a replica set, SQLite by default) send at once either way. docs/forms.md "When e-mails go out". + */ + emailsInTransaction?: boolean /** Field types available in the form builder. Sensible defaults applied. */ fields?: { checkbox?: boolean diff --git a/src/modules/integrations/status.ts b/src/modules/integrations/status.ts index 5b80b73..ec95710 100644 --- a/src/modules/integrations/status.ts +++ b/src/modules/integrations/status.ts @@ -3,6 +3,8 @@ import type { BasePayload, Field } from 'payload' import type { AdminTextKey } from '../admin-i18n/texts/index.js' import type { IntegrationLabel } from './texts.js' +import { transactionsBusy } from '../database/transactions.js' + /** * Health of a third-party integration (Turnstile today, SMTP/Graph later), * stored on the SiteIntegrations global so the panel can show it: @@ -88,7 +90,8 @@ export function buildIntegrationStatusBanner( /** * Persist a status change. Never throws — a status write must not break the - * request that triggered it. + * request that triggered it. The same change already being written is not + * written twice; under database load the write is not waited for. */ export async function recordIntegrationStatus( payload: BasePayload, @@ -106,6 +109,15 @@ export async function recordIntegrationStatus( if (!changed && !stale) {return} if (next.state === 'ok' && !previous?.state) {return} + // The same change already on its way (many sends failing at once): wait for that write, do not repeat it. + const key = `${field}|${next.state}|${next.code ?? ''}` + const pending = inFlight(payload) + // Under load (every transaction place taken, src/modules/database/transactions.ts) the caller may be + // inside a transaction itself: the write — a transaction of its own — is not waited for then. + const busy = transactionsBusy(payload) + const running = pending.get(key) + if (running) {return busy ? undefined : running} + const status: IntegrationStatus = { checkedAt: now.toISOString(), code: next.code ?? null, @@ -113,14 +125,30 @@ export async function recordIntegrationStatus( since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()), state: next.state, } - try { - await payload.updateGlobal({ - slug: SITE_INTEGRATIONS as never, - context: { ipalIntegrationStatus: true }, - data: { [field]: status } as never, - depth: 0, - }) - } catch (err) { - console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err) + const write = (async () => { + try { + await payload.updateGlobal({ + slug: SITE_INTEGRATIONS as never, + context: { ipalIntegrationStatus: true }, + data: { [field]: status } as never, + depth: 0, + }) + } catch (err) { + console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err) + } finally { + pending.delete(key) + } + })() + pending.set(key, write) + return busy ? undefined : write +} + +const writes = new WeakMap>>() +function inFlight(payload: BasePayload): Map> { + let map = writes.get(payload) + if (!map) { + map = new Map() + writes.set(payload, map) } + return map } diff --git a/src/plugin.ts b/src/plugin.ts index 558f21f..54d8855 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -30,6 +30,7 @@ import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js' import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' +import { defaultConnectionReserve, poolSize, watchTransactions } from './modules/database/transactions.js' import { buildDoctorEndpoint } from './modules/doctor/status.js' import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js' import { withAccountMailMark } from './modules/email/relay/accountMail.js' @@ -939,6 +940,9 @@ export const iapl = (options: IaplOptions): Plugin => { ) } adoptConfig(payload) + // Postgres: keep a few pool connections free of transactions (connectionReserve), and watch commits so + // that form e-mails go out after the submission's transaction (forms.emailsInTransaction). + watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10))) // Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set. if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)} // Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once. diff --git a/src/types.ts b/src/types.ts index 3112049..ad41aa1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -75,6 +75,18 @@ export type IaplOptions = { */ agency?: AgencyOption | false + /** + * Postgres: pool connections kept free of transactions. Payload holds a connection for the whole of a + * transaction, and code inside it that runs without the transaction's `req` (Payload's own "forgot + * password", an e-mail adapter reading its settings, a hook that forgot `req`) needs a second one: with + * the default pool of 10, ten such requests at once used to stop the whole site. With the reserve, at + * most `pool size − reserve` transactions are open at once and the next one waits for a place. + * Default: a fifth of the pool, at least 2 (1 in a pool of fewer than 4). A number sets it; `false` + * switches it off (as before 1.17.0). Other adapters: no effect. Building block: `reserveConnections`. + * docs/deployment.md "Postgres: the connection pool". + */ + connectionReserve?: false | number + /** Internationalization — locales, default locale, fallback behavior */ /** * Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records` diff --git a/test/formAttachments.test.ts b/test/formAttachments.test.ts index 7ab472e..3b76025 100644 --- a/test/formAttachments.test.ts +++ b/test/formAttachments.test.ts @@ -24,6 +24,7 @@ import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachme import { submitForm } from '../src/modules/forms/submitForm.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' vi.mock('server-only', () => ({})) @@ -127,7 +128,9 @@ beforeAll(async () => { { slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: mediaDir } }, ], - db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), + // SQLite in memory by default; IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI run the same tests there (on + // Postgres the e-mails go out after the submission's transaction commits: forms.emailsInTransaction). + db: testDatabase('formfiles'), editor: lexicalEditor(), email: recordingMail, plugins: [ diff --git a/test/transactionPool.test.ts b/test/transactionPool.test.ts new file mode 100644 index 0000000..82fbecc --- /dev/null +++ b/test/transactionPool.test.ts @@ -0,0 +1,291 @@ +/** + * Transactions and the Postgres pool (modules/database/transactions.ts, forms.emailsInTransaction; + * `true` is checked in transactionPoolInTx.test.ts). + * + * Payload holds a pool connection for the whole of a transaction; code inside it that runs without the + * transaction's `req` needs a second one. Ten such requests at once (form submissions sending e-mail, + * Payload's own "forgot password") used to hold the default pool of 10 and wait for an eleventh — the + * whole site stopped. Part 1 checks the watch against a fake adapter; part 2 runs a real Payload on + * Postgres when IPAL_TEST_POSTGRES_URI is set (test/http/db.ts), with the default pool: + * docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17 + * IPAL_TEST_POSTGRES_URI=postgres://postgres:test@127.0.0.1:55432/postgres pnpm vitest run test/transactionPool.test.ts + */ +import type { BasePayload, Payload } from 'payload' + +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.js' +import { submitForm } from '../src/modules/forms/submitForm.js' +import { startPayloadServer, type TestServer } from './http/server.js' +import { silentServer, site } from './transactionPoolSite.js' + +vi.mock('server-only', () => ({})) + +// ---- part 1: the watch, against a fake adapter --------------------------------------------------- + +type FakeDb = { + beginTransaction: () => Promise + commitTransaction: (id: Promise | string) => Promise + pool?: { options: { max?: number } } + rollbackTransaction: (id: Promise | string) => Promise +} + +function fakePayload({ max = 5, pool = true, transactions = true }: { max?: number; pool?: boolean; transactions?: boolean } = {}) { + let n = 0 + const events: string[] = [] + const db: FakeDb = { + beginTransaction: () => Promise.resolve(transactions ? `t${++n}` : null), + commitTransaction: async (id) => { + events.push(`commit ${await id}`) + }, + rollbackTransaction: async (id) => { + events.push(`rollback ${await id}`) + }, + ...(pool ? { pool: { options: { max } } } : {}), + } + const logger = { error: vi.fn(), info: vi.fn(), warn: vi.fn() } + return { db, events, logger, payload: { db, logger } as unknown as BasePayload } +} + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)) + +describe('the watch (fake adapter)', () => { + test('the default reserve: a fifth of the pool, at least 2; 1 in a pool of fewer than 4', () => { + expect([1, 2, 3, 4, 5, 10, 11, 20, 50].map(defaultConnectionReserve)).toEqual([1, 1, 1, 2, 2, 2, 3, 4, 10]) + }) + + test('at most pool size − reserve transactions are open; the next waits for a commit', async () => { + const { db, payload } = fakePayload({ max: 5 }) + watchTransactions(payload) + // each from its own operation, as Payload calls it (initTransaction inside the operation) + const open = async () => { + await tick() + return db.beginTransaction() + } + const ids = await Promise.all([open(), open(), open()]) + let fourth: null | string = null + void open().then((id) => (fourth = id)) + await tick() + expect(fourth).toBeNull() + expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 2, waiting: 1 }) + await db.commitTransaction(ids[0]!) + await tick() + expect(fourth).toBe('t4') + await db.rollbackTransaction(ids[1]!) + expect(transactionWatchState(payload)).toMatchObject({ active: 2, waiting: 0 }) + }) + + test('a transaction begun inside another one gets a place in the reserve after a second, so it never waits for ever on its caller', async () => { + const { db, payload } = fakePayload({ max: 5 }) // limit 3; after a second in the queue, up to 4 + watchTransactions(payload) + // Each operation opens a transaction and, inside it, a second one (a hook calling the Local API without + // `req`). Three outers fill the limit; without the escape every inner would wait for ever. + const operation = async () => { + await tick() + const outer = (await db.beginTransaction())! + await tick() + const inner = (await db.beginTransaction())! + await db.commitTransaction(inner) + await db.commitTransaction(outer) + } + const start = Date.now() + const all = Promise.all([operation(), operation(), operation()]) + const done = await Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), 4000))]) + expect(done).toBe('done') + expect(Date.now() - start).toBeGreaterThanOrEqual(900) + expect(transactionWatchState(payload)).toMatchObject({ active: 0, waiting: 0 }) + }) + + test('the escape leaves one connection that no transaction holds', async () => { + const { db, payload } = fakePayload({ max: 4 }) // reserve 2, limit 2, escape up to 3 + watchTransactions(payload) + const open = async () => { + await tick() + return db.beginTransaction() + } + await Promise.all([open(), open()]) + const later: (null | string)[] = [] + void open().then((id) => later.push(id)) + void open().then((id) => later.push(id)) + await new Promise((resolve) => setTimeout(resolve, 1300)) + expect(later).toHaveLength(1) + expect(transactionWatchState(payload)).toMatchObject({ active: 3, waiting: 1 }) + }) + + test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => { + const { db, events, logger, payload } = fakePayload() + watchTransactions(payload) + const a = (await db.beginTransaction())! + expect(inWatchedTransaction({ payload, transactionID: a })).toBe(true) + expect(afterCommit({ payload, transactionID: a }, () => void events.push('after a'))).toBe(true) + expect(afterCommit({ payload, transactionID: a }, () => Promise.reject(new Error('mail down')))).toBe(true) + expect(afterCommit({ payload, transactionID: a }, () => void events.push('after a, 3rd'))).toBe(true) + await db.commitTransaction(a) + expect(events).toEqual(['commit t1', 'after a', 'after a, 3rd']) + expect(logger.error).toHaveBeenCalledTimes(1) + + const b = (await db.beginTransaction())! + afterCommit({ payload, transactionID: b }, () => void events.push('after b')) + await db.rollbackTransaction(b) + expect(events).toContain('rollback t2') + expect(events).not.toContain('after b') + }) + + test('nothing to wait for → afterCommit returns false and schedules nothing', async () => { + const { db, payload } = fakePayload() + watchTransactions(payload) + expect(afterCommit({ payload, transactionID: undefined }, () => {})).toBe(false) + expect(afterCommit({ payload, transactionID: 'not-seen' }, () => {})).toBe(false) + expect(afterCommit({ payload, transactionID: Promise.resolve('t1') as never }, () => {})).toBe(false) + const id = (await db.beginTransaction())! + await db.commitTransaction(id) + expect(afterCommit({ payload, transactionID: id }, () => {})).toBe(false) // already committed + + // An adapter without transactions (MongoDB without a replica set, SQLite by default) begins none. + const none = fakePayload({ transactions: false }) + watchTransactions(none.payload) + expect(await none.db.beginTransaction()).toBeNull() + expect(transactionWatchState(none.payload)).toMatchObject({ active: 0 }) + }) + + test('`false`, or an adapter without a pool: no limit (the watch for afterCommit stays)', async () => { + for (const { payload, reserve } of [ + { payload: fakePayload({ max: 3 }).payload, reserve: false as const }, + { payload: fakePayload({ pool: false }).payload, reserve: 2 }, + ]) { + watchTransactions(payload, reserve) + const db = payload.db as unknown as FakeDb + const ids = await Promise.all(Array.from({ length: 12 }, () => db.beginTransaction())) + expect(transactionWatchState(payload)).toEqual({ active: 12, reserve: null, waiting: 0 }) + expect(afterCommit({ payload, transactionID: ids[0]! }, () => {})).toBe(true) + } + }) + + test('an adapter with no transaction functions is not watched', () => { + const payload = { db: {}, logger: console } as unknown as BasePayload + expect(watchTransactions(payload)).toBeNull() + expect(transactionWatchState(payload)).toBeNull() + }) + + test('installed once: a second call changes the reserve, it does not wrap again', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + const begin = db.beginTransaction + watchTransactions(payload, 7) + expect(db.beginTransaction).toBe(begin) + await Promise.all([db.beginTransaction(), db.beginTransaction(), db.beginTransaction()]) + expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 7, waiting: 0 }) + }) +}) + +// ---- part 2: a real Payload on Postgres, the default pool of 10 ----------------------------------- + +const POSTGRES = Boolean(process.env.IPAL_TEST_POSTGRES_URI) + +const N = 30 +const ACCOUNTS = Array.from({ length: N }, (_, i) => `account${i}@example.com`) +/** Resolves with `fallback` when `promise` takes longer than `ms`. */ +const within = (promise: Promise, ms: number, fallback: F) => Promise.race([promise, new Promise((resolve) => setTimeout(() => resolve(fallback), ms))]) + +describe.runIf(POSTGRES)('Postgres, default pool of 10', () => { + let payload: Payload + let formId: string + let server: TestServer + let silent: Awaited> + + const useSmtpPort = (port: number) => + payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: 'site@example.com', smtpHost: '127.0.0.1', smtpPassword: 'p', smtpPort: port, smtpUser: 'u' } as never }) + const submit = (i: number, message = `message ${i}`) => + submitForm({ data: { email: `visitor${i}@example.org`, message }, formId, ip: `10.9.0.${i}`, maxPerMinute: 0, payload }) + const forgot = (email: string) => + fetch(`${server.url}/api/users/forgot-password`, { body: JSON.stringify({ email }), headers: { 'Content-Type': 'application/json' }, method: 'POST' }).then((r) => r.status) + /** An ordinary request while the others wait: its time in ms, or 'no answer'. */ + const ordinaryRequest = async () => { + const start = Date.now() + const status = await within(fetch(`${server.url}/api/pages`).then((r) => r.status), 8000, 'no answer' as const) + return status === 200 ? Date.now() - start : status + } + + beforeAll(async () => { + ;({ formId, payload } = await site('txpool')) + const config = Promise.resolve(payload.config) + server = await startPayloadServer(config) + silent = await silentServer() + for (const email of ACCOUNTS) { + await payload.create({ collection: 'users' as never, data: { email, password: 'Correct-horse-battery-9' } as never, disableVerificationEmail: true }) + } + }, 120_000) + + afterAll(async () => { + await silent?.close() + await server?.close() + await payload?.destroy() + }) + + test('the reserve is in force: 2 of the 10 connections stay free of transactions', () => { + expect(transactionWatchState(payload)).toMatchObject({ reserve: 2 }) + }) + + test(`${N} form submissions at once finish, and an ordinary request answers meanwhile (SMTP refuses at once)`, async () => { + await useSmtpPort(9) + const pending = Promise.all(Array.from({ length: N }, (_, i) => submit(i))) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(await ordinaryRequest()).toBeLessThan(2000) + const results = await within(pending, 30_000, 'stuck' as const) + expect(results).not.toBe('stuck') + expect((results as { success: boolean }[]).every((r) => r.success)).toBe(true) + // the panel status says so + const integrations = (await payload.findGlobal({ slug: 'site-integrations' as never })) as { emailStatus?: { code?: string; state?: string } } + expect(integrations.emailStatus).toMatchObject({ code: 'smtp-error', state: 'degraded' }) + }, 60_000) + + test(`${N} "forgot password" requests for different accounts at once finish, and an ordinary request answers`, async () => { + await useSmtpPort(9) + const pending = Promise.all(ACCOUNTS.map(forgot)) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(await ordinaryRequest()).toBeLessThan(2000) + expect(await within(pending, 30_000, 'stuck')).toEqual(ACCOUNTS.map(() => 200)) + }, 60_000) + + test(`a hanging SMTP server: ${N} submissions and ${N} "forgot password" at once all finish; an ordinary request answers`, async () => { + await useSmtpPort(silent.port) + // Payload allows one reset request per account every 15 s: wait it out, so every request really sends. + await new Promise((resolve) => setTimeout(resolve, 15_500)) + const start = Date.now() + const submissions = Promise.all(Array.from({ length: N }, (_, i) => submit(100 + i))) + const resets = Promise.all(ACCOUNTS.map(forgot)) + await new Promise((resolve) => setTimeout(resolve, 500)) + expect(await ordinaryRequest()).toBeLessThan(2000) + const both = await within(Promise.all([submissions, resets]), 45_000, 'stuck' as const) + expect(both).not.toBe('stuck') + const [subs, codes] = both as [{ success: boolean }[], number[]] + expect(subs.every((r) => r.success)).toBe(true) + expect(codes).toEqual(ACCOUNTS.map(() => 200)) + // Submissions send in parallel after their commit (≈ one time-out); the resets send inside their + // transactions, eight at a time (30 × 2 s / 8 ≈ 8 s). + expect(Date.now() - start).toBeLessThan(30_000) + }, 90_000) + + test('form e-mails go out after the commit: the stored submission is visible to the send; a rolled-back one sends nothing', async () => { + await useSmtpPort(9) + const send = vi.spyOn(payload, 'sendEmail') + const seen: number[] = [] + send.mockImplementation(async () => { + // outside the transaction: only a committed submission can be found + seen.push((await payload.count({ collection: 'form-submissions' as never, where: { 'submissionData.value': { equals: 'after-commit-check' } } })).totalDocs) + return { sent: true } + }) + try { + expect(await submit(201, 'after-commit-check')).toMatchObject({ success: true }) + expect(seen).toEqual([1, 1]) // both e-mails of the form, each after the commit + + send.mockClear() + expect(await submit(202, 'roll-me-back')).toEqual({ reason: 'error', success: false }) + expect(send).not.toHaveBeenCalled() + expect((await payload.count({ collection: 'form-submissions' as never, where: { 'submissionData.value': { equals: 'roll-me-back' } } })).totalDocs).toBe(0) + } finally { + send.mockRestore() + } + }) + +}) diff --git a/test/transactionPoolInTx.test.ts b/test/transactionPoolInTx.test.ts new file mode 100644 index 0000000..4d56df1 --- /dev/null +++ b/test/transactionPoolInTx.test.ts @@ -0,0 +1,31 @@ +/** + * forms.emailsInTransaction: true — the e-mails of a form go out inside the submission's transaction, as + * before 1.17.0. Postgres only (IPAL_TEST_POSTGRES_URI); its own file, because one test process pushes the + * schema of one Payload (test/transactionPool.test.ts has the default). + */ +import { describe, expect, test, vi } from 'vitest' + +import { submitForm } from '../src/modules/forms/submitForm.js' +import { site } from './transactionPoolSite.js' + +vi.mock('server-only', () => ({})) + +describe.runIf(Boolean(process.env.IPAL_TEST_POSTGRES_URI))('Postgres, forms.emailsInTransaction: true', () => { + test('forms.emailsInTransaction: true sends inside the transaction, as before 1.17.0', async () => { + const other = await site('txpoolin', { emailsInTransaction: true }) + const send = vi.spyOn(other.payload, 'sendEmail') + const seen: number[] = [] + send.mockImplementation(async () => { + seen.push((await other.payload.count({ collection: 'form-submissions' as never })).totalDocs) + return { sent: true } + }) + try { + const result = await submitForm({ data: { email: 'v@example.org', message: 'm' }, formId: other.formId, maxPerMinute: 0, payload: other.payload }) + expect(result).toMatchObject({ success: true }) + expect(seen).toEqual([0, 0]) // not committed yet when the e-mails went out + } finally { + send.mockRestore() + await other.payload.destroy() + } + }, 60_000) +}) diff --git a/test/transactionPoolSite.ts b/test/transactionPoolSite.ts new file mode 100644 index 0000000..6ca5e07 --- /dev/null +++ b/test/transactionPoolSite.ts @@ -0,0 +1,89 @@ +/** The site of test/transactionPool*.test.ts: a contact form, accounts, mailAdapter with short SMTP time-outs. */ +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import net from 'node:net' +import os from 'node:os' +import path from 'node:path' +import { getPayload } from 'payload' + +import { mailAdapter } from '../src/modules/email/mailAdapter.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' + +const text = (value: string) => ({ + root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', text: value, version: 1 }], direction: null, format: '', indent: 0, version: 1 }], direction: null, format: '', indent: 0, version: 1 }, +}) + +/** An SMTP server that accepts the connection and never says a word. */ +export async function silentServer(): Promise<{ close: () => Promise; port: number }> { + const sockets = new Set() + const server = net.createServer((socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { + close: () => { + for (const s of sockets) {s.destroy()} + return new Promise((resolve) => server.close(() => resolve())) + }, + port: (server.address() as net.AddressInfo).port, + } +} + +export async function site(name: string, { emailsInTransaction = false } = {}) { + const payload = await getPayload({ + config: buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'users', auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-test-pool-media') } }, + { slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + ], + db: testDatabase(name), + editor: lexicalEditor(), + // Short SMTP time-outs: a server that hangs costs two seconds a send. + email: mailAdapter({ smtp: { timeouts: { connectionMs: 2000, greetingMs: 2000, socketMs: 2000 } } }), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + forms: { + emailsInTransaction, + formSubmissionOverrides: { + hooks: { + // a later hook that fails: the submission is rolled back + afterChange: [({ doc }) => { + if ((doc as { submissionData?: { value?: string }[] }).submissionData?.some((row) => row.value === 'roll-me-back')) {throw new Error('rolled back on purpose')} + }], + }, + }, + }, + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, + mail: { relay: false }, + twoFactor: false, + }), + ], + secret: 'transaction-pool-test-secret-0123456789', + serverURL: 'https://example.com', + telemetry: false, + }), + }) + const form = await payload.create({ + collection: 'forms' as never, + data: { + confirmationMessage: text('ok'), + confirmationType: 'message', + emails: [ + { emailTo: 'biuro@example.com', message: text('{{message}}'), subject: 'New message' }, + { emailTo: '{{email}}', message: text('Thank you'), subject: 'Thank you' }, + ], + fields: [ + { name: 'email', blockType: 'email', label: 'E-mail', required: true }, + { name: 'message', blockType: 'text', label: 'Message', required: true }, + ], + title: 'Contact', + } as never, + }) + return { formId: String(form.id), payload } +} + From 4efadb21d51a13f665459bd6fc99873099c7ae74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 01:19:27 +0100 Subject: [PATCH 2/3] Postgres pool, review round 1: nested transactions, account mail after commit P-1: a transaction begun inside another one (a hook calling the Local API without req) no longer queues behind its caller. An AsyncLocalStorage mark set when a transaction begins lets the inner one through at once, without a place, but never into the last connection (a second level may take that one). If the mark is lost, a queue that has not moved for a second admits its newest waiter. connectionReserve: false now admits everything, as before. Measured on Postgres 17: 9, 12 and 30 such submissions finish (before: stuck from 9). P-2: Payload's "forgot password" and "verify your e-mail" through mailAdapter() go out right after their transaction commits (mail.accountMailAfterCommit, default on). With the relay hanging, 30 resets + 30 submissions finish in about 11 s instead of 43.5 s. P-3: Postgres tests for the "not confirmed" file result after commit, a caller's outer transaction rolled back or committed, the relay hanging, and the nested rows; deployment.md has the measured table. Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 19 +- docs/agent/AGENT.md | 3 +- docs/agent/skills/iapl-debug/SKILL.md | 3 +- docs/agent/skills/iapl-upgrade/SKILL.md | 4 +- docs/deployment.md | 35 +++- docs/email.md | 9 +- reference/.agents/skills/iapl-debug/SKILL.md | 3 +- .../.agents/skills/iapl-upgrade/SKILL.md | 4 +- src/index.ts | 1 + src/modules/database/transactions.ts | 141 ++++++++++----- src/modules/email/accountMailAfterCommit.ts | 93 ++++++++++ src/modules/email/mailAdapter.ts | 10 +- src/plugin.ts | 6 + src/types.ts | 8 + test/accountRulesSuite.ts | 3 +- test/transactionPool.test.ts | 116 ++++++++---- test/transactionPoolRelay.test.ts | 166 ++++++++++++++++++ test/transactionPoolSite.ts | 17 +- 18 files changed, 534 insertions(+), 107 deletions(-) create mode 100644 src/modules/email/accountMailAfterCommit.ts create mode 100644 test/transactionPoolRelay.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 89d28ea..fb3df2b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -139,10 +139,17 @@ once there are more than 20. second one; the default pool has 10. Measured on Postgres 17: 12 submissions or 12 resets at once never finished; now 30 of each, also against an SMTP server that never answers, finish while an ordinary request answers at once. - **`connectionReserve`** (new plugin option, default on): a fifth of the pool, at least 2, stays free of - transactions; at most `pool size − reserve` transactions are open at once and the next one waits; one that has - waited a second may use all but the last connection. `false` = as before. Building blocks `reserveConnections`, - `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, - `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a). + transactions; at most `pool size − reserve` transactions are open at once and the next one waits. A transaction + begun inside another one (a project hook that calls the Local API without `req`) takes no place and goes at once, + but never takes the last connection — 9, 12 and 30 such submissions at once finish (before: 12 stopped the site). + `false` = as before. Building blocks `reserveConnections`, `watchTransactions`, `afterCommit`, + `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`, + `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a, with the measured table). +- **Payload's "forgot password" and "verify your e-mail" go out after their transaction commits** when sent through + `mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). With the mail + service hanging, 30 resets and 30 submissions at once finish in about one send budget (11 s) instead of 43.5 s. + Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMailFor`, + `releaseAccountMailFor`. - **Form e-mails go out after the submission's transaction commits** — same request, same answer to the visitor (a file that could not be sent is still reported). A submission rolled back by a later hook now sends nothing; a send that fails after the commit leaves the submission stored (as a failed e-mail always did). Sites without @@ -153,8 +160,8 @@ once there are more than 20. is busy the write is not waited for. - **SMTP time-outs**: 10 s to connect (was nodemailer's 2 min), 30 s for the greeting, 60 s of silence (was 10 min); `mailAdapter({ smtp: { timeouts } })` / `panelSmtpAdapter({ timeouts })`, `SMTP_TIMEOUT_DEFAULTS`, `SmtpTimeouts`. -- Not fixed here: Payload's own "forgot password" and "verify your e-mail" still send inside their transaction, so a - hanging mail server makes them hold a place until the SMTP time-out (others wait; nothing stops). +- Not covered: an e-mail adapter of your own (not `mailAdapter()`) still gets Payload's account mail inside the + transaction unless it calls `sendAccountMailAfterCommit` first. ### Deprecated - **Microsoft Graph as an e-mail transport** — `graphAdapter`, `GraphAdapterArgs`, `mailAdapter({ graph })`, diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 505f0dc..5ea1e04 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1246,7 +1246,8 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Account e-mails through the mail service: at most 5 to one address and 10 asked for by one visitor an hour | `mail: { relay: { accountMail: false } }` | `accountMail: { perAddress, perVisitor, windowMinutes }` | | Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` | | Microsoft Graph as transport: deprecated, one warning per start, removed in 2.0 | `mail: { graphDeprecationWarning: false }` (the warning only) | move off it: email.md "Moving off Microsoft Graph" | -| Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; one waiting a second may use all but the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: `; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) | +| Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; a transaction begun inside another one (a hook without `req`) takes no place and goes at once, but never the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: `; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) | +| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMailFor`, `releaseAccountMailFor` (email.md "Payload system mail") | | Form e-mails go out right after the submission's transaction commits (same request, same answer); a rolled-back submission sends nothing; a send that fails after the commit leaves the submission stored. No transactions (MongoDB without a replica set, SQLite): at once, as before | `forms: { emailsInTransaction: true }` | `sendAfterCommit(prepare, deliver)`, `sendFormEmails(req, emails)`, `afterCommit(req, fn)` (forms.md "When e-mails go out") | | SMTP time-outs: 10 s to connect, 30 s greeting, 60 s silence | — | `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })`, `panelSmtpAdapter({ timeouts })`; `SMTP_TIMEOUT_DEFAULTS`, type `SmtpTimeouts` (email.md "SMTP") | diff --git a/docs/agent/skills/iapl-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md index 43f3a13..00a78e7 100644 --- a/docs/agent/skills/iapl-debug/SKILL.md +++ b/docs/agent/skills/iapl-debug/SKILL.md @@ -121,7 +121,8 @@ through this procedure. Ask only when you are missing something you cannot get y | the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP | | start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` | | Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) | -| Postgres: requests are slow while a mail server hangs (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) | +| Postgres: requests are slow while a mail server hangs (logins and saves wait behind "forgot password") | the account mail is sent inside its transaction: `mail: { accountMailAfterCommit: false }`, `forms.emailsInTransaction: true`, or an e-mail adapter of your own that does not call `sendAccountMailAfterCommit` | remove the option / call it in your adapter; fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })` | +| Postgres: a project hook writes without `req` and the log row stays when its submission is rolled back | a Local API call without `req` is a transaction of its own (it no longer blocks the pool, but it is not rolled back with its caller) | pass `req` to every Local API call in a hook | | a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" | | old email sender | mail client cache | check the raw headers | | form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts | diff --git a/docs/agent/skills/iapl-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md index ff8f799..50c4fe4 100644 --- a/docs/agent/skills/iapl-upgrade/SKILL.md +++ b/docs/agent/skills/iapl-upgrade/SKILL.md @@ -581,7 +581,9 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's "forgot password" are marked by the plugin. 6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of - 10; `connectionReserve`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`), + 10; `connectionReserve`; a transaction begun inside another one takes no place), form e-mails and Payload's + "forgot password" / "verify your e-mail" go out right after their transaction commits (`forms.emailsInTransaction`, + `mail.accountMailAfterCommit`), SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out". **Check:** `pnpm exec iapl-doctor --deep --url ` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` / diff --git a/docs/deployment.md b/docs/deployment.md index 7708e27..4fdff7e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -366,29 +366,46 @@ Since 1.17.0 the plugin keeps a few connections free of transactions (`connectio - at most `pool size − reserve` transactions are open at once; the next one waits for a place — its request is slower, nothing stops. Default reserve: a fifth of the pool, at least 2 (1 in a pool of fewer than 4): with the default pool of 10, eight transactions at once and two connections for everything else; -- a transaction that has waited a second (`RESERVE_ESCAPE_MS`) may use the reserve too, all but one connection — so a - transaction begun inside another one (a hook without `req`) does not wait for ever on its caller, and one connection - is never held by a transaction; +- a transaction begun **inside** another one — a hook that calls the Local API without `req` writes in a + transaction of its own while its caller's is open — does not queue: it takes no place, because its caller cannot + finish without it. It may use the reserve but the last connection (a second level inside it that one too), so one + connection stays free for the queries outside transactions. "Inside" is told by a mark the plugin sets when a + transaction begins (`AsyncLocalStorage`); in case the mark is lost on the way, a queue that has not moved for a + second (`RESERVE_ESCAPE_MS`) lets its newest waiter use the reserve, all but the last connection; - form e-mails go out **after** the submission's transaction commits ([forms.md](./forms.md) "When e-mails go out"), - so a slow mail server holds no connection; Payload's own account mail ("forgot password", "verify your e-mail") is - still sent inside its transaction — with a mail server that hangs, those requests hold a place until the SMTP - time-out ([email.md](./email.md) "SMTP": 10 s to connect, 30 s for the greeting by default). + and so do Payload's own "forgot password" and "verify your e-mail" sent through `mailAdapter()` + (`mail.accountMailAfterCommit`, default on): a slow or hanging mail server holds no connection and no place; the + request still ends when the mail is out. A rolled-back operation sends nothing. + +Measured on Postgres 17, default pool of 10 (`test/transactionPool*.test.ts`): + +| At the same moment | 1.16.8 / `connectionReserve: false` | 1.17.0 | +|---|---|---| +| 12 or 30 form submissions, or 12 or 30 "forgot password" | site stops for good, pages too | all finish, a page answers in milliseconds | +| 9 / 12 / 30 submissions whose hook writes without `req` | 9 finish (363 ms); 12 and 30 stop the site | all finish (under 2 s) | +| 30 "forgot password" + 30 submissions, the mail service hanging (10 s budget a send) | site stops for good | all finish in about 11 s (one budget); with the reset mail inside its transaction (`accountMailAfterCommit: false`) the last waited 43.5 s | +| the same with an SMTP server that never answers (2 s time-outs in the test) | site stops for good | all finish in a few seconds | ```ts iapl({ connectionReserve: 3 }) // keep three connections free iapl({ connectionReserve: false }) // no limit, as before 1.17.0 (not recommended) +iapl({ mail: { accountMailAfterCommit: false } }) // "forgot password" mail inside its transaction, as before ``` MongoDB, SQLite and other adapters without a pool: no effect. A larger pool (`postgresAdapter({ pool: { max: 20 } })`) moves the reserve with it; the Postgres server's own `max_connections` must allow every instance's pool. Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnections(payload) }`. Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction -commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route), -`poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`. +commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route: +`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail +`withAccountMailAfterCommit(collection)` (the hook the plugin puts on every auth collection), +`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMailFor`, +`releaseAccountMailFor`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled +back with its caller's. Pass `req`. **Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different accounts) while loading a page — the page answers at once, every request finishes. `transactionWatchState(payload)` -shows `{ active, waiting, reserve }`. +shows `{ active, nested, waiting, reserve }`. ### 4.4 Health check and rolling updates diff --git a/docs/email.md b/docs/email.md index 4514e3f..3cc2885 100644 --- a/docs/email.md +++ b/docs/email.md @@ -425,7 +425,8 @@ and password switches the site to the client's server. - The adapter reads the config on every send, so changing the mailbox in the panel works without a restart. - **Time-outs** (since 1.17.0): 10 s to connect, 30 s for the server's greeting, 60 s of silence during the dialogue (`SMTP_TIMEOUT_DEFAULTS`; nodemailer's own were 2 min and 10 min). A send inside a database transaction — - Payload's "forgot password" — holds a connection that long ([deployment.md](./deployment.md) §4.3a). Change them: + Payload's "forgot password" with `mail: { accountMailAfterCommit: false }` — holds a connection that long + ([deployment.md](./deployment.md) §4.3a; by default that mail goes out after its transaction commits). Change them: `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })` or `panelSmtpAdapter({ timeouts })` (type `SmtpTimeouts`). @@ -494,7 +495,11 @@ if (result.sent) { Password reset and e-mail verification go through Payload's built-in mechanism (`config.email`). With `mailAdapter()` wired they take the same transport as everything else; with the mail service they are sent as -account mail ("What a message is"). +account mail ("What a message is"). Payload sends them inside the operation's database transaction; `mailAdapter()` +sends them right **after** it commits instead (still in the same request; nothing when it is rolled back), so a slow +mail server holds no database connection — `mail: { accountMailAfterCommit: false }` keeps them inside +([deployment.md](./deployment.md) §4.3a). An e-mail adapter of your own does the same by calling +`sendAccountMailAfterCommit(message, () => send(message))` first. ## Masking secrets in the panel (MaskedField) diff --git a/reference/.agents/skills/iapl-debug/SKILL.md b/reference/.agents/skills/iapl-debug/SKILL.md index 43f3a13..00a78e7 100644 --- a/reference/.agents/skills/iapl-debug/SKILL.md +++ b/reference/.agents/skills/iapl-debug/SKILL.md @@ -121,7 +121,8 @@ through this procedure. Ask only when you are missing something you cannot get y | the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP | | start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` | | Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) | -| Postgres: requests are slow while a mail server hangs (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) | +| Postgres: requests are slow while a mail server hangs (logins and saves wait behind "forgot password") | the account mail is sent inside its transaction: `mail: { accountMailAfterCommit: false }`, `forms.emailsInTransaction: true`, or an e-mail adapter of your own that does not call `sendAccountMailAfterCommit` | remove the option / call it in your adapter; fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })` | +| Postgres: a project hook writes without `req` and the log row stays when its submission is rolled back | a Local API call without `req` is a transaction of its own (it no longer blocks the pool, but it is not rolled back with its caller) | pass `req` to every Local API call in a hook | | a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" | | old email sender | mail client cache | check the raw headers | | form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts | diff --git a/reference/.agents/skills/iapl-upgrade/SKILL.md b/reference/.agents/skills/iapl-upgrade/SKILL.md index ff8f799..50c4fe4 100644 --- a/reference/.agents/skills/iapl-upgrade/SKILL.md +++ b/reference/.agents/skills/iapl-upgrade/SKILL.md @@ -581,7 +581,9 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi 5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's "forgot password" are marked by the plugin. 6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of - 10; `connectionReserve`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`), + 10; `connectionReserve`; a transaction begun inside another one takes no place), form e-mails and Payload's + "forgot password" / "verify your e-mail" go out right after their transaction commits (`forms.emailsInTransaction`, + `mail.accountMailAfterCommit`), SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out". **Check:** `pnpm exec iapl-doctor --deep --url ` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` / diff --git a/src/index.ts b/src/index.ts index cea894f..79e6df4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -209,6 +209,7 @@ export type { SearchResult } from './modules/content/index.js' // Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool"). export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js' // Files on panel forms (forms.attachments): checked, e-mailed, never stored. +export { holdAccountMailFor, releaseAccountMailFor, sendAccountMailAfterCommit, withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js' export { mailAttachmentLimit } from './modules/email/attachmentLimit.js' export { graphAdapter } from './modules/email/graphAdapter.js' export type { GraphAdapterArgs } from './modules/email/graphAdapter.js' diff --git a/src/modules/database/transactions.ts b/src/modules/database/transactions.ts index 16eeac0..b499474 100644 --- a/src/modules/database/transactions.ts +++ b/src/modules/database/transactions.ts @@ -1,5 +1,7 @@ import type { BasePayload, PayloadRequest } from 'payload' +import { AsyncLocalStorage } from 'node:async_hooks' + /** * Transactions and the Postgres pool. * @@ -11,19 +13,31 @@ import type { BasePayload, PayloadRequest } from 'payload' * * `reserveConnections` keeps a few connections free of transactions: at most `pool size − reserve` * transactions are open at once, the next one waits for a free place (its request is slower, nothing - * stops). A transaction that has waited a second (ESCAPE_MS) may use the reserve too, all but its last - * connection — so a transaction begun inside another one (a hook that calls the Local API without `req`) - * does not wait for ever on its own caller, and one connection is never held by a transaction. + * stops). + * + * A transaction begun INSIDE another one — a hook that calls the Local API without `req` writes in a + * transaction of its own while its caller's stays open — is not queued: it takes no place and goes + * straight to the pool, because its caller cannot finish without it. "Inside" is told by an + * AsyncLocalStorage mark set when the outer one begins. In case the mark is lost on the way (Node 22 + * keeps such a mark per callback, not per operation), a queue that has not moved for a second + * (RESERVE_ESCAPE_MS) lets its NEWEST waiter — the one most likely begun by a waiting caller — use the + * reserve, all but the last connection. * * `afterCommit(req, fn)` runs `fn` right after the transaction of `req` commits, before the operation that * began it returns — for work that must not hold a connection, such as sending e-mail. */ type TransactionID = number | string -type Entry = { after: (() => Promise | void)[] } -type Waiter = { resolve: () => void; since: number } +type Entry = { after: (() => Promise | void)[]; depth: number; slot: boolean } +/** `depth`: 0 = an outer transaction, 1 = begun inside one, 2 = inside that, … */ +type Waiter = { depth: number; resolve: () => void; since: number } type Watch = { + /** Transactions holding one of the limited places. */ active: number + /** When a place was last given back (or the watch started). */ + moved: number + /** Transactions begun inside another one: no place, straight to the pool. */ + nested: number /** Open transactions begun through this watch, by id. */ open: Map queue: Waiter[] @@ -40,9 +54,12 @@ type WatchedDb = { } const WATCH = Symbol.for('iapl.transactionWatch') -/** After this long in the queue a transaction may use the reserve (all but one connection). */ +/** A queue that has not moved this long lets its newest waiter use the reserve (all but one connection). */ export const RESERVE_ESCAPE_MS = 1000 +/** The transaction the running code is inside: set in the caller's own continuation when it begins one. */ +const current = new AsyncLocalStorage<{ depth: number; id?: TransactionID }>() + const dbOf = (payload: BasePayload) => ((payload as { db?: unknown } | undefined)?.db ?? {}) as WatchedDb /** The size of the adapter's pool (pg's default is 10), or null for an adapter without one. */ @@ -58,22 +75,52 @@ export function defaultConnectionReserve(size: number): number { return size < 4 ? 1 : Math.max(2, Math.ceil(size / 5)) } -function drain(payload: BasePayload, watch: Watch): void { +const limitOf = (payload: BasePayload, watch: Watch) => { const size = poolSize(payload) ?? Infinity - const limit = watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve) - const escapeLimit = Math.max(limit, size - 1) + return { limit: watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve), size } +} + +/** How many transactions may be open in all when one begun at nesting `depth` (1 = inside an outer one) is let in. */ +const nestedRoom = (size: number, limit: number, depth: number) => Math.max(size - 2, limit) + depth + +function admit(watch: Watch, waiter: Waiter): void { + watch.queue.splice(watch.queue.indexOf(waiter), 1) + if (waiter.depth > 0) {watch.nested += 1} + else {watch.active += 1} + waiter.resolve() +} + +function drain(payload: BasePayload, watch: Watch): void { + const { limit, size } = limitOf(payload, watch) + // No reserve (switched off, or an adapter without a pool): nobody waits. + if (watch.reserve === null) { + while (watch.queue.length) {admit(watch, watch.queue[0])} + return + } + const open = () => watch.active + watch.nested + // A transaction begun inside another one first, the deepest first: its caller holds a place and waits for it. + // It may use the reserve but the last connection (a second level that one too; in a pool of 3 or 4, one place + // past the limit per level), so that a connection is left for the queries that run outside transactions. + for (const waiter of [...watch.queue].filter((w) => w.depth > 0).sort((a, b) => b.depth - a.depth)) { + if (open() < nestedRoom(size, limit, waiter.depth)) {admit(watch, waiter)} + } + // Then first come, first served while there is a place. + let head = watch.queue.find((w) => w.depth === 0) + while (head && watch.active < limit && open() < size - 1) { + admit(watch, head) + head = watch.queue.find((w) => w.depth === 0) + } + if (!watch.queue.length) {return} const now = Date.now() - // First come, first served; a waiter that has waited ESCAPE_MS may use the reserve but the last connection. - while (watch.queue.length) { - const waiter = watch.queue[0] - const room = now - waiter.since >= RESERVE_ESCAPE_MS ? escapeLimit : limit - if (watch.active >= room) {break} - watch.queue.shift() - watch.active += 1 - waiter.resolve() + // The queue has not moved for a second: the places may all be held by callers waiting for a transaction of + // their own whose mark was lost. The newest waiter may use the reserve, all but the last connection. + const oldest = Math.min(...watch.queue.map((w) => w.since)) + if (now - Math.max(watch.moved, oldest) >= RESERVE_ESCAPE_MS && open() < size - 1) { + admit(watch, watch.queue[watch.queue.length - 1]) + watch.moved = now } if (watch.queue.length && !watch.timer) { - const wait = Math.max(1, watch.queue[0].since + RESERVE_ESCAPE_MS - now) + const wait = Math.max(1, Math.max(watch.moved, oldest) + RESERVE_ESCAPE_MS - now) watch.timer = setTimeout(() => { watch.timer = undefined drain(payload, watch) @@ -82,17 +129,19 @@ function drain(payload: BasePayload, watch: Watch): void { } } -function acquire(payload: BasePayload, watch: Watch): Promise | undefined { +function acquire(payload: BasePayload, watch: Watch, depth: number): Promise | undefined { let resolve = () => {} const done = new Promise((r) => (resolve = r)) - const waiter: Waiter = { resolve: () => resolve(), since: Date.now() } + const waiter: Waiter = { depth, resolve: () => resolve(), since: Date.now() } watch.queue.push(waiter) drain(payload, watch) return watch.queue.includes(waiter) ? done : undefined } -function release(payload: BasePayload, watch: Watch): void { - watch.active = Math.max(0, watch.active - 1) +function release(payload: BasePayload, watch: Watch, slot = true): void { + if (slot) {watch.active = Math.max(0, watch.active - 1)} + else {watch.nested = Math.max(0, watch.nested - 1)} + watch.moved = Date.now() drain(payload, watch) } @@ -100,7 +149,7 @@ function finish(payload: BasePayload, watch: Watch, id: TransactionID): Entry | const entry = watch.open.get(id) if (!entry) {return undefined} watch.open.delete(id) - release(payload, watch) + release(payload, watch, entry.slot) return entry } @@ -119,29 +168,39 @@ export function watchTransactions(payload: BasePayload, reserve: false | number drain(payload, db[WATCH]) return db[WATCH] } - const watch: Watch = { active: 0, open: new Map(), queue: [], reserve: wanted } + const watch: Watch = { active: 0, moved: Date.now(), nested: 0, open: new Map(), queue: [], reserve: wanted } db[WATCH] = watch const begin = db.beginTransaction const commit = db.commitTransaction const rollback = db.rollbackTransaction - db.beginTransaction = async function (this: unknown, ...args: unknown[]) { - const waiting = acquire(payload, watch) - if (waiting) {await waiting} - let id: null | TransactionID - try { - id = await begin.apply(this, args) - } catch (err) { - release(payload, watch) - throw err - } - if (id === null || id === undefined) { - release(payload, watch) + // Not `async`: the mark must be set in the caller's own (synchronous) part, so that what the caller does + // next — its hooks, a Local API call without `req` — carries it. + db.beginTransaction = function (this: unknown, ...args: unknown[]) { + const outer = current.getStore() + const outerEntry = outer?.id !== undefined ? watch.open.get(outer.id) : undefined + const depth = outerEntry ? outerEntry.depth + 1 : 0 + const mark: { depth: number; id?: TransactionID } = { depth } + current.enterWith(mark) + return (async () => { + const waiting = acquire(payload, watch, depth) + if (waiting) {await waiting} + let id: null | TransactionID + try { + id = await begin.apply(this, args) + } catch (err) { + release(payload, watch, depth === 0) + throw err + } + if (id === null || id === undefined) { + release(payload, watch, depth === 0) + return id + } + mark.id = id + watch.open.set(id, { after: [], depth, slot: depth === 0 }) return id - } - watch.open.set(id, { after: [] }) - return id + })() } db.commitTransaction = async function (this: unknown, incoming) { @@ -221,7 +280,7 @@ export function transactionsBusy(payload: BasePayload): boolean { } /** For tests and diagnostics: open transactions, waiting ones and the reserve in force. */ -export function transactionWatchState(payload: BasePayload): { active: number; reserve: null | number; waiting: number } | null { +export function transactionWatchState(payload: BasePayload): { active: number; nested: number; reserve: null | number; waiting: number } | null { const watch = dbOf(payload)[WATCH] - return watch ? { active: watch.active, reserve: watch.reserve, waiting: watch.queue.length } : null + return watch ? { active: watch.active, nested: watch.nested, reserve: watch.reserve, waiting: watch.queue.length } : null } diff --git a/src/modules/email/accountMailAfterCommit.ts b/src/modules/email/accountMailAfterCommit.ts new file mode 100644 index 0000000..75d68b5 --- /dev/null +++ b/src/modules/email/accountMailAfterCommit.ts @@ -0,0 +1,93 @@ +import type { CollectionConfig, PayloadRequest } from 'payload' + +import { afterCommit, inWatchedTransaction } from '../database/transactions.js' +import { expectMailTo, takeExpectedMail } from './relay/kinds.js' +import { bareAddresses } from './relay/message.js' + +/** + * Payload sends "forgot password" and "verify your e-mail" INSIDE the operation's transaction, so a slow or + * hanging mail server holds the transaction — and its database connection — until the send gives up. With + * many such requests at once every place for a transaction is taken by requests that only wait for mail + * (docs/deployment.md §4.3a). + * + * This hook on an auth collection says, when such an operation starts inside a watched transaction, that the + * next message to that address belongs to it; `mailAdapter()` then sends that message right AFTER the + * transaction commits — still inside the same request, so the request ends when the mail is out, as before — + * and drops it when the transaction is rolled back (no token was stored, the link would not work). + * By address, like the account-mail mark (relay/kinds.ts): Payload passes nothing else to the adapter. + * Without a transaction (MongoDB without a replica set, SQLite) nothing changes. + * `iapl({ mail: { accountMailAfterCommit: false } })` = inside the transaction, as before. + */ + +const MARK = Symbol.for('iapl.accountMailAfterCommit') +type Pending = { req: PayloadRequest; until: number } +const pending = new Map() +// The mail follows its operation's hook within the same request. +const TTL_MS = 30_000 + +const keyOf = (address: string) => address.trim().toLowerCase() + +/** The message to `address` belongs to the transaction of `req` (when there is one to wait for). */ +export function holdAccountMailFor(address: string, req: PayloadRequest): void { + const key = keyOf(address) + if (!key || !inWatchedTransaction(req)) {return} + const now = Date.now() + if (pending.size > 1000) { + for (const [k, entry] of pending) { + if (entry.until <= now) {pending.delete(k)} + } + } + pending.set(key, { req, until: now + TTL_MS }) +} + +/** The operation ended without a mail to `address`: nothing is held for it any more. */ +export function releaseAccountMailFor(address: string): void { + pending.delete(keyOf(address)) +} + +/** + * For a transport: when this message is the account mail of an operation whose transaction is still open, + * schedules `send` for right after its commit and returns true (the caller sends nothing now). The kind the + * relay transport was told for the address (`account`, with the visitor) is carried over to that send. + */ +export function sendAccountMailAfterCommit(message: { to?: unknown }, send: () => Promise): boolean { + const { addresses } = bareAddresses(message.to) + if (addresses.length !== 1) {return false} + const key = keyOf(addresses[0]) + const entry = pending.get(key) + if (!entry) {return false} + pending.delete(key) + if (entry.until <= Date.now()) {return false} + const expected = takeExpectedMail(addresses) + return afterCommit(entry.req, async () => { + if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })} + await send() + }) +} + +type OperationArgs = { args?: { data?: { email?: unknown }; req?: PayloadRequest }; operation: string; req?: PayloadRequest; result?: unknown } + +/** + * Adds the hook to an auth collection (idempotent): `forgotPassword` always, `create` where the collection + * verifies e-mail addresses. + */ +export function withAccountMailAfterCommit(collection: CollectionConfig): CollectionConfig { + const hooks = collection.hooks?.beforeOperation ?? [] + if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection} + const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify) + const applies = (operation: string) => operation === 'forgotPassword' || (verifies && operation === 'create') + const hold = ((args: OperationArgs) => { + const email = args.args?.data?.email + const req = args.req ?? args.args?.req + if (applies(args.operation) && typeof email === 'string' && req) {holdAccountMailFor(email, req)} + return args.args + }) as unknown as { [MARK]?: boolean } & NonNullable['beforeOperation']>[number] + hold[MARK] = true + // Ran without a mail (no such account, Payload's interval between two requests): forget the address. + const done = ((args: OperationArgs) => { + const email = args.args?.data?.email + if (applies(args.operation) && typeof email === 'string') {releaseAccountMailFor(email)} + return args.result + }) as unknown as NonNullable['afterOperation']>[number] + return { ...collection, hooks: { ...collection.hooks, afterOperation: [...(collection.hooks?.afterOperation ?? []), done], beforeOperation: [...hooks, hold] } } +} diff --git a/src/modules/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index d0d2064..bcb62d4 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -2,6 +2,7 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js' import { getSiteIntegrations } from '../payload/index.js' +import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js' import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js' import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js' import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js' @@ -153,6 +154,14 @@ export const mailAdapter = defaultFromName: smtp.defaultFromName, sendEmail: async (message: SendEmailOptions) => { + // Payload's "forgot password" / "verify your e-mail" inside a transaction: sent right after it commits + // (accountMailAfterCommit.ts), so a slow mail server holds no database connection. + if (sendAccountMailAfterCommit(message, () => send(message))) {return { deferred: true }} + return send(message) + }, + } + + async function send(message: SendEmailOptions): Promise { const settings = await getSiteIntegrations(payload) const choice = settings.emailTransport ?? 'smtp' const previous = settings[STATUS_FIELD] @@ -241,6 +250,5 @@ export const mailAdapter = : { state: 'ok' }, ) return result - }, } } diff --git a/src/plugin.ts b/src/plugin.ts index 54d8855..160884a 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -32,6 +32,7 @@ import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' import { defaultConnectionReserve, poolSize, watchTransactions } from './modules/database/transactions.js' import { buildDoctorEndpoint } from './modules/doctor/status.js' +import { withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js' import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js' import { withAccountMailMark } from './modules/email/relay/accountMail.js' import { relayConfirmEndpoint } from './modules/email/relay/confirm.js' @@ -757,6 +758,11 @@ export const iapl = (options: IaplOptions): Plugin => { ...config.custom, iapl: { ...iaplCustom, mail: { ...(options.mail?.graphDeprecationWarning === false ? { graphDeprecationWarning: false } : {}), relay: relay === false ? false : (relay ?? {}) } }, } + // "Forgot password" and "verify your e-mail" through mailAdapter(): sent right after their transaction + // commits, not inside it (mail.accountMailAfterCommit; docs/deployment.md §4.3a). + if (options.mail?.accountMailAfterCommit !== false) { + config.collections = (config.collections ?? []).map((c) => (c.auth ? withAccountMailAfterCommit(c) : c)) + } if (relay !== false) { // The public route the service calls a site back at (404 unless this site just started an // enrolment), and the admin-only routes of the state block on the e-mail tab. diff --git a/src/types.ts b/src/types.ts index ad41aa1..9d111a4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -468,6 +468,14 @@ export type ThemeOptions = { export type IpalOptions = IaplOptions export type MailOptions = { + /** + * Payload's "forgot password" and "verify your e-mail", sent through `mailAdapter()`: right AFTER the + * operation's transaction commits (still in the same request), so a slow mail server holds no database + * connection; nothing is sent when the transaction is rolled back. Default true; `false` = inside the + * transaction, as before 1.17.0. No transactions (MongoDB without a replica set, SQLite): no change. + * docs/deployment.md §4.3a. + */ + accountMailAfterCommit?: boolean /** `false` silences the one warning per process start of a site on Microsoft Graph (deprecated, removed in 2.0). */ graphDeprecationWarning?: boolean /** The Intecion Notifications Webservice. Default on; `false` switches it off. */ diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index e71597a..653ef96 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -33,7 +33,8 @@ import { totp } from './http/totp.js' * A `beforeOperation` hook of the account rules. Every auth collection also carries the mark that tells the mail * service what Payload's own account mail is (modules/email/relay/accountMail.ts): that one is not counted here. */ -const ruleHook = (hook: unknown) => !(hook as Record)[Symbol.for('iapl.accountMailMark')] +// the account-mail hooks (the relay's kind mark, the after-commit hold) are not account rules +const ruleHook = (hook: unknown) => !(hook as Record)[Symbol.for('iapl.accountMailMark')] && !(hook as Record)[Symbol.for('iapl.accountMailAfterCommit')] const TOTP_SECRET = 'JBSWY3DPEHPK3PXP' diff --git a/test/transactionPool.test.ts b/test/transactionPool.test.ts index 82fbecc..0782a76 100644 --- a/test/transactionPool.test.ts +++ b/test/transactionPool.test.ts @@ -12,6 +12,7 @@ */ import type { BasePayload, Payload } from 'payload' +import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.js' @@ -48,26 +49,27 @@ function fakePayload({ max = 5, pool = true, transactions = true }: { max?: numb } const tick = () => new Promise((resolve) => setTimeout(resolve, 0)) +/** Runs a function in the context this file started in (before any transaction mark). */ +const root = AsyncLocalStorage.snapshot() describe('the watch (fake adapter)', () => { test('the default reserve: a fifth of the pool, at least 2; 1 in a pool of fewer than 4', () => { expect([1, 2, 3, 4, 5, 10, 11, 20, 50].map(defaultConnectionReserve)).toEqual([1, 1, 1, 2, 2, 2, 3, 4, 10]) }) + // Each call runs in a context of its own that starts from the file's (no transaction mark), as two unrelated + // requests do: Node 22 keeps an AsyncLocalStorage mark per callback, which siblings started together share. + const apart = (fn: () => T): T => root(() => new AsyncResource('iapl-test-operation').runInAsyncScope(fn)) + test('at most pool size − reserve transactions are open; the next waits for a commit', async () => { const { db, payload } = fakePayload({ max: 5 }) watchTransactions(payload) - // each from its own operation, as Payload calls it (initTransaction inside the operation) - const open = async () => { - await tick() - return db.beginTransaction() - } - const ids = await Promise.all([open(), open(), open()]) + const ids = await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())]) let fourth: null | string = null - void open().then((id) => (fourth = id)) + void apart(() => db.beginTransaction()).then((id) => (fourth = id)) await tick() expect(fourth).toBeNull() - expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 2, waiting: 1 }) + expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 2, waiting: 1 }) await db.commitTransaction(ids[0]!) await tick() expect(fourth).toBe('t4') @@ -75,42 +77,64 @@ describe('the watch (fake adapter)', () => { expect(transactionWatchState(payload)).toMatchObject({ active: 2, waiting: 0 }) }) - test('a transaction begun inside another one gets a place in the reserve after a second, so it never waits for ever on its caller', async () => { - const { db, payload } = fakePayload({ max: 5 }) // limit 3; after a second in the queue, up to 4 + /** An operation whose hook calls the Local API without `req`: `levels` transactions, each inside the last. */ + const nestedOperation = (db: FakeDb, levels = 2, lost = false) => + apart(async () => { + const ids: string[] = [] + for (let level = 0; level < levels; level++) { + await tick() + // `lost`: the inner one begins where the mark does not reach (the backstop must still move the queue) + ids.push((await (lost && level > 0 ? apart(() => db.beginTransaction()) : db.beginTransaction()))!) + } + for (const id of ids.reverse()) {await db.commitTransaction(id)} + }) + const finishes = (all: Promise, ms = 8000) => Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), ms))]) + + for (const [max, count] of [[10, 9], [10, 10], [10, 12], [10, 30], [5, 8], [3, 6]] as const) { + test(`pool ${max}: ${count} transactions at once, each with one begun inside it, finish at once (no place for the inner one)`, async () => { + const { db, payload } = fakePayload({ max }) + watchTransactions(payload) + const start = Date.now() + expect(await finishes(Promise.all(Array.from({ length: count }, () => nestedOperation(db))))).toBe('done') + expect(Date.now() - start).toBeLessThan(500) + expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 }) + }) + } + + test('two levels inside one another: 12 operations at once in a pool of 10 finish', async () => { + const { db, payload } = fakePayload({ max: 10 }) watchTransactions(payload) - // Each operation opens a transaction and, inside it, a second one (a hook calling the Local API without - // `req`). Three outers fill the limit; without the escape every inner would wait for ever. - const operation = async () => { - await tick() - const outer = (await db.beginTransaction())! - await tick() - const inner = (await db.beginTransaction())! - await db.commitTransaction(inner) - await db.commitTransaction(outer) - } - const start = Date.now() - const all = Promise.all([operation(), operation(), operation()]) - const done = await Promise.race([all.then(() => 'done'), new Promise((resolve) => setTimeout(() => resolve('stuck'), 4000))]) - expect(done).toBe('done') - expect(Date.now() - start).toBeGreaterThanOrEqual(900) - expect(transactionWatchState(payload)).toMatchObject({ active: 0, waiting: 0 }) + expect(await finishes(Promise.all(Array.from({ length: 12 }, () => nestedOperation(db, 3))))).toBe('done') }) - test('the escape leaves one connection that no transaction holds', async () => { - const { db, payload } = fakePayload({ max: 4 }) // reserve 2, limit 2, escape up to 3 + test('the inner ones never take the last connection: one stays free for the queries outside transactions', async () => { + const { db, payload } = fakePayload({ max: 10 }) watchTransactions(payload) - const open = async () => { - await tick() - return db.beginTransaction() - } - await Promise.all([open(), open()]) + let most = 0 + const watchOpen = setInterval(() => { + const state = transactionWatchState(payload)! + most = Math.max(most, state.active + state.nested) + }, 0) + await Promise.all(Array.from({ length: 30 }, () => nestedOperation(db))) + clearInterval(watchOpen) + expect(most).toBeLessThanOrEqual(9) + }) + + test('the mark is lost on the way: the queue still moves (its newest waiter after a second), and one connection stays free', async () => { + const { db, payload } = fakePayload({ max: 5 }) // limit 3; the newest waiter may take the 4th place, never the 5th + watchTransactions(payload) + const start = Date.now() + expect(await finishes(Promise.all(Array.from({ length: 4 }, () => nestedOperation(db, 2, true))), 10_000)).toBe('done') + expect(Date.now() - start).toBeGreaterThanOrEqual(900) + expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 }) + + await Promise.all([apart(() => db.beginTransaction()), apart(() => db.beginTransaction()), apart(() => db.beginTransaction())]) const later: (null | string)[] = [] - void open().then((id) => later.push(id)) - void open().then((id) => later.push(id)) + for (let i = 0; i < 3; i++) {void apart(() => db.beginTransaction()).then((id) => later.push(id))} await new Promise((resolve) => setTimeout(resolve, 1300)) expect(later).toHaveLength(1) - expect(transactionWatchState(payload)).toMatchObject({ active: 3, waiting: 1 }) - }) + expect(transactionWatchState(payload)).toMatchObject({ active: 4, waiting: 2 }) + }, 15_000) test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => { const { db, events, logger, payload } = fakePayload() @@ -156,7 +180,7 @@ describe('the watch (fake adapter)', () => { watchTransactions(payload, reserve) const db = payload.db as unknown as FakeDb const ids = await Promise.all(Array.from({ length: 12 }, () => db.beginTransaction())) - expect(transactionWatchState(payload)).toEqual({ active: 12, reserve: null, waiting: 0 }) + expect(transactionWatchState(payload)).toEqual({ active: 12, nested: 0, reserve: null, waiting: 0 }) expect(afterCommit({ payload, transactionID: ids[0]! }, () => {})).toBe(true) } }) @@ -174,7 +198,7 @@ describe('the watch (fake adapter)', () => { watchTransactions(payload, 7) expect(db.beginTransaction).toBe(begin) await Promise.all([db.beginTransaction(), db.beginTransaction(), db.beginTransaction()]) - expect(transactionWatchState(payload)).toEqual({ active: 3, reserve: 7, waiting: 0 }) + expect(transactionWatchState(payload)).toEqual({ active: 3, nested: 0, reserve: 7, waiting: 0 }) }) }) @@ -266,6 +290,20 @@ describe.runIf(POSTGRES)('Postgres, default pool of 10', () => { expect(Date.now() - start).toBeLessThan(30_000) }, 90_000) + for (const count of [9, 12, 30]) { + test(`${count} submissions at once whose hook writes WITHOUT req (a transaction inside the submission's) finish; an ordinary request answers after`, async () => { + await useSmtpPort(9) + const before = (await payload.count({ collection: 'log' as never })).totalDocs + const all = Promise.all(Array.from({ length: count }, (_, i) => submit(300 + count * 10 + i, `nested-${count}-${i}`))) + const results = await within(all, 20_000, 'stuck' as const) + expect(results).not.toBe('stuck') + expect((results as { success: boolean }[]).every((r) => r.success)).toBe(true) + expect((await payload.count({ collection: 'log' as never })).totalDocs - before).toBe(count) + expect(await ordinaryRequest()).toBeLessThan(2000) + expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 }) + }, 40_000) + } + test('form e-mails go out after the commit: the stored submission is visible to the send; a rolled-back one sends nothing', async () => { await useSmtpPort(9) const send = vi.spyOn(payload, 'sendEmail') diff --git a/test/transactionPoolRelay.test.ts b/test/transactionPoolRelay.test.ts new file mode 100644 index 0000000..9d1e137 --- /dev/null +++ b/test/transactionPoolRelay.test.ts @@ -0,0 +1,166 @@ +/** + * Transactions and the Postgres pool with the Intecion mail service as the transport, the service hanging: + * it takes every request and never answers (each send gives up after its budget). Postgres only + * (IPAL_TEST_POSTGRES_URI); its own file because one test process pushes the schema of one Payload. + * - 30 "forgot password" + 30 submissions at once finish within about one send budget: the reset mail goes out + * after its transaction commits (mail.accountMailAfterCommit), so no request waits for a place behind it; + * - a file on a form whose e-mail is "not confirmed" after the commit: the visitor gets `unconfirmed`, the + * submission is stored; + * - a submission created inside the caller's own transaction that is rolled back sends nothing. + */ +import type { Payload } from 'payload' + +import { lexicalEditor } from '@payloadcms/richtext-lexical' +import os from 'node:os' +import path from 'node:path' +import { createLocalReq, getPayload } from 'payload' +import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' + +import { transactionWatchState } from '../src/modules/database/transactions.js' +import { mailAdapter } from '../src/modules/email/mailAdapter.js' +import { submitForm } from '../src/modules/forms/submitForm.js' +import { iapl } from '../src/plugin.js' +import { buildTestConfig } from './helpers.js' +import { testDatabase } from './http/db.js' +import { startPayloadServer, type TestServer } from './http/server.js' + +vi.mock('server-only', () => ({})) + +const text = (value: string) => ({ + root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', text: value, version: 1 }], direction: null, format: '', indent: 0, version: 1 }], direction: null, format: '', indent: 0, version: 1 }, +}) +const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n'), Buffer.alloc(4000, 0x20)]) +const within = (promise: Promise, ms: number, fallback: F) => Promise.race([promise, new Promise((resolve) => setTimeout(() => resolve(fallback), ms))]) + +/** The service: takes the request and never answers (the client aborts it at its time-out). */ +let calls = 0 +const hanging: typeof fetch = (_url, init) => { + calls += 1 + return new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))) +} + +const N = 30 +const ACCOUNTS = Array.from({ length: N }, (_, i) => `relay-account${i}@example.com`) +const BUDGET_MS = 3000 + +describe.runIf(Boolean(process.env.IPAL_TEST_POSTGRES_URI))('Postgres, the mail service hanging', () => { + let payload: Payload + let server: TestServer + let formId: string + let fileFormId: string + + beforeAll(async () => { + payload = await getPayload({ + config: buildTestConfig({ + admin: { user: 'users' }, + collections: [ + { slug: 'users', auth: true, fields: [] }, + { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-test-pool-relay-media') } }, + { slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + ], + db: testDatabase('txrelay'), + editor: lexicalEditor(), + email: mailAdapter(), + plugins: [ + iapl({ + access: { authCollection: 'users' }, + forms: { attachments: { maxConcurrent: 0 } }, + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, + // a token from the deployment: no enrolment, every send goes to /v1/send and hangs there + mail: { relay: { fetchImpl: hanging, timeoutMs: BUDGET_MS, token: `ims_${'a'.repeat(43)}`, totalTimeoutMs: BUDGET_MS, url: 'http://relay.test' } }, + twoFactor: false, + }), + ], + secret: 'transaction-pool-relay-secret-0123456789', + serverURL: 'https://client-pool.example.com', + telemetry: false, + }), + }) + await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: 'office@client-pool.example.com' } as never }) + const emails = [{ emailTo: 'office@client-pool.example.com', message: text('{{message}}'), subject: 'New message' }] + formId = String( + (await payload.create({ collection: 'forms' as never, data: { confirmationMessage: text('ok'), confirmationType: 'message', emails, fields: [{ name: 'message', blockType: 'text', label: 'Message', required: true }], title: 'Contact' } as never })).id, + ) + fileFormId = String( + ( + await payload.create({ + collection: 'forms' as never, + data: { + confirmationMessage: text('ok'), + confirmationType: 'message', + emails, + fields: [ + { name: 'message', blockType: 'text', label: 'Message', required: true }, + { name: 'cv', allowedTypes: ['pdf'], blockType: 'file', label: 'CV', maxFiles: 1, maxSizeMB: 1 }, + ], + title: 'Careers', + } as never, + }) + ).id, + ) + for (const email of ACCOUNTS) { + await payload.create({ collection: 'users' as never, data: { email, password: 'Correct-horse-battery-9' } as never, disableVerificationEmail: true }) + } + server = await startPayloadServer(Promise.resolve(payload.config)) + }, 180_000) + + afterAll(async () => { + await server?.close() + await payload?.destroy() + }) + + test(`${N} "forgot password" + ${N} submissions at once finish within about one send budget; an ordinary request answers`, async () => { + const start = Date.now() + const resets = Promise.all( + ACCOUNTS.map((email) => + fetch(`${server.url}/api/users/forgot-password`, { body: JSON.stringify({ email }), headers: { 'Content-Type': 'application/json' }, method: 'POST' }).then((r) => [r.status, Date.now() - start] as const), + ), + ) + const submissions = Promise.all( + Array.from({ length: N }, (_, i) => submitForm({ data: { message: `m${i}` }, formId, ip: `10.7.0.${i}`, maxPerMinute: 0, payload }).then((r) => [r.success, Date.now() - start] as const)), + ) + await new Promise((resolve) => setTimeout(resolve, 500)) + const ordinary = Date.now() + expect(await within(fetch(`${server.url}/api/pages`).then((r) => r.status), 8000, 'no answer')).toBe(200) + expect(Date.now() - ordinary).toBeLessThan(2000) + // the reset transactions commit at once and give their places back; the mail waits outside them + const both = await within(Promise.all([resets, submissions]), 60_000, 'stuck' as const) + expect(both).not.toBe('stuck') + const [r, s] = both as [(readonly [number, number])[], (readonly [boolean, number])[]] + expect(r.every(([status]) => status === 200)).toBe(true) + expect(s.every(([ok]) => ok)).toBe(true) + // Before (inside the transaction, eight at a time): about four budgets. Now about one. + expect(Math.max(...r.map(([, ms]) => ms), ...s.map(([, ms]) => ms))).toBeLessThan(BUDGET_MS * 2.5) + expect(calls).toBeGreaterThan(0) + expect(transactionWatchState(payload)).toMatchObject({ active: 0, nested: 0, waiting: 0 }) + }, 90_000) + + test('a file whose e-mail is not confirmed after the commit: the visitor gets `unconfirmed`, the submission is stored', async () => { + const result = await submitForm({ data: { message: 'with a file' }, files: { cv: [{ name: 'cv.pdf', data: PDF }] }, formId: fileFormId, ip: '10.7.1.1', maxPerMinute: 0, payload }) + expect(result).toMatchObject({ field: 'cv', file: 'cv.pdf', reason: 'delivery', success: false, unconfirmed: true }) + const stored = (await payload.findByID({ id: (result as { submissionId: number | string }).submissionId, collection: 'form-submissions' as never, depth: 0 })) as { filesDelivery?: string; filesDeliveryNote?: string } + expect(stored.filesDelivery).toBe('failed') + expect(stored.filesDeliveryNote).toMatch(/not confirmed/i) + }, 30_000) + + test('a submission created inside the caller\'s own transaction that is rolled back sends nothing', async () => { + const send = vi.spyOn(payload, 'sendEmail').mockResolvedValue({ sent: true }) + try { + const req = (await createLocalReq({}, payload)) + req.transactionID = (await payload.db.beginTransaction())! + await payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [{ field: 'message', value: 'outer-rolled-back' }] } as never, req }) + expect(send).not.toHaveBeenCalled() // composed, waiting for the caller's commit + await payload.db.rollbackTransaction(req.transactionID) + expect(send).not.toHaveBeenCalled() + + const committed = (await createLocalReq({}, payload)) + committed.transactionID = (await payload.db.beginTransaction())! + await payload.create({ collection: 'form-submissions' as never, data: { form: formId, submissionData: [{ field: 'message', value: 'outer-committed' }] } as never, req: committed }) + expect(send).not.toHaveBeenCalled() + await payload.db.commitTransaction(committed.transactionID) + expect(send).toHaveBeenCalledTimes(1) + } finally { + send.mockRestore() + } + }) +}) diff --git a/test/transactionPoolSite.ts b/test/transactionPoolSite.ts index 6ca5e07..3a640ac 100644 --- a/test/transactionPoolSite.ts +++ b/test/transactionPoolSite.ts @@ -39,6 +39,7 @@ export async function site(name: string, { emailsInTransaction = false } = {}) { { slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-test-pool-media') } }, { slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }, + { slug: 'log', fields: [{ name: 'note', type: 'text' }] }, ], db: testDatabase(name), editor: lexicalEditor(), @@ -52,9 +53,19 @@ export async function site(name: string, { emailsInTransaction = false } = {}) { formSubmissionOverrides: { hooks: { // a later hook that fails: the submission is rolled back - afterChange: [({ doc }) => { - if ((doc as { submissionData?: { value?: string }[] }).submissionData?.some((row) => row.value === 'roll-me-back')) {throw new Error('rolled back on purpose')} - }], + afterChange: [ + ({ doc }) => { + if ((doc as { submissionData?: { value?: string }[] }).submissionData?.some((row) => row.value === 'roll-me-back')) {throw new Error('rolled back on purpose')} + }, + // a project's hook that writes through the Local API WITHOUT `req`: a transaction of its own, + // begun while the submission's is still open + async ({ doc, req }) => { + const rows = (doc as { id: number | string; submissionData?: { value?: string }[] }).submissionData ?? [] + if (!rows.some((row) => row.value?.startsWith('nested-'))) {return} + await new Promise((resolve) => setTimeout(resolve, 50)) + await req.payload.create({ collection: 'log' as never, data: { note: `submission ${doc.id}` } as never }) + }, + ], }, }, }, From 919953e65ef724e1eb56286a4fee61be3fd155c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 26 Nov 2026 01:36:17 +0100 Subject: [PATCH 3/3] Account mail after commit: matched by its token, not by the address (P-4) holdAccountMailFor bound the next message to an address to whichever request held it: two resets for one account at once could lose the first one's mail on the second's rollback, and a form's mail to that address was deferred to the reset's transaction. Payload calls generateEmailSubject({ req, token, user }) right before it sends the reset or verify mail, and the mail carries that token. The plugin now wraps that function on every auth collection (a project's own one is kept, Payload's subject otherwise) and holds the token for the request's transaction; mailAdapter defers only a message to that account alone whose body contains a held token. An AsyncLocalStorage mark set in a beforeOperation hook was not used: Payload awaits the hook, and a mark set inside it does not reach the send (relay/kinds.ts says the same). Building blocks renamed with it: holdAccountMail(token, address, req), releaseAccountMail(token). Both review rows are tests. Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 7 +- docs/agent/AGENT.md | 2 +- docs/deployment.md | 7 +- docs/email.md | 5 +- src/index.ts | 2 +- src/modules/email/accountMailAfterCommit.ts | 125 +++++++++++--------- test/plugin.test.ts | 3 +- test/transactionPool.test.ts | 67 ++++++++++- 8 files changed, 151 insertions(+), 67 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index fb3df2b..ec963e4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -146,10 +146,11 @@ once there are more than 20. `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a, with the measured table). - **Payload's "forgot password" and "verify your e-mail" go out after their transaction commits** when sent through - `mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). With the mail + `mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). The message is + matched to its request by its token (Payload's `generateEmailSubject` is wrapped; a project's own one is kept). With the mail service hanging, 30 resets and 30 submissions at once finish in about one send budget (11 s) instead of 43.5 s. - Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMailFor`, - `releaseAccountMailFor`. + Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMail`, + `releaseAccountMail`. - **Form e-mails go out after the submission's transaction commits** — same request, same answer to the visitor (a file that could not be sent is still reported). A submission rolled back by a later hook now sends nothing; a send that fails after the commit leaves the submission stored (as a failed e-mail always did). Sites without diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 5ea1e04..fdd3883 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1247,7 +1247,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` | | Microsoft Graph as transport: deprecated, one warning per start, removed in 2.0 | `mail: { graphDeprecationWarning: false }` (the warning only) | move off it: email.md "Moving off Microsoft Graph" | | Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; a transaction begun inside another one (a hook without `req`) takes no place and goes at once, but never the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: `; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) | -| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMailFor`, `releaseAccountMailFor` (email.md "Payload system mail") | +| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMail`, `releaseAccountMail` (email.md "Payload system mail") | | Form e-mails go out right after the submission's transaction commits (same request, same answer); a rolled-back submission sends nothing; a send that fails after the commit leaves the submission stored. No transactions (MongoDB without a replica set, SQLite): at once, as before | `forms: { emailsInTransaction: true }` | `sendAfterCommit(prepare, deliver)`, `sendFormEmails(req, emails)`, `afterCommit(req, fn)` (forms.md "When e-mails go out") | | SMTP time-outs: 10 s to connect, 30 s greeting, 60 s silence | — | `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })`, `panelSmtpAdapter({ timeouts })`; `SMTP_TIMEOUT_DEFAULTS`, type `SmtpTimeouts` (email.md "SMTP") | diff --git a/docs/deployment.md b/docs/deployment.md index 4fdff7e..378f7e1 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -398,9 +398,10 @@ Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnecti Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route: `{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail -`withAccountMailAfterCommit(collection)` (the hook the plugin puts on every auth collection), -`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMailFor`, -`releaseAccountMailFor`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled +`withAccountMailAfterCommit(collection)` (what the plugin does to every auth collection: wraps its +`generateEmailSubject`, which Payload calls with the request and the token right before the send), +`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMail`, +`releaseAccountMail`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled back with its caller's. Pass `req`. **Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different diff --git a/docs/email.md b/docs/email.md index 3cc2885..fcf7b3c 100644 --- a/docs/email.md +++ b/docs/email.md @@ -498,7 +498,10 @@ Password reset and e-mail verification go through Payload's built-in mechanism ( account mail ("What a message is"). Payload sends them inside the operation's database transaction; `mailAdapter()` sends them right **after** it commits instead (still in the same request; nothing when it is rolled back), so a slow mail server holds no database connection — `mail: { accountMailAfterCommit: false }` keeps them inside -([deployment.md](./deployment.md) §4.3a). An e-mail adapter of your own does the same by calling +([deployment.md](./deployment.md) §4.3a). The message is matched to its request by the token it carries (and the +account's address), never by the address alone: a form's mail to the same address goes out as usual. A project's own +`forgotPassword.generateEmailSubject` / `verify.generateEmailSubject` is kept; an own `generateEmailHTML` must put the +token in the body (any working reset link does), or that mail is sent inside the transaction as before. An e-mail adapter of your own does the same by calling `sendAccountMailAfterCommit(message, () => send(message))` first. ## Masking secrets in the panel (MaskedField) diff --git a/src/index.ts b/src/index.ts index 79e6df4..d786451 100644 --- a/src/index.ts +++ b/src/index.ts @@ -209,7 +209,7 @@ export type { SearchResult } from './modules/content/index.js' // Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool"). export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js' // Files on panel forms (forms.attachments): checked, e-mailed, never stored. -export { holdAccountMailFor, releaseAccountMailFor, sendAccountMailAfterCommit, withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js' +export { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js' export { mailAttachmentLimit } from './modules/email/attachmentLimit.js' export { graphAdapter } from './modules/email/graphAdapter.js' export type { GraphAdapterArgs } from './modules/email/graphAdapter.js' diff --git a/src/modules/email/accountMailAfterCommit.ts b/src/modules/email/accountMailAfterCommit.ts index 75d68b5..6c77a49 100644 --- a/src/modules/email/accountMailAfterCommit.ts +++ b/src/modules/email/accountMailAfterCommit.ts @@ -10,84 +10,97 @@ import { bareAddresses } from './relay/message.js' * many such requests at once every place for a transaction is taken by requests that only wait for mail * (docs/deployment.md §4.3a). * - * This hook on an auth collection says, when such an operation starts inside a watched transaction, that the - * next message to that address belongs to it; `mailAdapter()` then sends that message right AFTER the - * transaction commits — still inside the same request, so the request ends when the mail is out, as before — - * and drops it when the transaction is rolled back (no token was stored, the link would not work). - * By address, like the account-mail mark (relay/kinds.ts): Payload passes nothing else to the adapter. - * Without a transaction (MongoDB without a replica set, SQLite) nothing changes. + * Payload calls the collection's `generateEmailSubject({ req, token, user })` right before it sends that mail, + * and the mail carries the same token (in its link). The wrapper below holds the token for the transaction of + * that `req`; `mailAdapter()` sends the message whose body contains a held token right AFTER that transaction + * commits — still inside the same request, so the request ends when the mail is out, as before — and drops it + * when the transaction is rolled back (the token was not stored, the link would not work). + * Matched by the token (and the account's address as a second check), never by the address alone: two + * requests for one account at once, or a form's mail to the same address, are each their own message. + * A project's own `generateEmailSubject` is kept and called; without one the subject is Payload's own. + * Without a transaction (MongoDB without a replica set, SQLite) nothing changes; a message without a held + * token (a project's own e-mail template that leaves the token out) is sent at once, as before. * `iapl({ mail: { accountMailAfterCommit: false } })` = inside the transaction, as before. */ const MARK = Symbol.for('iapl.accountMailAfterCommit') -type Pending = { req: PayloadRequest; until: number } -const pending = new Map() -// The mail follows its operation's hook within the same request. +type Held = { address: string; req: PayloadRequest; until: number } +const held = new Map() +// Payload sends the mail right after it composed the subject, within the same request. const TTL_MS = 30_000 +// Payload's tokens are 40 hexadecimal characters; a shorter one could be found in an unrelated message. +const MIN_TOKEN = 16 const keyOf = (address: string) => address.trim().toLowerCase() -/** The message to `address` belongs to the transaction of `req` (when there is one to wait for). */ -export function holdAccountMailFor(address: string, req: PayloadRequest): void { - const key = keyOf(address) - if (!key || !inWatchedTransaction(req)) {return} +/** The message that carries `token` (to `address`) belongs to the transaction of `req`, when there is one to wait for. */ +export function holdAccountMail(token: string, address: string, req: PayloadRequest): void { + if (typeof token !== 'string' || token.length < MIN_TOKEN || !inWatchedTransaction(req)) {return} const now = Date.now() - if (pending.size > 1000) { - for (const [k, entry] of pending) { - if (entry.until <= now) {pending.delete(k)} - } + for (const [k, entry] of held) { + if (entry.until <= now) {held.delete(k)} } - pending.set(key, { req, until: now + TTL_MS }) + held.set(token, { address: keyOf(address), req, until: now + TTL_MS }) } -/** The operation ended without a mail to `address`: nothing is held for it any more. */ -export function releaseAccountMailFor(address: string): void { - pending.delete(keyOf(address)) +/** Nothing is held for `token` any more. */ +export function releaseAccountMail(token: string): void { + held.delete(token) } +const bodyOf = (message: { html?: unknown; text?: unknown }) => `${typeof message.html === 'string' ? message.html : ''}\n${typeof message.text === 'string' ? message.text : ''}` + /** - * For a transport: when this message is the account mail of an operation whose transaction is still open, - * schedules `send` for right after its commit and returns true (the caller sends nothing now). The kind the - * relay transport was told for the address (`account`, with the visitor) is carried over to that send. + * For a transport: when this message carries the token of an account operation whose transaction is still + * open, and goes to that account's address alone, schedules `send` for right after the commit and returns + * true (the caller sends nothing now). The kind the relay transport was told for the address (`account`, with + * the visitor) is carried over to that send. */ -export function sendAccountMailAfterCommit(message: { to?: unknown }, send: () => Promise): boolean { +export function sendAccountMailAfterCommit(message: { html?: unknown; text?: unknown; to?: unknown }, send: () => Promise): boolean { + if (!held.size) {return false} const { addresses } = bareAddresses(message.to) if (addresses.length !== 1) {return false} - const key = keyOf(addresses[0]) - const entry = pending.get(key) - if (!entry) {return false} - pending.delete(key) - if (entry.until <= Date.now()) {return false} - const expected = takeExpectedMail(addresses) - return afterCommit(entry.req, async () => { - if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })} - await send() - }) + const body = bodyOf(message) + const now = Date.now() + for (const [token, entry] of held) { + if (entry.until <= now || entry.address !== keyOf(addresses[0]) || !body.includes(token)) {continue} + held.delete(token) + const expected = takeExpectedMail(addresses) + return afterCommit(entry.req, async () => { + if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })} + await send() + }) + } + return false } -type OperationArgs = { args?: { data?: { email?: unknown }; req?: PayloadRequest }; operation: string; req?: PayloadRequest; result?: unknown } +type SubjectArgs = { req: PayloadRequest; token: string; user: { email?: unknown } } +type SubjectFn = ((args: SubjectArgs) => Promise | string) & { [MARK]?: boolean } + +function holdingSubject(own: SubjectFn | undefined, fallback: string): SubjectFn { + if (own?.[MARK]) {return own} + const fn: SubjectFn = async (args) => { + const subject = own ? await own(args) : args.req.t(fallback as never) + if (typeof args.user?.email === 'string') {holdAccountMail(args.token, args.user.email, args.req)} + return subject + } + fn[MARK] = true + return fn +} /** - * Adds the hook to an auth collection (idempotent): `forgotPassword` always, `create` where the collection - * verifies e-mail addresses. + * Wraps an auth collection's `forgotPassword.generateEmailSubject`, and `verify.generateEmailSubject` where it + * verifies e-mail addresses (idempotent). Payload's own subjects stay when the collection has none. */ export function withAccountMailAfterCommit(collection: CollectionConfig): CollectionConfig { - const hooks = collection.hooks?.beforeOperation ?? [] - if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection} - const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify) - const applies = (operation: string) => operation === 'forgotPassword' || (verifies && operation === 'create') - const hold = ((args: OperationArgs) => { - const email = args.args?.data?.email - const req = args.req ?? args.args?.req - if (applies(args.operation) && typeof email === 'string' && req) {holdAccountMailFor(email, req)} - return args.args - }) as unknown as { [MARK]?: boolean } & NonNullable['beforeOperation']>[number] - hold[MARK] = true - // Ran without a mail (no such account, Payload's interval between two requests): forget the address. - const done = ((args: OperationArgs) => { - const email = args.args?.data?.email - if (applies(args.operation) && typeof email === 'string') {releaseAccountMailFor(email)} - return args.result - }) as unknown as NonNullable['afterOperation']>[number] - return { ...collection, hooks: { ...collection.hooks, afterOperation: [...(collection.hooks?.afterOperation ?? []), done], beforeOperation: [...hooks, hold] } } + const auth = collection.auth + if (!auth) {return collection} + const own = typeof auth === 'object' ? auth : {} + if (own.disableLocalStrategy === true) {return collection} + const forgotPassword = { ...own.forgotPassword, generateEmailSubject: holdingSubject(own.forgotPassword?.generateEmailSubject as SubjectFn | undefined, 'authentication:resetYourPassword') } + const verify = + own.verify === true || (own.verify && typeof own.verify === 'object') + ? { ...(typeof own.verify === 'object' ? own.verify : {}), generateEmailSubject: holdingSubject((typeof own.verify === 'object' ? own.verify.generateEmailSubject : undefined) as SubjectFn | undefined, 'authentication:verifyYourEmail') } + : own.verify + return { ...collection, auth: { ...own, forgotPassword: forgotPassword as never, ...(verify !== undefined ? { verify: verify as never } : {}) } } } diff --git a/test/plugin.test.ts b/test/plugin.test.ts index d62d1fa..1b8c5dc 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -72,7 +72,8 @@ describe('iapl — auth collection', () => { secret: 'x', } as unknown as Config) const users = config.collections?.find((c) => c.slug === 'users') - expect(users?.auth).toBe(true) + // an auth collection with Payload's defaults; the plugin only wraps the reset mail's subject (mail.accountMailAfterCommit) + expect(users?.auth).toEqual({ forgotPassword: { generateEmailSubject: expect.any(Function) } }) expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true) }) diff --git a/test/transactionPool.test.ts b/test/transactionPool.test.ts index 0782a76..0e72750 100644 --- a/test/transactionPool.test.ts +++ b/test/transactionPool.test.ts @@ -10,12 +10,13 @@ * docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17 * IPAL_TEST_POSTGRES_URI=postgres://postgres:test@127.0.0.1:55432/postgres pnpm vitest run test/transactionPool.test.ts */ -import type { BasePayload, Payload } from 'payload' +import type { BasePayload, Payload, PayloadRequest } from 'payload' import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.js' +import { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAccountMailAfterCommit } from '../src/modules/email/accountMailAfterCommit.js' import { submitForm } from '../src/modules/forms/submitForm.js' import { startPayloadServer, type TestServer } from './http/server.js' import { silentServer, site } from './transactionPoolSite.js' @@ -136,6 +137,70 @@ describe('the watch (fake adapter)', () => { expect(transactionWatchState(payload)).toMatchObject({ active: 4, waiting: 2 }) }, 15_000) + describe('account mail after commit (matched by its token, never by the address alone)', () => { + const TOKEN_A = 'a'.repeat(40) + const TOKEN_B = 'b'.repeat(40) + const reqOf = async (payload: BasePayload, db: FakeDb) => ({ payload, transactionID: (await db.beginTransaction())! }) as unknown as PayloadRequest + const resetMail = (token: string, to = 'victim@client.example') => ({ html: `reset`, to }) + + test('two "forgot password" for one address at once, the second rolled back: the first one\'s mail goes out at its commit', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + const sent: string[] = [] + const a = await reqOf(payload, db) + const b = await reqOf(payload, db) + holdAccountMail(TOKEN_A, 'victim@client.example', a) + holdAccountMail(TOKEN_B, 'Victim@Client.example', b) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A), async () => void sent.push('A'))).toBe(true) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_B), async () => void sent.push('B'))).toBe(true) + await db.commitTransaction(a.transactionID as string) + expect(sent).toEqual(['A']) + await db.rollbackTransaction(b.transactionID as string) + expect(sent).toEqual(['A']) + }) + + test('a form\'s mail to an address whose "forgot password" is in flight is sent at once; the reset mail waits for its commit', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + const sent: string[] = [] + const reset = await reqOf(payload, db) + holdAccountMail(TOKEN_A, 'office@client.example', reset) + expect(sendAccountMailAfterCommit({ html: '

New message from the contact form

', to: 'office@client.example' }, async () => void sent.push('form'))).toBe(false) + // the same token to another address, or to several, is not the account's mail either + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, 'other@client.example'), async () => {})).toBe(false) + expect(sendAccountMailAfterCommit({ ...resetMail(TOKEN_A), to: ['office@client.example', 'x@client.example'] }, async () => {})).toBe(false) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, 'office@client.example'), async () => void sent.push('reset'))).toBe(true) + await db.rollbackTransaction(reset.transactionID as string) + expect(sent).toEqual([]) // the form mail was the caller's to send; the reset of a rolled-back request is dropped + releaseAccountMail(TOKEN_A) + }) + + test('nothing held without a watched transaction, or for a short token', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + holdAccountMail(TOKEN_A, 'x@client.example', { payload, transactionID: undefined } as unknown as PayloadRequest) + holdAccountMail('short', 'x@client.example', await reqOf(payload, db)) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, 'x@client.example'), async () => {})).toBe(false) + expect(sendAccountMailAfterCommit({ html: 'short', to: 'x@client.example' }, async () => {})).toBe(false) + }) + + test('the collection: Payload\'s own subjects, a project\'s own one kept; collections without a password left alone', async () => { + const t = (key: string) => `t:${key}` + const plain = withAccountMailAfterCommit({ slug: 'users', auth: true, fields: [] }) + const auth = plain.auth as { forgotPassword: { generateEmailSubject: (a: unknown) => Promise }; verify?: unknown } + expect(await auth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: 'u@x.example' } })).toBe('t:authentication:resetYourPassword') + expect(auth.verify).toBeUndefined() + const own = withAccountMailAfterCommit({ slug: 'members', auth: { forgotPassword: { generateEmailSubject: () => 'Reset' }, verify: true }, fields: [] }) + const ownAuth = own.auth as { forgotPassword: { generateEmailSubject: (a: unknown) => Promise }; verify: { generateEmailSubject: (a: unknown) => Promise } } + expect(await ownAuth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: 'u@x.example' } })).toBe('Reset') + expect(await ownAuth.verify.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: 'u@x.example' } })).toBe('t:authentication:verifyYourEmail') + expect(withAccountMailAfterCommit(own)).toEqual(own) // idempotent + const keyOnly = { slug: 'keys', auth: { disableLocalStrategy: true as const }, fields: [] } + expect(withAccountMailAfterCommit(keyOnly)).toBe(keyOnly) + expect(withAccountMailAfterCommit({ slug: 'pages', fields: [] })).toEqual({ slug: 'pages', fields: [] }) + }) + }) + test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => { const { db, events, logger, payload } = fakePayload() watchTransactions(payload)