fix(server): plan 3h close-out — new-value-wins COALESCE restores stay/reservation propagation; doc-sync state filter truthiness; request-context and parity ratchets for share, doc-sync and the integrations

This commit is contained in:
jubnl
2026-09-24 02:39:30 +02:00
parent 915ab84faf
commit f337f116d9
14 changed files with 379 additions and 103 deletions
@@ -78,6 +78,7 @@ import type {
} from '../../../../src/nest/doc-sync/doc-sync.dto';
import type { User } from '../../../../src/types';
import { createTestUnitOfWork, createTestTripsRepo } from '../../../helpers/test-uow';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import {
createTestDocumentConnectionsRepo,
createTestDocumentProviderFieldsRepo,
@@ -156,6 +157,7 @@ const realtime = { broadcast: vi.fn() };
// createTestUnitOfWork is async — module-scope construction cannot await it.
let config: DocSyncConfigService;
let controller: DocSyncController;
let t: TestOrm;
/** Only what publicOrigin reads: header lookup plus the connection's own scheme. */
function makeReq(headers: Record<string, string> = {}, protocol = 'http'): Request {
@@ -210,6 +212,11 @@ let otherTripId: number;
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
// L1 (Plan 3h Task 7 review): createLink's fire-and-forget syncLink call
// is now wrapped in its own withRequestContext fork, which needs a real
// MikroORM instance — sync itself stays a spy, this ORM never resolves a
// repository through it.
t = await createTestOrm(testDb);
config = new DocSyncConfigService(
await createTestTripsRepo(testDb),
await createTestDocumentProvidersRepo(testDb),
@@ -220,7 +227,7 @@ beforeAll(async () => {
registry,
await createTestUnitOfWork(testDb),
);
controller = new DocSyncController(config, sync as unknown as DocSyncService, registry, realtime as unknown as RealtimeService);
controller = new DocSyncController(config, sync as unknown as DocSyncService, registry, realtime as unknown as RealtimeService, t.orm);
const o = createUser(testDb, { username: 'owner', email: 'owner@test.local' }).user;
const m = createUser(testDb, { username: 'member', email: 'member@test.local' }).user;
const a = createUser(testDb, { username: 'admin', email: 'admin@test.local', role: 'admin' }).user;
@@ -232,7 +239,8 @@ beforeAll(async () => {
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, m.id);
});
afterAll(() => {
afterAll(async () => {
await t.close();
testDb.close();
});
@@ -434,7 +434,13 @@ describe('DocSyncService', () => {
const tieBreakFirst = await makeLink({ lastSyncAt: null }); // same ties; id is the ONLY thing that can separate these two
const midStale = await makeLink({ lastSyncAt: sqlTime('-2 hours') }); // next=NULL, last=2h ago — after the NULL/NULL pair, before the recent one
const midRecent = await makeLink({ lastSyncAt: sqlTime('-1 minute') }); // next=NULL, last=1m ago — last of the NULL-next-attempt group
const backedOff = await makeLink({ nextAttemptAt: sqlTime('-1 hour'), lastSyncAt: sqlTime('-1 minute') }); // next_attempt_at is NON-null — sorts after every NULL row regardless of last_sync_at
// Plan 3h Task 7 review, M4: this row's `last_sync_at` used to be
// `-1 minute` — the newest of every row in this test — so it was
// ALSO the sort-first row under `last_sync_at`-before-`next_attempt_at`
// (the swapped-key mutation), leaving the test green either way. `-3
// hours` is older than every other row's `last_sync_at`, so only the
// correct key order (next_attempt_at first) still sorts this row last.
const backedOff = await makeLink({ nextAttemptAt: sqlTime('-1 hour'), lastSyncAt: sqlTime('-3 hours') }); // next_attempt_at is NON-null — sorts after every NULL row regardless of last_sync_at
const ids = (await service.dueLinks()).map((l) => l.id);
const expected = [tieBreakSecond.id, tieBreakFirst.id].sort((a, b) => a - b);
@@ -1176,6 +1182,41 @@ describe('DocSyncService', () => {
});
});
describe('itemsForTrip', () => {
it('M2 (Plan 3h Task 7 review): an empty `?state=` returns every item, not none — legacy truthiness, not an `undefined` check', async () => {
const link = await makeLink();
const fileId = makeFile();
const withFile = seedItem(link, { remoteId: 'r1', state: 'synced', fileId });
const withoutFile = seedItem(link, { remoteId: 'r2', state: 'conflict' });
// `state === undefined ? listForTrip : listForTripByState` (the R2
// regression this ratchet pins) would treat `''` as a real filter
// value and match nothing; the legacy/fixed gate is `state ?
// listForTripByState : listForTrip`, so an empty string behaves the
// same as omitting the query param entirely.
const withEmptyState = await service.itemsForTrip(tripId, '');
const withNoState = await service.itemsForTrip(tripId);
expect(withEmptyState.map((r) => r.id).sort()).toEqual([withFile, withoutFile].sort());
expect(withNoState.map((r) => r.id).sort()).toEqual([withFile, withoutFile].sort());
// The file-joined row carries the LEFT JOIN trip_files column; the
// file-less row must not, so `listForTrip`'s join shape is exercised
// by both a hit and a miss (M1's coverage gap on these two methods).
expect(withNoState.find((r) => r.id === withFile)?.file_name).toBe('boarding.pdf');
expect(withNoState.find((r) => r.id === withoutFile)?.file_name).toBeNull();
});
it('a real state value still narrows to that one state', async () => {
const link = await makeLink();
seedItem(link, { remoteId: 'r1', state: 'synced' });
const conflicted = seedItem(link, { remoteId: 'r2', state: 'conflict' });
const rows = await service.itemsForTrip(tripId, 'conflict');
expect(rows.map((r) => r.id)).toEqual([conflicted]);
});
});
describe('resolveConflict', () => {
/** A conflicted pairing: the provider moved on, and TREK holds its own copy. */
function seedConflict(link: LinkRow): { itemId: number; fileId: number } {