feat(core): optimize query resource lifecycle

This commit is contained in:
t8y2 committed 2026-07-16 00:19:24 +08:00
1 parent b4bd6c42a7
commit 295b67dd36
29 files changed
+1857 -335

No files matched your search

@@ -0,0 +1,51 @@
import type { QueryResult } from "@/types/database";
const ARRAY_OVERHEAD_BYTES = 24;
const OBJECT_OVERHEAD_BYTES = 32;
const VALUE_SLOT_BYTES = 8;
function estimateValueBytes(value: unknown, seen: WeakSet<object>): number {
if (value == null) return VALUE_SLOT_BYTES;
if (typeof value === "string") return VALUE_SLOT_BYTES + value.length * 2;
if (typeof value === "number" || typeof value === "bigint") return 16;
if (typeof value === "boolean") return 8;
if (value instanceof Uint8Array) return OBJECT_OVERHEAD_BYTES + value.byteLength;
if (value instanceof ArrayBuffer) return OBJECT_OVERHEAD_BYTES + value.byteLength;
if (value instanceof Date) return OBJECT_OVERHEAD_BYTES;
if (typeof value !== "object") return VALUE_SLOT_BYTES;
if (seen.has(value)) return VALUE_SLOT_BYTES;
seen.add(value);
if (Array.isArray(value)) {
return ARRAY_OVERHEAD_BYTES + value.reduce((total, item) => total + estimateValueBytes(item, seen), 0);
}
return OBJECT_OVERHEAD_BYTES + Object.entries(value).reduce((total, [key, entry]) => total + key.length * 2 + estimateValueBytes(entry, seen), 0);
}
export function estimateQueryResultBytes(result: QueryResult | undefined): number {
if (!result) return 0;
return estimateValueBytes(result, new WeakSet<object>());
}
export function estimateQueryResultsBytes(result: QueryResult | undefined, results: QueryResult[] | undefined): number {
if (results?.length) return results.reduce((total, item) => total + estimateQueryResultBytes(item), ARRAY_OVERHEAD_BYTES);
return estimateQueryResultBytes(result);
}
export interface InactiveResultResidency {
id: string;
estimatedBytes: number;
accessedAt: number;
}
export function selectInactiveResultEvictions(entries: InactiveResultResidency[], maxBytes: number, maxCount: number): string[] {
const ordered = [...entries].sort((left, right) => left.accessedAt - right.accessedAt);
let bytes = ordered.reduce((total, entry) => total + entry.estimatedBytes, 0);
const evicted: string[] = [];
while (ordered.length - evicted.length > maxCount || bytes > maxBytes) {
const entry = ordered[evicted.length];
if (!entry) break;
evicted.push(entry.id);
bytes -= entry.estimatedBytes;
}
return evicted;
}
+366 -54
View File
@@ -5,8 +5,12 @@ import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { apiUrl } from "@/lib/common/webPath";
const DB_NAME = "dbx-tab-runtime-cache";
const DB_VERSION = 1;
const DB_VERSION = 2;
const RESULT_STORE = "resultSnapshots";
const RESULT_METADATA_STORE = "resultSnapshotMetadata";
const DEFAULT_PERSISTENT_CACHE_BYTES = 512 * 1024 * 1024;
const DEFAULT_ORPHAN_GRACE_MS = 24 * 60 * 60 * 1000;
const DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
const PAYLOAD_MAGIC = "DBX_TAB_RESULT_CACHE";
const PAYLOAD_VERSION = 1;
const PAYLOAD_CODEC = "msgpack-columnar";
@@ -80,6 +84,58 @@ interface TabResultCacheEnvelope {
payload: TabResultSnapshotPayload;
}
export type ResultCacheBackendName = "indexed-db" | "runtime";
export interface ResultCacheMetadata {
key: string;
rowCount: number;
columnCount: number;
byteSize: number;
createdAt: number;
lastAccessedAt: number;
ownerId?: string;
}
export interface ResultCachePruneOptions {
liveKeys: string[];
maxBytes: number;
orphanGraceMs: number;
maxAgeMs?: number;
}
export interface ResultCachePruneResult {
deletedEntries: number;
deletedBytes: number;
orphanDeletions: number;
remainingEntries: number;
remainingBytes: number;
}
export interface ResultCacheBackend {
name: ResultCacheBackendName;
available: () => boolean;
read: (key: string) => Promise<Uint8Array | undefined>;
write: (key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }, ownerId?: string) => Promise<boolean>;
delete: (key: string) => Promise<void>;
listMetadata: () => Promise<ResultCacheMetadata[]>;
prune: (options: ResultCachePruneOptions) => Promise<ResultCachePruneResult>;
deleteOwner: (ownerId: string) => Promise<void>;
}
const resultCacheDiagnostics = {
cacheBytes: 0,
evictions: 0,
serializationCount: 0,
serializationDurationMs: 0,
serializedBytes: 0,
orphanDeletions: 0,
corruptSnapshots: 0,
};
export function getResultCacheDiagnostics() {
return { ...resultCacheDiagnostics };
}
function indexedDb(): IDBFactory | undefined {
return typeof globalThis.indexedDB === "undefined" ? undefined : globalThis.indexedDB;
}
@@ -118,6 +174,7 @@ function openCacheDb(): Promise<IDBDatabase | null> {
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(RESULT_STORE)) db.createObjectStore(RESULT_STORE);
if (!db.objectStoreNames.contains(RESULT_METADATA_STORE)) db.createObjectStore(RESULT_METADATA_STORE);
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => {
@@ -129,6 +186,129 @@ function openCacheDb(): Promise<IDBDatabase | null> {
return dbPromise;
}
async function writeIndexedDbCache(key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }, ownerId?: string): Promise<boolean> {
const db = await openCacheDb();
if (!db) return false;
const previous = (await requestToPromise(db.transaction(RESULT_METADATA_STORE, "readonly").objectStore(RESULT_METADATA_STORE).get(key))) as ResultCacheMetadata | undefined;
const transaction = db.transaction([RESULT_STORE, RESULT_METADATA_STORE], "readwrite");
const metadataStore = transaction.objectStore(RESULT_METADATA_STORE);
const now = Date.now();
await Promise.all([
requestToPromise(transaction.objectStore(RESULT_STORE).put(bytes, key)),
requestToPromise(
metadataStore.put(
{
key,
rowCount: stats.rowCount,
columnCount: stats.columnCount,
byteSize: bytes.byteLength,
createdAt: previous?.createdAt ?? now,
lastAccessedAt: now,
ownerId,
} satisfies ResultCacheMetadata,
key,
),
),
]);
return true;
}
async function readIndexedDbCache(key: string): Promise<Uint8Array | undefined> {
const db = await openCacheDb();
if (!db) return undefined;
const value = await requestToPromise(db.transaction(RESULT_STORE, "readonly").objectStore(RESULT_STORE).get(key));
if (isBinaryPayload(value)) {
const previous = (await requestToPromise(db.transaction(RESULT_METADATA_STORE, "readonly").objectStore(RESULT_METADATA_STORE).get(key))) as ResultCacheMetadata | undefined;
const store = db.transaction(RESULT_METADATA_STORE, "readwrite").objectStore(RESULT_METADATA_STORE);
const now = Date.now();
await requestToPromise(store.put(previous ? { ...previous, lastAccessedAt: now } : { key, rowCount: 0, columnCount: 0, byteSize: value.byteLength, createdAt: now, lastAccessedAt: now }, key));
}
return isBinaryPayload(value) ? new Uint8Array(value) : undefined;
}
async function deleteIndexedDbCache(key: string): Promise<void> {
const db = await openCacheDb();
if (!db) return;
const transaction = db.transaction([RESULT_STORE, RESULT_METADATA_STORE], "readwrite");
await Promise.all([requestToPromise(transaction.objectStore(RESULT_STORE).delete(key)), requestToPromise(transaction.objectStore(RESULT_METADATA_STORE).delete(key))]);
}
async function listIndexedDbCacheMetadata(): Promise<ResultCacheMetadata[]> {
const db = await openCacheDb();
if (!db) return [];
const transaction = db.transaction([RESULT_STORE, RESULT_METADATA_STORE], "readonly");
const metadataRequest = transaction.objectStore(RESULT_METADATA_STORE).getAll();
const keysRequest = transaction.objectStore(RESULT_STORE).getAllKeys();
const [metadata, keys] = await Promise.all([requestToPromise(metadataRequest) as Promise<ResultCacheMetadata[]>, requestToPromise(keysRequest)]);
const byKey = new Map(metadata.map((entry) => [entry.key, entry]));
const missingKeys = keys.map(String).filter((key) => !byKey.has(key));
const migratedMetadata: ResultCacheMetadata[] = [];
for (const key of missingKeys) {
const value = await requestToPromise(db.transaction(RESULT_STORE, "readonly").objectStore(RESULT_STORE).get(key));
const now = Date.now();
const entry: ResultCacheMetadata = {
key,
rowCount: 0,
columnCount: 0,
byteSize: isBinaryPayload(value) ? value.byteLength : 0,
createdAt: now,
lastAccessedAt: now,
};
byKey.set(key, entry);
migratedMetadata.push(entry);
}
if (migratedMetadata.length) {
const migration = db.transaction(RESULT_METADATA_STORE, "readwrite").objectStore(RESULT_METADATA_STORE);
await Promise.all(migratedMetadata.map((entry) => requestToPromise(migration.put(entry, entry.key))));
}
return [...byKey.values()];
}
export function selectResultCachePruneKeys(metadata: ResultCacheMetadata[], options: ResultCachePruneOptions, now = Date.now()): { keys: string[]; result: ResultCachePruneResult } {
const live = new Set(options.liveKeys);
const ordered = [...metadata].sort((left, right) => left.lastAccessedAt - right.lastAccessedAt || left.key.localeCompare(right.key));
const deleted = new Set<string>();
let remainingBytes = ordered.reduce((total, entry) => total + entry.byteSize, 0);
let orphanDeletions = 0;
for (const entry of ordered) {
if (live.has(entry.key)) continue;
const orphanExpired = now - entry.createdAt >= Math.max(0, options.orphanGraceMs);
const ageExpired = options.maxAgeMs !== undefined && now - entry.lastAccessedAt >= Math.max(0, options.maxAgeMs);
if (!orphanExpired && !ageExpired) continue;
deleted.add(entry.key);
remainingBytes -= entry.byteSize;
if (orphanExpired) orphanDeletions += 1;
}
for (const entry of ordered) {
if (remainingBytes <= Math.max(0, options.maxBytes)) break;
if (live.has(entry.key) || deleted.has(entry.key)) continue;
deleted.add(entry.key);
remainingBytes -= entry.byteSize;
}
const deletedBytes = ordered.filter((entry) => deleted.has(entry.key)).reduce((total, entry) => total + entry.byteSize, 0);
return {
keys: [...deleted],
result: {
deletedEntries: deleted.size,
deletedBytes,
orphanDeletions,
remainingEntries: ordered.length - deleted.size,
remainingBytes,
},
};
}
async function pruneIndexedDbCache(options: ResultCachePruneOptions): Promise<ResultCachePruneResult> {
const selection = selectResultCachePruneKeys(await listIndexedDbCacheMetadata(), options);
await Promise.all(selection.keys.map(deleteIndexedDbCache));
return selection.result;
}
async function deleteIndexedDbCacheOwner(ownerId: string): Promise<void> {
const metadata = await listIndexedDbCacheMetadata();
await Promise.all(metadata.filter((entry) => entry.ownerId === ownerId).map((entry) => deleteIndexedDbCache(entry.key)));
}
function clonePlain<T>(value: T): T {
const raw = toRaw(value);
if (typeof structuredClone === "function") return structuredClone(raw);
@@ -272,7 +452,7 @@ function canUseRemoteRuntimeCache(): boolean {
return typeof btoa !== "undefined" && typeof atob !== "undefined" && (isTauriRuntime() || typeof fetch !== "undefined");
}
async function writeRemoteRuntimeCache(key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }): Promise<boolean> {
async function writeRemoteRuntimeCache(key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }, ownerId?: string): Promise<boolean> {
if (!canUseRemoteRuntimeCache()) return false;
try {
if (isTauriRuntime()) {
@@ -282,6 +462,7 @@ async function writeRemoteRuntimeCache(key: string, bytes: Uint8Array, stats: {
payloadBase64: bytesToBase64(bytes),
rowCount: stats.rowCount,
columnCount: stats.columnCount,
ownerId,
});
return true;
}
@@ -293,6 +474,7 @@ async function writeRemoteRuntimeCache(key: string, bytes: Uint8Array, stats: {
payloadBase64: bytesToBase64(bytes),
rowCount: stats.rowCount,
columnCount: stats.columnCount,
ownerId,
}),
});
return response.ok;
@@ -302,6 +484,53 @@ async function writeRemoteRuntimeCache(key: string, bytes: Uint8Array, stats: {
}
}
function normalizeRuntimeMetadata(entry: Record<string, unknown>): ResultCacheMetadata {
return {
key: String(entry.key ?? ""),
rowCount: Number(entry.rowCount ?? 0),
columnCount: Number(entry.columnCount ?? 0),
byteSize: Number(entry.byteSize ?? 0),
createdAt: Number(entry.createdAt ?? 0),
lastAccessedAt: Number(entry.lastAccessedAt ?? 0),
ownerId: typeof entry.ownerId === "string" ? entry.ownerId : undefined,
};
}
async function listRemoteRuntimeCacheMetadata(): Promise<ResultCacheMetadata[]> {
if (!canUseRemoteRuntimeCache()) return [];
if (isTauriRuntime()) {
const { invoke } = await import("@tauri-apps/api/core");
const entries = await invoke<Record<string, unknown>[]>("list_tab_runtime_cache_metadata");
return entries.map(normalizeRuntimeMetadata);
}
const response = await fetch(apiUrl("/api/tab-runtime-cache/metadata"));
if (!response.ok) return [];
return ((await response.json()) as Record<string, unknown>[]).map(normalizeRuntimeMetadata);
}
async function pruneRemoteRuntimeCache(options: ResultCachePruneOptions): Promise<ResultCachePruneResult> {
if (isTauriRuntime()) {
const { invoke } = await import("@tauri-apps/api/core");
return invoke<ResultCachePruneResult>("prune_tab_runtime_cache", { request: options });
}
const response = await fetch(apiUrl("/api/tab-runtime-cache/prune"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(options),
});
if (!response.ok) throw new Error(`Runtime cache prune failed: ${response.status}`);
return response.json() as Promise<ResultCachePruneResult>;
}
async function deleteRemoteRuntimeCacheOwner(ownerId: string): Promise<void> {
if (isTauriRuntime()) {
const { invoke } = await import("@tauri-apps/api/core");
await invoke("delete_tab_runtime_cache_owner", { ownerId });
return;
}
await fetch(apiUrl(`/api/tab-runtime-cache/owner?owner_id=${encodeURIComponent(ownerId)}`), { method: "DELETE" });
}
async function readRemoteRuntimeCache(key: string): Promise<Uint8Array | undefined> {
if (!canUseRemoteRuntimeCache()) return undefined;
try {
@@ -334,12 +563,82 @@ async function deleteRemoteRuntimeCache(key: string): Promise<void> {
}
}
function scheduleRemoteRuntimeCacheWrite(key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }, version: number) {
window.setTimeout(async () => {
if (!isCurrentCacheKeyVersion(key, version)) return;
await writeRemoteRuntimeCache(key, bytes, stats);
clearCacheKeyVersionIfCurrent(key, version);
}, 0);
const indexedDbBackend: ResultCacheBackend = {
name: "indexed-db",
available: () => indexedDb() !== undefined,
read: readIndexedDbCache,
write: writeIndexedDbCache,
delete: deleteIndexedDbCache,
listMetadata: listIndexedDbCacheMetadata,
prune: pruneIndexedDbCache,
deleteOwner: deleteIndexedDbCacheOwner,
};
const runtimeBackend: ResultCacheBackend = {
name: "runtime",
available: canUseRemoteRuntimeCache,
read: readRemoteRuntimeCache,
write: writeRemoteRuntimeCache,
delete: deleteRemoteRuntimeCache,
listMetadata: listRemoteRuntimeCacheMetadata,
prune: pruneRemoteRuntimeCache,
deleteOwner: deleteRemoteRuntimeCacheOwner,
};
export interface ResultCacheRuntimeConfig {
primary: ResultCacheBackendName;
fallbackEnabled: boolean;
}
export function resultCacheRuntimeConfig(tauriRuntime = isTauriRuntime(), environment = import.meta.env): ResultCacheRuntimeConfig {
const configured = environment.VITE_DBX_RESULT_CACHE_BACKEND;
const primary = tauriRuntime || configured === "http" || configured === "runtime" ? "runtime" : "indexed-db";
return { primary, fallbackEnabled: environment.VITE_DBX_RESULT_CACHE_FALLBACK !== "false" };
}
export function resultCacheBackendOrder(tauriRuntime = isTauriRuntime(), config = resultCacheRuntimeConfig(tauriRuntime)): ResultCacheBackendName[] {
return config.primary === "runtime" ? ["runtime", "indexed-db"] : ["indexed-db", "runtime"];
}
function availableResultCacheBackends(includeLegacyFallback = true): ResultCacheBackend[] {
const byName: Record<ResultCacheBackendName, ResultCacheBackend> = {
"indexed-db": indexedDbBackend,
runtime: runtimeBackend,
};
const config = resultCacheRuntimeConfig();
const order = resultCacheBackendOrder(isTauriRuntime(), config);
const selected = includeLegacyFallback || config.fallbackEnabled ? order : order.slice(0, 1);
return selected.map((name) => byName[name]).filter((backend) => backend.available());
}
export async function writeResultCacheBackends(backends: ResultCacheBackend[], key: string, bytes: Uint8Array, stats: { rowCount: number; columnCount: number }, isCurrent: () => boolean = () => true, ownerId?: string): Promise<boolean> {
for (const backend of backends) {
if (!isCurrent()) return false;
try {
if (await backend.write(key, bytes, stats, ownerId)) return true;
} catch (error) {
console.warn("[DBX][tab-result-cache:write:error]", { key, backend: backend.name, error });
}
}
return false;
}
export async function readResultCacheBackends(backends: ResultCacheBackend[], key: string): Promise<{ bytes: Uint8Array; backend: ResultCacheBackend } | undefined> {
for (const backend of backends) {
try {
const bytes = await backend.read(key);
if (bytes) return { bytes, backend };
} catch (error) {
console.warn("[DBX][tab-result-cache:read:error]", { key, backend: backend.name, error });
}
}
return undefined;
}
export async function promoteFallbackResultCacheRead(backends: ResultCacheBackend[], key: string, cached: { bytes: Uint8Array; backend: ResultCacheBackend }, stats: { rowCount: number; columnCount: number }, ownerId?: string): Promise<boolean> {
const primary = backends[0];
if (!primary || cached.backend === primary) return false;
return primary.write(key, cached.bytes, stats, ownerId);
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -375,7 +674,13 @@ export function encodeTabResultSnapshot(snapshot: TabResultSnapshot): Uint8Array
}
export function decodeTabResultSnapshot(bytes: Uint8Array | ArrayBuffer): TabResultSnapshot | undefined {
const decoded = decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
let decoded: unknown;
try {
decoded = decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
} catch {
resultCacheDiagnostics.corruptSnapshots += 1;
return undefined;
}
if (!isRecord(decoded)) return undefined;
if (decoded.magic !== PAYLOAD_MAGIC || decoded.version !== PAYLOAD_VERSION || decoded.codec !== PAYLOAD_CODEC) {
return undefined;
@@ -413,57 +718,48 @@ export function buildTabResultSnapshot(tab: QueryTab): TabResultSnapshot | undef
};
}
export async function writeTabResultSnapshot(key: string, snapshot: TabResultSnapshot | undefined): Promise<boolean> {
function afterActiveResultPaint(): Promise<void> {
if (typeof window === "undefined" || typeof requestAnimationFrame === "undefined") return Promise.resolve();
return new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
resolve();
};
requestAnimationFrame(finish);
// Background WebViews and test DOMs may throttle animation frames indefinitely.
setTimeout(finish, 100);
});
}
export async function writeTabResultSnapshot(key: string, snapshot: TabResultSnapshot | undefined, ownerId?: string): Promise<boolean> {
if (!snapshot) return false;
const version = bumpCacheKeyVersion(key);
const encoded = encodeTabResultSnapshot(snapshot);
const stats = resultStats(snapshot);
let wroteLocal = false;
try {
const db = await openCacheDb();
if (db) {
const tx = db.transaction(RESULT_STORE, "readwrite");
await requestToPromise(tx.objectStore(RESULT_STORE).put(encoded, key));
wroteLocal = true;
}
} catch (error) {
console.warn("[DBX][tab-result-cache:write:error]", { key, error });
}
if (wroteLocal) {
if (typeof window === "undefined") {
void writeRemoteRuntimeCache(key, encoded, stats).finally(() => clearCacheKeyVersionIfCurrent(key, version));
} else {
scheduleRemoteRuntimeCacheWrite(key, encoded, stats, version);
}
return true;
}
await afterActiveResultPaint();
if (!isCurrentCacheKeyVersion(key, version)) return false;
const startedAt = typeof performance === "undefined" ? Date.now() : performance.now();
const encoded = encodeTabResultSnapshot(snapshot);
const finishedAt = typeof performance === "undefined" ? Date.now() : performance.now();
resultCacheDiagnostics.serializationCount += 1;
resultCacheDiagnostics.serializationDurationMs += finishedAt - startedAt;
resultCacheDiagnostics.serializedBytes += encoded.byteLength;
const stats = resultStats(snapshot);
try {
return await writeRemoteRuntimeCache(key, encoded, stats);
return await writeResultCacheBackends(availableResultCacheBackends(false), key, encoded, stats, () => isCurrentCacheKeyVersion(key, version), ownerId);
} finally {
clearCacheKeyVersionIfCurrent(key, version);
}
}
export async function readTabResultSnapshot(key: string): Promise<TabResultSnapshot | undefined> {
try {
const db = await openCacheDb();
if (db) {
const value = await requestToPromise(db.transaction(RESULT_STORE, "readonly").objectStore(RESULT_STORE).get(key));
if (isBinaryPayload(value)) return decodeTabResultSnapshot(value);
if (value) return value as TabResultSnapshot;
}
const remoteBytes = await readRemoteRuntimeCache(key);
const remoteSnapshot = remoteBytes ? decodeTabResultSnapshot(remoteBytes) : undefined;
if (remoteBytes && remoteSnapshot && db) {
void requestToPromise(db.transaction(RESULT_STORE, "readwrite").objectStore(RESULT_STORE).put(remoteBytes, key));
}
return remoteSnapshot;
} catch (error) {
console.warn("[DBX][tab-result-cache:read:error]", { key, error });
const remoteBytes = await readRemoteRuntimeCache(key);
return remoteBytes ? decodeTabResultSnapshot(remoteBytes) : undefined;
}
const backends = availableResultCacheBackends(true);
const cached = await readResultCacheBackends(backends, key);
if (!cached) return undefined;
const snapshot = decodeTabResultSnapshot(cached.bytes);
if (!snapshot) return undefined;
void promoteFallbackResultCacheRead(backends, key, cached, resultStats(snapshot));
return snapshot;
}
export async function deleteTabResultSnapshot(key: string): Promise<void> {
@@ -474,13 +770,29 @@ export async function deleteTabResultSnapshot(key: string): Promise<void> {
else setTimeout(cleanup, 5000);
};
try {
const db = await openCacheDb();
if (db) await requestToPromise(db.transaction(RESULT_STORE, "readwrite").objectStore(RESULT_STORE).delete(key));
await deleteRemoteRuntimeCache(key);
await Promise.all(availableResultCacheBackends().map((backend) => backend.delete(key)));
clearVersionLater();
} catch (error) {
console.warn("[DBX][tab-result-cache:delete:error]", { key, error });
await deleteRemoteRuntimeCache(key);
clearVersionLater();
}
}
export async function pruneTabResultSnapshots(liveKeys: Iterable<string>, options: Partial<Omit<ResultCachePruneOptions, "liveKeys">> = {}): Promise<ResultCachePruneResult | undefined> {
const primary = availableResultCacheBackends(false)[0];
if (!primary) return undefined;
const result = await primary.prune({
liveKeys: [...new Set(liveKeys)],
maxBytes: options.maxBytes ?? DEFAULT_PERSISTENT_CACHE_BYTES,
orphanGraceMs: options.orphanGraceMs ?? DEFAULT_ORPHAN_GRACE_MS,
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
});
resultCacheDiagnostics.cacheBytes = result.remainingBytes;
resultCacheDiagnostics.evictions += result.deletedEntries;
resultCacheDiagnostics.orphanDeletions += result.orphanDeletions;
return result;
}
export async function deleteTabResultSnapshotsForOwner(ownerId: string): Promise<void> {
await Promise.all(availableResultCacheBackends(true).map((backend) => backend.deleteOwner(ownerId)));
}