|
| 1 | +import { describe, expect } from "vitest"; |
| 2 | +import { Pool } from "pg"; |
| 3 | +import { PrismaPg } from "@prisma/adapter-pg"; |
| 4 | +import { PrismaClient } from "@trigger.dev/database"; |
| 5 | +import { postgresBlipTest } from "./index"; |
| 6 | + |
| 7 | +// A minimal infra retry, standing in for the shared read-retry util so this |
| 8 | +// file can demonstrate the harness end-to-end on its own. |
| 9 | +async function withRetry<T>(fn: () => Promise<T>, maxAttempts = 8): Promise<T> { |
| 10 | + let lastError: unknown; |
| 11 | + for (let attempt = 0; attempt < maxAttempts; attempt++) { |
| 12 | + try { |
| 13 | + return await fn(); |
| 14 | + } catch (error) { |
| 15 | + lastError = error; |
| 16 | + await new Promise((r) => setTimeout(r, Math.min(50 * (attempt + 1), 250))); |
| 17 | + } |
| 18 | + } |
| 19 | + throw lastError; |
| 20 | +} |
| 21 | + |
| 22 | +// Production runs the pg driver adapter, so the client under test is adapter-backed. |
| 23 | +async function adapterClient(connectionString: string) { |
| 24 | + const pool = new Pool({ connectionString }); |
| 25 | + // A severed idle connection makes the pg Pool emit 'error'; swallow it so an |
| 26 | + // unhandled event can't crash the test worker before recovery is asserted. |
| 27 | + pool.on("error", () => {}); |
| 28 | + const client = new PrismaClient({ adapter: new PrismaPg(pool) }); |
| 29 | + const dispose = async () => { |
| 30 | + try { |
| 31 | + await client.$disconnect(); |
| 32 | + } finally { |
| 33 | + await pool.end(); |
| 34 | + } |
| 35 | + }; |
| 36 | + return { client, dispose }; |
| 37 | +} |
| 38 | + |
| 39 | +async function createProbeTable(client: PrismaClient) { |
| 40 | + await client.$executeRawUnsafe( |
| 41 | + `CREATE TABLE IF NOT EXISTS blip_probe (id uuid PRIMARY KEY, tag text NOT NULL)` |
| 42 | + ); |
| 43 | +} |
| 44 | + |
| 45 | +async function countTag(client: PrismaClient, tag: string): Promise<number> { |
| 46 | + const rows = await client.$queryRawUnsafe<{ n: number }[]>( |
| 47 | + `SELECT count(*)::int AS n FROM blip_probe WHERE tag = $1`, |
| 48 | + tag |
| 49 | + ); |
| 50 | + return rows[0]?.n ?? 0; |
| 51 | +} |
| 52 | + |
| 53 | +describe("DbBlipController", () => { |
| 54 | + postgresBlipTest( |
| 55 | + "a pooled adapter client transparently survives an idle-connection drop", |
| 56 | + { timeout: 60_000 }, |
| 57 | + async ({ postgresContainer, blip }) => { |
| 58 | + const { client, dispose } = await adapterClient(postgresContainer.getConnectionUri()); |
| 59 | + try { |
| 60 | + await client.user.count(); // warm the pool |
| 61 | + const terminated = await blip.severIdle(); |
| 62 | + expect(terminated).toBeGreaterThan(0); |
| 63 | + // The pool evicts the dead idle connection; the next read just works. |
| 64 | + await new Promise((r) => setTimeout(r, 200)); |
| 65 | + const count = await client.user.count(); |
| 66 | + expect(typeof count).toBe("number"); |
| 67 | + } finally { |
| 68 | + await dispose(); |
| 69 | + } |
| 70 | + } |
| 71 | + ); |
| 72 | + |
| 73 | + postgresBlipTest( |
| 74 | + "severDuringNextStatement fails an in-flight statement", |
| 75 | + { timeout: 60_000 }, |
| 76 | + async ({ postgresContainer, blip }) => { |
| 77 | + const { client, dispose } = await adapterClient(postgresContainer.getConnectionUri()); |
| 78 | + try { |
| 79 | + const slow = client.$queryRawUnsafe(`SELECT pg_sleep(3)`); |
| 80 | + // PrismaPromise is lazy — form the assertion so the query actually starts. |
| 81 | + const rejected = expect(slow).rejects.toThrow(); |
| 82 | + await blip.severDuringNextStatement({ queryContains: "pg_sleep" }); |
| 83 | + await rejected; |
| 84 | + } finally { |
| 85 | + await dispose(); |
| 86 | + } |
| 87 | + } |
| 88 | + ); |
| 89 | + |
| 90 | + postgresBlipTest( |
| 91 | + "a read recovers after a mid-flight blip", |
| 92 | + { timeout: 60_000 }, |
| 93 | + async ({ postgresContainer, blip }) => { |
| 94 | + const { client, dispose } = await adapterClient(postgresContainer.getConnectionUri()); |
| 95 | + try { |
| 96 | + const severed = client.$queryRawUnsafe(`SELECT pg_sleep(3)`).catch(() => undefined); |
| 97 | + await blip.severDuringNextStatement({ queryContains: "pg_sleep" }); |
| 98 | + await severed; |
| 99 | + const count = await withRetry(() => client.user.count()); |
| 100 | + expect(typeof count).toBe("number"); |
| 101 | + } finally { |
| 102 | + await dispose(); |
| 103 | + } |
| 104 | + } |
| 105 | + ); |
| 106 | + |
| 107 | + postgresBlipTest( |
| 108 | + "a non-idempotent write double-applies on retry after a post-commit blip; the idempotent form does not", |
| 109 | + { timeout: 60_000 }, |
| 110 | + async ({ postgresContainer, blip }) => { |
| 111 | + const { client, dispose } = await adapterClient(postgresContainer.getConnectionUri()); |
| 112 | + try { |
| 113 | + await createProbeTable(client); |
| 114 | + |
| 115 | + // Model the dangerous case: the write commits, then a later statement in |
| 116 | + // the same op is severed mid-flight (ack lost), and the caller retries. |
| 117 | + let nonIdempotentAttempts = 0; |
| 118 | + const nonIdempotentWrite = async () => { |
| 119 | + nonIdempotentAttempts++; |
| 120 | + await client.$executeRawUnsafe( |
| 121 | + `INSERT INTO blip_probe (id, tag) VALUES (gen_random_uuid(), 'non-idempotent')` |
| 122 | + ); |
| 123 | + if (nonIdempotentAttempts === 1) { |
| 124 | + await client.$queryRawUnsafe(`SELECT pg_sleep(3)`); // severed → throws after the commit |
| 125 | + } |
| 126 | + }; |
| 127 | + const nonIdempotentDone = withRetry(nonIdempotentWrite); |
| 128 | + await blip.severDuringNextStatement({ queryContains: "pg_sleep" }); |
| 129 | + await nonIdempotentDone; |
| 130 | + expect(await countTag(client, "non-idempotent")).toBe(2); // the hazard, proven |
| 131 | + |
| 132 | + // The idempotent form: a fixed id + ON CONFLICT makes the replay a no-op. |
| 133 | + let idempotentAttempts = 0; |
| 134 | + const idempotentWrite = async () => { |
| 135 | + idempotentAttempts++; |
| 136 | + await client.$executeRawUnsafe( |
| 137 | + `INSERT INTO blip_probe (id, tag) |
| 138 | + VALUES ('00000000-0000-0000-0000-000000000001', 'idempotent') |
| 139 | + ON CONFLICT (id) DO NOTHING` |
| 140 | + ); |
| 141 | + if (idempotentAttempts === 1) { |
| 142 | + await client.$queryRawUnsafe(`SELECT pg_sleep(3)`); |
| 143 | + } |
| 144 | + }; |
| 145 | + const idempotentDone = withRetry(idempotentWrite); |
| 146 | + await blip.severDuringNextStatement({ queryContains: "pg_sleep" }); |
| 147 | + await idempotentDone; |
| 148 | + expect(await countTag(client, "idempotent")).toBe(1); // exactly once despite retry |
| 149 | + } finally { |
| 150 | + await dispose(); |
| 151 | + } |
| 152 | + } |
| 153 | + ); |
| 154 | + |
| 155 | + // Regression: queryContains must match as literal text, not as an ILIKE pattern. |
| 156 | + // The active query contains "fooXbar"; under ILIKE the pattern "foo_bar" (with the |
| 157 | + // wildcard `_`) would wrongly match and terminate it. The literal matcher must not, |
| 158 | + // so the sever times out instead of killing the wrong statement. |
| 159 | + postgresBlipTest( |
| 160 | + "severDuringNextStatement matches queryContains literally, not as an ILIKE pattern", |
| 161 | + { timeout: 60_000 }, |
| 162 | + async ({ postgresContainer, blip }) => { |
| 163 | + const { client, dispose } = await adapterClient(postgresContainer.getConnectionUri()); |
| 164 | + const slow = client |
| 165 | + .$queryRawUnsafe(`SELECT pg_sleep(3) /* marker fooXbar */`) |
| 166 | + .catch(() => undefined); |
| 167 | + try { |
| 168 | + await expect( |
| 169 | + blip.severDuringNextStatement({ queryContains: "foo_bar", timeoutMs: 1000, pollMs: 25 }) |
| 170 | + ).rejects.toThrow(/no active statement/i); |
| 171 | + } finally { |
| 172 | + await dispose(); |
| 173 | + await slow; |
| 174 | + } |
| 175 | + } |
| 176 | + ); |
| 177 | +}); |
0 commit comments