feat: implement graceful shutdown handling

This commit is contained in:
syntaxbullet
2026-01-06 17:21:50 +01:00
parent 278ef4b6b0
commit 6ead0c0393
8 changed files with 190 additions and 6 deletions

56
src/lib/db.test.ts Normal file
View File

@@ -0,0 +1,56 @@
import { describe, it, expect, mock, beforeEach } from "bun:test";
// Mock shutdown module before importing db
mock.module("./shutdown", () => {
let shuttingDown = false;
let transactions = 0;
return {
isShuttingDown: () => shuttingDown,
setShuttingDown: (v: boolean) => { shuttingDown = v; },
incrementTransactions: () => { transactions++; },
decrementTransactions: () => { transactions--; },
getActiveTransactions: () => transactions,
};
});
// Mock DrizzleClient
mock.module("./DrizzleClient", () => ({
DrizzleClient: {
transaction: async (cb: any) => cb("MOCK_TX")
}
}));
import { withTransaction } from "./db";
import { setShuttingDown, getActiveTransactions } from "./shutdown";
describe("db withTransaction", () => {
beforeEach(() => {
setShuttingDown(false);
});
it("should allow transactions when not shutting down", async () => {
const result = await withTransaction(async (tx) => {
return "success";
});
expect(result).toBe("success");
expect(getActiveTransactions()).toBe(0);
});
it("should throw error when shutting down", async () => {
setShuttingDown(true);
expect(withTransaction(async (tx) => {
return "success";
})).rejects.toThrow("System is shutting down, no new transactions allowed.");
expect(getActiveTransactions()).toBe(0);
});
it("should increment and decrement transaction count", async () => {
let countDuring = 0;
await withTransaction(async (tx) => {
countDuring = getActiveTransactions();
return "ok";
});
expect(countDuring).toBe(1);
expect(getActiveTransactions()).toBe(0);
});
});