PostgreSQL error 57P01 (terminating connection due to administrator command)
is emitted as an 'error' event on the pg.Pool when an idle pooled client is
killed. Both attachRealtime (API) and createRemoteBroadcaster (ingest worker)
created pools without an 'error' listener, so Node treated it as an
uncaughtException and crashed the process. Add pool.on('error') handlers that
forward to onError (and skip noise during shutdown), mirroring the existing
client.on('error') reconnection logic.
Paperclip-Issue: BIT-32447
Paperclip-Cluster: 52b3174b839d
123 lines
5.4 KiB
TypeScript
123 lines
5.4 KiB
TypeScript
import { LIBRARY_CHANNEL, type LibraryMessage } from "@photoreport/contracts";
|
|
import type { AddressInfo } from "node:net";
|
|
import pg from "pg";
|
|
import { io, type Socket } from "socket.io-client";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { buildApp } from "../src/app.js";
|
|
import { createRemoteBroadcaster } from "../src/realtime.js";
|
|
import { createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
|
|
|
/** End to end: a separate process (the ingest worker) publishes, a signed-in browser receives. */
|
|
describe("realtime", () => {
|
|
let ctx: TestContext;
|
|
let live: Awaited<ReturnType<typeof buildApp>>;
|
|
let url: string;
|
|
const sockets: Socket[] = [];
|
|
|
|
beforeAll(async () => {
|
|
ctx = await createTestApp();
|
|
await resetDb(ctx.db);
|
|
live = await buildApp({ config: ctx.config, db: ctx.db, realtime: "socket" });
|
|
await live.listen({ port: 0, host: "127.0.0.1" });
|
|
url = `http://127.0.0.1:${(live.server.address() as AddressInfo).port}`;
|
|
});
|
|
afterAll(async () => {
|
|
for (const s of sockets) s.close();
|
|
await live.close();
|
|
await ctx.app.close();
|
|
await ctx.db.$disconnect();
|
|
});
|
|
|
|
const connect = (token: string) =>
|
|
new Promise<Socket>((resolve, reject) => {
|
|
const socket = io(url, { path: "/v1/realtime", transports: ["websocket"], auth: { token }, reconnection: false });
|
|
sockets.push(socket);
|
|
socket.on("connect", () => resolve(socket));
|
|
socket.on("connect_error", reject);
|
|
});
|
|
|
|
it("rejects connections without a valid token", async () => {
|
|
await expect(connect("nope")).rejects.toThrow(/unauthorized/);
|
|
});
|
|
|
|
it("delivers worker messages to members of the organization only", async () => {
|
|
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "EDITOR" });
|
|
await seedUser(ctx.db, "[email protected]", { org: "liga", role: "EDITOR" });
|
|
const member = await connect((await login(ctx.app, "[email protected]")).body.accessToken);
|
|
const outsider = await connect((await login(ctx.app, "[email protected]")).body.accessToken);
|
|
const leaked: unknown[] = [];
|
|
outsider.on(LIBRARY_CHANNEL, (m: unknown) => leaked.push(m));
|
|
|
|
const received = new Promise<LibraryMessage>((resolve) => member.on(LIBRARY_CHANNEL, resolve));
|
|
const worker = createRemoteBroadcaster(ctx.config.DATABASE_URL);
|
|
const message: LibraryMessage = { type: "photo.updated", ids: ["3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90"], patch: { flag: "PICK" } };
|
|
// The adapter subscribes asynchronously after connect; publish until it arrives.
|
|
const timer = setInterval(() => worker.library(org!.id, message), 100);
|
|
try {
|
|
expect(await received).toEqual(message);
|
|
} finally {
|
|
clearInterval(timer);
|
|
await worker.close();
|
|
}
|
|
expect(leaked).toEqual([]);
|
|
});
|
|
|
|
it("does not report pool-after-end when library() races close() (BIT-31177)", async () => {
|
|
const errors: unknown[] = [];
|
|
const worker = createRemoteBroadcaster(ctx.config.DATABASE_URL, (err) => errors.push(err));
|
|
const message: LibraryMessage = {
|
|
type: "photo.updated",
|
|
ids: ["3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90"],
|
|
patch: { flag: "PICK" },
|
|
};
|
|
worker.library("00000000-0000-4000-8000-000000000001", message);
|
|
await worker.close();
|
|
worker.library("00000000-0000-4000-8000-000000000001", message);
|
|
await worker.close();
|
|
expect(errors.filter((e) => e instanceof Error && /pool after calling end/i.test(e.message))).toEqual([]);
|
|
});
|
|
|
|
it("does not crash when Postgres terminates an idle pooled connection (BIT-32447)", async () => {
|
|
const errors: unknown[] = [];
|
|
const worker = createRemoteBroadcaster(ctx.config.DATABASE_URL, (err) => errors.push(err));
|
|
const message: LibraryMessage = {
|
|
type: "photo.updated",
|
|
ids: ["3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90"],
|
|
patch: { flag: "PICK" },
|
|
};
|
|
// Establish the pool's single connection by publishing once.
|
|
worker.library("00000000-0000-0000-8000-000000000002", message);
|
|
// Give the NOTIFY query a moment to complete so the client returns idle to the pool.
|
|
await new Promise((r) => setTimeout(r, 200));
|
|
|
|
// An uncaughtException here would fail the test.
|
|
const uncaught: unknown[] = [];
|
|
const onUncaught = (err: unknown) => uncaught.push(err);
|
|
process.once("uncaughtException", onUncaught);
|
|
|
|
try {
|
|
// Find the pool's idle backend and terminate it, simulating an admin command (error 57P01).
|
|
const admin = new pg.Client({ connectionString: ctx.config.DATABASE_URL });
|
|
await admin.connect();
|
|
const db = await admin.query<{ pid: number }>(
|
|
`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND state = 'idle' AND pid <> pg_backend_pid()`,
|
|
);
|
|
for (const { pid } of db.rows) await admin.query(`SELECT pg_terminate_backend($1)`, [pid]);
|
|
await admin.end();
|
|
|
|
// The pool emits 'error' for the killed client; wait for it to reach onError.
|
|
await new Promise((r) => setTimeout(r, 500));
|
|
expect(uncaught).toEqual([]);
|
|
expect(errors.some((e) => e instanceof Error && /terminating connection/i.test(e.message))).toBe(true);
|
|
|
|
// The pool must recover and publish again on a fresh connection without throwing.
|
|
worker.library("00000000-0000-0000-8000-000000000003", message);
|
|
await new Promise((r) => setTimeout(r, 300));
|
|
expect(uncaught).toEqual([]);
|
|
} finally {
|
|
process.removeListener("uncaughtException", onUncaught);
|
|
await worker.close();
|
|
}
|
|
});
|
|
});
|