195 lines
6.7 KiB
JavaScript
195 lines
6.7 KiB
JavaScript
// La synchro branchée sur l'app (mode d'emploi en tête de app/infra/sync.js) :
|
|
// la clé de l'appareil, quand synchroniser, l'état affiché.
|
|
//
|
|
// Quand : à l'ouverture (si une clé existe), après chaque événement local
|
|
// (délai de 3 s, regroupé), au retour du réseau (`online`) et au retour sur
|
|
// l'onglet (`visibilitychange`). Jamais de scrutation : sans saisie ni retour,
|
|
// aucune requête ne part.
|
|
//
|
|
// Gardé dans le magasin `meta` d'IndexedDB :
|
|
// - « syncKey » : la clé de synchro de l'appareil (null une fois désactivée) ;
|
|
// - « syncLastAt » : fin de la dernière synchro réussie (ISO).
|
|
|
|
import { createSync, SyncError } from "../infra/sync.js";
|
|
import { createSyncScheduler } from "./sync-model.js";
|
|
|
|
/** @typedef {import("./sync-model.js").SyncStatus} SyncStatus */
|
|
/** @typedef {import("../domain/events.js").DomainEvent} DomainEvent */
|
|
|
|
/**
|
|
* @typedef {object} MetaStore ce que le service 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 {unknown} e */
|
|
const errorCode = (e) => (e instanceof SyncError ? e.code : e instanceof Error && e.name === "SyncCryptoError" ? "key" : "server");
|
|
|
|
/**
|
|
* @param {{db: MetaStore, store: import("./store.js").Store, onNewProposals?: (count: number) => void, onErased?: () => Promise<void>|void}} options
|
|
* onNewProposals : des propositions sont arrivées par la synchro (de l'IA, d'un autre appareil)
|
|
* onErased : le journal a été effacé depuis un autre appareil ; la clé est déjà oubliée,
|
|
* reste à effacer les données de cet appareil
|
|
*/
|
|
export function createSyncService({ db, store, onNewProposals, onErased }) {
|
|
/** @type {string|null} */
|
|
let key = null;
|
|
/** @type {ReturnType<typeof createSync>|null} */
|
|
let sync = null;
|
|
/** @type {SyncStatus} */
|
|
const status = { hasKey: false, online: navigator.onLine, running: false, lastAt: null, error: null };
|
|
/** @type {Set<() => void>} */
|
|
const listeners = new Set();
|
|
const notify = () => { for (const fn of [...listeners]) fn(); };
|
|
|
|
/** Relit le journal après des événements reçus ; signale les nouvelles propositions. */
|
|
async function reload() {
|
|
const before = new Set(store.getState().proposals.map((p) => p.id));
|
|
store.load(await db.list());
|
|
const fresh = store.getState().proposals.filter((p) => !before.has(p.id)).length;
|
|
if (fresh) onNewProposals?.(fresh);
|
|
}
|
|
|
|
async function run() {
|
|
const current = sync;
|
|
if (!current) return null;
|
|
status.running = true;
|
|
notify();
|
|
try {
|
|
const result = await current.sync();
|
|
if (current !== sync) return result; // clé changée pendant la synchro
|
|
status.error = null;
|
|
status.lastAt = new Date().toISOString();
|
|
await db.setMeta("syncLastAt", status.lastAt);
|
|
if (result.pulled) await reload();
|
|
return result;
|
|
} catch (e) {
|
|
// Effacé depuis un autre appareil (« Tout effacer partout ») : on suit.
|
|
if (current === sync && errorCode(e) === "erased") {
|
|
await current.forget();
|
|
await setKey(null);
|
|
await onErased?.();
|
|
return null;
|
|
}
|
|
if (current === sync) status.error = errorCode(e);
|
|
throw e;
|
|
} finally {
|
|
status.running = false;
|
|
notify();
|
|
}
|
|
}
|
|
|
|
const scheduler = createSyncScheduler({ run });
|
|
|
|
/** @param {string|null} next */
|
|
async function setKey(next) {
|
|
scheduler.cancel();
|
|
key = next;
|
|
sync = next ? createSync({ store: db, syncKey: next }) : null;
|
|
status.hasKey = !!next;
|
|
status.error = null;
|
|
await db.setMeta("syncKey", next);
|
|
notify();
|
|
}
|
|
|
|
return {
|
|
/** Lit la clé enregistrée et branche les déclencheurs. */
|
|
async start() {
|
|
const saved = await db.getMeta("syncKey");
|
|
const last = await db.getMeta("syncLastAt");
|
|
status.lastAt = typeof last === "string" ? last : null;
|
|
if (typeof saved === "string" && saved) {
|
|
key = saved;
|
|
sync = createSync({ store: db, syncKey: saved });
|
|
status.hasKey = true;
|
|
}
|
|
window.addEventListener("online", () => {
|
|
status.online = true;
|
|
notify();
|
|
if (sync) void scheduler.now();
|
|
});
|
|
window.addEventListener("offline", () => {
|
|
status.online = false;
|
|
notify();
|
|
});
|
|
document.addEventListener("visibilitychange", () => {
|
|
if (document.visibilityState === "visible" && sync) void scheduler.now();
|
|
});
|
|
if (sync) void scheduler.now();
|
|
},
|
|
|
|
getKey: () => key,
|
|
/** @returns {Readonly<SyncStatus>} */
|
|
getStatus: () => status,
|
|
/** @param {() => void} fn @returns {() => void} */
|
|
subscribe(fn) {
|
|
listeners.add(fn);
|
|
return () => { listeners.delete(fn); };
|
|
},
|
|
|
|
/** Synchronise tout de suite ; renvoie l'état ensuite. */
|
|
async syncNow() {
|
|
await scheduler.now();
|
|
return status;
|
|
},
|
|
|
|
/** Un événement local vient d'être écrit : synchro dans 3 s, regroupée. */
|
|
later() {
|
|
if (sync) scheduler.later();
|
|
},
|
|
|
|
/**
|
|
* Lit le relais avec une clé, avant de l'adopter (« J'ai déjà une clé ») :
|
|
* les événements trouvés rejoignent le journal local.
|
|
* @param {string} candidate clé normalisée
|
|
* @returns {Promise<{exists: boolean, added: number}>} lève une SyncError
|
|
*/
|
|
async probe(candidate) {
|
|
const { exists, added } = await createSync({ store: db, syncKey: candidate }).pull();
|
|
if (added) await reload();
|
|
return { exists, added };
|
|
},
|
|
|
|
/**
|
|
* Adopte une clé (nouvelle, collée ou appariée) puis synchronise : les
|
|
* événements du relais rejoignent le journal local, et les événements
|
|
* locaux partent vers le relais.
|
|
* @param {string} next clé normalisée
|
|
*/
|
|
async enable(next) {
|
|
await setKey(next);
|
|
await scheduler.now();
|
|
return status;
|
|
},
|
|
|
|
/** Oublie la clé sur cet appareil ; le journal local et le relais restent. */
|
|
async disable() {
|
|
await setKey(null);
|
|
},
|
|
|
|
/**
|
|
* Avant d'effacer cet appareil seulement : la synchro est coupée, et ce que
|
|
* l'appareil avait lu est oublié (une clé réactivée relira tout le relais).
|
|
*/
|
|
async detach() {
|
|
await sync?.forget();
|
|
await setKey(null);
|
|
},
|
|
|
|
/**
|
|
* « Tout effacer partout » : vide le journal du relais, puis coupe la synchro.
|
|
* Lève une SyncError si le relais est injoignable : rien n'est alors effacé.
|
|
*/
|
|
async eraseEverywhere() {
|
|
if (!sync) return;
|
|
await sync.erase();
|
|
await sync.forget();
|
|
await setKey(null);
|
|
},
|
|
};
|
|
}
|
|
|
|
/** @typedef {ReturnType<typeof createSyncService>} SyncService */
|