ReviewOS

also looking at this

stacks/bun-query-builder

test: raise instead of skipping when a provided live service is missing

#1187
Merged glennmichael123 wants to merge test/loud-service-gates into main
4 files +194 -9
packages/bun-query-builder/test/pg.tsmodified+35-8
Changes to packages/bun-query-builder/test/pg.ts
@@ -26,6 +26,7 @@
2626
2727import { SQL } from 'bun'
2828import process from 'node:process'
29import { gateUnavailable, requiredInCi } from './gate'
2930
3031export const PG_URL: string
3132 = process.env.DATABASE_URL
@@ -41,15 +42,41 @@ export const PG_URL: string
4142 * trade. Callers await it at the top of their own `.test.ts`, where the rule
4243 * does not apply. The URL above is the part that was wrong and the part worth
4344 * sharing; this is three lines of probe.
45 *
46 * It no longer answers `false` unconditionally. Fixing the URL fixed the cause
47 * of the incident above but not its mechanism: `catch { return false }` reads
48 * every possible failure — a rotated password, a service that never came up,
49 * an exhausted connection limit — as "this machine has no Postgres", and the
50 * 14 files gated on it disappear. Measured on the suite as it stands, a
51 * Postgres that does not answer takes 30 passing live-Postgres assertions down
52 * to 11 and still exits 0. So where the environment is one that supplies
53 * Postgres, an unreachable server raises; see `gate.ts`.
4454 */
4555export async function probePostgres(): Promise<boolean> {
46 try {
47 const probe = new SQL(PG_URL)
48 await probe.unsafe('SELECT 1')
49 await probe.end()
50 return true
51 }
52 catch {
53 return false
56 // Only where a failure is fatal, and only then: locally the connection is
57 // refused immediately and retrying three times per file for a developer who
58 // has no Postgres is pure latency. In CI the workflow already waits for
59 // `pg_isready`, so this is for a blip after that point rather than for boot.
60 const attempts = requiredInCi() ? 3 : 1
61 let lastError: unknown
62
63 for (let attempt = 1; attempt <= attempts; attempt++) {
64 try {
65 const probe = new SQL(PG_URL)
66 await probe.unsafe('SELECT 1')
67 await probe.end()
68 return true
69 }
70 catch (error) {
71 lastError = error
72 if (attempt < attempts)
73 await Bun.sleep(attempt * 250)
74 }
5475 }
76
77 return gateUnavailable(
78 'live Postgres',
79 `${PG_URL} did not answer after ${attempts} attempt${attempts === 1 ? '' : 's'} (${(lastError as Error)?.message ?? lastError})`,
80 'Start Postgres, or point DATABASE_URL at one.',
81 )
5582}