fix(server): plan 3a re-review follow-ups — plugin boot activation and the airports backfill inside a request context; the supervisor answers the child before failing closed; BOOT-SWEEP-001 drives the real boot hooks; ws adapter seam pinned

This commit is contained in:
jubnl
2026-09-22 17:39:38 +02:00
parent 761cd14b2b
commit 46bb11f508
10 changed files with 370 additions and 54 deletions
@@ -0,0 +1,81 @@
/**
* AirportsService boot backfill (task-6-rereview.md M1 — the exact C1 shape
* task-6-review-parity.md found elsewhere: `onApplicationBootstrap` used to
* `await this.backfillFlightEndpoints()` directly, outside any request
* context. Raw SQL only today (harmless now), but the wrap belongs at the
* entrypoint — the same reasoning `place-photo-cache.job.ts`/
* `trek-photo-cache.job.ts` already carry for their own raw-SQL sweeps — so
* it stays safe if this dependency graph goes repository-backed later, and so
* every one-off boot sweep in the tree goes through the one choke point).
*/
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
import { SchedulerRegistry } from '@nestjs/schedule';
const logMock = vi.hoisted(() => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
vi.mock('../../../../src/nest/audit/audit-log.logger', () => logMock);
import { AirportsService } from '../../../../src/nest/airports/airports.service';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
const testDb = createSnapshotTestDb();
let t: TestOrm;
beforeAll(async () => {
// Global context disallowed — the production setting — so this genuinely
// proves the boot backfill runs (or doesn't) inside a request context,
// rather than happening to work because the test default allows it.
t = await createTestOrm(testDb, { allowGlobalContext: false });
});
afterAll(async () => { await t.close(); testDb.close(); });
beforeEach(() => vi.clearAllMocks());
describe('AirportsService boot backfill', () => {
it('AIRPORTS-SVC-001: onApplicationBootstrap delegates the boot-time backfill through CronRegistrarService.runOnBoot, not a direct await', async () => {
const registered: Array<[string, () => void | Promise<void>]> = [];
const registrar = {
isEnabled: vi.fn(() => true),
register: vi.fn(() => true),
unregister: vi.fn(),
runOnBoot: vi.fn(async (name: string, fn: () => void | Promise<void>) => { registered.push([name, fn]); await fn(); }),
};
const svc = new AirportsService(new DatabaseService(testDb), registrar as unknown as CronRegistrarService);
const backfillSpy = vi.spyOn(svc, 'backfillFlightEndpoints').mockResolvedValue(undefined);
await svc.onApplicationBootstrap();
expect(registrar.runOnBoot).toHaveBeenCalledWith('airports-flight-endpoints-boot', expect.any(Function));
expect(backfillSpy).toHaveBeenCalledTimes(1);
});
it('AIRPORTS-SVC-002: with MikroORM wired into the registrar, the boot-time backfill actually runs — no cannotUseGlobalContext, nothing swallowed', async () => {
const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService, t.orm);
const svc = new AirportsService(new DatabaseService(testDb), registrar);
const backfillSpy = vi.spyOn(svc, 'backfillFlightEndpoints');
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
await svc.onApplicationBootstrap();
expect(backfillSpy).toHaveBeenCalledTimes(1);
expect(errSpy).not.toHaveBeenCalled();
expect(logMock.logError).not.toHaveBeenCalled();
} finally {
errSpy.mockRestore();
}
});
it('AIRPORTS-SVC-003: without MikroORM, the boot-time backfill never runs at all — logged with runOnBoot\'s own distinct message, never swallowed into "[DB] Flight endpoint backfill failed"', async () => {
const registrar = new CronRegistrarService(new SchedulerRegistry(), { isTest: () => false } as RuntimeEnvService); // no orm
const svc = new AirportsService(new DatabaseService(testDb), registrar);
const backfillSpy = vi.spyOn(svc, 'backfillFlightEndpoints');
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
await svc.onApplicationBootstrap();
expect(backfillSpy).not.toHaveBeenCalled();
expect(logMock.logError).toHaveBeenCalledWith(expect.stringMatching(/runOnBoot: no MikroORM available.*airports-flight-endpoints-boot/));
expect(errSpy).not.toHaveBeenCalled();
} finally {
errSpy.mockRestore();
}
});
});
@@ -29,7 +29,7 @@
* shared helpers use to let ordinary unit tests call a repository with no
* request wrapper at all: that default would hide this exact bug.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createUser } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
@@ -112,16 +112,26 @@ function makeSupervisor(resolveOrm?: () => { em: EntityManager } | undefined) {
}
describe('PluginSupervisor request context (D6, C3)', () => {
it('CTX-PLUGIN-001: without a resolveOrm thunk, the dispatch THROWS rather than running unwrapped (task-6-fix-brief.md item 1: fail closed at the choke point, not just downstream)', async () => {
it('CTX-PLUGIN-001: without a resolveOrm thunk, the dispatch THROWS (host-side visibility) but the child still gets answered first (task-6-rereview.md §5 RULING: an unanswered \'req\' hangs the plugin forever — plugin-host-entry.ts\'s pending map has no timeout)', async () => {
permissions.invalidatePermissionsCache();
const { supervisor, sup, sent } = makeSupervisor(); // no resolveOrm — the bug's exact reproduction
const canCreateAsSpy = vi.spyOn(guards, 'canCreateAs');
await expect(
supervisor.onMessage(sup, { k: 'req', id: 'r1', method: 'trips.create', params: { _inv: 'inv-1' } }),
).rejects.toThrow(/no ORM available/i);
// The dispatch never ran, so the child never got a response at all —
// not even the old fail-closed HOST_ERROR envelope.
expect(sent).toHaveLength(0);
// The dispatch itself never ran — same fail-closed guarantee as before.
expect(canCreateAsSpy).not.toHaveBeenCalled();
// But unlike the previous wave, the child DOES get a response: a HOST_ERROR
// envelope, matching the rate-limiter refusal's shape, so its ctx.* promise
// settles instead of hanging forever.
expect(sent).toHaveLength(1);
const res = sent[0];
expect(res.ok).toBe(false);
if (res.ok === false) {
expect(res.error.code).toBe('HOST_ERROR');
expect(res.error.message).toMatch(/no ORM available/i);
}
});
it('CTX-PLUGIN-002: wrapped in withRequestContext, the same dispatch enforces the stored override — a "user" role is refused', async () => {