Serialize toolbox writes and preserve concurrent edits
Some checks failed
Deploy Sokko G / deploy (push) Failing after 2s
Some checks failed
Deploy Sokko G / deploy (push) Failing after 2s
This commit is contained in:
parent
7521d50626
commit
a4cf633ab4
12 changed files with 381 additions and 320 deletions
50
website/src/features/toolboxes/storage/persistenceQueue.js
Normal file
50
website/src/features/toolboxes/storage/persistenceQueue.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// Rôle : sérialise les écritures et reconstruit l'état optimiste depuis les succès confirmés.
|
||||
export function createPersistenceQueue(initialState, onChange) {
|
||||
let confirmed = initialState;
|
||||
let current = initialState;
|
||||
let running = false;
|
||||
const pending = [];
|
||||
|
||||
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);
|
||||
await operation.persist(next);
|
||||
confirmed = next;
|
||||
success = true;
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
pending.shift();
|
||||
publish();
|
||||
operation.resolve(success);
|
||||
if (!success) operation.onError?.(failure);
|
||||
}
|
||||
running = false;
|
||||
}
|
||||
|
||||
return {
|
||||
getCurrent: () => current,
|
||||
initialize(state) {
|
||||
if (running || pending.length) throw new Error("Cannot initialize while writes are pending");
|
||||
confirmed = state;
|
||||
publish();
|
||||
},
|
||||
enqueue(apply, persist, onError) {
|
||||
const result = new Promise((resolve) => pending.push({ apply, persist, onError, resolve }));
|
||||
publish();
|
||||
void drain();
|
||||
return result;
|
||||
}
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue