refactor: simplify widget reload persistence
This commit is contained in:
8 files changed
+79
-241
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import type { QueryClient, QueryKey } from "@tanstack/react-query";
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
import type { PersistedClient, Persister } from "@tanstack/react-query-persist-client";
|
||||
import { removeOldestQuery } from "@tanstack/react-query-persist-client";
|
||||
import { parse, stringify } from "superjson";
|
||||
@@ -7,40 +7,22 @@ import { isWidgetDataQueryKey, queryCacheDefaultGcTimeMs } from "@homarr/api/que
|
||||
|
||||
export const queryPersistenceMaxAgeMs = queryCacheDefaultGcTimeMs;
|
||||
export const queryPersistenceMaxDataBytes = 256 * 1024;
|
||||
const queryPersistenceBuster = "v1-session-superjson";
|
||||
export const queryPersistenceBuster = "v2-session-superjson";
|
||||
|
||||
const queryPersistenceStoragePrefix = "homarr:widget-query-cache:v1";
|
||||
|
||||
const hashScope = (scope: string) => {
|
||||
let hash = 2_166_136_261;
|
||||
for (let index = 0; index < scope.length; index += 1) {
|
||||
hash ^= scope.charCodeAt(index);
|
||||
hash = Math.imul(hash, 16_777_619);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
};
|
||||
const queryPersistenceStoragePrefix = "homarr:widget-query-cache";
|
||||
|
||||
export const getQueryPersistenceStorageKey = (scope: string | null) =>
|
||||
`${queryPersistenceStoragePrefix}:${hashScope(scope ?? "anonymous")}`;
|
||||
|
||||
export const getQueryPersistenceBuster = (scope: string | null) => `${queryPersistenceBuster}:${scope ?? "anonymous"}`;
|
||||
`${queryPersistenceStoragePrefix}:${encodeURIComponent(scope ?? "anonymous")}`;
|
||||
|
||||
interface PersistableQuery {
|
||||
queryHash?: string;
|
||||
queryKey: QueryKey;
|
||||
state: {
|
||||
data: unknown;
|
||||
dataUpdatedAt: number;
|
||||
status: string;
|
||||
};
|
||||
}
|
||||
|
||||
type RestoredDashboardQueryPredicate = (query: PersistableQuery) => boolean;
|
||||
|
||||
export interface SessionQueryPersister extends Persister {
|
||||
flush: () => void;
|
||||
takeRestoredDashboardQueryPredicate: () => RestoredDashboardQueryPredicate | undefined;
|
||||
}
|
||||
export type SessionQueryPersister = Persister & { flush: () => void };
|
||||
|
||||
export const shouldPersistDashboardQuery = (query: PersistableQuery) => {
|
||||
if (query.state.data === undefined || query.state.dataUpdatedAt <= 0 || !isWidgetDataQueryKey(query.queryKey)) {
|
||||
@@ -66,6 +48,7 @@ const sanitizePersistedQuery = (query: DehydratedQuery): DehydratedQuery => ({
|
||||
fetchFailureCount: 0,
|
||||
fetchFailureReason: null,
|
||||
fetchStatus: "idle",
|
||||
isInvalidated: true,
|
||||
status: "success",
|
||||
},
|
||||
});
|
||||
@@ -74,9 +57,6 @@ const sanitizePersistedClient = (client: PersistedClient): PersistedClient => ({
|
||||
...client,
|
||||
clientState: {
|
||||
mutations: [],
|
||||
// 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),
|
||||
@@ -120,9 +100,7 @@ const getSessionStorage = (): Storage | undefined => {
|
||||
const removeStorageItem = (storage: Storage | undefined, key: string) => {
|
||||
try {
|
||||
storage?.removeItem(key);
|
||||
} catch {
|
||||
// Persistence is optional. Treat blocked or unavailable storage as an empty cache.
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export const createSessionQueryPersister = (
|
||||
@@ -130,8 +108,6 @@ export const createSessionQueryPersister = (
|
||||
storage: Storage | undefined = getSessionStorage(),
|
||||
): SessionQueryPersister => {
|
||||
const key = getQueryPersistenceStorageKey(scope);
|
||||
const buster = getQueryPersistenceBuster(scope);
|
||||
let restoredQueries = new Map<string, number>();
|
||||
let pendingClient: PersistedClient | undefined;
|
||||
let persistTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
@@ -175,15 +151,13 @@ export const createSessionQueryPersister = (
|
||||
if (persistTimer !== undefined) return;
|
||||
persistTimer = setTimeout(flush, 0);
|
||||
},
|
||||
async restoreClient() {
|
||||
restoredQueries = new Map();
|
||||
restoreClient() {
|
||||
try {
|
||||
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) {
|
||||
if (!client || client.timestamp > Date.now()) {
|
||||
removeStorageItem(storage, key);
|
||||
return undefined;
|
||||
}
|
||||
@@ -193,9 +167,6 @@ export const createSessionQueryPersister = (
|
||||
return undefined;
|
||||
}
|
||||
|
||||
restoredQueries = new Map(
|
||||
client.clientState.queries.map((query) => [query.queryHash, query.state.dataUpdatedAt]),
|
||||
);
|
||||
return client;
|
||||
} catch {
|
||||
removeStorageItem(storage, key);
|
||||
@@ -205,34 +176,8 @@ export const createSessionQueryPersister = (
|
||||
removeClient() {
|
||||
clearPersistTimer();
|
||||
pendingClient = undefined;
|
||||
restoredQueries = new Map();
|
||||
removeStorageItem(storage, key);
|
||||
},
|
||||
flush,
|
||||
takeRestoredDashboardQueryPredicate() {
|
||||
if (restoredQueries.size === 0) return undefined;
|
||||
const restoredSnapshot = restoredQueries;
|
||||
restoredQueries = new Map();
|
||||
return (query) =>
|
||||
query.queryHash !== undefined &&
|
||||
restoredSnapshot.get(query.queryHash) === query.state.dataUpdatedAt &&
|
||||
shouldPersistDashboardQuery(query);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const scheduleRestoredDashboardQueryRefresh = (queryClient: QueryClient, persister: SessionQueryPersister) => {
|
||||
const predicate = persister.takeRestoredDashboardQueryPredicate();
|
||||
if (!predicate) return;
|
||||
|
||||
setTimeout(() => {
|
||||
// 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);
|
||||
};
|
||||
|
||||
export const removeSessionQueryCache = (scope: string | null, storage: Storage | undefined = getSessionStorage()) => {
|
||||
removeStorageItem(storage, getQueryPersistenceStorageKey(scope));
|
||||
};
|
||||
Reference in new issue
Block a user