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 } +} +