refactor(doc-sync): connections, reconciler and controller-SQL relocation through repositories

This commit is contained in:
jubnl
2026-09-24 00:40:23 +02:00
parent 182744e416
commit 8bcfd92142
23 changed files with 2658 additions and 638 deletions
+105
View File
@@ -0,0 +1,105 @@
/**
* Plan 3h Task 5 (doc-sync) — the repositories a hand-constructed
* `DocSyncConfigService`/`DocSyncService`/`DocSyncController`/
* `DocSyncWebhookController`/`DocSyncJob` needs, bound to a suite's own
* better-sqlite3 handle.
*
* A separate file from `tests/helpers/test-uow.ts` on purpose: that file is
* a shared-window append target for THREE concurrent Plan 3h tasks
* (collections, dawarich, doc-sync — the plan's own "shared-file windows"
* note), and this task's brief names this file specifically so its own
* repository helpers land without racing another task's append to the same
* file. Same memoisation-per-handle pattern as every helper in
* `test-uow.ts` (one `sharedTestOrm(db)` per test file's better-sqlite3
* handle, imported from there rather than opening a second `MikroORM.init`
* over the same connection — `test-uow.ts`'s own `sharedTestOrm` docstring
* explains why a second ORM instance is a real, if subtle, bug: two
* identity maps and two Kysely clients, neither closed).
*/
import type Database from 'better-sqlite3';
import { sharedTestOrm } from './test-uow';
import { DocumentConnections } from '../../src/db/entities/DocumentConnections.entity';
import type { DocumentConnectionsRepository } from '../../src/db/repositories/DocumentConnections.repository';
import { DocumentProviders } from '../../src/db/entities/DocumentProviders.entity';
import type { DocumentProvidersRepository } from '../../src/db/repositories/DocumentProviders.repository';
import { DocumentProviderFields } from '../../src/db/entities/DocumentProviderFields.entity';
import type { DocumentProviderFieldsRepository } from '../../src/db/repositories/DocumentProviderFields.repository';
import { TripDocumentLinks } from '../../src/db/entities/TripDocumentLinks.entity';
import type { TripDocumentLinksRepository } from '../../src/db/repositories/TripDocumentLinks.repository';
import { DocumentSyncItems } from '../../src/db/entities/DocumentSyncItems.entity';
import type { DocumentSyncItemsRepository } from '../../src/db/repositories/DocumentSyncItems.repository';
import { TripFiles } from '../../src/db/entities/TripFiles.entity';
import type { TripFilesRepository } from '../../src/db/repositories/TripFiles.repository';
import { FileLinks } from '../../src/db/entities/FileLinks.entity';
import type { FileLinksRepository } from '../../src/db/repositories/FileLinks.repository';
const documentConnectionsPerHandle = new WeakMap<Database.Database, Promise<DocumentConnectionsRepository>>();
const documentProvidersPerHandle = new WeakMap<Database.Database, Promise<DocumentProvidersRepository>>();
const documentProviderFieldsPerHandle = new WeakMap<Database.Database, Promise<DocumentProviderFieldsRepository>>();
const tripDocumentLinksPerHandle = new WeakMap<Database.Database, Promise<TripDocumentLinksRepository>>();
const documentSyncItemsPerHandle = new WeakMap<Database.Database, Promise<DocumentSyncItemsRepository>>();
const tripFilesPerHandle = new WeakMap<Database.Database, Promise<TripFilesRepository>>();
const fileLinksPerHandle = new WeakMap<Database.Database, Promise<FileLinksRepository>>();
/** The `DocumentConnectionsRepository` a hand-constructed `DocSyncConfigService` needs. */
export function createTestDocumentConnectionsRepo(db: Database.Database): Promise<DocumentConnectionsRepository> {
const existing = documentConnectionsPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(DocumentConnections));
documentConnectionsPerHandle.set(db, pending);
return pending;
}
/** The `DocumentProvidersRepository` a hand-constructed `DocSyncConfigService` needs. */
export function createTestDocumentProvidersRepo(db: Database.Database): Promise<DocumentProvidersRepository> {
const existing = documentProvidersPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(DocumentProviders));
documentProvidersPerHandle.set(db, pending);
return pending;
}
/** The `DocumentProviderFieldsRepository` a hand-constructed `DocSyncConfigService` needs. */
export function createTestDocumentProviderFieldsRepo(db: Database.Database): Promise<DocumentProviderFieldsRepository> {
const existing = documentProviderFieldsPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(DocumentProviderFields));
documentProviderFieldsPerHandle.set(db, pending);
return pending;
}
/** The `TripDocumentLinksRepository` a hand-constructed `DocSyncConfigService`/`DocSyncService` needs. */
export function createTestTripDocumentLinksRepo(db: Database.Database): Promise<TripDocumentLinksRepository> {
const existing = tripDocumentLinksPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(TripDocumentLinks));
tripDocumentLinksPerHandle.set(db, pending);
return pending;
}
/** The `DocumentSyncItemsRepository` a hand-constructed `DocSyncService` needs. */
export function createTestDocumentSyncItemsRepo(db: Database.Database): Promise<DocumentSyncItemsRepository> {
const existing = documentSyncItemsPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(DocumentSyncItems));
documentSyncItemsPerHandle.set(db, pending);
return pending;
}
/** The `TripFilesRepository` a hand-constructed `DocSyncService` needs (cross-domain, 3e — DS4/DS15/DS19/DS29/DS32/DS36). */
export function createTestTripFilesRepo(db: Database.Database): Promise<TripFilesRepository> {
const existing = tripFilesPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(TripFiles));
tripFilesPerHandle.set(db, pending);
return pending;
}
/** The `FileLinksRepository` a hand-constructed `DocSyncService` needs (cross-domain, 3e — DS16). */
export function createTestFileLinksRepo(db: Database.Database): Promise<FileLinksRepository> {
const existing = fileLinksPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(FileLinks));
fileLinksPerHandle.set(db, pending);
return pending;
}
@@ -0,0 +1,123 @@
/**
* Doc-sync webhook request-context ratchet (Plan 3h Task 5, R9).
*
* `DocSyncWebhookController#schedule()`'s `setTimeout` callback runs fully
* detached from the HTTP request that triggered it: `nudge()` already
* answered `{received:true}` before the debounce window
* (`WEBHOOK_NUDGE_DEBOUNCE_SECONDS`) elapses, so whatever request-scoped
* `EntityManager` fork the triggering request held is long gone by the time
* the timer body runs. Per 3f's own R3 precedent (measured: `AsyncLocalStorage`
* survives a detached chain intact in this codebase today), the timer body
* now forks its OWN fresh request context via `withRequestContext` — insurance,
* not a fix for an observed failure.
*
* This test drives the REAL `DocSyncWebhookController.nudge()` (not a
* hand-built double) through a real HTTP request against a compiled
* `buildApp()` boot — `nudge()` itself needs the per-request `EntityManager`
* fork Nest's own middleware provides, so only the schedule()`'s DETACHED
* TIMER body (which runs from a genuinely bare context, after the response
* has already gone out) is what this test's assertion is about — and asserts
* that body never logs `cannotUseGlobalContext` — the same
* regression class `boot-sweeps-request-context.test.ts` guards for the seven
* cron boot sweeps and `storage-health-notifier-request-context.test.ts`
* guards for Plan 3f's own R3 listener.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import type { Server } from 'http';
vi.mock('../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
vi.mock('../../src/config', () => ({
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
SESSION_DURATION: '24h',
SESSION_DURATION_MS: 86400000,
SESSION_DURATION_SECONDS: 86400,
DEFAULT_LANGUAGE: 'en',
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn(), getOnlineUserIds: vi.fn(() => []) }));
import { db as testDb } from '../../src/db/database';
import { buildApp } from '../../src/bootstrap';
import { createUser, createTrip } from '../helpers/factories';
import { WEBHOOK_NUDGE_DEBOUNCE_SECONDS } from '../../src/nest/doc-sync/doc-sync.constants';
describe('DocSyncWebhookController#schedule() runs its detached timer body inside its own request context', () => {
let app: INestApplication;
let server: Server;
let token: string;
beforeAll(async () => {
app = await buildApp();
server = app.getHttpServer();
// The addon gate and the provider both have to be genuinely on: nudge()
// returns before ever scheduling anything otherwise (isSwitchedOff's own
// early-out), and this ratchet needs schedule() to actually fire.
testDb.exec("UPDATE addons SET enabled = 1 WHERE id = 'documents'");
testDb.exec("UPDATE document_providers SET enabled = 1 WHERE id = 'paperless'");
const owner = createUser(testDb, { username: 'docsync-webhook-ctx', email: 'docsync-webhook-ctx@test.local' }).user;
const trip = createTrip(testDb, owner.id, { title: 'Japan' });
const connInfo = testDb
.prepare(
`INSERT INTO document_connections (trip_id, provider_id, owner_user_id, base_url, secrets, settings)
VALUES (?, 'paperless', ?, 'https://paperless.example.com', NULL, '{}')`,
)
.run(trip.id, owner.id);
token = 'webhook-ctx-ratchet-token';
testDb
.prepare(
`INSERT INTO trip_document_links
(trip_id, connection_id, provider_id, remote_scope_key, remote_label, direction, delete_policy,
conflict_policy, sync_enabled, webhook_token, created_by)
VALUES (?, ?, 'paperless', 'tag:1', 'Japan', 'both', 'unlink', 'manual', 1, ?, ?)`,
)
.run(trip.id, connInfo.lastInsertRowid, token, owner.id);
});
afterAll(async () => {
await app.close();
testDb.close();
});
it(
'WEBHOOK-CTX-001: nudging from a bare (non-request) context never logs cannotUseGlobalContext once the debounce timer fires',
async () => {
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
// A REAL HTTP request through the compiled app — not a hand-built
// double, and not a direct method call either: `nudge()` itself
// needs the per-request `EntityManager` fork Nest's own middleware
// provides (its own `getLinkByToken` read would otherwise throw
// `cannotUseGlobalContext` before ever reaching `schedule()` — this
// is what a direct `app.get(...).nudge(...)` call, tried first,
// actually surfaced: confirmation this test needs the real request
// path, not a shortcut around it). Only the DETACHED TIMER body
// that fires after this response is the "bare context" under test.
const res = await request(server).post(`/api/docsync/webhook/${token}`).send({});
expect(res.status).toBe(200);
expect(res.body).toEqual({ received: true });
// Let the real debounce timer fire, then drain the microtasks its
// async body queues (real timers here — the detached body is a
// genuine `setTimeout`, not something fake timers can fast-forward
// through a real HTTP-free integration boot safely).
await new Promise((resolve) => setTimeout(resolve, (WEBHOOK_NUDGE_DEBOUNCE_SECONDS + 2) * 1000));
const suspicious = errSpy.mock.calls
.map((args) => args.map(String).join(' '))
.filter((line) => /cannotUseGlobalContext|global EntityManager/i.test(line));
expect(suspicious).toEqual([]);
} finally {
errSpy.mockRestore();
}
},
20_000,
);
});
@@ -12,6 +12,7 @@ import {
castInteger,
castIntegerKysely,
coalesce,
coalesceOverride,
coalesceParam,
collateNoCase,
columnIncrementedBy,
@@ -21,9 +22,11 @@ import {
countAll,
countAllRef,
currentTimestamp,
currentTimestampKysely,
dateAdd,
dateOf,
dayDistance,
foundAgainState,
lower,
lowerParam,
lowerTrim,
@@ -337,6 +340,42 @@ describe('sql-functions (sqlite)', () => {
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('Fallback Name');
});
// Plan 3h Task 5 (doc-sync, DS23/DS24) — `coalesceOverride`, the
// mirror-image value-side shape `COALESCE(?, col)`: the caller's NEW
// value wins unless it is null, unlike `coalesceParam`'s `COALESCE(col,
// ?)` above (existing column wins unless IT is null). Confirmed
// genuinely the opposite direction by a live round-trip, not assumed from
// the two functions' similar names.
it('SQLF-090: coalesceOverride(value, ref) writes COALESCE(?, col) — a non-null new value overwrites the existing column', async () => {
const { user } = createUser(testDb);
testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Old Name', user.id);
const platform = t.em.getPlatform();
await t.em.createQueryBuilder(Users, 'u')
.update({ display_name: coalesceOverride(platform, 'New Name', 'display_name') })
.where({ id: user.id })
.execute('run');
t.clear();
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('New Name');
});
it('SQLF-091: coalesceOverride(null, ref) leaves the existing column untouched — a null new value never clobbers what is stored', async () => {
const { user } = createUser(testDb);
testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Keep Me', user.id);
const platform = t.em.getPlatform();
await t.em.createQueryBuilder(Users, 'u')
.update({ display_name: coalesceOverride(platform, null, 'display_name') })
.where({ id: user.id })
.execute('run');
t.clear();
expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('Keep Me');
});
it('SQLF-092: an unknown platform fails closed for coalesceOverride', () => {
class FakePlatform extends Platform {}
const foreign = new FakePlatform();
expect(() => coalesceOverride(foreign, 'x', 'u.a')).toThrow(/no implementation for platform FakePlatform/);
});
it('SQLF-021: absDifference is usable as a filter key, matching ABS(col - ?) <= tolerance', async () => {
const { user: near } = createUser(testDb);
testDb.prepare('UPDATE users SET login_count = 12 WHERE id = ?').run(near.id);
@@ -1124,6 +1163,79 @@ describe('sql-functions (sqlite)', () => {
const eb = expressionBuilder<UsersKyselyDB, 'users'>();
expect(() => nowPlusSecondsKysely(foreign, eb, 1)).toThrow(/no implementation for platform FakePlatform/);
});
// Plan 3h Task 5 (doc-sync) — `foundAgainState`, the typed rebuild of
// `doc-sync.service.ts`'s module-level `FOUND_AGAIN` SQL-text constant
// (DS2/DS3/DS5/DS12's shared SET clause). A scratch temp table stands in
// for `document_sync_items` here — the CASE only ever reads the two
// columns it names, so a two-column probe table exercises its logic
// exactly, without a trip/connection/link FK chain this file has no other
// reason to build.
describe('foundAgainState (doc-sync FOUND_AGAIN)', () => {
beforeEach(() => {
testDb.exec('DROP TABLE IF EXISTS found_again_probe');
testDb.exec('CREATE TEMP TABLE found_again_probe (id INTEGER PRIMARY KEY, state TEXT NOT NULL, file_id INTEGER)');
});
function apply(state: string, fileId: number | null): string {
const platform = t.em.getPlatform();
testDb.prepare('DELETE FROM found_again_probe WHERE id = 1').run();
testDb.prepare('INSERT INTO found_again_probe (id, state, file_id) VALUES (1, ?, ?)').run(state, fileId);
testDb.prepare(`UPDATE found_again_probe SET state = ${foundAgainState(platform, 'state', 'file_id').sql} WHERE id = 1`).run();
return (testDb.prepare('SELECT state FROM found_again_probe WHERE id = 1').get() as { state: string }).state;
}
it("SQLF-083: recovers a row on record as missing once its file is paired again, matching the legacy FOUND_AGAIN text (state='remote_missing' AND file_id IS NOT NULL -> 'synced')", () => {
expect(apply('remote_missing', 42)).toBe('synced');
});
it('SQLF-084: leaves a row on record as missing alone while it has no paired file (a rename/move under a path-as-id provider, not yet re-matched)', () => {
expect(apply('remote_missing', null)).toBe('remote_missing');
});
it('SQLF-085: leaves every other state untouched — error is never silently cleared by FOUND_AGAIN', () => {
for (const state of ['error', 'conflict', 'synced', 'pending', 'local_deleted']) {
expect(apply(state, 7)).toBe(state);
}
});
it('SQLF-086: an unknown platform fails closed for foundAgainState', () => {
class FakePlatform extends Platform {}
const foreign = new FakePlatform();
expect(() => foundAgainState(foreign, 'state', 'file_id')).toThrow(/no implementation for platform FakePlatform/);
});
});
// Plan 3h Task 5 (doc-sync, R3) — `currentTimestampKysely`, DS24's
// `last_seen_at = CURRENT_TIMESTAMP` inside the partial-index `ON
// CONFLICT ... DO UPDATE`.
describe('currentTimestampKysely', () => {
it('SQLF-087: compiles to the bare CURRENT_TIMESTAMP keyword with no parameters, matching currentTimestamp\'s own raw text and a real row\'s clock value', async () => {
const platform = t.em.getPlatform();
const compiled = t.em
.getKysely<UsersKyselyDB>()
.selectFrom('users')
.select(() => [currentTimestampKysely(platform).as('d')])
.compile();
expect(compiled.sql).toBe('select CURRENT_TIMESTAMP as "d" from "users"');
expect(compiled.parameters).toEqual([]);
createUser(testDb);
const got = testDb.prepare(compiled.sql).get(...compiled.parameters) as { d: string };
const raw = testDb.prepare(`SELECT ${currentTimestamp(platform).sql} as d`).get() as { d: string };
expect(Math.abs(new Date(`${got.d.replace(' ', 'T')}Z`).getTime() - new Date(`${raw.d.replace(' ', 'T')}Z`).getTime())).toBeLessThan(10_000);
});
it('SQLF-088: current_timestamp() called as a function is rejected by SQLite — proving the bare-keyword shape is load-bearing, not a style choice', () => {
expect(() => testDb.prepare('SELECT current_timestamp() as d').get()).toThrow(/syntax error/);
});
it('SQLF-089: an unknown platform fails closed for currentTimestampKysely', () => {
class FakePlatform extends Platform {}
const foreign = new FakePlatform();
expect(() => currentTimestampKysely(foreign)).toThrow(/no implementation for platform FakePlatform/);
});
});
});
/**
@@ -0,0 +1,245 @@
/**
* `DocumentSyncItemsRepository` (Plan 3h Task 5, R3's own two named
* requirements): DS24's partial-unique-index upsert
* (`insertOrUpsertOnConflict`, `ON CONFLICT(link_id, remote_id) WHERE
* remote_id IS NOT NULL DO UPDATE`) and DS23's plain conditional update
* (`recordAttempt`, ten `COALESCE` columns + the backoff second-count).
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createTrip, createUser } from '../../../helpers/factories';
import { DocumentSyncItems } from '../../../../src/db/entities/DocumentSyncItems.entity';
import type { DocumentSyncItemsRepository } from '../../../../src/db/repositories/DocumentSyncItems.repository';
import { currentTimestampKysely } from '../../../../src/db/dialect/sql-functions';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: DocumentSyncItemsRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(DocumentSyncItems);
});
beforeEach(() => { resetTestDb(testDb); t.clear(); });
afterAll(async () => { await t.close(); testDb.close(); });
function fixture() {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const connInfo = testDb
.prepare(
`INSERT INTO document_connections (trip_id, provider_id, owner_user_id, base_url, secrets, settings)
VALUES (?, 'paperless', ?, 'https://paperless.example.com', NULL, '{}')`,
)
.run(trip.id, user.id);
const linkInfo = testDb
.prepare(
`INSERT INTO trip_document_links (trip_id, connection_id, provider_id, remote_scope_key, remote_label, direction, delete_policy, conflict_policy, sync_enabled, created_by)
VALUES (?, ?, 'paperless', 'tag:1', 'Japan', 'both', 'unlink', 'manual', 1, ?)`,
)
.run(trip.id, connInfo.lastInsertRowid, user.id);
return { user, trip, linkId: Number(linkInfo.lastInsertRowid) };
}
function insertData(linkId: number, tripId: number, over: Partial<Parameters<DocumentSyncItemsRepository['insertOrUpsertOnConflict']>[0]> = {}) {
return {
link_id: linkId,
trip_id: tripId,
file_id: null,
trek_doc_uid: `uid-${Math.random()}`,
remote_id: null,
remote_name: null,
remote_version: null,
remote_size: null,
remote_modified_at: null,
content_sha256: null,
pushed_sha256: null,
state: 'synced',
error_code: null,
attempts: 0,
next_attempt_after_seconds: null,
synced_now: true,
...over,
};
}
describe('DocumentSyncItemsRepository', () => {
describe('insertOrUpsertOnConflict (DS24, R3 — the partial-unique-index upsert)', () => {
it('DS24REPO-001: pinned rendered SQL for the ON CONFLICT DO UPDATE target and SET clause', () => {
const platform = t.em.getPlatform();
const compiled = t.em
.getKysely<{ document_sync_items: Record<string, unknown> }>()
.insertInto('document_sync_items')
.values({
link_id: 1, trip_id: 1, file_id: null, trek_doc_uid: 'x', remote_id: 'r1', remote_name: null,
remote_version: null, remote_size: null, remote_modified_at: null, content_sha256: null,
pushed_sha256: null, state: 'synced', error_code: null, attempts: 0, next_attempt_at: null,
synced_at: null, last_seen_at: 'CURRENT_TIMESTAMP',
})
.onConflict((oc) =>
oc
.columns(['link_id', 'remote_id'])
.where('remote_id', 'is not', null)
.doUpdateSet({
state: (eb) => eb.ref('excluded.state'),
error_code: (eb) => eb.ref('excluded.error_code'),
file_id: (eb) => eb.fn.coalesce(eb.ref('excluded.file_id'), eb.ref('document_sync_items.file_id')),
remote_version: (eb) => eb.fn.coalesce(eb.ref('excluded.remote_version'), eb.ref('document_sync_items.remote_version')),
content_sha256: (eb) => eb.fn.coalesce(eb.ref('excluded.content_sha256'), eb.ref('document_sync_items.content_sha256')),
pushed_sha256: (eb) => eb.fn.coalesce(eb.ref('excluded.pushed_sha256'), eb.ref('document_sync_items.pushed_sha256')),
last_seen_at: () => currentTimestampKysely(platform),
}),
)
.compile();
// Pinned for the task report — the exact ON CONFLICT clause Kysely
// renders for this table, proving the partial-index predicate is
// restated verbatim (SQLite's own requirement, DS24's own doc
// comment) and the DO UPDATE SET matches the legacy statement's own
// five re-written columns plus the two verbatim-from-excluded ones.
expect(compiled.sql).toContain('on conflict ("link_id", "remote_id") where "remote_id" is not null do update set');
expect(compiled.sql).toContain('"state" = "excluded"."state"');
expect(compiled.sql).toContain('"error_code" = "excluded"."error_code"');
expect(compiled.sql).toContain('"file_id" = coalesce("excluded"."file_id", "document_sync_items"."file_id")');
expect(compiled.sql).toContain('"remote_version" = coalesce("excluded"."remote_version", "document_sync_items"."remote_version")');
expect(compiled.sql).toContain('"content_sha256" = coalesce("excluded"."content_sha256", "document_sync_items"."content_sha256")');
expect(compiled.sql).toContain('"pushed_sha256" = coalesce("excluded"."pushed_sha256", "document_sync_items"."pushed_sha256")');
expect(compiled.sql).toContain('"last_seen_at" = CURRENT_TIMESTAMP');
// Pinned in full, for the task report:
expect(compiled.sql).toBe(
'insert into "document_sync_items" ("link_id", "trip_id", "file_id", "trek_doc_uid", "remote_id", "remote_name", "remote_version", "remote_size", "remote_modified_at", "content_sha256", "pushed_sha256", "state", "error_code", "attempts", "next_attempt_at", "synced_at", "last_seen_at") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) on conflict ("link_id", "remote_id") where "remote_id" is not null do update set "state" = "excluded"."state", "error_code" = "excluded"."error_code", "file_id" = coalesce("excluded"."file_id", "document_sync_items"."file_id"), "remote_version" = coalesce("excluded"."remote_version", "document_sync_items"."remote_version"), "content_sha256" = coalesce("excluded"."content_sha256", "document_sync_items"."content_sha256"), "pushed_sha256" = coalesce("excluded"."pushed_sha256", "document_sync_items"."pushed_sha256"), "last_seen_at" = CURRENT_TIMESTAMP',
);
});
/**
* R3's own required mutation test: insert two rows differing only in
* `remote_id` under the same `link_id` (both succeed — the partial
* index only constrains non-NULL `remote_id`s against each other), then
* a THIRD insert colliding on `(link_id, remote_id)` with one of them —
* proving the partial index still enforces "at most one non-NULL
* remote_id per link" post-conversion by upserting (not duplicating).
*/
it('DS24REPO-002 (R3 mutation proof): a colliding (link_id, remote_id) pair upserts in place rather than duplicating', async () => {
const { linkId, trip } = fixture();
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: 'r1', trek_doc_uid: 'uid-a', state: 'synced', remote_version: 'v1' }));
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: 'r2', trek_doc_uid: 'uid-b', state: 'synced', remote_version: 'v1' }));
const afterTwo = testDb.prepare('SELECT id, remote_id, remote_version FROM document_sync_items WHERE link_id = ? ORDER BY id').all(linkId) as Array<{ id: number; remote_id: string; remote_version: string }>;
expect(afterTwo).toHaveLength(2);
const r1Id = afterTwo.find((r) => r.remote_id === 'r1')!.id;
// The colliding insert: same link_id + remote_id='r1' as the first row.
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: 'r1', trek_doc_uid: 'uid-c', state: 'conflict', remote_version: 'v2' }));
const afterThree = testDb.prepare('SELECT id, remote_id, remote_version, state FROM document_sync_items WHERE link_id = ? ORDER BY id').all(linkId) as Array<{ id: number; remote_id: string; remote_version: string; state: string }>;
// Still exactly two rows — the third insert upserted onto the first, not a third row.
expect(afterThree).toHaveLength(2);
const upserted = afterThree.find((r) => r.id === r1Id)!;
expect(upserted.remote_id).toBe('r1');
expect(upserted.state).toBe('conflict');
expect(upserted.remote_version).toBe('v2');
});
it('DS24REPO-003: two rows with NULL remote_id under the same link never collide (the partial index only constrains non-NULL)', async () => {
const { linkId, trip } = fixture();
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: null, trek_doc_uid: 'uid-x' }));
await repo.insertOrUpsertOnConflict(insertData(linkId, trip.id, { remote_id: null, trek_doc_uid: 'uid-y' }));
const rows = testDb.prepare('SELECT id FROM document_sync_items WHERE link_id = ?').all(linkId);
expect(rows).toHaveLength(2);
});
});
describe('recordAttempt (DS23, R3 — the plain conditional update, itemId≠null)', () => {
async function seedRow(linkId: number, tripId: number) {
const id = await repo.insertOrUpsertOnConflict(
insertData(linkId, tripId, {
remote_id: 'r1', file_id: null, remote_name: 'a.pdf', remote_version: 'v1', remote_size: 512,
remote_modified_at: '2026-09-01T08:00:00Z', content_sha256: 'old-hash', pushed_sha256: 'old-pushed',
}),
).then(() => (testDb.prepare('SELECT id FROM document_sync_items WHERE link_id = ? AND remote_id = ?').get(linkId, 'r1') as { id: number }).id);
return id;
}
/**
* R3's full-key parity test: all ten `COALESCE` columns win with a
* non-null new value (branch 1) — matching the legacy `COALESCE(?,
* col)` — and each falls back to the EXISTING column when the new
* value is null (branch 2), the same statement's other half. Both
* branches proved on the SAME row, sequentially, so branch 2 is
* genuinely proving "kept", not merely "never changed".
*/
it('DS23REPO-001 (R3 parity): a non-null new value overwrites every COALESCE column; a null one keeps the existing value', async () => {
const { linkId, trip } = fixture();
const itemId = await seedRow(linkId, trip.id);
const newFileId = Number(
testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)').run(trip.id, 'stored.pdf', 'b.pdf').lastInsertRowid,
);
// Branch 1: every COALESCE column gets a genuinely new, non-null value.
await repo.recordAttempt(itemId, {
state: 'synced', error_code: null, file_id: newFileId, remote_id: 'r1-new', remote_version: 'v2',
remote_name: 'b.pdf', remote_size: 2048, remote_modified_at: '2026-09-18T10:00:00Z',
content_sha256: 'new-hash', pushed_sha256: 'new-pushed', attempts: 0, next_attempt_after_seconds: null,
});
let row = testDb.prepare('SELECT * FROM document_sync_items WHERE id = ?').get(itemId) as Record<string, unknown>;
expect(row).toMatchObject({
file_id: newFileId, remote_id: 'r1-new', remote_version: 'v2', remote_name: 'b.pdf', remote_size: 2048,
remote_modified_at: '2026-09-18T10:00:00Z', content_sha256: 'new-hash', pushed_sha256: 'new-pushed',
});
// Branch 2: every COALESCE column arrives null — the existing (branch-1) value survives untouched.
await repo.recordAttempt(itemId, {
state: 'synced', error_code: null, file_id: null, remote_id: null, remote_version: null,
remote_name: null, remote_size: null, remote_modified_at: null, content_sha256: null,
pushed_sha256: null, attempts: 0, next_attempt_after_seconds: null,
});
row = testDb.prepare('SELECT * FROM document_sync_items WHERE id = ?').get(itemId) as Record<string, unknown>;
expect(row).toMatchObject({
file_id: newFileId, remote_id: 'r1-new', remote_version: 'v2', remote_name: 'b.pdf', remote_size: 2048,
remote_modified_at: '2026-09-18T10:00:00Z', content_sha256: 'new-hash', pushed_sha256: 'new-pushed',
});
});
it('DS23REPO-002: next_attempt_after_seconds shifts the DB clock forward by the given second count; null leaves it NULL', async () => {
const { linkId, trip } = fixture();
const itemId = await seedRow(linkId, trip.id);
await repo.recordAttempt(itemId, {
state: 'error', error_code: 'timeout', file_id: null, remote_id: null, remote_version: null,
remote_name: null, remote_size: null, remote_modified_at: null, content_sha256: null,
pushed_sha256: null, attempts: 1, next_attempt_after_seconds: 300,
});
const row = testDb.prepare("SELECT next_attempt_at, datetime('now', '+300 seconds') AS expected FROM document_sync_items WHERE id = ?").get(itemId) as { next_attempt_at: string; expected: string };
expect(row.next_attempt_at).not.toBeNull();
expect(Math.abs(new Date(`${row.next_attempt_at.replace(' ', 'T')}Z`).getTime() - new Date(`${row.expected.replace(' ', 'T')}Z`).getTime())).toBeLessThan(5000);
await repo.recordAttempt(itemId, {
state: 'synced', error_code: null, file_id: null, remote_id: null, remote_version: null,
remote_name: null, remote_size: null, remote_modified_at: null, content_sha256: null,
pushed_sha256: null, attempts: 0, next_attempt_after_seconds: null,
});
const cleared = testDb.prepare('SELECT next_attempt_at FROM document_sync_items WHERE id = ?').get(itemId) as { next_attempt_at: string | null };
expect(cleared.next_attempt_at).toBeNull();
});
it('DS23REPO-003: synced_at is stamped only when state is synced, and left alone otherwise', async () => {
const { linkId, trip } = fixture();
const itemId = await seedRow(linkId, trip.id);
testDb.prepare("UPDATE document_sync_items SET synced_at = '2020-01-01 00:00:00' WHERE id = ?").run(itemId);
await repo.recordAttempt(itemId, {
state: 'error', error_code: 'timeout', file_id: null, remote_id: null, remote_version: null,
remote_name: null, remote_size: null, remote_modified_at: null, content_sha256: null,
pushed_sha256: null, attempts: 1, next_attempt_after_seconds: null,
});
expect((testDb.prepare('SELECT synced_at FROM document_sync_items WHERE id = ?').get(itemId) as { synced_at: string }).synced_at).toBe('2020-01-01 00:00:00');
await repo.recordAttempt(itemId, {
state: 'synced', error_code: null, file_id: null, remote_id: null, remote_version: null,
remote_name: null, remote_size: null, remote_modified_at: null, content_sha256: null,
pushed_sha256: null, attempts: 0, next_attempt_after_seconds: null,
});
expect((testDb.prepare('SELECT synced_at FROM document_sync_items WHERE id = ?').get(itemId) as { synced_at: string }).synced_at).not.toBe('2020-01-01 00:00:00');
});
});
});
@@ -56,7 +56,6 @@ import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { resetTestDb } from '../../../helpers/test-db';
import { createTrip, createUser } from '../../../helpers/factories';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import {
DocSyncConfigService,
type ConnectionRow,
@@ -67,7 +66,14 @@ import type { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/doc
// off, so the boolean discriminant stops discriminating. The domain's own
// predicate is what every call site uses instead.
import { docFailed } from '../../../../src/nest/doc-sync/document-provider';
import { createTestUnitOfWork } from '../../../helpers/test-uow';
import { createTestUnitOfWork, createTestTripsRepo } from '../../../helpers/test-uow';
import {
createTestDocumentConnectionsRepo,
createTestDocumentProviderFieldsRepo,
createTestDocumentProvidersRepo,
createTestDocumentSyncItemsRepo,
createTestTripDocumentLinksRepo,
} from '../../../helpers/doc-sync-repos';
let svc: DocSyncConfigService;
@@ -120,7 +126,16 @@ async function storedSecret(connectionId: number): Promise<string | undefined> {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
svc = new DocSyncConfigService(new DatabaseService(testDb), {} as DocumentProviderRegistry, await createTestUnitOfWork(testDb));
svc = new DocSyncConfigService(
await createTestTripsRepo(testDb),
await createTestDocumentProvidersRepo(testDb),
await createTestDocumentProviderFieldsRepo(testDb),
await createTestDocumentConnectionsRepo(testDb),
await createTestTripDocumentLinksRepo(testDb),
await createTestDocumentSyncItemsRepo(testDb),
{} as DocumentProviderRegistry,
await createTestUnitOfWork(testDb),
);
});
beforeEach(() => {
@@ -727,6 +742,44 @@ describe('markOrphanedLinks', () => {
expect(await svc.getLink(kept.id)).toMatchObject({ last_sync_state: 'never', sync_enabled: 1 });
});
/**
* DSC20/DSC21's shared predicate (`DocumentConnectionsRepository
* .listOrphanedIds`) — the single-link check (`isOrphaned`, which
* delegates to the private `ownerLeft`) and the bulk sweep
* (`markOrphanedLinks`) must agree on every case, since both now draw
* from the SAME repository method rather than two independent
* re-implementations of the `NOT IN (... UNION ...)` subquery. Three
* cases in one test: an owner still on the trip via `trip_members`, an
* owner on it only via `trips.user_id` (no membership row), and an owner
* genuinely gone.
*/
it('the single-link check and the bulk sweep agree on every case: owner via trip_members, owner via trips.user_id, owner genuinely gone', async () => {
// A connection is keyed per (trip_id, provider_id) — `upsertConnection`
// treats a second `connect()` call for a provider this trip already
// has as an EDIT of that same row, not a new connection. Three
// independent connections therefore need three distinct providers.
const viaMembership = await bind(MEMBER, 'paperless');
const viaTripOwner = await bind(OWNER, 'nextcloud');
// A stranger who was never on the trip at all — indistinguishable from
// "genuinely gone" to the shared predicate, which only asks "is the
// owner currently IN the membership set", never why they are not.
const strangerId = createUser(testDb, { username: 'stranger-doc-sync', email: 'stranger-doc-sync@test.local' }).user.id;
const goneConn = await connect(
{ providerId: 'synologydrive', credentials: { username: 'anna', password: 'nas-pw' }, baseUrl: 'https://nas.example.com:5001' },
strangerId,
);
const goneLink = await link(goneConn.id, { scopeKey: 'scope:gone' });
expect(await svc.isOrphaned(await svc.getLink(viaMembership.id) as LinkRow)).toBe(false);
expect(await svc.isOrphaned(await svc.getLink(viaTripOwner.id) as LinkRow)).toBe(false);
expect(await svc.isOrphaned(await svc.getLink(goneLink.id) as LinkRow)).toBe(true);
expect(await svc.markOrphanedLinks()).toBe(1);
expect((await svc.getLink(viaMembership.id))?.last_sync_state).toBe('never');
expect((await svc.getLink(viaTripOwner.id))?.last_sync_state).toBe('never');
expect((await svc.getLink(goneLink.id))?.last_sync_state).toBe('orphaned');
});
it('counts nothing on a second sweep, so the job stays quiet after the first one', async () => {
await bind(MEMBER, 'paperless');
testDb.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(TRIP, MEMBER);
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import crypto from 'crypto';
import type { Request } from 'express';
@@ -16,7 +16,8 @@ vi.mock('../../../../src/db/database', () => ({
import { DocSyncWebhookController } from '../../../../src/nest/doc-sync/doc-sync-webhook.controller';
import type { DocSyncConfigService, LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
import type { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
import type { DatabaseService } from '../../../../src/nest/database/database.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestOrm } from '../../../helpers/test-orm';
/**
* The webhook endpoint, with both services stubbed.
@@ -64,6 +65,9 @@ const link = (over: Partial<LinkRow> = {}): LinkRow => ({
last_sync_error: null,
failure_count: 0,
next_attempt_at: null,
created_by: 1,
created_at: '2026-09-01 08:00:00',
updated_at: '2026-09-01 08:00:00',
...over,
});
@@ -75,26 +79,35 @@ const config = {
webhookSecret: vi.fn(() => SECRET),
};
const settings = new Map<string, string>();
const db = {
get: vi.fn((_sql: string, key?: unknown) => {
const value = settings.get(String(key));
return value === undefined ? undefined : { value };
}),
};
const sync = {
syncLink: vi.fn(async (_link: LinkRow) => ({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })),
// The Documents addon and the binding's provider, as one answer. What goes
// into it is the service's business and tested there.
isSwitchedOff: vi.fn((_link: LinkRow) => false),
// DSWH1 (R2 — moved off this controller onto DocSyncService.isSyncEnabled):
// the instance-wide kill switch, the same rule the job's own tick obeys.
isSyncEnabled: vi.fn(() => true),
};
const controller = new DocSyncWebhookController(
config as unknown as DocSyncConfigService,
sync as unknown as DocSyncService,
db as unknown as DatabaseService,
);
// R9's withRequestContext wrap needs a real MikroORM EntityManager to fork
// (RequestContext.create calls em.fork(...)) — a bare `{ em: {} }` double
// cannot satisfy that, so this file draws the same shared test ORM
// `StorageHealthNotifierService`'s own unit test uses for the identical
// reason (its class docstring: "these hand-built doubles pass the shared
// test ORM instead"). Nothing in this file's own assertions touches SQLite
// (`config`/`sync` are still full mocks), so no `createTables`/migrations
// beyond what `createSnapshotTestDb`'s cached snapshot already carries.
const testDb = createSnapshotTestDb();
let controller: DocSyncWebhookController;
beforeAll(async () => {
const t = await createTestOrm(testDb);
controller = new DocSyncWebhookController(config as unknown as DocSyncConfigService, sync as unknown as DocSyncService, t.orm);
});
afterAll(() => {
testDb.close();
});
/** Only what the handler reads: headers, the parsed body, and the raw bytes. */
function makeReq(headers: Record<string, string> = {}, opts: { body?: unknown; rawBody?: Buffer | undefined } = {}): Request {
@@ -123,8 +136,8 @@ function papraReq(payload: string, signature: string, sent = payload): Request {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
settings.clear();
sync.isSwitchedOff.mockReturnValue(false);
sync.isSyncEnabled.mockReturnValue(true);
config.getLinkByToken.mockImplementation((token: string) => (token === 'tok-live' ? link() : undefined));
config.getLink.mockImplementation((id: number) => (id === 4 ? link() : undefined));
config.webhookSecret.mockReturnValue(SECRET);
@@ -404,7 +417,7 @@ describe('the admin switches', () => {
});
it('does nothing while the kill switch is set', async () => {
settings.set('docsync_sync_enabled', 'false');
sync.isSyncEnabled.mockReturnValue(false);
await controller.nudge('tok-live', makeReq({ 'x-trek-docsync-secret': SECRET }));
await settle();
expect(sync.syncLink).not.toHaveBeenCalled();
@@ -60,7 +60,6 @@ vi.mock('../../../../src/utils/ssrfGuard', async (importOriginal) => ({
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { createTrip, createUser } from '../../../helpers/factories';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import { DocSyncController } from '../../../../src/nest/doc-sync/doc-sync.controller';
import { DocSyncConfigService } from '../../../../src/nest/doc-sync/doc-sync-config.service';
import { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/document-provider.registry';
@@ -78,7 +77,14 @@ import type {
DocsyncLinkDto,
} from '../../../../src/nest/doc-sync/doc-sync.dto';
import type { User } from '../../../../src/types';
import { createTestUnitOfWork } from '../../../helpers/test-uow';
import { createTestUnitOfWork, createTestTripsRepo } from '../../../helpers/test-uow';
import {
createTestDocumentConnectionsRepo,
createTestDocumentProviderFieldsRepo,
createTestDocumentProvidersRepo,
createTestDocumentSyncItemsRepo,
createTestTripDocumentLinksRepo,
} from '../../../helpers/doc-sync-repos';
const CAPS = {
push: 'webhook-self-registered' as const,
@@ -121,10 +127,30 @@ const sync = {
isSwitchedOff: vi.fn((_link: LinkRow) => false),
status: vi.fn(() => ({ links: [], items: {} })),
resolveConflict: vi.fn(async () => true),
// R2 (DSCTRL4/DSCTRL5, moved off the controller onto DocSyncService) — a
// real read against this file's own testDb, not a stub: "the document
// list" describe block below is testing the join/trip-scoping SHAPE this
// method now owns, and a canned return would only restate the assertion.
itemsForTrip: vi.fn((tripId: number, state?: string) =>
state
? testDb
.prepare(
`SELECT i.*, f.original_name AS file_name FROM document_sync_items i
LEFT JOIN trip_files f ON f.id = i.file_id
WHERE i.trip_id = ? AND i.state = ? ORDER BY i.id DESC LIMIT 500`,
)
.all(tripId, state)
: testDb
.prepare(
`SELECT i.*, f.original_name AS file_name FROM document_sync_items i
LEFT JOIN trip_files f ON f.id = i.file_id
WHERE i.trip_id = ? ORDER BY i.id DESC LIMIT 500`,
)
.all(tripId),
),
};
const registry = new DocumentProviderRegistry([paperless, nextcloud] as unknown as DocumentProvider[]);
const dbs = new DatabaseService(testDb);
const realtime = { broadcast: vi.fn() };
// Built in beforeAll: DocSyncConfigService now takes a UnitOfWork, and
// createTestUnitOfWork is async — module-scope construction cannot await it.
@@ -184,8 +210,17 @@ let otherTripId: number;
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
config = new DocSyncConfigService(dbs, registry, await createTestUnitOfWork(testDb));
controller = new DocSyncController(config, sync as unknown as DocSyncService, registry, dbs, realtime as unknown as RealtimeService);
config = new DocSyncConfigService(
await createTestTripsRepo(testDb),
await createTestDocumentProvidersRepo(testDb),
await createTestDocumentProviderFieldsRepo(testDb),
await createTestDocumentConnectionsRepo(testDb),
await createTestTripDocumentLinksRepo(testDb),
await createTestDocumentSyncItemsRepo(testDb),
registry,
await createTestUnitOfWork(testDb),
);
controller = new DocSyncController(config, sync as unknown as DocSyncService, registry, realtime as unknown as RealtimeService);
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;
@@ -33,7 +33,7 @@ import { DocSyncService } from '../../../../src/nest/doc-sync/doc-sync.service';
import { DocumentProviderRegistry } from '../../../../src/nest/doc-sync/document-provider.registry';
import type { DocumentProvider } from '../../../../src/nest/doc-sync/document-provider';
import type { AddonsService } from '../../../../src/nest/addons/addons.service';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import type { AppSettingsRepository } from '../../../../src/db/repositories/AppSettings.repository';
import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
import { AllowedFileTypesService } from '../../../../src/nest/files/allowed-file-types.service';
import type { FilesService } from '../../../../src/nest/files/files.service';
@@ -42,7 +42,16 @@ import type { RealtimeService } from '../../../../src/nest/realtime/realtime.ser
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { createTrip, createUser } from '../../../helpers/factories';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestTripsRepo } from '../../../helpers/test-uow';
import {
createTestDocumentConnectionsRepo,
createTestDocumentProviderFieldsRepo,
createTestDocumentProvidersRepo,
createTestDocumentSyncItemsRepo,
createTestFileLinksRepo,
createTestTripDocumentLinksRepo,
createTestTripFilesRepo,
} from '../../../helpers/doc-sync-repos';
const link = (id: number): LinkRow => ({ id, provider_id: 'paperless' } as LinkRow);
@@ -65,13 +74,11 @@ function makeJob(over: Partial<Setup> = {}) {
if (setup.interval !== undefined) settings.set(SETTING_POLL_INTERVAL, setup.interval);
if (setup.killSwitch !== undefined) settings.set(SETTING_SYNC_ENABLED, setup.killSwitch);
// Shaped like the real `get<T>(sql, ...params)` so the stub cannot drift from
// the signature the job calls, and so a case can tell the two keys apart.
const db = {
get: vi.fn((_sql: string, key?: unknown) => {
const value = settings.get(String(key));
return value === undefined ? undefined : { value };
}),
// Shaped like the real `AppSettingsRepository.getValue(key): Promise<string
// | null>` so the stub cannot drift from the signature the job calls, and
// so a case can tell the two keys apart.
const appSettings = {
getValue: vi.fn(async (key: string) => settings.get(key) ?? null),
};
let onTick: (() => void | Promise<void>) | undefined;
@@ -99,13 +106,13 @@ function makeJob(over: Partial<Setup> = {}) {
const addons = { isAddonEnabled: vi.fn(() => setup.addonOn) };
const job = new DocSyncJob(
db as unknown as DatabaseService,
appSettings as unknown as AppSettingsRepository,
sync as unknown as DocSyncService,
config as unknown as DocSyncConfigService,
addons as unknown as AddonsService,
registrar as unknown as CronRegistrarService,
);
return { job, db, registrar, sync, config, addons, takeTick: () => onTick };
return { job, appSettings, registrar, sync, config, addons, takeTick: () => onTick };
}
beforeEach(() => vi.clearAllMocks());
@@ -114,10 +121,10 @@ describe('DocSyncJob bootstrap', () => {
it('schedules nothing, reads nothing and logs nothing while the registrar is off', async () => {
// The test gate. A job that registered past it would have every suite boot
// start polling whatever document store sits in the fixture database.
const { job, registrar, db } = makeJob({ registrarEnabled: false });
const { job, registrar, appSettings } = makeJob({ registrarEnabled: false });
await job.onApplicationBootstrap();
expect(registrar.register).not.toHaveBeenCalled();
expect(db.get).not.toHaveBeenCalled();
expect(appSettings.getValue).not.toHaveBeenCalled();
expect(log.logInfo).not.toHaveBeenCalled();
});
@@ -134,9 +141,9 @@ describe('DocSyncJob bootstrap', () => {
});
it('reads the interval from its own app_settings key', async () => {
const { job, db } = makeJob({ interval: '600' });
const { job, appSettings } = makeJob({ interval: '600' });
await job.onApplicationBootstrap();
expect(db.get).toHaveBeenCalledWith('SELECT value FROM app_settings WHERE key = ?', SETTING_POLL_INTERVAL);
expect(appSettings.getValue).toHaveBeenCalledWith(SETTING_POLL_INTERVAL);
});
it('hands the registrar the tick itself, so a fired cron reaches the sync', async () => {
@@ -165,12 +172,12 @@ describe('DocSyncJob bootstrap', () => {
describe('DocSyncJob tick', () => {
it('does nothing at all while the documents addon is off', async () => {
const { job, sync, config, db } = makeJob({ addonOn: false, links: [link(1)] });
const { job, sync, config, appSettings } = makeJob({ addonOn: false, links: [link(1)] });
await job.tick();
expect(sync.dueLinks).not.toHaveBeenCalled();
expect(sync.syncLink).not.toHaveBeenCalled();
expect(config.markOrphanedLinks).not.toHaveBeenCalled();
expect(db.get).not.toHaveBeenCalled();
expect(appSettings.getValue).not.toHaveBeenCalled();
});
it('asks the addon gate again on every tick, so switching it on needs no restart', async () => {
@@ -186,9 +193,9 @@ describe('DocSyncJob tick', () => {
});
it('stops the run on the kill switch, without touching the bindings', async () => {
const { job, sync, config, db } = makeJob({ killSwitch: 'false', links: [link(1)] });
const { job, sync, config, appSettings } = makeJob({ killSwitch: 'false', links: [link(1)] });
await job.tick();
expect(db.get).toHaveBeenCalledWith('SELECT value FROM app_settings WHERE key = ?', SETTING_SYNC_ENABLED);
expect(appSettings.getValue).toHaveBeenCalledWith(SETTING_SYNC_ENABLED);
expect(config.markOrphanedLinks).not.toHaveBeenCalled();
expect(sync.dueLinks).not.toHaveBeenCalled();
});
@@ -206,10 +213,10 @@ describe('DocSyncJob tick', () => {
});
it('re-reads the kill switch per tick instead of remembering the first answer', async () => {
const { job, db } = makeJob({ links: [link(1)] });
const { job, appSettings } = makeJob({ links: [link(1)] });
await job.tick();
await job.tick();
const killSwitchReads = db.get.mock.calls.filter((c) => c[1] === SETTING_SYNC_ENABLED).length;
const killSwitchReads = appSettings.getValue.mock.calls.filter((c) => c[0] === SETTING_SYNC_ENABLED).length;
expect(killSwitchReads).toBe(2);
});
@@ -367,18 +374,15 @@ describe('DocSyncJob due-ness', () => {
it('takes a changed setting without a restart, which is the whole point', async () => {
const settings = new Map<string, string>([[SETTING_POLL_INTERVAL, '3600']]);
const db = {
get: vi.fn((_sql: string, key?: unknown) => {
const value = settings.get(String(key));
return value === undefined ? undefined : { value };
}),
const appSettings = {
getValue: vi.fn(async (key: string) => settings.get(key) ?? null),
};
const sync = {
dueLinks: vi.fn(() => [link(1)]),
syncLink: vi.fn(async () => RUN),
};
const job = new DocSyncJob(
db as unknown as DatabaseService,
appSettings as unknown as AppSettingsRepository,
sync as unknown as DocSyncService,
{ markOrphanedLinks: vi.fn(() => 0) } as unknown as DocSyncConfigService,
{ isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService,
@@ -414,7 +418,6 @@ describe('DocSyncJob due-ness', () => {
*/
describe('DocSyncJob and a provider switched off in the admin panel', () => {
const testDb = new Database(':memory:');
const dbs = new DatabaseService(testDb);
let paperlessLink: number;
let nextcloudLink: number;
@@ -437,25 +440,42 @@ describe('DocSyncJob and a provider switched off in the admin panel', () => {
// cannot await it.
let config: DocSyncConfigService;
let service: DocSyncService;
let appSettingsRepo: AppSettingsRepository;
const registrar = { isEnabled: () => false } as unknown as CronRegistrarService;
/** A job of its own per pass, so the interval never decides whether a tick runs. */
const tick = () => new DocSyncJob(dbs, service, config, addons, registrar).tick();
const tick = () => new DocSyncJob(appSettingsRepo, service, config, addons, registrar).tick();
const switchProvider = (id: string, on: boolean) =>
testDb.prepare('UPDATE document_providers SET enabled = ? WHERE id = ?').run(on ? 1 : 0, id);
const linkRow = (id: number) => testDb.prepare('SELECT * FROM trip_document_links WHERE id = ?').get(id);
beforeAll(async () => {
config = new DocSyncConfigService(dbs, registry, await createTestUnitOfWork(testDb));
createTables(testDb);
runMigrations(testDb);
appSettingsRepo = await createTestAppSettingsRepo(testDb);
config = new DocSyncConfigService(
await createTestTripsRepo(testDb),
await createTestDocumentProvidersRepo(testDb),
await createTestDocumentProviderFieldsRepo(testDb),
await createTestDocumentConnectionsRepo(testDb),
await createTestTripDocumentLinksRepo(testDb),
await createTestDocumentSyncItemsRepo(testDb),
registry,
await createTestUnitOfWork(testDb),
);
service = new DocSyncService(
dbs, config, registry,
{} as StorageService, {} as FilesService, new AllowedFileTypesService(await createTestAppSettingsRepo(testDb)),
await createTestTripDocumentLinksRepo(testDb),
await createTestDocumentSyncItemsRepo(testDb),
await createTestTripFilesRepo(testDb),
await createTestFileLinksRepo(testDb),
appSettingsRepo,
config,
registry,
{} as StorageService, {} as FilesService, new AllowedFileTypesService(appSettingsRepo),
{ broadcast: vi.fn() } as unknown as RealtimeService,
addons,
await createTestUnitOfWork(testDb),
);
createTables(testDb);
runMigrations(testDb);
const ownerId = createUser(testDb, { username: 'owner', email: 'owner@docsync-job.test' }).user.id;
const tripId = createTrip(testDb, ownerId, { title: 'Japan' }).id;
const bind = (providerId: string) => {
@@ -46,7 +46,6 @@ import type { DocsyncErrorCode } from '@trek/shared';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { createTrip, createUser } from '../../../helpers/factories';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import { AllowedFileTypesService } from '../../../../src/nest/files/allowed-file-types.service';
import { MAX_FILE_SIZE } from '../../../../src/nest/files/files.constants';
import { DocSyncConfigService, type LinkRow } from '../../../../src/nest/doc-sync/doc-sync-config.service';
@@ -70,7 +69,16 @@ import type { AddonsService } from '../../../../src/nest/addons/addons.service';
import type { FilesService } from '../../../../src/nest/files/files.service';
import type { StorageService } from '../../../../src/nest/storage/storage.service';
import type { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../../helpers/test-uow';
import { createTestUnitOfWork, createTestAppSettingsRepo, createTestTripsRepo } from '../../../helpers/test-uow';
import {
createTestDocumentConnectionsRepo,
createTestDocumentProviderFieldsRepo,
createTestDocumentProvidersRepo,
createTestDocumentSyncItemsRepo,
createTestFileLinksRepo,
createTestTripDocumentLinksRepo,
createTestTripFilesRepo,
} from '../../../helpers/doc-sync-repos';
// ── Fixtures ─────────────────────────────────────────────────────────────────
@@ -319,11 +327,23 @@ describe('DocSyncService', () => {
.run(tripId, ownerId);
connectionId = Number(info.lastInsertRowid);
const dbs = new DatabaseService(testDb);
const registry = new DocumentProviderRegistry([provider as unknown as DocumentProvider]);
config = new DocSyncConfigService(dbs, registry, await createTestUnitOfWork(testDb));
config = new DocSyncConfigService(
await createTestTripsRepo(testDb),
await createTestDocumentProvidersRepo(testDb),
await createTestDocumentProviderFieldsRepo(testDb),
await createTestDocumentConnectionsRepo(testDb),
await createTestTripDocumentLinksRepo(testDb),
await createTestDocumentSyncItemsRepo(testDb),
registry,
await createTestUnitOfWork(testDb),
);
service = new DocSyncService(
dbs,
await createTestTripDocumentLinksRepo(testDb),
await createTestDocumentSyncItemsRepo(testDb),
await createTestTripFilesRepo(testDb),
await createTestFileLinksRepo(testDb),
await createTestAppSettingsRepo(testDb),
config,
registry,
storage,
@@ -396,6 +416,31 @@ describe('DocSyncService', () => {
expect((await service.dueLinks(5)).length).toBe(5);
});
/**
* R3's own named test, per the plan's exact instruction: the whole
* 3-key ORDER BY (`next_attempt_at`, then `last_sync_at`, then `id`) in
* one assertion, not folded into any of the shape-specific cases above.
* Insertion order is DELIBERATELY scrambled relative to the expected
* result, so a regression to "no ORDER BY" (SQLite's own insertion-order
* fallback) or to "ORDER BY id only" would both fail this test, not just
* the narrower cases above.
*/
it('doc-sync-svc: dueLinks orders by next_attempt_at then last_sync_at then id, not insertion order', async () => {
// Two ties on next_attempt_at (both NULL, sorting as the epoch) broken
// by last_sync_at; within THAT tie, two rows broken by id — created in
// an order that would fail every one of these three keys if it were
// read back as inserted.
const tieBreakSecond = await makeLink({ lastSyncAt: null }); // next=NULL, last=NULL — ties tieBreakFirst on both keys
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
const ids = (await service.dueLinks()).map((l) => l.id);
const expected = [tieBreakSecond.id, tieBreakFirst.id].sort((a, b) => a - b);
expect(ids).toEqual([...expected, midStale.id, midRecent.id, backedOff.id]);
});
it('lets a binding back in one failure before the circuit opens', async () => {
const nearly = await makeLink({ failureCount: LINK_CIRCUIT_OPEN_AFTER - 1 });
expect((await service.dueLinks()).map((l) => l.id)).toEqual([nearly.id]);