Clarify local persistence and backup states
This commit is contained in:
parent
2f2e79d200
commit
1171eee510
24 changed files with 678 additions and 269 deletions
|
|
@ -1,9 +1,15 @@
|
|||
// Rôle : sérialise les écritures et reconstruit l'état optimiste depuis les succès confirmés.
|
||||
export function createPersistenceQueue(initialState, onChange) {
|
||||
// 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);
|
||||
|
|
@ -28,6 +34,23 @@ export function createPersistenceQueue(initialState, onChange) {
|
|||
}
|
||||
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);
|
||||
}
|
||||
|
|
@ -36,13 +59,18 @@ export function createPersistenceQueue(initialState, onChange) {
|
|||
|
||||
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) {
|
||||
const result = new Promise((resolve) => pending.push({ apply, persist, onError, resolve }));
|
||||
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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue