Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion apps/server/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { mkdir } from "node:fs/promises";
import { dirname } from "node:path";
import { PGlite } from "@electric-sql/pglite";
import pg from "pg";
import { backgroundFailure } from "./log.ts";

type Row = { data: Record<string, unknown> };
interface Database {
Expand Down Expand Up @@ -111,12 +112,19 @@ export class Store {
}
}

/** Idle clients can be disconnected by a database restart; without a listener pg's `error` event crashes the process. */
export function createPool(connectionString: string) {
const pool = new pg.Pool({ connectionString, max: 5 });
pool.on("error", (error) => backgroundFailure("postgres pool", error));
return pool;
}

export async function createStore(
options: { dataDir?: string; databaseUrl?: string } = {},
): Promise<Store> {
let database: Database;
if (options.databaseUrl) {
const pool = new pg.Pool({ connectionString: options.databaseUrl, max: 5 });
const pool = createPool(options.databaseUrl);
database = { query: async (sql, params) => pool.query(sql, params), close: () => pool.end() };
} else {
if (options.dataDir) await mkdir(dirname(options.dataDir), { recursive: true, mode: 0o700 });
Expand Down
13 changes: 12 additions & 1 deletion tests/persistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { createStore } from "../apps/server/src/db.ts";
import { createPool, createStore } from "../apps/server/src/db.ts";

test("fresh nested data directory starts and survives a database restart", async () => {
const root = await mkdtemp(join(tmpdir(), "openmuse-db-"));
Expand All @@ -20,3 +20,14 @@ test("fresh nested data directory starts and survives a database restart", async
await rm(root, { recursive: true, force: true });
}
});

test("idle Postgres client errors are logged instead of crashing the process", async (t) => {
const logged = t.mock.method(console, "error", () => {});
const pool = createPool("postgres://127.0.0.1:1/openmuse");
try {
assert.doesNotThrow(() => pool.emit("error", new Error("terminating connection")));
assert.equal(logged.mock.callCount(), 1);
} finally {
await pool.end();
}
});
Loading