|
| 1 | +import { describe, it, expect, vi, beforeEach } from "vitest"; |
| 2 | +import { EventEmitter } from "events"; |
| 3 | +import { CANCEL_QUERY_TIMEOUT_MS } from "../../utils/query-timeout.js"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Unit coverage for the PostgreSQL client-side query timeout fallback. |
| 7 | + * |
| 8 | + * node-postgres's `query_timeout` only rejects the query's promise: the client |
| 9 | + * keeps waiting for the server's answer, so anything sent on it afterwards |
| 10 | + * queues behind the abandoned statement. The integration suite exercises the |
| 11 | + * fallback against a real server; these tests pin the order of operations. |
| 12 | + */ |
| 13 | + |
| 14 | +const BACKEND_PID = 4242; |
| 15 | + |
| 16 | +/** The error node-postgres raises for its client-side timeout: no `code`. */ |
| 17 | +const clientTimeout = () => new Error("Query read timeout"); |
| 18 | + |
| 19 | +class FakePgPool extends EventEmitter { |
| 20 | + statements: string[] = []; |
| 21 | + failOn: (sql: string) => Error | undefined = () => undefined; |
| 22 | + client = { |
| 23 | + processID: BACKEND_PID, |
| 24 | + query: vi.fn(async (sql: string) => { |
| 25 | + this.statements.push(sql); |
| 26 | + const failure = this.failOn(sql); |
| 27 | + if (failure) throw failure; |
| 28 | + return { rows: [{ ok: 1 }], rowCount: 1 }; |
| 29 | + }), |
| 30 | + release: vi.fn(), |
| 31 | + }; |
| 32 | + connect = vi.fn(async () => this.client); |
| 33 | + query = vi.fn(async (_config: unknown) => ({ rows: [{ pg_cancel_backend: true }], rowCount: 1 })); |
| 34 | + end = vi.fn().mockResolvedValue(undefined); |
| 35 | +} |
| 36 | + |
| 37 | +let pool: FakePgPool; |
| 38 | + |
| 39 | +vi.mock("pg", () => ({ |
| 40 | + default: { |
| 41 | + Pool: function () { |
| 42 | + return pool; |
| 43 | + }, |
| 44 | + types: { builtins: {}, getTypeParser: () => (value: string) => value }, |
| 45 | + }, |
| 46 | +})); |
| 47 | + |
| 48 | +const { PostgresConnector } = await import("../postgres/index.js"); |
| 49 | + |
| 50 | +async function connect() { |
| 51 | + const connector = new PostgresConnector(); |
| 52 | + await connector.connect("postgres://u:p@localhost:5432/db", undefined, { |
| 53 | + queryTimeoutSeconds: 30, |
| 54 | + }); |
| 55 | + // connect() checks out and releases a client to test the connection. |
| 56 | + pool.client.release.mockClear(); |
| 57 | + pool.connect.mockClear(); |
| 58 | + return connector; |
| 59 | +} |
| 60 | + |
| 61 | +describe("PostgreSQL client-side query timeout", () => { |
| 62 | + beforeEach(() => { |
| 63 | + pool = new FakePgPool(); |
| 64 | + }); |
| 65 | + |
| 66 | + it.each([ |
| 67 | + ["a read-only statement", "SELECT pg_sleep(600)", { readonly: true }], |
| 68 | + ["a writable statement", "SELECT pg_sleep(600)", {}], |
| 69 | + ["a multi-statement batch", "SET statement_timeout = 0; SELECT pg_sleep(600)", {}], |
| 70 | + ])("discards the client and cancels the backend for %s, skipping rollback", async (_label, sql, options) => { |
| 71 | + pool.failOn = (statement) => (statement.includes("pg_sleep") ? clientTimeout() : undefined); |
| 72 | + const connector = await connect(); |
| 73 | + |
| 74 | + await expect(connector.executeSQL(sql, options)).rejects.toThrow("Query read timeout"); |
| 75 | + |
| 76 | + // The client is still waiting on the abandoned statement, so a ROLLBACK |
| 77 | + // would queue behind it. |
| 78 | + expect(pool.statements).not.toContain("ROLLBACK"); |
| 79 | + // Released exactly once, with a truthy argument: pg-pool closes the socket |
| 80 | + // and drops the client instead of returning it to the pool. |
| 81 | + expect(pool.client.release).toHaveBeenCalledTimes(1); |
| 82 | + expect(pool.client.release).toHaveBeenCalledWith(true); |
| 83 | + // The statement is cancelled on the server over another pooled connection, |
| 84 | + // bounded by its own short timeout... |
| 85 | + expect(pool.query).toHaveBeenCalledWith({ |
| 86 | + text: "SELECT pg_cancel_backend($1)", |
| 87 | + values: [BACKEND_PID], |
| 88 | + query_timeout: CANCEL_QUERY_TIMEOUT_MS, |
| 89 | + }); |
| 90 | + // ...after the client was discarded, so the cancel can use its pool slot |
| 91 | + // (pool_max_connections = 1 would otherwise wait on itself). |
| 92 | + expect(pool.client.release.mock.invocationCallOrder[0]).toBeLessThan( |
| 93 | + pool.query.mock.invocationCallOrder[0] |
| 94 | + ); |
| 95 | + }); |
| 96 | + |
| 97 | + it("surfaces the timeout even if the cancel fails", async () => { |
| 98 | + pool.failOn = (statement) => (statement.includes("pg_sleep") ? clientTimeout() : undefined); |
| 99 | + pool.query.mockRejectedValue(new Error("connection refused")); |
| 100 | + const connector = await connect(); |
| 101 | + |
| 102 | + await expect(connector.executeSQL("SELECT pg_sleep(600)", { readonly: true })).rejects.toThrow( |
| 103 | + "Query read timeout" |
| 104 | + ); |
| 105 | + expect(pool.client.release).toHaveBeenCalledWith(true); |
| 106 | + }); |
| 107 | + |
| 108 | + it("keeps the client for a server-side statement_timeout cancellation", async () => { |
| 109 | + const cancelled = Object.assign(new Error("canceling statement due to statement timeout"), { |
| 110 | + code: "57014", |
| 111 | + }); |
| 112 | + pool.failOn = (statement) => (statement.includes("pg_sleep") ? cancelled : undefined); |
| 113 | + const connector = await connect(); |
| 114 | + |
| 115 | + await expect(connector.executeSQL("SELECT pg_sleep(600)", { readonly: true })).rejects.toBe( |
| 116 | + cancelled |
| 117 | + ); |
| 118 | + |
| 119 | + // The server ended the statement itself: the client is clean, so it is |
| 120 | + // rolled back and returned to the pool as usual, and nothing is cancelled. |
| 121 | + expect(pool.statements[pool.statements.length - 1]).toBe("ROLLBACK"); |
| 122 | + expect(pool.client.release).toHaveBeenCalledTimes(1); |
| 123 | + expect(pool.client.release).toHaveBeenCalledWith(); |
| 124 | + expect(pool.query).not.toHaveBeenCalled(); |
| 125 | + }); |
| 126 | +}); |
0 commit comments