sokko-g/website/src/features/toolboxes/storage/persistenceQueue.js

79 lines
2.5 KiB
JavaScript

// Rôle : sérialise les écritures, publie leur état et reconstruit l'optimiste depuis les succès confirmés.
export function createPersistenceQueue(initialState, onChange, onStatusChange = () => {}) {
let confirmed = initialState;
let current = initialState;
let running = false;
const pending = [];
let status = { phase: "loading", pendingCount: 0, lastConfirmedAt: "", message: "" };
function publishStatus(update) {
status = { ...status, ...update };
onStatusChange(status);
}
function publish() {
current = pending.reduce((state, operation) => operation.apply(state), confirmed);
onChange(current);
}
async function drain() {
if (running) return;
running = true;
while (pending.length) {
const operation = pending[0];
let success = false;
let failure;
try {
const next = operation.apply(confirmed);
const persisted = await operation.persist(next, confirmed);
confirmed = persisted ?? next;
success = true;
} catch (error) {
failure = error;
if (error?.confirmedState) confirmed = error.confirmedState;
}
pending.shift();
publish();
if (operation.trackStatus) {
const pendingCount = Math.max(0, status.pendingCount - 1);
if (success) {
publishStatus({
phase: pendingCount ? "pending" : "confirmed",
pendingCount,
lastConfirmedAt: new Date().toISOString(),
message: ""
});
} else {
publishStatus({
phase: failure?.name === "StorageConflictError" ? "conflict" : "error",
pendingCount,
message: failure?.message || "Erreur de stockage IndexedDB."
});
}
}
operation.resolve(success);
if (!success) operation.onError?.(failure);
}
running = false;
}
return {
getCurrent: () => current,
getStatus: () => status,
initialize(state) {
if (running || pending.length) throw new Error("Cannot initialize while writes are pending");
confirmed = state;
publish();
publishStatus({ phase: "confirmed", pendingCount: 0, message: "" });
},
enqueue(apply, persist, onError, { trackStatus = true } = {}) {
const result = new Promise((resolve) => pending.push({ apply, persist, onError, resolve, trackStatus }));
if (trackStatus) {
publishStatus({ phase: "pending", pendingCount: status.pendingCount + 1, message: "" });
}
publish();
void drain();
return result;
}
};
}