chore(server): promise safety net and sweep tooling for the async migration

This commit is contained in:
jubnl
2026-09-21 19:01:38 +02:00
parent ef184ec7c2
commit 27d044f9e8
18 changed files with 711 additions and 23 deletions
+24
View File
@@ -0,0 +1,24 @@
import type Database from 'better-sqlite3';
import { UnitOfWork } from '../../src/nest/database/unit-of-work';
import { createTestOrm } from './test-orm';
const perHandle = new WeakMap<Database.Database, Promise<UnitOfWork>>();
/**
* The `UnitOfWork` a hand-constructed service needs, bound to the suite's own
* better-sqlite3 handle.
*
* `UnitOfWork.transactional` opens the transaction through MikroORM on that same
* handle, so the legacy raw statements a service still issues inside the
* callback run inside it — the arrangement the Phase 1 sweep relies on. Memoised
* per handle: one ORM per test file, however many services the file builds.
*/
export function createTestUnitOfWork(db: Database.Database): Promise<UnitOfWork> {
// `=== undefined` rather than a truthiness test: a Promise is always truthy,
// which is exactly what no-misused-promises/checksConditionals rejects.
const existing = perHandle.get(db);
if (existing !== undefined) return existing;
const pending = createTestOrm(db).then((t) => new UnitOfWork(t.em));
perHandle.set(db, pending);
return pending;
}
@@ -68,8 +68,8 @@ describe('demo-reset DB path', () => {
expect(copyFileSync).toHaveBeenCalledWith(LIVE_DB, BASELINE);
});
it('DEMORESET-002: restores the baseline onto that same file, not data/travel.db', () => {
resetDemoUser();
it('DEMORESET-002: restores the baseline onto that same file, not data/travel.db', async () => {
await resetDemoUser();
expect(copyFileSync).toHaveBeenCalledWith(BASELINE, LIVE_DB);
// Closed before the copy and reopened after it — copying over an open
// SQLite file is how a database ends up half of each.
@@ -77,10 +77,10 @@ describe('demo-reset DB path', () => {
expect(databaseModule.reinitialize).toHaveBeenCalled();
});
it('DEMORESET-003: an in-memory database is left alone rather than copied around', () => {
it('DEMORESET-003: an in-memory database is left alone rather than copied around', async () => {
dbStub.name = ':memory:';
saveBaseline();
resetDemoUser();
await resetDemoUser();
expect(copyFileSync).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,42 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { resetTestDb } from '../../helpers/test-db';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { createUser } from '../../helpers/factories';
import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
const testDb = createSnapshotTestDb();
let uow: UnitOfWork;
beforeAll(async () => {
uow = await createTestUnitOfWork(testDb);
});
beforeEach(() => resetTestDb(testDb));
afterAll(() => testDb.close());
const countUsers = () => (testDb.prepare('SELECT COUNT(*) AS n FROM users').get() as { n: number }).n;
describe('createTestUnitOfWork', () => {
it('TUOW-001: raw better-sqlite3 statements inside transactional() commit together', async () => {
await uow.transactional(async () => {
createUser(testDb);
createUser(testDb);
});
expect(countUsers()).toBe(2);
});
it('TUOW-002: a throw rolls raw statements back', async () => {
await expect(
uow.transactional(async () => {
createUser(testDb);
throw new Error('boom');
}),
).rejects.toThrow('boom');
expect(countUsers()).toBe(0);
});
it('TUOW-003: the helper is memoised per handle', async () => {
const again = await createTestUnitOfWork(testDb);
expect(again).toBe(uow);
});
});
+2 -2
View File
@@ -79,9 +79,9 @@ describe('DemoResetJob', () => {
expect(logMock.logInfo).not.toHaveBeenCalled();
});
it('AJOB-006 — the tick runs resetDemoUser and contains a throw to the Demo reset log line', () => {
it('AJOB-006 — the tick runs resetDemoUser and contains a throw to the Demo reset log line', async () => {
const { job } = make(true);
job.tick();
await job.tick();
expect(resetDemoUserMock).toHaveBeenCalledTimes(1);
resetDemoUserMock.mockImplementation(() => { throw new Error('baseline gone'); });
@@ -229,7 +229,7 @@ describe('BackupService (wrapper)', () => {
await expect(wrapper.restoreBackup('svc.zip')).resolves.toEqual({ success: true });
expect(backupSvc.restoreBackup).toHaveBeenCalledWith(storage, 'svc.zip');
wrapper.deleteBackup('svc.zip');
await wrapper.deleteBackup('svc.zip');
expect(backupSvc.deleteBackup).toHaveBeenCalledWith(storage, 'svc.zip');
expect(wrapper.isValidBackupFilename('svc.zip')).toBe(true);
@@ -61,13 +61,13 @@ describe('BudgetController (parity with the legacy /api/trips/:tripId/budget rou
expect(settlement).toHaveBeenLastCalledWith('5', undefined, 'EUR');
});
it('GET /settlement forwards the base query and the trip currency', () => {
it('GET /settlement forwards the base query and the trip currency', async () => {
const settlement = vi.fn().mockReturnValue({ transfers: [] });
const svc = makeService({
verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1, currency: 'USD' }),
settlement,
} as Partial<BudgetService>);
new BudgetController(svc).settlement(user, tripRow, '5', 'GBP');
await new BudgetController(svc).settlement(user, tripRow, '5', 'GBP');
expect(settlement).toHaveBeenCalledWith('5', 'GBP', 'USD');
});
@@ -99,7 +99,7 @@ describe('CollectionsController', () => {
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
c.savePlace(user, { collection_id: 3, name: 'A' } as never, 'sid');
expect(svc.savePlace).toHaveBeenCalledWith(1, { collection_id: 3, name: 'A' }, 'sid');
c.updatePlace(user, '9', { name: 'B' } as never, 'sid');
await c.updatePlace(user, '9', { name: 'B' } as never, 'sid');
expect(svc.updatePlace).toHaveBeenCalledWith(1, 9, { name: 'B' }, 'sid');
c.setStatus(user, '9', { status: 'want' } as never, 'sid');
expect(svc.setStatus).toHaveBeenCalledWith(1, 9, 'want', 'sid');
@@ -128,19 +128,19 @@ describe('UnifiedMemoriesController (parity with /api/integrations/memories/unif
});
describe('DELETE /trips/:tripId/photos', () => {
it('removes the photo on success', () => {
it('removes the photo on success', async () => {
const removeTripPhoto = vi.fn().mockReturnValue({ data: {} });
const svc = makeService({ removeTripPhoto });
const res = makeRes();
new UnifiedMemoriesController(svc).removePhoto(user, '5', { photo_id: 11 }, res);
await new UnifiedMemoriesController(svc).removePhoto(user, '5', { photo_id: 11 }, res);
expect(removeTripPhoto).toHaveBeenCalledWith('5', 7, 11);
expect(res.json).toHaveBeenCalledWith({ success: true });
});
it('maps the error envelope', () => {
it('maps the error envelope', async () => {
const svc = makeService({ removeTripPhoto: vi.fn().mockReturnValue({ error: { status: 404, message: 'Photo not found' } }) });
const res = makeRes();
new UnifiedMemoriesController(svc).removePhoto(user, '5', { photo_id: 11 }, res);
await new UnifiedMemoriesController(svc).removePhoto(user, '5', { photo_id: 11 }, res);
expect(res.status).toHaveBeenCalledWith(404);
expect(res.json).toHaveBeenCalledWith({ error: 'Photo not found' });
});
+6 -3
View File
@@ -94,8 +94,9 @@ describe('runShutdown', () => {
const deps = makeDeps({ getWsClients: () => [socket] });
const server = deps.server as unknown as ReturnType<typeof makeServer>;
// Never resolves on its own: this is the hang #2193 died on.
runShutdown('SIGTERM', deps);
// Never resolves on its own: this is the hang #2193 died on. Deliberately
// not awaited, so the rejection path is logged rather than left unobserved.
void runShutdown('SIGTERM', deps).catch((err: unknown) => console.error(err));
await vi.advanceTimersByTimeAsync(SOCKET_DRAIN_MS);
expect(socket.terminate).toHaveBeenCalled();
@@ -117,7 +118,9 @@ describe('runShutdown', () => {
// WAL behind for boot-time recovery on every restart.
const deps = makeDeps({ closeNestApp: vi.fn(() => new Promise<void>(() => {})) });
runShutdown('SIGTERM', deps);
// Deliberately not awaited: the close callback never fires, so this promise
// only settles through the forced exit below.
void runShutdown('SIGTERM', deps).catch((err: unknown) => console.error(err));
await vi.advanceTimersByTimeAsync(FORCED_EXIT_MS);
expect(deps.closeDb).toHaveBeenCalledTimes(1);