test(sync): automate the post-merge sync checks against the real companion (#169) #195
7 changed files with 855 additions and 6 deletions
|
|
@ -183,11 +183,12 @@ npx tsc --noEmit
|
|||
npx expo export --platform android --no-bytecode --clear --output-dir <dossier>
|
||||
```
|
||||
|
||||
Companion web, depuis `web/` :
|
||||
Companion web, depuis `web/` (après le `npm ci` de la racine, voir le harnais de sync ci-dessous) :
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm test # vitest : schémas de sync (syncData.test.ts) et isolation des comptes sur la vraie route, PGlite en mémoire (api/sync/route.test.ts)
|
||||
npm test # vitest : schémas de sync (syncData.test.ts), isolation des comptes sur la vraie route, PGlite en mémoire (api/sync/route.test.ts), puis le harnais de sync
|
||||
npm run test:sync # harnais de sync seul (#169) : le vrai syncClient de l'app contre la vraie route /api/sync
|
||||
npx tsc --noEmit
|
||||
npm run lint
|
||||
npm run build
|
||||
|
|
@ -196,7 +197,8 @@ npm run build
|
|||
- Comparer deux exports : `(cd <dossier> && find . -type f | sort | xargs sha256sum)` sur l'arbre de base deux fois (déterminisme), puis sur la PR ; même nombre de fichiers et mêmes empreintes, ou une différence expliquée.
|
||||
- Côté `web/`, vitest mélange l'ordre des tests à chaque run (`sequence.shuffle` dans `web/vitest.config.mts`, #148) et affiche sa graine (`Running tests with seed "<n>"`). Un échec qui dépend de l'ordre se rejoue avec la même graine : `npx vitest run --sequence.seed=<n>`.
|
||||
- Un `npm test` ne compte qu'après une sonde : une vérification volontairement rouge doit le faire sortir en code non nul (`smoke FAIL`, sortie 1 ; côté `web/`, une assertion de vitest volontairement fausse, sortie 1).
|
||||
- Ce que ces commandes ne prouvent pas : le comportement sur un appareil (widget, notifications, connexion Logto, sync réelle), qui se teste sur un build de développement ; le site déployé, qui se vérifie après le déploiement manuel.
|
||||
- Harnais de sync (`web/src/test/sync/`, #169) : il charge le code de l'app (`src/services/syncClient.ts`, les repositories, `syncRules`, `syncSchedule`) et ses dépendances depuis le `node_modules` de la **racine** ; sans `npm ci` à la racine, `npm test` de `web/` échoue à l'import. Chaque appareil a sa base `node:sqlite`, son planificateur et ses réglages ; le serveur est la vraie route sur PGlite, `fetch` y est aiguillé en mémoire, sous fausses minuteries. Huit scénarios : fusion d'un 2e appareil, réinitialisation d'un compte neuf, réparation de l'Inbox scindée, champs locaux et modifications hors ligne au pull, file de plus de 400 entrées et refus rejoués, étiquettes et sous-tâches, changement de compte, budget et 429 du planificateur. Le dossier est exclu de `tsc` (`web/tsconfig.json`) et de `web/vitest.config.mts` ; sa config, `web/src/test/sync/vitest.config.mts`, ne ramasse que lui. Les clés étrangères SQLite y sont coupées, comme sur l'appareil (aucun `PRAGMA` dans l'app). Il ne couvre pas le runtime expo-sqlite réel, le démarrage de l'app (`app/_layout.tsx`, hydratation des réglages), l'interface, Logto réel, le WebSocket, le widget, les notifications ni le calendrier (simulés) : la liste fait foi en tête de `harness.ts`.
|
||||
- Ce que ces commandes ne prouvent pas : le comportement sur un appareil (widget, notifications, connexion Logto, runtime expo-sqlite), qui se teste sur un build de développement ; le site déployé, qui se vérifie après le déploiement manuel.
|
||||
|
||||
## Pièges de revue
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run && npm run test:sync",
|
||||
"test:sync": "vitest run -c src/test/sync/vitest.config.mts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@logto/next": "^4.2.9",
|
||||
|
|
|
|||
441
web/src/test/sync/harness.ts
Normal file
441
web/src/test/sync/harness.ts
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
/**
|
||||
* Sync harness (#169): the app's real sync code (src/services/syncClient.ts,
|
||||
* the repositories, syncRules, syncSchedule) against the companion's real
|
||||
* GET/POST /api/sync handlers, in one node process, without a device.
|
||||
*
|
||||
* - Server: one PGlite with the companion migrations, shared by every device
|
||||
* of a test file. Auth is stubbed (the bearer token names the account), the
|
||||
* WebSocket notification is a no-op, the rate limiter is the real one when
|
||||
* `server.rateLimit` is on, off otherwise. The idempotency store is real.
|
||||
* - Device: `vi.resetModules()` then `vi.doMock` of the native modules, then a
|
||||
* dynamic `import()` of the app modules. Each device has its own SQLite
|
||||
* (node:sqlite behind drizzle-orm/sqlite-proxy, app migrations replayed from
|
||||
* meta/_journal.json), its own settings, its own scheduler and request
|
||||
* budget, its own firstSyncInProgress flag.
|
||||
* - fetch: routed in memory to the route handlers (no port, no network); any
|
||||
* other URL throws.
|
||||
* - Time: the scenarios run under vitest fake timers (Date, setTimeout,
|
||||
* clearTimeout); `drive()` lets in-flight work finish and jumps the clock to
|
||||
* the next timer only when everything waits for one.
|
||||
*
|
||||
* NOT covered: the real expo-sqlite runtime (and its SQLite build), the app
|
||||
* start-up sequence (app/_layout.tsx, hydration of the persisted settings),
|
||||
* the interface (settings screen, alerts), the real Logto tokens and the
|
||||
* server's bearer check, the WebSocket (server notification and app socket),
|
||||
* the widget, notifications and calendar (stubbed), and the production
|
||||
* network (TLS, proxy, latency). The production probe is #176.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { vi } from 'vitest';
|
||||
import type { PGlite } from 'electric-sql-pglite';
|
||||
|
||||
const REPO = path.resolve(__dirname, '../../../..');
|
||||
/** Host hard-coded in syncClient.ts (SYNC_API_BASE). */
|
||||
export const SYNC_HOST = 'https://liste.lacompagniemaximus.com';
|
||||
/** Fixed id of the Inbox of a device that never synced (syncRules.ts). */
|
||||
export const LOCAL_INBOX_ID = '00000000-0000-0000-0000-000000000001';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Time
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function macrotask(): Promise<void> {
|
||||
// setImmediate is not faked: it lets every pending microtask run first
|
||||
return new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
/** Rounds without progress before the clock jumps to the next timer. */
|
||||
const IDLE_ROUNDS = 5;
|
||||
/** Rounds without any timer after which a wait is declared stalled. */
|
||||
const STALL_ROUNDS = 200;
|
||||
|
||||
/**
|
||||
* Wait for `cond`, letting in-flight work run and moving the fake clock to
|
||||
* the next timer when nothing else can progress. Throws when the condition
|
||||
* cannot be reached: no timer left to fire, or `maxClockMs` of clock spent.
|
||||
*/
|
||||
export async function driveUntil(
|
||||
cond: () => boolean | Promise<boolean>,
|
||||
{ maxClockMs = 60 * 60_000, label = 'condition' } = {},
|
||||
): Promise<void> {
|
||||
const start = Date.now();
|
||||
let idle = 0;
|
||||
for (;;) {
|
||||
if (await cond()) return;
|
||||
await macrotask();
|
||||
idle++;
|
||||
if (idle < IDLE_ROUNDS) continue;
|
||||
if (vi.getTimerCount() > 0) {
|
||||
if (Date.now() - start > maxClockMs) throw new Error(`drive: ${label} not reached after ${maxClockMs} ms of clock`);
|
||||
await vi.advanceTimersToNextTimerAsync();
|
||||
idle = 0;
|
||||
} else if (idle > STALL_ROUNDS) {
|
||||
throw new Error(`drive: ${label} stalled, no timer pending`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Settle a promise of the app, firing the fake timers it waits for. */
|
||||
export async function drive<T>(p: Promise<T>, label = 'promise'): Promise<T> {
|
||||
let done = false;
|
||||
const tracked = p.finally(() => {
|
||||
done = true;
|
||||
});
|
||||
tracked.catch(() => {});
|
||||
await driveUntil(() => done, { label });
|
||||
return tracked;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Server
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface LoggedRequest {
|
||||
method: 'GET' | 'POST';
|
||||
userId: string;
|
||||
/** Fake clock when the request reached the server, in ms. */
|
||||
at: number;
|
||||
status: number;
|
||||
retryAfter: number | null;
|
||||
/** Results of a 2xx POST. */
|
||||
results?: { status: string; error?: string }[];
|
||||
/** Entity ids of the operations of a POST. */
|
||||
entityIds?: string[];
|
||||
}
|
||||
|
||||
export interface Server {
|
||||
pg: PGlite;
|
||||
/** Every request a device sent through fetch, in order. */
|
||||
log: LoggedRequest[];
|
||||
/** Real rate limiter (10 sync requests per minute and per account) when true. */
|
||||
rateLimit: boolean;
|
||||
rows<T = Row>(sql: string, params?: unknown[]): Promise<T[]>;
|
||||
/** A request of the companion itself (web page): not logged, rate-limited like the app's. */
|
||||
companion(userId: string, method: 'GET' | 'POST', body?: unknown): Promise<Response>;
|
||||
}
|
||||
|
||||
type RouteModule = typeof import('@/app/api/sync/route');
|
||||
|
||||
export async function startServer(): Promise<Server> {
|
||||
const { PGlite } = await import('electric-sql-pglite');
|
||||
const pg = new PGlite() as PGlite;
|
||||
const dir = path.join(REPO, 'web/src/db/migrations');
|
||||
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
|
||||
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
|
||||
if (stmt.trim()) await pg.exec(stmt);
|
||||
}
|
||||
}
|
||||
|
||||
const state = { userId: '', rateLimit: false };
|
||||
|
||||
vi.doMock('@/db/client', async () => {
|
||||
const { drizzle } = await import('drizzle-orm/pglite');
|
||||
const schema = await import('@/db/schema');
|
||||
return { db: drizzle(pg, { schema }) };
|
||||
});
|
||||
vi.doMock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null }));
|
||||
// Read synchronously when the handler starts: the router sets it just before
|
||||
vi.doMock('@/lib/api', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/lib/api')>()),
|
||||
requireAuth: async () => ({ userId: state.userId }),
|
||||
}));
|
||||
vi.doMock('@/lib/rateLimit', async (importOriginal) => {
|
||||
const mod = await importOriginal<typeof import('@/lib/rateLimit')>();
|
||||
return {
|
||||
rateLimit: (...args: Parameters<typeof mod.rateLimit>) => (state.rateLimit ? mod.rateLimit(...args) : null),
|
||||
};
|
||||
});
|
||||
vi.doMock('@/lib/ws', () => ({ notifyUserChanged: () => {} }));
|
||||
|
||||
const route: RouteModule = await import('@/app/api/sync/route');
|
||||
const { NextRequest } = await import('next/server');
|
||||
|
||||
function call(userId: string, url: URL, init: RequestInit): Promise<Response> {
|
||||
state.userId = userId;
|
||||
const method = (init.method ?? 'GET').toUpperCase();
|
||||
if (method === 'GET') return route.GET(new NextRequest(url, init));
|
||||
if (method === 'POST') return route.POST(new Request(url, init));
|
||||
throw new Error(`harness: unexpected method ${method}`);
|
||||
}
|
||||
|
||||
const log: LoggedRequest[] = [];
|
||||
|
||||
const fetchStub = async (input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> => {
|
||||
const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
|
||||
if (url.origin !== SYNC_HOST || url.pathname !== '/api/sync') {
|
||||
throw new Error(`harness: unexpected fetch ${url.href}`);
|
||||
}
|
||||
const auth = new Headers(init.headers).get('authorization') ?? '';
|
||||
const userId = auth.startsWith('Bearer token:') ? auth.slice('Bearer token:'.length) : '';
|
||||
if (!userId) return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });
|
||||
const method = (init.method ?? 'GET').toUpperCase() as 'GET' | 'POST';
|
||||
const entry: LoggedRequest = { method, userId, at: Date.now(), status: 0, retryAfter: null };
|
||||
if (method === 'POST' && typeof init.body === 'string') {
|
||||
const ops = (JSON.parse(init.body) as { operations: { entityId: string }[] }).operations;
|
||||
entry.entityIds = ops.map((o) => o.entityId);
|
||||
}
|
||||
log.push(entry);
|
||||
const res = await call(userId, url, init);
|
||||
entry.status = res.status;
|
||||
const ra = res.headers.get('Retry-After');
|
||||
entry.retryAfter = ra == null ? null : Number(ra);
|
||||
if (method === 'POST' && res.ok) {
|
||||
entry.results = ((await res.clone().json()) as { results: { status: string; error?: string }[] }).results;
|
||||
}
|
||||
return res;
|
||||
};
|
||||
vi.stubGlobal('fetch', fetchStub);
|
||||
|
||||
return {
|
||||
pg,
|
||||
log,
|
||||
get rateLimit() {
|
||||
return state.rateLimit;
|
||||
},
|
||||
set rateLimit(on: boolean) {
|
||||
state.rateLimit = on;
|
||||
},
|
||||
async rows<T = Row>(sql: string, params: unknown[] = []) {
|
||||
return (await pg.query<T>(sql, params)).rows;
|
||||
},
|
||||
companion(userId, method, body) {
|
||||
const url = new URL(`${SYNC_HOST}/api/sync`);
|
||||
if (method === 'GET') url.searchParams.set('since', new Date(0).toISOString());
|
||||
return call(userId, url, method === 'POST' ? { method, body: JSON.stringify(body) } : { method });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A fresh account id (Logto `sub`). */
|
||||
export function newAccount(): string {
|
||||
return `user-${randomUUID()}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Device
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type SyncModule = typeof import('@/src/services/syncClient');
|
||||
type ListsModule = typeof import('@/src/db/repository/lists');
|
||||
type TasksModule = typeof import('@/src/db/repository/tasks');
|
||||
type TagsModule = typeof import('@/src/db/repository/tags');
|
||||
type OutboxModule = typeof import('@/src/db/repository/outbox');
|
||||
|
||||
interface SettingsState {
|
||||
theme: 'light' | 'dark' | 'system';
|
||||
locale: 'fr' | 'en';
|
||||
notificationsEnabled: boolean;
|
||||
reminderOffset: number;
|
||||
calendarSyncEnabled: boolean;
|
||||
widgetPeriodWeeks: number;
|
||||
syncEnabled: boolean;
|
||||
lastSyncAt: string | null;
|
||||
userId: string | null;
|
||||
dataOwnerId: string | null;
|
||||
setSyncEnabled(v: boolean): void;
|
||||
setLastSyncAt(v: string | null): void;
|
||||
setUserId(v: string | null): void;
|
||||
setDataOwnerId(v: string | null): void;
|
||||
setCalendarSyncEnabled(v: boolean): void;
|
||||
}
|
||||
|
||||
/** In-memory stand-in for the persisted zustand store (already hydrated). */
|
||||
function createSettings() {
|
||||
let state: SettingsState;
|
||||
const setState = (patch: Partial<SettingsState>) => {
|
||||
state = { ...state, ...patch };
|
||||
};
|
||||
state = {
|
||||
theme: 'system',
|
||||
locale: 'fr',
|
||||
notificationsEnabled: true,
|
||||
reminderOffset: 0,
|
||||
calendarSyncEnabled: false,
|
||||
widgetPeriodWeeks: 0,
|
||||
syncEnabled: false,
|
||||
lastSyncAt: null,
|
||||
userId: null,
|
||||
dataOwnerId: null,
|
||||
setSyncEnabled: (syncEnabled) => setState({ syncEnabled }),
|
||||
setLastSyncAt: (lastSyncAt) => setState({ lastSyncAt }),
|
||||
setUserId: (userId) => setState({ userId }),
|
||||
setDataOwnerId: (dataOwnerId) => setState({ dataOwnerId }),
|
||||
setCalendarSyncEnabled: (calendarSyncEnabled) => setState({ calendarSyncEnabled }),
|
||||
};
|
||||
const hook = <T>(selector?: (s: SettingsState) => T) => (selector ? selector(state) : state);
|
||||
return Object.assign(hook, { getState: () => state, setState });
|
||||
}
|
||||
|
||||
type Settings = ReturnType<typeof createSettings>;
|
||||
|
||||
/** Replay the app migrations (src/db/migrations, drizzle journal order). */
|
||||
function migrateApp(sqlite: DatabaseSync) {
|
||||
const dir = path.join(REPO, 'src/db/migrations');
|
||||
const journal = JSON.parse(fs.readFileSync(path.join(dir, 'meta/_journal.json'), 'utf8')) as {
|
||||
entries: { tag: string }[];
|
||||
};
|
||||
for (const { tag } of journal.entries) {
|
||||
for (const stmt of fs.readFileSync(path.join(dir, `${tag}.sql`), 'utf8').split('--> statement-breakpoint')) {
|
||||
if (stmt.trim()) sqlite.exec(stmt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type SqlParam = null | number | bigint | string | Uint8Array;
|
||||
|
||||
/** drizzle-orm/sqlite-proxy callback over a node:sqlite database. */
|
||||
function proxyOf(sqlite: DatabaseSync) {
|
||||
return async (sql: string, params: unknown[], method: 'run' | 'all' | 'values' | 'get') => {
|
||||
const stmt = sqlite.prepare(sql);
|
||||
const args = params as SqlParam[];
|
||||
if (method === 'run') {
|
||||
stmt.run(...args);
|
||||
return { rows: [] };
|
||||
}
|
||||
stmt.setReturnArrays(true);
|
||||
if (method === 'get') return { rows: stmt.get(...args) as unknown as unknown[] };
|
||||
return { rows: stmt.all(...args) as unknown as unknown[] };
|
||||
};
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
name: string;
|
||||
settings: Settings;
|
||||
sync: SyncModule;
|
||||
lists: ListsModule;
|
||||
tasks: TasksModule;
|
||||
tags: TagsModule;
|
||||
outbox: OutboxModule;
|
||||
/** Plain SQL on the device database, rows as objects. */
|
||||
query<T = Row>(sql: string, params?: SqlParam[]): T[];
|
||||
exec(sql: string, params?: SqlParam[]): void;
|
||||
/** Let the fire-and-forget outbox writes of the repositories land. */
|
||||
flush(): Promise<void>;
|
||||
/** Launch: repairInbox then ensureInbox (prepareInbox of app/_layout.tsx). */
|
||||
startup(): Promise<void>;
|
||||
/** Signed in to Logto: `sub` in the settings, a token for the account. */
|
||||
signIn(userId: string): void;
|
||||
/** First-sync choice of the settings screen (runFirstSync), then sync on. */
|
||||
firstSync(kind: 'merge' | 'reset'): Promise<void>;
|
||||
/** A sync through the scheduler (Settings button, write, interval). */
|
||||
syncNow(): Promise<void>;
|
||||
/** Sign-out of the settings screen: push first, then forget the account. Returns the unsent count. */
|
||||
signOut(): Promise<number>;
|
||||
/** Unsynced outbox entries. */
|
||||
pending(): number;
|
||||
}
|
||||
|
||||
export async function createDevice(name: string): Promise<Device> {
|
||||
// A new module registry: this device's syncClient, scheduler and outbox flag
|
||||
vi.resetModules();
|
||||
|
||||
// Foreign keys off, SQLite's default, which expo-sqlite keeps (the app sets
|
||||
// no PRAGMA): node:sqlite turns them on, and initialMerge relies on them
|
||||
// being off (tasks moved to the server Inbox before its row is inserted).
|
||||
const sqlite = new DatabaseSync(':memory:', { enableForeignKeyConstraints: false });
|
||||
migrateApp(sqlite);
|
||||
const settings = createSettings();
|
||||
const auth: { token: string | null } = { token: null };
|
||||
|
||||
vi.doMock('@/src/db/client', async () => {
|
||||
const { drizzle } = await import('drizzle-orm/sqlite-proxy');
|
||||
const schema = await import('@/src/db/schema');
|
||||
return { db: drizzle(proxyOf(sqlite), { schema }) };
|
||||
});
|
||||
vi.doMock('@/src/stores/useSettingsStore', () => ({
|
||||
useSettingsStore: settings,
|
||||
whenSettingsHydrated: async () => {},
|
||||
}));
|
||||
vi.doMock('@/src/lib/authToken', () => ({
|
||||
getAccessToken: async () => auth.token,
|
||||
setTokenGetter: () => {},
|
||||
clearTokenGetter: () => {},
|
||||
}));
|
||||
vi.doMock('@/src/lib/uuid', () => ({ randomUUID: () => randomUUID() }));
|
||||
vi.doMock('@/src/services/widgetSync', () => ({ syncWidgetData: async () => {} }));
|
||||
vi.doMock('@/src/services/notifications', () => ({
|
||||
scheduleTaskReminder: async () => {},
|
||||
cancelTaskReminder: async () => {},
|
||||
}));
|
||||
vi.doMock('@/src/services/calendar', () => ({
|
||||
addTaskToCalendar: async () => `cal-${randomUUID()}`,
|
||||
updateCalendarEvent: async () => {},
|
||||
removeCalendarEvent: async () => {},
|
||||
}));
|
||||
|
||||
const sync: SyncModule = await import('@/src/services/syncClient');
|
||||
const lists: ListsModule = await import('@/src/db/repository/lists');
|
||||
const tasks: TasksModule = await import('@/src/db/repository/tasks');
|
||||
const tags: TagsModule = await import('@/src/db/repository/tags');
|
||||
const outbox: OutboxModule = await import('@/src/db/repository/outbox');
|
||||
|
||||
const query = <T = Row>(sql: string, params: SqlParam[] = []) => sqlite.prepare(sql).all(...params) as T[];
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 5; i++) await macrotask();
|
||||
};
|
||||
|
||||
const device: Device = {
|
||||
name,
|
||||
settings,
|
||||
sync,
|
||||
lists,
|
||||
tasks,
|
||||
tags,
|
||||
outbox,
|
||||
query,
|
||||
exec: (sql, params = []) => {
|
||||
sqlite.prepare(sql).run(...params);
|
||||
},
|
||||
flush,
|
||||
async startup() {
|
||||
await drive(lists.repairInbox(), `${name} repairInbox`);
|
||||
await drive(lists.ensureInbox(), `${name} ensureInbox`);
|
||||
await flush();
|
||||
},
|
||||
signIn(userId) {
|
||||
settings.setState({ userId });
|
||||
auth.token = `token:${userId}`;
|
||||
},
|
||||
async firstSync(kind) {
|
||||
const accountId = settings.getState().userId;
|
||||
if (!accountId) throw new Error(`${name}: not signed in`);
|
||||
await drive(kind === 'merge' ? sync.initialMerge(accountId) : sync.initialReset(accountId), `${name} ${kind}`);
|
||||
settings.getState().setSyncEnabled(true);
|
||||
},
|
||||
async syncNow() {
|
||||
await flush();
|
||||
await drive(sync.scheduleSync(), `${name} sync`);
|
||||
},
|
||||
async signOut() {
|
||||
await flush();
|
||||
const unsent = await drive(sync.pushBeforeSignOut(), `${name} sign-out push`);
|
||||
settings.setState({ syncEnabled: false, userId: null });
|
||||
auth.token = null;
|
||||
return unsent;
|
||||
},
|
||||
pending() {
|
||||
return query<{ n: number }>('SELECT count(*) AS n FROM sync_outbox WHERE synced_at IS NULL')[0].n;
|
||||
},
|
||||
};
|
||||
return device;
|
||||
}
|
||||
|
||||
/** Ids of the Inbox lists of a device. */
|
||||
export function inboxIds(device: Device): string[] {
|
||||
return device.query<{ id: string }>('SELECT id FROM lists WHERE is_inbox = 1 ORDER BY id').map((r) => r.id);
|
||||
}
|
||||
|
||||
/** Requests of one account, per sliding window of `windowMs`: the largest count. */
|
||||
export function maxPerWindow(log: LoggedRequest[], windowMs = 60_000): number {
|
||||
let max = 0;
|
||||
for (const a of log) {
|
||||
const n = log.filter((b) => b.at >= a.at && b.at < a.at + windowMs).length;
|
||||
max = Math.max(max, n);
|
||||
}
|
||||
return max;
|
||||
}
|
||||
363
web/src/test/sync/sync.test.ts
Normal file
363
web/src/test/sync/sync.test.ts
Normal file
|
|
@ -0,0 +1,363 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
|
||||
import {
|
||||
startServer,
|
||||
createDevice,
|
||||
newAccount,
|
||||
inboxIds,
|
||||
driveUntil,
|
||||
maxPerWindow,
|
||||
LOCAL_INBOX_ID,
|
||||
type Device,
|
||||
type LoggedRequest,
|
||||
type Server,
|
||||
} from './harness';
|
||||
|
||||
// The post-merge sync checks of #145-#152, #165, #168/#180 and #178, run by
|
||||
// `npm test` instead of by hand on two phones (#169). Each scenario seeds its
|
||||
// own accounts on the shared server: the file runs shuffled. What the harness
|
||||
// does not cover is listed at the top of harness.ts.
|
||||
|
||||
let server: Server;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await startServer();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'], now: new Date('2026-11-07T12:00:00.000Z') });
|
||||
server.rateLimit = false;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
async function activeInboxes(userId: string): Promise<string[]> {
|
||||
const rows = await server.rows<{ id: string }>(
|
||||
'SELECT id FROM sl_lists WHERE user_id = $1 AND is_inbox AND deleted_at IS NULL',
|
||||
[userId],
|
||||
);
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
async function serverTaskCount(userId: string): Promise<number> {
|
||||
const [row] = await server.rows<{ n: number }>(
|
||||
'SELECT count(*)::int AS n FROM sl_tasks WHERE user_id = $1 AND deleted_at IS NULL',
|
||||
[userId],
|
||||
);
|
||||
return row.n;
|
||||
}
|
||||
|
||||
function localTasks(d: Device) {
|
||||
return d.query<{ id: string; title: string; completed: number; list_id: string; parent_id: string | null; calendar_event_id: string | null }>(
|
||||
'SELECT id, title, completed, list_id, parent_id, calendar_event_id FROM tasks ORDER BY id',
|
||||
);
|
||||
}
|
||||
|
||||
function refusals(log: LoggedRequest[]): number {
|
||||
return log.flatMap((r) => r.results ?? []).filter((r) => r.error !== undefined).length;
|
||||
}
|
||||
|
||||
/** Seconds since the epoch: the unit of the app's timestamp columns. */
|
||||
function nowS(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
describe('1. First sync « Fusionner » of a second device', () => {
|
||||
it('ends with one Inbox, the tasks of both devices and their completed tasks (#145, #146, #150)', async () => {
|
||||
const U = newAccount();
|
||||
|
||||
const a = await createDevice('a');
|
||||
await a.startup();
|
||||
const a1 = await a.tasks.createTask({ title: 'a open', listId: await a.lists.getInboxId() });
|
||||
const a2 = await a.tasks.createTask({ title: 'a done', listId: await a.lists.getInboxId() });
|
||||
await a.tasks.toggleComplete(a2);
|
||||
a.signIn(U);
|
||||
await a.firstSync('merge');
|
||||
|
||||
const b = await createDevice('b');
|
||||
await b.startup();
|
||||
const b1 = await b.tasks.createTask({ title: 'b open', listId: await b.lists.getInboxId() });
|
||||
const b2 = await b.tasks.createTask({ title: 'b done', listId: await b.lists.getInboxId() });
|
||||
await b.tasks.toggleComplete(b2);
|
||||
b.signIn(U);
|
||||
await b.firstSync('merge');
|
||||
|
||||
await a.syncNow();
|
||||
|
||||
const inboxes = await activeInboxes(U);
|
||||
expect(inboxes).toHaveLength(1);
|
||||
const all = [a1, a2, b1, b2].sort();
|
||||
for (const d of [a, b]) {
|
||||
expect(inboxIds(d), d.name).toEqual(inboxes);
|
||||
const rows = localTasks(d);
|
||||
expect(rows.map((t) => t.id), d.name).toEqual(all);
|
||||
expect(rows.filter((t) => t.completed).map((t) => t.id).sort(), d.name).toEqual([a2, b2].sort());
|
||||
expect(new Set(rows.map((t) => t.list_id)), d.name).toEqual(new Set(inboxes));
|
||||
}
|
||||
const done = await server.rows<{ id: string }>(
|
||||
'SELECT id FROM sl_tasks WHERE user_id = $1 AND completed ORDER BY id',
|
||||
[U],
|
||||
);
|
||||
expect(done.map((r) => r.id)).toEqual([a2, b2].sort());
|
||||
expect(await serverTaskCount(U)).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2. « Réinitialiser » on a new account', () => {
|
||||
it('pushes the Inbox it creates, and a task sent there is applied (#152 B)', async () => {
|
||||
const U = newAccount();
|
||||
const d = await createDevice('d');
|
||||
await d.startup();
|
||||
expect(inboxIds(d)).toEqual([LOCAL_INBOX_ID]);
|
||||
|
||||
d.signIn(U);
|
||||
await d.firstSync('reset');
|
||||
await d.syncNow();
|
||||
|
||||
const inboxes = await activeInboxes(U);
|
||||
expect(inboxes).toHaveLength(1);
|
||||
expect(inboxIds(d)).toEqual(inboxes);
|
||||
|
||||
const mark = server.log.length;
|
||||
const taskId = await d.tasks.createTask({ title: 'first', listId: await d.lists.getInboxId() });
|
||||
await d.syncNow();
|
||||
const [task] = await server.rows<{ list_id: string }>('SELECT list_id FROM sl_tasks WHERE id = $1', [taskId]);
|
||||
expect(task?.list_id).toBe(inboxes[0]);
|
||||
expect(refusals(server.log.slice(mark))).toBe(0);
|
||||
expect(d.pending()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('3. Split device (fixed Inbox beside the server Inbox)', () => {
|
||||
it('is repaired at start-up by repairInbox, and its tasks then go through without refusal (#152 A)', async () => {
|
||||
const U = newAccount();
|
||||
const d = await createDevice('d');
|
||||
await d.startup();
|
||||
d.signIn(U);
|
||||
await d.firstSync('merge');
|
||||
await d.syncNow();
|
||||
const [serverInbox] = inboxIds(d);
|
||||
expect(serverInbox).not.toBe(LOCAL_INBOX_ID);
|
||||
|
||||
// Before #152, ensureInbox recreated the fixed Inbox beside the server one,
|
||||
// and the tasks written there were refused by the server.
|
||||
d.exec('INSERT INTO lists (id, name, position, is_inbox, created_at, updated_at) VALUES (?, ?, 0, 1, ?, ?)', [
|
||||
LOCAL_INBOX_ID,
|
||||
'Inbox',
|
||||
nowS(),
|
||||
nowS(),
|
||||
]);
|
||||
const stranded = await d.tasks.createTask({ title: 'in the fixed Inbox', listId: LOCAL_INBOX_ID });
|
||||
const before = server.log.length;
|
||||
await d.syncNow();
|
||||
expect(refusals(server.log.slice(before))).toBeGreaterThan(0);
|
||||
|
||||
const mark = server.log.length;
|
||||
await d.startup();
|
||||
await d.syncNow();
|
||||
|
||||
expect(inboxIds(d)).toEqual([serverInbox]);
|
||||
const [task] = await server.rows<{ list_id: string }>('SELECT list_id FROM sl_tasks WHERE id = $1', [stranded]);
|
||||
expect(task?.list_id).toBe(serverInbox);
|
||||
expect(refusals(server.log.slice(mark))).toBe(0);
|
||||
expect(d.pending()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('4. Pull: local fields and newer offline edits', () => {
|
||||
it('keeps calendarEventId and a later offline edit, which goes back to the server (#149)', async () => {
|
||||
const U = newAccount();
|
||||
const a = await createDevice('a');
|
||||
await a.startup();
|
||||
a.settings.setState({ calendarSyncEnabled: true });
|
||||
a.signIn(U);
|
||||
await a.firstSync('merge');
|
||||
const t = await a.tasks.createTask({
|
||||
title: 'v1',
|
||||
listId: await a.lists.getInboxId(),
|
||||
dueDate: new Date('2026-11-20T09:00:00.000Z'),
|
||||
});
|
||||
await a.syncNow();
|
||||
const [{ calendar_event_id: calendarId }] = a.query<{ calendar_event_id: string }>(
|
||||
'SELECT calendar_event_id FROM tasks WHERE id = ?',
|
||||
[t],
|
||||
);
|
||||
expect(calendarId).toMatch(/^cal-/);
|
||||
|
||||
// Edited on another device: the pull brings the title, not the calendar id
|
||||
const b = await createDevice('b');
|
||||
await b.startup();
|
||||
b.signIn(U);
|
||||
await b.firstSync('reset');
|
||||
await b.tasks.updateTask(t, { title: 'from b' });
|
||||
await b.syncNow();
|
||||
await a.syncNow();
|
||||
expect(localTasks(a).find((r) => r.id === t)).toMatchObject({ title: 'from b', calendar_event_id: calendarId });
|
||||
|
||||
// Signed out, edited offline later, signed in again: the full pull keeps
|
||||
// the newer local row and pushes it back.
|
||||
expect(await a.signOut()).toBe(0);
|
||||
vi.setSystemTime(Date.now() + 10_000);
|
||||
await a.tasks.updateTask(t, { title: 'offline' });
|
||||
a.signIn(U);
|
||||
await a.firstSync('merge');
|
||||
await a.syncNow();
|
||||
|
||||
expect(localTasks(a).find((r) => r.id === t)).toMatchObject({ title: 'offline', calendar_event_id: calendarId });
|
||||
const [row] = await server.rows<{ title: string }>('SELECT title FROM sl_tasks WHERE id = $1', [t]);
|
||||
expect(row.title).toBe('offline');
|
||||
await b.syncNow();
|
||||
expect(localTasks(b).find((r) => r.id === t)?.title).toBe('offline');
|
||||
});
|
||||
});
|
||||
|
||||
describe('5. Push: a queue of more than 400 entries', () => {
|
||||
it('is sent over several syncs, and its refusals are replayed within their bounds (#147, #151)', async () => {
|
||||
const U = newAccount();
|
||||
const d = await createDevice('d');
|
||||
await d.startup();
|
||||
d.signIn(U);
|
||||
await d.firstSync('merge');
|
||||
const inbox = await d.lists.getInboxId();
|
||||
|
||||
// 105 refusals: updates of tasks the server never had
|
||||
for (let i = 0; i < 105; i++) {
|
||||
await d.outbox.queueOutboxEntry('task', randomUUID(), 'update', { title: 'ghost' });
|
||||
}
|
||||
for (let i = 0; i < 420; i++) await d.tasks.createTask({ title: `t${i}`, listId: inbox });
|
||||
await d.flush();
|
||||
expect(d.pending()).toBe(525);
|
||||
|
||||
const mark = server.log.length;
|
||||
// One request: the scheduler goes on by itself while the budget leaves entries unsent
|
||||
await d.syncNow();
|
||||
await driveUntil(async () => (await serverTaskCount(U)) === 420, { label: '420 tasks on the server' });
|
||||
await d.syncNow();
|
||||
|
||||
const posts = server.log.slice(mark).filter((r) => r.method === 'POST');
|
||||
expect(posts.length).toBeGreaterThan(8); // more than MAX_PUSH_BATCHES: several syncs
|
||||
expect(refusals(posts)).toBeGreaterThan(105); // replayed by later pushes
|
||||
expect(d.pending()).toBe(100); // MAX_KEPT_REFUSALS
|
||||
|
||||
// Older than REJECTED_RETENTION_DAYS: dropped
|
||||
vi.setSystemTime(Date.now() + 31 * 24 * 60 * 60 * 1000);
|
||||
await d.syncNow();
|
||||
expect(d.pending()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('6. Tags and subtasks end to end', () => {
|
||||
it('brings tags, links and subtasks to another device, and a link removed there disappears here (#168, #180)', async () => {
|
||||
const U = newAccount();
|
||||
const a = await createDevice('a');
|
||||
await a.startup();
|
||||
a.signIn(U);
|
||||
await a.firstSync('merge');
|
||||
const inbox = await a.lists.getInboxId();
|
||||
const tag = await a.tags.createTag('urgent', '#E57373');
|
||||
const parent = await a.tasks.createTask({ title: 'parent', listId: inbox });
|
||||
const child = await a.tasks.createTask({ title: 'child', listId: inbox, parentId: parent });
|
||||
await a.tags.setTagsForTask(parent, [tag]);
|
||||
await a.syncNow();
|
||||
expect(a.pending()).toBe(0);
|
||||
|
||||
const b = await createDevice('b');
|
||||
await b.startup();
|
||||
b.signIn(U);
|
||||
await b.firstSync('reset');
|
||||
expect(b.query('SELECT name FROM tags WHERE id = ?', [tag])).toEqual([{ name: 'urgent' }]);
|
||||
expect(localTasks(b).find((r) => r.id === child)?.parent_id).toBe(parent);
|
||||
expect(b.query('SELECT task_id, tag_id FROM task_tags')).toEqual([{ task_id: parent, tag_id: tag }]);
|
||||
|
||||
await b.tags.setTagsForTask(parent, []);
|
||||
await b.syncNow();
|
||||
expect(await server.rows('SELECT * FROM sl_task_tags WHERE task_id = $1', [parent])).toEqual([]);
|
||||
|
||||
await a.syncNow();
|
||||
expect(a.query('SELECT task_id, tag_id FROM task_tags')).toEqual([]);
|
||||
expect(localTasks(a).find((r) => r.id === child)?.parent_id).toBe(parent);
|
||||
});
|
||||
});
|
||||
|
||||
describe('7. Change of account', () => {
|
||||
it('pushes the queue at sign-out, syncs nothing under the new account before the choice, and « Charger ce compte » brings nothing of the old one (#165)', async () => {
|
||||
const A = newAccount();
|
||||
const B = newAccount();
|
||||
const d = await createDevice('d');
|
||||
await d.startup();
|
||||
d.signIn(A);
|
||||
await d.firstSync('merge');
|
||||
const pendingTask = await d.tasks.createTask({ title: 'pending at sign-out', listId: await d.lists.getInboxId() });
|
||||
await d.flush();
|
||||
expect(d.pending()).toBeGreaterThan(0);
|
||||
|
||||
expect(await d.signOut()).toBe(0);
|
||||
const [pushed] = await server.rows<{ user_id: string }>('SELECT user_id FROM sl_tasks WHERE id = $1', [pendingTask]);
|
||||
expect(pushed?.user_id).toBe(A);
|
||||
|
||||
// Signed in to B on a device holding A's data. Even with sync left on and
|
||||
// a new local write, the scheduler sends nothing (canSync).
|
||||
d.signIn(B);
|
||||
expect(d.settings.getState().dataOwnerId).toBe(A);
|
||||
d.settings.getState().setSyncEnabled(true);
|
||||
const afterSwitch = await d.tasks.createTask({ title: 'after the switch', listId: await d.lists.getInboxId() });
|
||||
const mark = server.log.length;
|
||||
await d.syncNow();
|
||||
expect(server.log.slice(mark)).toEqual([]);
|
||||
|
||||
// « Charger ce compte »: the only choice offered (sync off until it succeeds)
|
||||
d.settings.getState().setSyncEnabled(false);
|
||||
await d.firstSync('reset');
|
||||
await d.syncNow();
|
||||
|
||||
expect(d.settings.getState().dataOwnerId).toBe(B);
|
||||
const bInbox = await activeInboxes(B);
|
||||
expect(bInbox).toHaveLength(1);
|
||||
expect(inboxIds(d)).toEqual(bInbox);
|
||||
expect(localTasks(d)).toEqual([]);
|
||||
expect(await serverTaskCount(B)).toBe(0);
|
||||
const pushedUnderB = server.log.filter((r) => r.userId === B && r.method === 'POST').flatMap((r) => r.entityIds ?? []);
|
||||
expect(pushedUnderB).toEqual(bInbox);
|
||||
// A keeps its data, and the write made under B never left the device
|
||||
expect(await serverTaskCount(A)).toBe(1);
|
||||
expect(await server.rows('SELECT id FROM sl_tasks WHERE id = $1', [afterSwitch])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('8. Scheduler wiring', () => {
|
||||
it('counts every request in the budget and waits for the Retry-After of a real 429 before going on (#178)', async () => {
|
||||
server.rateLimit = true;
|
||||
const U = newAccount();
|
||||
const d = await createDevice('d');
|
||||
await d.startup();
|
||||
d.signIn(U);
|
||||
await d.firstSync('merge');
|
||||
const inbox = await d.lists.getInboxId();
|
||||
for (let i = 0; i < 300; i++) await d.tasks.createTask({ title: `t${i}`, listId: inbox });
|
||||
await d.flush();
|
||||
|
||||
// The web page used the account meanwhile: the server's 10 per minute run out
|
||||
for (let i = 0; i < 8; i++) expect((await server.companion(U, 'GET')).status).toBe(200);
|
||||
|
||||
const mark = server.log.length;
|
||||
await d.syncNow();
|
||||
await driveUntil(async () => (await serverTaskCount(U)) === 300, { label: '300 tasks on the server' });
|
||||
await d.syncNow();
|
||||
expect(d.pending()).toBe(0);
|
||||
|
||||
const mine = server.log.slice(mark);
|
||||
expect(mine.every((r) => r.userId === U)).toBe(true);
|
||||
// Budget of syncSchedule.ts: 6 requests per sliding minute, POST and GET together
|
||||
expect(maxPerWindow(mine)).toBeLessThanOrEqual(6);
|
||||
const limited = mine.filter((r) => r.status === 429);
|
||||
expect(limited.length).toBeGreaterThan(0);
|
||||
for (const r of limited) {
|
||||
expect(r.retryAfter).toBeGreaterThan(0);
|
||||
const next = mine[mine.indexOf(r) + 1];
|
||||
expect(next, 'the sync resumes after the 429').toBeDefined();
|
||||
expect(next!.at - r.at).toBeGreaterThanOrEqual(r.retryAfter! * 1000);
|
||||
}
|
||||
});
|
||||
});
|
||||
39
web/src/test/sync/vitest.config.mts
Normal file
39
web/src/test/sync/vitest.config.mts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { fileURLToPath } from 'node:url';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
// Sync harness (#169): the app's real src/services/syncClient.ts against the
|
||||
// companion's real /api/sync route. Kept out of the root of web/ and out of
|
||||
// web/vitest.config.mts (which excludes this folder): `npm run test:sync`.
|
||||
// The app code and its own dependencies (date-fns...) are loaded from the
|
||||
// repository root: `npm ci` is needed at the root as well as in web/.
|
||||
|
||||
const webDir = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
const webSrc = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const appSrc = fileURLToPath(new URL('../../../../src/', import.meta.url));
|
||||
const webDrizzle = fileURLToPath(new URL('../../../node_modules/drizzle-orm', import.meta.url));
|
||||
|
||||
export default defineConfig({
|
||||
root: webDir,
|
||||
resolve: {
|
||||
alias: [
|
||||
// App imports (`@/src/...`, tsconfig of the app): declared before `@/`,
|
||||
// which is the companion's own `@/*` path.
|
||||
{ find: /^@\/src\//, replacement: appSrc },
|
||||
{ find: /^@\//, replacement: webSrc },
|
||||
// One drizzle-orm for both sides: the copy of web/, not the one of the
|
||||
// repository root that the app files would resolve otherwise.
|
||||
{ find: /^drizzle-orm(\/.*)?$/, replacement: `${webDrizzle}$1` },
|
||||
// Same npm alias as web/vitest.config.mts (PGlite kept out of the image).
|
||||
{ find: /^@electric-sql\/pglite$/, replacement: 'electric-sql-pglite' },
|
||||
],
|
||||
},
|
||||
test: {
|
||||
include: ['src/test/sync/**/*.test.ts'],
|
||||
// drizzle-orm/pglite imports `@electric-sql/pglite`: inline it so the alias applies.
|
||||
server: { deps: { inline: ['drizzle-orm'] } },
|
||||
// Same as web/vitest.config.mts: each scenario seeds its own accounts.
|
||||
sequence: { shuffle: true },
|
||||
testTimeout: 20_000,
|
||||
hookTimeout: 30_000,
|
||||
},
|
||||
});
|
||||
|
|
@ -30,5 +30,5 @@
|
|||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
"exclude": ["node_modules", "src/test/sync/**"]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { fileURLToPath } from 'node:url';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { configDefaults, defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
|
|
@ -13,6 +13,9 @@ export default defineConfig({
|
|||
],
|
||||
},
|
||||
test: {
|
||||
// The sync harness has its own config (app aliases, Expo stubs):
|
||||
// `npm run test:sync`, chained by `npm test`.
|
||||
exclude: [...configDefaults.exclude, 'src/test/sync/**'],
|
||||
// drizzle-orm/pglite imports `@electric-sql/pglite`: inline it so the alias applies.
|
||||
server: { deps: { inline: ['drizzle-orm'] } },
|
||||
// Always shuffle: the sync route tests once depended on their order (#148).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue