also looking at this
test: raise instead of skipping when a provided live service is missing
#1187
4 files
+194
-9
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | |
| 27 | 27 | import { SQL } from 'bun' |
| 28 | 28 | import process from 'node:process' |
| 29 | import { gateUnavailable, requiredInCi } from './gate' | |
| 29 | 30 | |
| 30 | 31 | export const PG_URL: string |
| 31 | 32 | = process.env.DATABASE_URL |
| @@ -41,15 +42,41 @@ export const PG_URL: string | ||
| 41 | 42 | * trade. Callers await it at the top of their own `.test.ts`, where the rule |
| 42 | 43 | * does not apply. The URL above is the part that was wrong and the part worth |
| 43 | 44 | * 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`. | |
| 44 | 54 | */ |
| 45 | 55 | export 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 | } | |
| 54 | 75 | } |
| 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 | ) | |
| 55 | 82 | } |