Repository navigation
feat(preview): retry a connection while a preview's Postgres wakes - #1185
Conversation
A Railway service asleep under Serverless wakes on the first private-network connection to it, and that connection is refused. `@payloadcms/db-postgres` does not retry, so the request behind it failed — and `request-magic-link` answers every failure as a 200 with no token, which is how CI's fixture fill broke when a preview's Postgres was allowed to sleep (#1178). On a PR preview the adapter's own `pg` is wrapped so its pool retries a connection for up to 30 s, 1 s apart, on the network errors a waking service answers with and on 57P03. Both connect forms retry, since the pool's `query()` — what Drizzle calls — connects through the callback form. Production's adapter is untouched: its Postgres never sleeps. This is the prerequisite for letting a preview's Postgres sleep; the setting itself comes with the preview-sleep workflow. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-1185 environment in sahajcloud
1 service not affected by this PR
|
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The PR is the size of its problem: a gate, a wrapper, a doc paragraph. The payload.config.ts change is a wrap plus re-indent. Placement is right: src/AGENTS.md gives src/plugins/ the modules payload.config.ts registers as db, and the gate mirrors jobAutoRun()'s. Two shape questions remain. The retry loop is hand-rolled beside p-retry, which this repo already depends on and calls twice. And the seam the change hangs on — the adapter reading db.pg after init returns — is neither stated nor tested, while the body admits no sleeping Postgres was seen. The diff also touches src/plugins/, a fixture.surfacePaths entry, with no ## Preview section in the body: the rule allows none, and a reviewer checking a wake wants the preview's admin link.
Findings
- should-fix — the retry loop reimplements
p-retry, already a dependency with two callers (src/plugins/postgresWake/wakeRetry.ts:67). - should-fix — the ⚠ names
scripts/preview-sleep.ts, which no commit on this branch has (src/plugins/postgresWake/index.ts:25). - should-fix — no
## Previewlink, though the diff touches a preview surface (PR body). - consider — the
db.pgseam is unstated and untested (src/plugins/postgresWake/index.ts:37).
What was checked
Diff read whole, then each new piece against the ladder. src/AGENTS.md places the folder and makes index.ts barrel + wakeRetry.ts the convention. The gate reuses railwayEnvironmentName() and isPreviewEnvironmentName(). src/plugins/databaseErrors/ reads SQLSTATE 22P02 into a 400, a different concern. A hunt for an in-repo retry helper found only p-retry's callers. payload.config.ts read whole: no logic added there, so no whole-file pass is owed. No contract surface moves. node_modules is absent here, so the adapter's connect path went unread.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The wrapper's own loop, its deadline arithmetic and the exported WAKE_BUDGET_MS reimplemented p-retry, which this repo already depends on and calls in src/lib/mapbox/geocoder.ts and src/jobs/SyncLectureMetadata. p-retry's maxRetryTime is the budget, shouldRetry is isPostgresWaking, and factor: 1 with minTimeout is the flat interval. Two of its edges are load-bearing and now carried by comments: the budget, not a count, is what ends the retrying, so retries must be Infinity; and onFailedAttempt runs on an error nothing retries, so the one-time log repeats isPostgresWaking rather than assuming a retry followed. maxRetryTime exhaustion rethrows the original error, so a caller still sees the last refusal. WAKE_BUDGET_MS had no importer, so it is module-private now. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
The ⚠ asked a reader to keep `scripts/preview-sleep.ts` in sync with this folder, and no commit on this branch adds that file, so nobody could act on it. The coupling it names is real but belongs beside the script that turns sleep on, in the pull request that lands it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
The wrapper rests on the adapter reading `db.pg` after `init` returns, and nothing stated or checked it: the existing case asserted against a fake adapter, and no sleeping Postgres had been observed. `@payloadcms/[email protected]`'s compiled `dist/connect.js` builds the pool inside `connect()`, as `new this.pg.Pool(this.poolOptions)`, while `dist/index.js` leaves `pool: undefined` at init — so `init` is the seam, and the docblock now says so. The new case drives the real adapter at a refused port, which is what a sleeping Postgres looks like to a first connection. Watched fail with the wrap removed: the adapter gave up in 10 ms and reported no wake. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
The plugin and its spec landed with no row, and that section already tracks a plugin's own wiring (`sentryPlugin`), so the map had a hole where a reader looks for one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
|
Four findings, four built. Pushed e93eeaf.
Also committed: a
Anomaly: the body gained a Verification bullet at 18:30Z, after I read it. The refresh keeps it. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Why
Letting a PR preview's Postgres sleep saves roughly $10 a month at today's preview count, but the sleep test on #1178 showed it breaks the first request after a wake: the connection that wakes Postgres is refused,
@payloadcms/db-postgresdoes not retry, and Payload's init fails withcannot connect to Postgres.request-magic-linkhides that as a200 {"ok":true}with no token, which is how CI's fixture fill failed twice.This is the prerequisite. #1186 adds the workflow and script that turn sleep on for each preview's app and Postgres after CI.
What
src/plugins/postgresWake/: on a Railway PR preview,retryWhilePostgresWakeswraps the adapter's ownpgso its pool retries a connection for up to 30 s, 1 s apart. It retriesECONNREFUSED,ECONNRESET,ETIMEDOUT,EHOSTUNREACH,ENOTFOUND,EAI_AGAIN,57P03(database starting up), and pg's code-less "Connection terminated" and connection-timeout errors. Anything else, such as a bad password, fails at once.p-retry, already a dependency with two callers:maxRetryTimeis the budget,shouldRetryisisPostgresWaking, andfactor: 1withminTimeoutis the flat interval.connect()forms retry. The pool's ownquery(), which Drizzle calls, connects through the callback form.pgrather than passing the app's through thepgoption, because the two resolve to differentpgversions (8.20 and 8.23). A preview keeps the driver production runs.Postgres refused a connection; retrying while it wakes.initis the seam because the adapter builds its pool later, inside its ownconnect(), asnew this.pg.Pool(this.poolOptions)—initleavespoolundefined.jobAutoRun().DEPLOYMENT.md, Cost Monitoring: one paragraph on the retry.tests/COVERAGE.md: a row for the plugin, beside the onesentryPluginalready had.Preview
Any read of a fixture row is a connection through the wrapped pool, so each link below exercises this change — and the preview's Postgres is already asleep between visits (see Verification).
query(), the callback form the retry also covers/api/health—fixture: loadedmeans the boot connection got throughVerification
tests/unit/postgres-wake-retry.spec.ts:pgpool'squery()against a refused port, retrying for the whole budget;postgresAdapter's ownconnect()against a refused port — it builds its pool from thepgthatinitleft, so the retry reaches the adapter's own connect path;/api/healthanswered200in 3.3 s, and the fixture reportedloaded4 s later. The log shows the refused connection (anAggregateError, Node's dual-stack refusal), thenPostgres refused a connection; retrying while it wakes, then[fixture] loaded … 211 unchanged.Notes for reviewer
p-retryreplaces the hand-rolled loop, the ⚠ pointing at an unlandedscripts/preview-sleep.tsis gone, thedb.pgseam is named from the compiled adapter and driven by a case against the real one, and this body now has a## Previewsection.WAKE_RETRY_PATHinscripts/preview-sleep.ts, which sleeps a preview's Postgres only at a commit holdingsrc/plugins/postgresWake/wakeRetry.ts. Nothing here renames that file, so that check still answers.origin/mainis merged in — one commit, no conflicts.## Why/## What/## Verificationshape rather than the template's headings; only the missing## Previewwas added.Detail
Why
p-retryand not the loop. The loop, its deadline arithmetic and an exportedWAKE_BUDGET_MSwith no importer were a second implementation of a dependency this repo already calls insrc/lib/mapbox/geocoder.tsandsrc/jobs/SyncLectureMetadata. Two ofp-retry's edges are commented because they are easy to get wrong:retriesmust beInfinity, since the budget rather than a count is what ends the retrying; andonFailedAttemptruns on a failure nothing retries, so the one-time log repeats the wake test instead of assuming a retry followed.maxRetryTimeexhaustion rethrows the original error, so the caller still sees the last refusal.Why both
connect()forms.@payloadcms/[email protected]'s compileddist/connect.jstakes the boot connection through the promise form, and Drizzle'snode-postgresdriver takes every query throughpool.query(), which connects via the callback form. Retrying one leaves the other unprotected.How the seam is checked without a sleep. A refused port is what a first connection to a sleeping service sees, so the new case builds the real adapter at one, replaces its
pg, and asserts the adapter's ownconnect()retried for the whole budget before raisingcannot connect to Postgres. Watched fail with the wrap removed: the adapter gave up in 10 ms and reported no wake.🤖 Generated with Claude Code