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:
co-authored by
Claude Opus 5.5
parent
91ee787ba0
commit
86bf709da3
@@ -9,6 +9,7 @@
|
||||
// relit en entier et se replie en mémoire.
|
||||
// - Magasin `meta` : réglages de l'appareil, clés explicites (sans keyPath).
|
||||
// « deviceId » : identifiant aléatoire de l'appareil (UUID v4), créé une fois.
|
||||
// « sync:<journalId> » : état de la synchro avec le relais (app/infra/sync.js).
|
||||
//
|
||||
// Ce module ne valide pas les événements : l'appelant le fait (createEvent,
|
||||
// readImport). Les événements invalides déjà stockés sont gardés (foldEvents les
|
||||
@@ -109,6 +110,26 @@ export async function openEventStore(dbName = "ia-fit") {
|
||||
return id;
|
||||
},
|
||||
|
||||
/**
|
||||
* Lit un réglage de l'appareil (magasin `meta`), ou undefined.
|
||||
* @param {string} key
|
||||
* @returns {Promise<unknown>}
|
||||
*/
|
||||
async getMeta(key) {
|
||||
return done(db.transaction("meta").objectStore("meta").get(key));
|
||||
},
|
||||
|
||||
/**
|
||||
* Écrit un réglage de l'appareil (magasin `meta`).
|
||||
* @param {string} key
|
||||
* @param {unknown} value clonable (structuredClone)
|
||||
*/
|
||||
async setMeta(key, value) {
|
||||
const tx = db.transaction("meta", "readwrite");
|
||||
tx.objectStore("meta").put(value, key);
|
||||
await committed(tx);
|
||||
},
|
||||
|
||||
/** Ferme la base (tests, changement de clé). */
|
||||
close() {
|
||||
db.close();
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// Synchro avec le relais chiffré (ADR 0005, point 3), côté navigateur.
|
||||
//
|
||||
// Chaque événement est chiffré un par un avec la clé tirée de la clé de synchro,
|
||||
// envoyé au relais, et les événements des autres appareils (et de l'IA) sont
|
||||
// récupérés puis fusionnés par union (ADR 0006). Le relais ne voit que des blocs.
|
||||
//
|
||||
// État gardé dans le magasin `meta` (clé « sync:<journalId> ») :
|
||||
// - `lastSeq` : dernier numéro d'ordre lu sur le relais ;
|
||||
// - `known` : identifiants des événements que le relais a déjà (lus, ou
|
||||
// envoyés avec succès). Un événement local absent de cette liste est à envoyer.
|
||||
// Un envoi dont la réponse se perd est refait : le relais reçoit alors deux blocs
|
||||
// du même événement, que la fusion par union dédoublonne.
|
||||
//
|
||||
// MODE D'EMPLOI POUR L'INTERFACE
|
||||
// const sync = createSync({ store, syncKey }); // store : openEventStore()
|
||||
// const { pushed, pulled, ignored } = await sync.sync();
|
||||
// - à l'ouverture de l'app (si une clé de synchro est enregistrée) ;
|
||||
// - après chaque événement local, avec un délai (2 à 5 s, regroupé : plusieurs
|
||||
// saisies rapprochées donnent une seule synchro) ;
|
||||
// - au retour du réseau (événement `online`) et au retour sur l'onglet
|
||||
// (`visibilitychange` vers visible).
|
||||
// Après un `pulled > 0`, recharger l'état depuis store.list(). sync() n'en
|
||||
// lance jamais deux à la fois : un appel pendant une synchro attend la même.
|
||||
// Erreurs : SyncError, avec `code` :
|
||||
// - "offline" (réseau absent : réessayer plus tard, sans alerte) ;
|
||||
// - "forbidden" (le relais refuse la clé d'accès : journal pris par une autre
|
||||
// clé, cas anormal) ; "journal_full", "rate_limited", "server".
|
||||
// Appariement d'un nouvel appareil : `await sync.pull()` d'abord ; `exists`
|
||||
// false signale une clé qui ne correspond à aucun journal (faute de frappe ?)
|
||||
// avant que le premier envoi ne crée un journal neuf.
|
||||
|
||||
import { validateEvent } from "../domain/events.js";
|
||||
import { deriveKeys, decryptEvent, encryptEvent } from "../domain/sync-crypto.js";
|
||||
|
||||
/** @typedef {import("../domain/events.js").DomainEvent} DomainEvent */
|
||||
|
||||
/** Événements par envoi (le relais en accepte 500, et 4 Mo par requête). */
|
||||
const PUSH_BATCH = 100;
|
||||
const PUSH_BATCH_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export class SyncError extends Error {
|
||||
/** @param {string} code @param {string} message @param {number} [status] */
|
||||
constructor(code, message, status) {
|
||||
super(message);
|
||||
this.name = "SyncError";
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} SyncStore ce que la synchro utilise de openEventStore()
|
||||
* @property {() => Promise<DomainEvent[]>} list
|
||||
* @property {(events: readonly DomainEvent[]) => Promise<number>} add
|
||||
* @property {(key: string) => Promise<unknown>} getMeta
|
||||
* @property {(key: string, value: unknown) => Promise<void>} setMeta
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {{store: SyncStore, syncKey: string, baseUrl?: string, fetch?: typeof fetch}} options
|
||||
* baseUrl : adresse du serveur, vide pour la même origine
|
||||
*/
|
||||
export function createSync({ store, syncKey, baseUrl = "", fetch: doFetch = globalThis.fetch.bind(globalThis) }) {
|
||||
const keysPromise = deriveKeys(syncKey);
|
||||
/** @type {Promise<{pushed: number, pulled: number, ignored: number}>|null} */
|
||||
let running = null;
|
||||
|
||||
async function context() {
|
||||
const keys = await keysPromise;
|
||||
const metaKey = "sync:" + keys.journalId;
|
||||
const saved = /** @type {{lastSeq?: number, known?: string[]}|undefined} */ (await store.getMeta(metaKey));
|
||||
const state = { lastSeq: saved?.lastSeq ?? 0, known: new Set(saved?.known ?? []) };
|
||||
const save = () => store.setMeta(metaKey, { lastSeq: state.lastSeq, known: [...state.known] });
|
||||
const url = `${baseUrl.replace(/\/+$/, "")}/api/journals/${keys.journalId}/events`;
|
||||
return { keys, state, save, url };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {RequestInit} init
|
||||
*/
|
||||
async function request(url, init) {
|
||||
let res;
|
||||
try {
|
||||
res = await doFetch(url, init);
|
||||
} catch {
|
||||
throw new SyncError("offline", "Relais injoignable : la synchro reprendra au retour du réseau.");
|
||||
}
|
||||
if (res.ok || res.status === 404) return res;
|
||||
const body = await res.json().catch(() => ({}));
|
||||
const code = res.status === 403 ? "forbidden" : res.status === 429 ? "rate_limited" : body.error === "journal_full" ? "journal_full" : "server";
|
||||
throw new SyncError(code, body.error_description ?? `Relais : erreur ${res.status}.`, res.status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoie les événements que le relais n'a pas encore.
|
||||
* @param {readonly DomainEvent[]} events
|
||||
* @returns {Promise<number>} nombre d'événements envoyés
|
||||
*/
|
||||
async function push(events) {
|
||||
const { keys, state, save, url } = await context();
|
||||
const todo = events.filter((e) => !state.known.has(e.id));
|
||||
let sent = 0;
|
||||
while (sent < todo.length) {
|
||||
const batch = [];
|
||||
const blobs = [];
|
||||
let bytes = 0;
|
||||
for (const e of todo.slice(sent, sent + PUSH_BATCH)) {
|
||||
const blob = await encryptEvent(keys.encKey, e);
|
||||
if (blobs.length && bytes + blob.length > PUSH_BATCH_BYTES) break;
|
||||
batch.push(e);
|
||||
blobs.push(blob);
|
||||
bytes += blob.length;
|
||||
}
|
||||
await request(url, {
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer " + keys.authToken, "content-type": "application/json" },
|
||||
body: JSON.stringify(blobs),
|
||||
});
|
||||
for (const e of batch) state.known.add(e.id);
|
||||
await save();
|
||||
sent += batch.length;
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les événements déposés depuis la dernière lecture, les déchiffre,
|
||||
* les valide et ajoute les valides au magasin.
|
||||
* @returns {Promise<{events: DomainEvent[], added: number, ignored: number, exists: boolean}>}
|
||||
* events : événements valides lus ; added : ceux qui manquaient au magasin ;
|
||||
* ignored : blocs illisibles ou invalides ;
|
||||
* exists : false si aucun journal ne correspond encore à cette clé
|
||||
*/
|
||||
async function pull() {
|
||||
const { keys, state, save, url } = await context();
|
||||
/** @type {DomainEvent[]} */
|
||||
const events = [];
|
||||
let ignored = 0;
|
||||
let added = 0;
|
||||
for (;;) {
|
||||
const res = await request(`${url}?after=${state.lastSeq}`, { headers: { authorization: "Bearer " + keys.authToken } });
|
||||
if (res.status === 404) return { events, added, ignored, exists: false };
|
||||
const page = /** @type {{events: {seq: number, blob: string}[], last: number, more: boolean}} */ (await res.json());
|
||||
/** @type {DomainEvent[]} */
|
||||
const valid = [];
|
||||
for (const { blob } of page.events) {
|
||||
try {
|
||||
const e = await decryptEvent(keys.encKey, blob);
|
||||
if (validateEvent(e) === null) valid.push(/** @type {DomainEvent} */ (e));
|
||||
else ignored++;
|
||||
} catch {
|
||||
ignored++;
|
||||
}
|
||||
}
|
||||
if (valid.length) added += await store.add(valid);
|
||||
for (const e of valid) state.known.add(e.id);
|
||||
events.push(...valid);
|
||||
if (page.events.length) state.lastSeq = page.events[page.events.length - 1].seq;
|
||||
await save();
|
||||
if (!page.more || !page.events.length) break;
|
||||
}
|
||||
return { events, added, ignored, exists: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Lit d'abord (ce que le relais a déjà n'est pas renvoyé), puis envoie.
|
||||
* @returns {Promise<{pushed: number, pulled: number, ignored: number}>}
|
||||
*/
|
||||
function sync() {
|
||||
running ??= (async () => {
|
||||
try {
|
||||
const { added, ignored } = await pull();
|
||||
const pushed = await push(await store.list());
|
||||
return { pushed, pulled: added, ignored };
|
||||
} finally {
|
||||
running = null;
|
||||
}
|
||||
})();
|
||||
return running;
|
||||
}
|
||||
|
||||
return { push, pull, sync };
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
Reference in New Issue
Block a user