fix: harden widget query persistence

This commit is contained in:
Thomas Camlong committed 2026-08-23 09:00:33 +02:00
1 parent a2a408410a
commit 357355283c
7 files changed
+401 -96

No files matched your search

@@ -1,7 +1,6 @@
import type { QueryClient, QueryKey } from "@tanstack/react-query";
import type { PersistedClient, Persister } from "@tanstack/react-query-persist-client";
import { removeOldestQuery } from "@tanstack/react-query-persist-client";
import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
import { parse, stringify } from "superjson";
import { isWidgetDataQueryKey, queryCacheDefaultGcTimeMs } from "@homarr/api/query-cache";
@@ -39,6 +38,7 @@ interface PersistableQuery {
type RestoredDashboardQueryPredicate = (query: PersistableQuery) => boolean;
export interface SessionQueryPersister extends Persister {
flush: () => void;
takeRestoredDashboardQueryPredicate: () => RestoredDashboardQueryPredicate | undefined;
}
@@ -54,25 +54,59 @@ export const shouldPersistDashboardQuery = (query: PersistableQuery) => {
}
};
type DehydratedQuery = PersistedClient["clientState"]["queries"][number];
const sanitizePersistedQuery = (query: DehydratedQuery): DehydratedQuery => ({
...query,
state: {
...query.state,
error: null,
errorUpdateCount: 0,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchStatus: "idle",
status: "success",
},
});
const sanitizePersistedClient = (client: PersistedClient): PersistedClient => ({
...client,
clientState: {
mutations: [],
queries: client.clientState.queries.map((query) => ({
...query,
state: {
...query.state,
error: null,
errorUpdateCount: 0,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
status: "success",
},
})),
// Keep this guard inside the persister as well as in the provider's
// dehydration options so a future caller cannot accidentally store an
// unrelated query payload.
queries: client.clientState.queries
.filter((query) => shouldPersistDashboardQuery(query as PersistableQuery))
.map(sanitizePersistedQuery),
},
});
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const isRestorableQuery = (value: unknown): value is DehydratedQuery => {
if (!isRecord(value) || typeof value.queryHash !== "string" || !Array.isArray(value.queryKey)) return false;
if (!isRecord(value.state) || typeof value.state.status !== "string") return false;
return shouldPersistDashboardQuery(value as unknown as PersistableQuery);
};
const sanitizeRestoredClient = (value: unknown): PersistedClient | undefined => {
if (!isRecord(value) || !Number.isFinite(value.timestamp) || typeof value.buster !== "string") return undefined;
if (!isRecord(value.clientState) || !Array.isArray(value.clientState.queries)) return undefined;
return {
timestamp: value.timestamp as number,
buster: value.buster,
clientState: {
mutations: [],
queries: value.clientState.queries.filter(isRestorableQuery).map(sanitizePersistedQuery),
},
};
};
const getSessionStorage = (): Storage | undefined => {
if (typeof window === "undefined") return undefined;
@@ -98,30 +132,70 @@ export const createSessionQueryPersister = (
const key = getQueryPersistenceStorageKey(scope);
const buster = getQueryPersistenceBuster(scope);
let restoredQueries = new Map<string, number>();
const persister = createSyncStoragePersister({
storage,
key,
retry: removeOldestQuery,
serialize: (client) => stringify(sanitizePersistedClient(client)),
deserialize: (value) => parse<PersistedClient>(value),
});
let pendingClient: PersistedClient | undefined;
let persistTimer: ReturnType<typeof setTimeout> | undefined;
const persistNow = (client: PersistedClient) => {
if (!storage) return;
let candidate: PersistedClient | undefined = sanitizePersistedClient(client);
let errorCount = 0;
while (candidate) {
try {
storage.setItem(key, stringify(candidate));
return;
} catch (error) {
errorCount += 1;
candidate = removeOldestQuery({
persistedClient: candidate,
error: error instanceof Error ? error : new Error("Failed to persist the widget query cache"),
errorCount,
});
}
}
};
const clearPersistTimer = () => {
if (persistTimer === undefined) return;
clearTimeout(persistTimer);
persistTimer = undefined;
};
const flush = () => {
clearPersistTimer();
const client = pendingClient;
pendingClient = undefined;
if (client) persistNow(client);
};
return {
...persister,
persistClient(client) {
if (!storage) return;
pendingClient = client;
if (persistTimer !== undefined) return;
persistTimer = setTimeout(flush, 0);
},
async restoreClient() {
restoredQueries = new Map();
try {
const client = await persister.restoreClient();
if (
client &&
client.timestamp > 0 &&
Date.now() - client.timestamp <= queryPersistenceMaxAgeMs &&
client.buster === buster
) {
restoredQueries = new Map(
client.clientState.queries.map((query) => [query.queryHash, query.state.dataUpdatedAt]),
);
const storedValue = storage?.getItem(key);
if (!storedValue) return undefined;
const client = sanitizeRestoredClient(parse<unknown>(storedValue));
const age = client ? Date.now() - client.timestamp : Number.POSITIVE_INFINITY;
if (!client || age < 0 || age > queryPersistenceMaxAgeMs || client.buster !== buster) {
removeStorageItem(storage, key);
return undefined;
}
if (client.clientState.queries.length === 0) {
removeStorageItem(storage, key);
return undefined;
}
restoredQueries = new Map(
client.clientState.queries.map((query) => [query.queryHash, query.state.dataUpdatedAt]),
);
return client;
} catch {
removeStorageItem(storage, key);
@@ -129,9 +203,12 @@ export const createSessionQueryPersister = (
}
},
removeClient() {
clearPersistTimer();
pendingClient = undefined;
restoredQueries = new Map();
removeStorageItem(storage, key);
},
flush,
takeRestoredDashboardQueryPredicate() {
if (restoredQueries.size === 0) return undefined;
const restoredSnapshot = restoredQueries;
@@ -149,7 +226,10 @@ export const scheduleRestoredDashboardQueryRefresh = (queryClient: QueryClient,
if (!predicate) return;
setTimeout(() => {
void queryClient.invalidateQueries({ type: "active", predicate });
// Mark restored data stale even if its widget observer has not mounted yet.
// TanStack still refetches only active queries; a widget that mounts after
// this callback observes stale cached data and refreshes immediately.
void queryClient.invalidateQueries({ type: "all", refetchType: "active", predicate });
}, 0);
};