Audit the project and secure toolbox data
This commit is contained in:
parent
96af62edf0
commit
e87edda5c7
40 changed files with 2324 additions and 125 deletions
|
|
@ -1,19 +1,14 @@
|
|||
// Rôle : synchronise l'état optimiste des toolboxes avec une file d'écritures IndexedDB.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
getAllModuleData as dbGetAllModuleData,
|
||||
getModuleDataEntries as dbGetModuleDataEntries,
|
||||
getLinks as dbGetLinks,
|
||||
getSetting as dbGetSetting,
|
||||
getStorageEstimate,
|
||||
getToolboxSnapshot as dbGetToolboxSnapshot,
|
||||
getToolboxes as dbGetToolboxes,
|
||||
removeModuleData as dbRemoveModuleData,
|
||||
removeModuleDataKeys as dbRemoveModuleDataKeys,
|
||||
setLinks as dbSetLinks,
|
||||
setModuleData as dbSetModuleData,
|
||||
mutateToolboxStorage as dbMutateToolboxStorage,
|
||||
setSetting as dbSetSetting,
|
||||
setToolboxes as dbSetToolboxes,
|
||||
setToolboxSnapshot as dbSetToolboxSnapshot
|
||||
} from "../../../utils/indexedDbStorage.js";
|
||||
import {
|
||||
compactToolboxesForStorage,
|
||||
|
|
@ -24,19 +19,62 @@ import {
|
|||
import { applyModuleDataValue, removeModuleDataKeys } from "./optimisticModuleData.js";
|
||||
import { createPersistenceQueue } from "./persistenceQueue.js";
|
||||
import { createQuotaRefresh } from "./quotaRefresh.js";
|
||||
import { DEFERRED_MODULE_DATA, getDeferredModuleKeys, mergeLoadedModuleData, splitModuleData } from "./deferredModuleData.js";
|
||||
import { DEFERRED_MODULE_DATA, getDeferredModuleKeys, mergeLoadedModuleData } from "./deferredModuleData.js";
|
||||
import { AUTO_BACKUP_DATA_CHANGED_EVENT } from "./autoBackup.js";
|
||||
import { createStorageMutation, getStorageMutationNotice } from "./storageMutation.js";
|
||||
|
||||
const STORAGE_CHANNEL = "sokkog:toolbox-storage";
|
||||
|
||||
function normalizeToolboxes(toolboxes) {
|
||||
return compactToolboxesForStorage(toolboxes).map(normalizeToolbox).filter(Boolean);
|
||||
}
|
||||
|
||||
function normalizeToolboxesForStorage(toolboxes) {
|
||||
return compactToolboxesForStorage(normalizeToolboxes(toolboxes));
|
||||
}
|
||||
|
||||
async function readStoredState({ preservedModuleData = {}, refreshedModuleKeys = [] } = {}) {
|
||||
const [toolboxes, links, toastPosition] = await Promise.all([
|
||||
dbGetToolboxes(), dbGetLinks(), dbGetSetting("toastPosition", "right")
|
||||
]);
|
||||
const normalizedToolboxes = (Array.isArray(toolboxes) ? toolboxes : []).map(normalizeToolbox).filter(Boolean);
|
||||
const registeredKeys = new Set(normalizedToolboxes.flatMap((toolbox) => (toolbox.modules || [])
|
||||
.map((module) => `${toolbox.id}:${module.id}`)));
|
||||
const deferredKeys = getDeferredModuleKeys(normalizedToolboxes);
|
||||
const refreshed = new Set(refreshedModuleKeys);
|
||||
const excludedKeys = [...registeredKeys].filter((key) => {
|
||||
if (refreshed.has(key)) return false;
|
||||
if (preservedModuleData[key] !== undefined && preservedModuleData[key] !== DEFERRED_MODULE_DATA) return true;
|
||||
return deferredKeys.includes(key);
|
||||
});
|
||||
const excluded = new Set(excludedKeys);
|
||||
const modules = await dbGetModuleDataEntries([...registeredKeys].filter((key) => !excluded.has(key)));
|
||||
const moduleData = Object.fromEntries([
|
||||
...deferredKeys.map((key) => [key, DEFERRED_MODULE_DATA]),
|
||||
...(modules || []).map((entry) => [entry.key, entry.data])
|
||||
]);
|
||||
for (const key of excludedKeys) {
|
||||
const preserved = preservedModuleData[key];
|
||||
if (preserved !== undefined && preserved !== DEFERRED_MODULE_DATA) moduleData[key] = preserved;
|
||||
}
|
||||
for (const key of refreshed) {
|
||||
if (deferredKeys.includes(key) && !(modules || []).some((entry) => entry.key === key)) delete moduleData[key];
|
||||
}
|
||||
return {
|
||||
toolboxes: normalizedToolboxes,
|
||||
links: links && typeof links === "object" ? links : {},
|
||||
moduleData,
|
||||
toastPosition: toastPosition === "left" ? "left" : "right"
|
||||
};
|
||||
}
|
||||
|
||||
export function useIndexedToolboxes(onError) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const [loadAttempt, setLoadAttempt] = useState(0);
|
||||
const writableRef = useRef(false);
|
||||
const pendingReadsRef = useRef(new Map());
|
||||
const storageChannelRef = useRef(null);
|
||||
const [state, setState] = useState({ toolboxes: [], links: {}, moduleData: {}, toastPosition: "right" });
|
||||
const [queue] = useState(() => createPersistenceQueue(state, setState));
|
||||
const [storageUsage, setStorageUsage] = useState({ used: 0, limit: 0, ratio: 0 });
|
||||
|
|
@ -68,22 +106,9 @@ export function useIndexedToolboxes(onError) {
|
|||
let cancelled = false;
|
||||
async function loadStore() {
|
||||
try {
|
||||
const [toolboxes, links, toastPosition] = await Promise.all([
|
||||
dbGetToolboxes(), dbGetLinks(), dbGetSetting("toastPosition", "right")
|
||||
]);
|
||||
const normalizedToolboxes = (Array.isArray(toolboxes) ? toolboxes : []).map(normalizeToolbox).filter(Boolean);
|
||||
const deferredKeys = getDeferredModuleKeys(normalizedToolboxes);
|
||||
const modules = await dbGetAllModuleData(deferredKeys);
|
||||
const storedState = await readStoredState();
|
||||
if (cancelled) return;
|
||||
queue.initialize({
|
||||
toolboxes: normalizedToolboxes,
|
||||
links: links && typeof links === "object" ? links : {},
|
||||
moduleData: Object.fromEntries([
|
||||
...deferredKeys.map((key) => [key, DEFERRED_MODULE_DATA]),
|
||||
...(modules || []).map((entry) => [entry.key, entry.data])
|
||||
]),
|
||||
toastPosition: toastPosition === "left" ? "left" : "right"
|
||||
});
|
||||
queue.initialize(storedState);
|
||||
writableRef.current = true;
|
||||
setReady(true);
|
||||
refreshQuota();
|
||||
|
|
@ -97,6 +122,26 @@ export function useIndexedToolboxes(onError) {
|
|||
return () => { cancelled = true; writableRef.current = false; };
|
||||
}, [queue, refreshQuota, loadAttempt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || typeof BroadcastChannel === "undefined") return undefined;
|
||||
const channel = new BroadcastChannel(STORAGE_CHANNEL);
|
||||
storageChannelRef.current = channel;
|
||||
channel.onmessage = (event) => {
|
||||
if (!writableRef.current || !event.data || event.data.type !== "changed") return;
|
||||
const current = queue.getCurrent();
|
||||
const refreshedModuleKeys = (event.data.moduleKeys || []).filter((key) => current.moduleData[key] !== DEFERRED_MODULE_DATA);
|
||||
void queue.enqueue(
|
||||
(confirmed) => confirmed,
|
||||
(next) => readStoredState({ preservedModuleData: next.moduleData, refreshedModuleKeys }),
|
||||
reportStorageError
|
||||
);
|
||||
};
|
||||
return () => {
|
||||
channel.close();
|
||||
if (storageChannelRef.current === channel) storageChannelRef.current = null;
|
||||
};
|
||||
}, [queue, ready, reportStorageError]);
|
||||
|
||||
function retryLoad() {
|
||||
if (ready || !loadError) return;
|
||||
setLoadError("");
|
||||
|
|
@ -116,12 +161,44 @@ export function useIndexedToolboxes(onError) {
|
|||
return result;
|
||||
}
|
||||
|
||||
async function persistMutation(next, confirmed) {
|
||||
const expectedStorage = {
|
||||
toolboxes: compactToolboxesForStorage(confirmed.toolboxes),
|
||||
links: confirmed.links,
|
||||
moduleData: confirmed.moduleData
|
||||
};
|
||||
const nextStorage = {
|
||||
toolboxes: compactToolboxesForStorage(next.toolboxes),
|
||||
links: next.links,
|
||||
moduleData: next.moduleData
|
||||
};
|
||||
const mutation = createStorageMutation(expectedStorage, nextStorage);
|
||||
if (!mutation.changed) return next;
|
||||
const notice = getStorageMutationNotice(mutation);
|
||||
try {
|
||||
await dbMutateToolboxStorage(mutation, { normalizeToolboxes: normalizeToolboxesForStorage });
|
||||
} catch (error) {
|
||||
if (error?.name === "StorageConflictError") {
|
||||
error.confirmedState = await readStoredState({
|
||||
preservedModuleData: confirmed.moduleData,
|
||||
refreshedModuleKeys: notice.moduleKeys
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const persisted = await readStoredState({
|
||||
preservedModuleData: next.moduleData
|
||||
});
|
||||
storageChannelRef.current?.postMessage({ type: "changed", ...notice });
|
||||
return persisted;
|
||||
}
|
||||
|
||||
function persistToolboxes(value) {
|
||||
if (!writableRef.current) return false;
|
||||
const apply = typeof value === "function" ? value : () => value;
|
||||
enqueue(
|
||||
(current) => ({ ...current, toolboxes: normalizeToolboxes(apply(current.toolboxes)) }),
|
||||
(next) => dbSetToolboxes(compactToolboxesForStorage(next.toolboxes))
|
||||
persistMutation
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -130,7 +207,7 @@ export function useIndexedToolboxes(onError) {
|
|||
if (!writableRef.current) return false;
|
||||
enqueue(
|
||||
(current) => ({ ...current, links: typeof value === "function" ? value(current.links) : value }),
|
||||
(next) => dbSetLinks(next.links)
|
||||
persistMutation
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -147,10 +224,7 @@ export function useIndexedToolboxes(onError) {
|
|||
const hasModule = (current) => current.toolboxes.some((toolbox) => toolbox.id === toolboxId && toolbox.modules.some((module) => module.id === moduleId));
|
||||
enqueue(
|
||||
(current) => hasModule(current) ? { ...current, moduleData: applyModuleDataValue(current.moduleData, key, compact) } : current,
|
||||
(next) => {
|
||||
if (!hasModule(next)) return;
|
||||
return compact == null ? dbRemoveModuleData(key) : dbSetModuleData(key, compact);
|
||||
}
|
||||
persistMutation
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -159,7 +233,7 @@ export function useIndexedToolboxes(onError) {
|
|||
const key = moduleStorageKey(toolboxId, moduleId);
|
||||
return enqueue(
|
||||
(current) => ({ ...current, moduleData: removeModuleDataKeys(current.moduleData, [key]) }),
|
||||
() => dbRemoveModuleData(key)
|
||||
persistMutation
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -169,7 +243,7 @@ export function useIndexedToolboxes(onError) {
|
|||
if (!keys.length) return Promise.resolve(true);
|
||||
return enqueue(
|
||||
(current) => ({ ...current, moduleData: removeModuleDataKeys(current.moduleData, keys) }),
|
||||
() => dbRemoveModuleDataKeys(keys)
|
||||
persistMutation
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -177,10 +251,7 @@ export function useIndexedToolboxes(onError) {
|
|||
return enqueue((current) => {
|
||||
const next = updater(current);
|
||||
return { ...current, ...next, toolboxes: normalizeToolboxes(next.toolboxes) };
|
||||
}, (next) => {
|
||||
const { stored, deferred } = splitModuleData(next.moduleData);
|
||||
return dbSetToolboxSnapshot(compactToolboxesForStorage(next.toolboxes), next.links, stored, deferred);
|
||||
});
|
||||
}, persistMutation);
|
||||
}
|
||||
|
||||
const ensureModuleData = useCallback((toolboxId, moduleId) => {
|
||||
|
|
@ -202,11 +273,15 @@ export function useIndexedToolboxes(onError) {
|
|||
async function getExportSnapshot(toolboxId, options = {}) {
|
||||
if (!writableRef.current) return null;
|
||||
let snapshot;
|
||||
const success = await queue.enqueue((current) => current, async (current) => {
|
||||
const { deferred } = splitModuleData(current.moduleData);
|
||||
const keys = deferred.filter((key) => !toolboxId || key.startsWith(`${toolboxId}:`));
|
||||
const entries = await dbGetModuleDataEntries(keys);
|
||||
snapshot = { ...current, moduleData: mergeLoadedModuleData(current.moduleData, keys, entries) };
|
||||
const success = await queue.enqueue((current) => current, async () => {
|
||||
const stored = await dbGetToolboxSnapshot(toolboxId);
|
||||
const toolboxes = (stored.toolboxes || []).map(normalizeToolbox).filter(Boolean);
|
||||
snapshot = {
|
||||
toolboxes,
|
||||
links: stored.links,
|
||||
moduleData: stored.moduleData,
|
||||
toastPosition: queue.getCurrent().toastPosition
|
||||
};
|
||||
}, options.onError || reportStorageError);
|
||||
return success ? snapshot : null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue