Synchro du navigateur avec le relais (app/infra/sync.js)

Ajoute getMeta et setMeta au magasin IndexedDB pour garder l'état de la synchro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-18 05:12:06 +01:00
co-authored by Claude Opus 5.5
parent 91ee787ba0
commit 86bf709da3
3 changed files with 311 additions and 0 deletions
+106
View File
@@ -0,0 +1,106 @@
// app/infra/sync.js contre le vrai serveur, avec un magasin en mémoire qui
// imite openEventStore() (list, add, getMeta, setMeta).
import { test } from "node:test";
import assert from "node:assert/strict";
import { createSync, SyncError } from "../../app/infra/sync.js";
import { createEvent, compareEvents } from "../../app/domain/events.js";
import { deriveKeys, encryptEvent, generateSyncKey } from "../../app/domain/sync-crypto.js";
import { startServer, push } from "./helpers.js";
function memoryStore() {
/** @type {Map<string, any>} */
const events = new Map();
/** @type {Map<string, unknown>} */
const meta = new Map();
return {
async list() { return [...events.values()].sort(compareEvents); },
/** @param {readonly any[]} list */
async add(list) {
let n = 0;
for (const e of list) if (!events.has(e.id)) { events.set(e.id, e); n++; }
return n;
},
/** @param {string} k */
async getMeta(k) { return structuredClone(meta.get(k)); },
/** @param {string} k @param {unknown} v */
async setMeta(k, v) { meta.set(k, structuredClone(v)); },
meta,
};
}
/** @param {string} device @param {string} date @param {number} kg */
const weight = (device, date, kg) => createEvent("WeightRecorded", { date, kg }, { device, at: date + "T07:00:00.000Z" });
test("deux appareils : chacun envoie les siens et reçoit ceux de l'autre, sans doublon", async () => {
const s = await startServer();
try {
const syncKey = generateSyncKey();
const pc = memoryStore();
const phone = memoryStore();
await pc.add([weight("pc", "2026-11-01", 80), weight("pc", "2026-11-02", 79.8)]);
const syncPc = createSync({ store: pc, syncKey, baseUrl: s.base });
const syncPhone = createSync({ store: phone, syncKey, baseUrl: s.base });
// Le téléphone, avant tout dépôt : la clé ne correspond à aucun journal.
assert.equal((await syncPhone.pull()).exists, false);
assert.deepEqual(await syncPc.sync(), { pushed: 2, pulled: 0, ignored: 0 });
assert.deepEqual(await syncPc.sync(), { pushed: 0, pulled: 0, ignored: 0 }, "rien de nouveau");
await phone.add([weight("phone", "2026-11-03", 79.5)]);
assert.deepEqual(await syncPhone.sync(), { pushed: 1, pulled: 2, ignored: 0 });
assert.deepEqual(await syncPc.sync(), { pushed: 0, pulled: 1, ignored: 0 });
assert.deepEqual((await pc.list()).map((e) => e.id), (await phone.list()).map((e) => e.id));
assert.equal((await pc.list()).length, 3);
// L'état est gardé dans meta, par journal.
const { journalId } = await deriveKeys(syncKey);
const saved = /** @type {any} */ (pc.meta.get("sync:" + journalId));
assert.equal(saved.lastSeq, 3);
assert.equal(saved.known.length, 3);
// Une nouvelle instance (rechargement de la page) reprend où elle en était.
assert.deepEqual(await createSync({ store: pc, syncKey, baseUrl: s.base }).sync(), { pushed: 0, pulled: 0, ignored: 0 });
} finally {
await s.close();
}
});
test("blocs illisibles ou événements invalides : ignorés et comptés", async () => {
const s = await startServer();
try {
const syncKey = generateSyncKey();
const k = await deriveKeys(syncKey);
const intruder = await deriveKeys(generateSyncKey());
await push(s, k.journalId, k.authToken, [
await encryptEvent(k.encKey, weight("pc", "2026-11-01", 80)),
await encryptEvent(k.encKey, { id: "x", type: "WeightRecorded", data: {} }),
await encryptEvent(intruder.encKey, weight("pc", "2026-11-02", 80)),
]);
const store = memoryStore();
const r = await createSync({ store, syncKey, baseUrl: s.base }).pull();
assert.deepEqual([r.events.length, r.added, r.ignored, r.exists], [1, 1, 2, true]);
assert.equal((await store.list()).length, 1);
} finally {
await s.close();
}
});
test("erreurs : réseau absent, clé d'accès refusée ; un seul sync() à la fois", async () => {
const store = memoryStore();
await store.add([weight("pc", "2026-11-01", 80)]);
const offline = createSync({ store, syncKey: generateSyncKey(), fetch: async () => { throw new TypeError("Failed to fetch"); } });
await assert.rejects(offline.sync(), (e) => e instanceof SyncError && e.code === "offline");
const forbidden = createSync({ store, syncKey: generateSyncKey(), fetch: async () => new Response(JSON.stringify({ error: "forbidden" }), { status: 403 }) });
await assert.rejects(forbidden.pull(), (e) => e instanceof SyncError && e.code === "forbidden");
let calls = 0;
const slow = createSync({
store, syncKey: generateSyncKey(),
fetch: async () => { calls++; return new Response(JSON.stringify({ last: 1, accepted: 1, events: [], more: false }), { status: 200 }); },
});
const [a, b] = [slow.sync(), slow.sync()];
assert.equal(a, b, "le même appel en cours est rendu");
await a;
assert.equal(calls, 2, "une lecture, un envoi");
});