tsdf 17.0.0-alpha.7 → 17.0.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +140 -0
- package/README.md +3 -0
- package/dist/async-storage.d.ts +2 -0
- package/dist/async-storage.js +2 -0
- package/dist/asyncStorageAdapter-BMYAF6rt.d.ts +6 -0
- package/dist/asyncStorageAdapter-BZSj1ZO5.js +1868 -0
- package/dist/asyncStorageAdapters-DbyKyARM.js +3 -0
- package/dist/indexed-db-storage.d.ts +14 -0
- package/dist/indexed-db-storage.js +2 -0
- package/dist/indexedDbPersistentStorage-DlUjN1qY.js +902 -0
- package/dist/main.d.ts +413 -1835
- package/dist/main.js +1832 -4606
- package/dist/opfs-storage.d.ts +2 -0
- package/dist/opfs-storage.js +2 -0
- package/dist/opfsPersistentStorage-BO_uDxe4.js +838 -0
- package/dist/opfsPersistentStorage-CBnUebnf.d.ts +6 -0
- package/dist/types-2zQlbxtw.d.ts +1475 -0
- package/docs/README.md +14 -14
- package/docs/batch-fetching.md +1 -1
- package/docs/browser-tabs-sync.md +2 -0
- package/docs/collection-store.md +24 -22
- package/docs/document-store.md +4 -2
- package/docs/fetch-scheduling.md +7 -7
- package/docs/list-query-store.md +35 -33
- package/docs/mutations.md +2 -0
- package/docs/persistent-storage.md +14 -6
- package/docs/real-time-updates.md +5 -5
- package/docs/store-manager.md +31 -12
- package/package.json +24 -7
|
@@ -0,0 +1,1868 @@
|
|
|
1
|
+
import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
|
|
2
|
+
import { klona } from "klona/json";
|
|
3
|
+
import { isObject } from "@ls-stack/utils/typeGuards";
|
|
4
|
+
import { createCache } from "@ls-stack/utils/cache";
|
|
5
|
+
import { deepEqual } from "@ls-stack/utils/deepEqual";
|
|
6
|
+
import { sleep } from "@ls-stack/utils/sleep";
|
|
7
|
+
import { rc_array, rc_discriminated_union, rc_literals, rc_number, rc_object, rc_parse, rc_parse_json, rc_record, rc_string, rc_tuple, rc_unknown } from "runcheck";
|
|
8
|
+
import { asPossiblyUndefined } from "@ls-stack/utils/typingFnUtils";
|
|
9
|
+
//#region src/persistentStorage/scheduleIdleCleanup.ts
|
|
10
|
+
/**
|
|
11
|
+
* Schedules a fire-and-forget cleanup callback during idle time.
|
|
12
|
+
* Uses `requestIdleCallback` when available, falls back to `setTimeout(fn, 2000)`.
|
|
13
|
+
*/
|
|
14
|
+
function scheduleIdleCleanup(callback) {
|
|
15
|
+
if (typeof requestIdleCallback === "function") {
|
|
16
|
+
const idleCallbackId = requestIdleCallback(() => callback(), { timeout: 3e3 });
|
|
17
|
+
return () => cancelIdleCallback(idleCallbackId);
|
|
18
|
+
} else {
|
|
19
|
+
const timeoutId = setTimeout(callback, 2e3);
|
|
20
|
+
return () => clearTimeout(timeoutId);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/persistentStorage/asyncStorageShared.ts
|
|
25
|
+
const PAYLOAD_RECORD_PREFIX = "__tsdf_payload__:";
|
|
26
|
+
function getNamespaceId(scope) {
|
|
27
|
+
return JSON.stringify([
|
|
28
|
+
scope.sessionKey,
|
|
29
|
+
scope.storeName,
|
|
30
|
+
scope.kind
|
|
31
|
+
]);
|
|
32
|
+
}
|
|
33
|
+
function encodePersistedAsyncNamespaceKind(kind) {
|
|
34
|
+
switch (kind) {
|
|
35
|
+
case "document": return "d";
|
|
36
|
+
case "collection.item": return "ci";
|
|
37
|
+
case "listQuery.item": return "li";
|
|
38
|
+
case "listQuery.query": return "lq";
|
|
39
|
+
case "offline.queue": return "oq";
|
|
40
|
+
case "offline.conflict": return "oc";
|
|
41
|
+
case "offline.entity": return "oe";
|
|
42
|
+
case "__internal.protected": return "ip";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function parsePersistedAsyncNamespaceKind(value) {
|
|
46
|
+
switch (value) {
|
|
47
|
+
case "d": return "document";
|
|
48
|
+
case "ci": return "collection.item";
|
|
49
|
+
case "li": return "listQuery.item";
|
|
50
|
+
case "lq": return "listQuery.query";
|
|
51
|
+
case "oq": return "offline.queue";
|
|
52
|
+
case "oc": return "offline.conflict";
|
|
53
|
+
case "oe": return "offline.entity";
|
|
54
|
+
case "ip": return "__internal.protected";
|
|
55
|
+
default: return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function getPersistedNamespaceId(scope) {
|
|
59
|
+
return JSON.stringify([
|
|
60
|
+
scope.sessionKey,
|
|
61
|
+
scope.storeName,
|
|
62
|
+
encodePersistedAsyncNamespaceKind(scope.kind)
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
function getPayloadRecordKey(key) {
|
|
66
|
+
return `${PAYLOAD_RECORD_PREFIX}${key}`;
|
|
67
|
+
}
|
|
68
|
+
function serializeProtectedRef$1(ref) {
|
|
69
|
+
return JSON.stringify([
|
|
70
|
+
ref.sessionKey,
|
|
71
|
+
ref.storeName,
|
|
72
|
+
encodePersistedAsyncNamespaceKind(ref.kind),
|
|
73
|
+
ref.key
|
|
74
|
+
]);
|
|
75
|
+
}
|
|
76
|
+
function parseProtectedRef(value) {
|
|
77
|
+
const parsed = rc_parse_json(value, rc_tuple([
|
|
78
|
+
rc_string,
|
|
79
|
+
rc_string,
|
|
80
|
+
rc_string,
|
|
81
|
+
rc_string
|
|
82
|
+
])).unwrapOrNull();
|
|
83
|
+
if (parsed === null) return null;
|
|
84
|
+
const [sessionKey, storeName, rawKind, key] = parsed;
|
|
85
|
+
const kind = parsePersistedAsyncNamespaceKind(rawKind);
|
|
86
|
+
if (kind === null) return null;
|
|
87
|
+
return {
|
|
88
|
+
sessionKey,
|
|
89
|
+
storeName,
|
|
90
|
+
kind,
|
|
91
|
+
key
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function parseAsyncStorageRecordKey(key) {
|
|
95
|
+
if (key.startsWith("__tsdf_payload__:")) return {
|
|
96
|
+
recordKind: "payload",
|
|
97
|
+
userKey: key.slice(17)
|
|
98
|
+
};
|
|
99
|
+
return {
|
|
100
|
+
rawKey: key,
|
|
101
|
+
recordKind: "raw"
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function normalizeStaticPolicy(policy) {
|
|
105
|
+
if (policy === void 0 || policy === null) return null;
|
|
106
|
+
const maxBytes = typeof policy.maxBytes === "number" && Number.isInteger(policy.maxBytes) && policy.maxBytes >= 0 ? policy.maxBytes : void 0;
|
|
107
|
+
const pinnedKeys = Array.isArray(policy.pinnedKeys) ? [...new Set(policy.pinnedKeys)].sort((left, right) => left.localeCompare(right)) : [];
|
|
108
|
+
if (maxBytes === void 0 && pinnedKeys.length === 0) return null;
|
|
109
|
+
return {
|
|
110
|
+
...maxBytes !== void 0 ? { maxBytes } : {},
|
|
111
|
+
...pinnedKeys.length > 0 ? { pinnedKeys } : {}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function compareMetadata(left, right, order) {
|
|
115
|
+
if (order === "key") return left.key.localeCompare(right.key);
|
|
116
|
+
if (left.lastAccessAt !== right.lastAccessAt) return order === "lru-asc" ? left.lastAccessAt - right.lastAccessAt : right.lastAccessAt - left.lastAccessAt;
|
|
117
|
+
return left.key.localeCompare(right.key);
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/persistentStorage/compactLocalStorageEntry.ts
|
|
121
|
+
function createCompactLocalStorageEntry(value, version) {
|
|
122
|
+
if ("v" in value && value.v !== void 0) throw new Error("[TSDF] Compact localStorage entries cannot use the reserved \"v\" key.");
|
|
123
|
+
if (version === void 0) return value;
|
|
124
|
+
return {
|
|
125
|
+
...value,
|
|
126
|
+
v: version
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function parseCompactLocalStorageEntry(raw) {
|
|
130
|
+
if (raw === null) return null;
|
|
131
|
+
const value = rc_parse_json(raw, rc_unknown).unwrapOrNull();
|
|
132
|
+
if (value === null) return null;
|
|
133
|
+
if (!isObject(value) || !("d" in value)) return null;
|
|
134
|
+
if ("v" in value && value.v !== void 0 && typeof value.v !== "number") return null;
|
|
135
|
+
return {
|
|
136
|
+
value,
|
|
137
|
+
...typeof value.v === "number" ? { version: value.v } : {}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region src/persistentStorage/navigatorLocks.ts
|
|
142
|
+
function getNavigatorLockManager() {
|
|
143
|
+
return asPossiblyUndefined(globalThis.navigator)?.locks ?? null;
|
|
144
|
+
}
|
|
145
|
+
const warnedLockUnavailable = /* @__PURE__ */ new Set();
|
|
146
|
+
function warnIfNavigatorLockUnavailable(warning) {
|
|
147
|
+
if (getNavigatorLockManager() !== null) return;
|
|
148
|
+
if (!warnedLockUnavailable.has(warning)) {
|
|
149
|
+
warnedLockUnavailable.add(warning);
|
|
150
|
+
console.warn(warning);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async function runWithNavigatorLock(lockName, unavailableWarning, callback) {
|
|
154
|
+
const lockManager = getNavigatorLockManager();
|
|
155
|
+
if (lockManager === null) {
|
|
156
|
+
warnIfNavigatorLockUnavailable(unavailableWarning);
|
|
157
|
+
return await callback();
|
|
158
|
+
}
|
|
159
|
+
return lockManager.request(lockName, callback);
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/persistentStorage/offline/sessionProtectionRegistry.ts
|
|
163
|
+
const protectedKeysBySession = /* @__PURE__ */ new Map();
|
|
164
|
+
function setSessionProtectedKeysSnapshot(sessionKey, protectedKeys) {
|
|
165
|
+
protectedKeysBySession.set(sessionKey, new Set(protectedKeys));
|
|
166
|
+
}
|
|
167
|
+
function getSessionProtectedKeysSnapshot(sessionKey) {
|
|
168
|
+
return protectedKeysBySession.get(sessionKey) ?? null;
|
|
169
|
+
}
|
|
170
|
+
function clearSessionProtectedKeysSnapshot(sessionKey) {
|
|
171
|
+
protectedKeysBySession.delete(sessionKey);
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/persistentStorage/offline/types.ts
|
|
175
|
+
/** Runtime schema for validating serialized offline item entity references. */
|
|
176
|
+
/** @internal */
|
|
177
|
+
const offlineItemEntityRefSchema = rc_object({
|
|
178
|
+
entityKey: rc_string,
|
|
179
|
+
entityKind: rc_literals("item")
|
|
180
|
+
});
|
|
181
|
+
const offlineResolutionEntityRefSchema = rc_object({
|
|
182
|
+
entityKey: rc_string,
|
|
183
|
+
entityKind: rc_literals("document", "item", "query")
|
|
184
|
+
});
|
|
185
|
+
const offlineResolutionBaseFields = {
|
|
186
|
+
id: rc_string,
|
|
187
|
+
entryId: rc_string,
|
|
188
|
+
sessionKey: rc_string,
|
|
189
|
+
storeName: rc_string,
|
|
190
|
+
storeType: rc_literals("document", "collection", "listQuery"),
|
|
191
|
+
operation: rc_string,
|
|
192
|
+
input: rc_unknown,
|
|
193
|
+
enqueuedAt: rc_number,
|
|
194
|
+
entityRefs: rc_array(offlineResolutionEntityRefSchema),
|
|
195
|
+
createdAt: rc_number,
|
|
196
|
+
updatedAt: rc_number,
|
|
197
|
+
attachedUploadIds: rc_record(rc_string).optionalKey(),
|
|
198
|
+
dependencyUploadIds: rc_array(rc_string).optionalKey()
|
|
199
|
+
};
|
|
200
|
+
/** Runtime schema for validating persisted offline resolution records on hydration. */
|
|
201
|
+
/** @internal */
|
|
202
|
+
const offlineResolutionRecordSchema = rc_discriminated_union("kind", {
|
|
203
|
+
conflict: {
|
|
204
|
+
...offlineResolutionBaseFields,
|
|
205
|
+
kind: rc_literals("conflict"),
|
|
206
|
+
conflict: rc_unknown
|
|
207
|
+
},
|
|
208
|
+
"retry-exhausted": {
|
|
209
|
+
...offlineResolutionBaseFields,
|
|
210
|
+
kind: rc_literals("retry-exhausted"),
|
|
211
|
+
lastReplayError: rc_object({ message: rc_string })
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
/** Default runtime config when offline is not configured or no session exists. */
|
|
215
|
+
const defaultOfflineRuntimeConfig = {
|
|
216
|
+
network: { enabled: false },
|
|
217
|
+
outage: { enabled: false },
|
|
218
|
+
mutationQueueing: {
|
|
219
|
+
network: "allow",
|
|
220
|
+
outage: "allow"
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const compactOfflineStatusModeStateSchema = rc_object({
|
|
224
|
+
e: rc_literals(1).optionalKey(),
|
|
225
|
+
a: rc_literals(1).optionalKey()
|
|
226
|
+
});
|
|
227
|
+
/** Runtime schema for compact persisted offline status snapshots. */
|
|
228
|
+
/** @internal */
|
|
229
|
+
const compactOfflineStatusSnapshotSchema = rc_object({
|
|
230
|
+
n: compactOfflineStatusModeStateSchema.optionalKey(),
|
|
231
|
+
o: compactOfflineStatusModeStateSchema.optionalKey(),
|
|
232
|
+
u: rc_number.optionalKey(),
|
|
233
|
+
lf: rc_number.optionalKey(),
|
|
234
|
+
lr: rc_number.optionalKey()
|
|
235
|
+
});
|
|
236
|
+
function isModeEffectivelyActive(mode) {
|
|
237
|
+
return mode.enabled && mode.active;
|
|
238
|
+
}
|
|
239
|
+
function getIsOfflineModeFromStatus(status) {
|
|
240
|
+
return status.network.active || status.outage.active;
|
|
241
|
+
}
|
|
242
|
+
function isOfflineModeStatusValue(value) {
|
|
243
|
+
const status = rc_parse(value, compactOfflineStatusSnapshotSchema).unwrapOrNull();
|
|
244
|
+
if (status === null) return false;
|
|
245
|
+
return status.n?.a === 1 || status.o?.a === 1;
|
|
246
|
+
}
|
|
247
|
+
function formatSchemaValidationError(error) {
|
|
248
|
+
if (error.length === 0) return "invalid-conflict-payload";
|
|
249
|
+
if (typeof error[0] === "string") {
|
|
250
|
+
let message = error[0];
|
|
251
|
+
for (const entry of error.slice(1)) {
|
|
252
|
+
if (typeof entry !== "string") return JSON.stringify(error);
|
|
253
|
+
message += `; ${entry}`;
|
|
254
|
+
}
|
|
255
|
+
return message;
|
|
256
|
+
}
|
|
257
|
+
return JSON.stringify(error);
|
|
258
|
+
}
|
|
259
|
+
function getOfflineResolutionConflictParseErrorMessage(args) {
|
|
260
|
+
if (args.code === "invalid-conflict-payload" && args.validationError) return formatSchemaValidationError(args.validationError);
|
|
261
|
+
return args.code;
|
|
262
|
+
}
|
|
263
|
+
/** Error returned when decoding a stored offline conflict payload fails. */
|
|
264
|
+
var OfflineResolutionConflictParseError = class extends Error {
|
|
265
|
+
code;
|
|
266
|
+
operation;
|
|
267
|
+
kind;
|
|
268
|
+
rawValue;
|
|
269
|
+
validationError;
|
|
270
|
+
constructor(args) {
|
|
271
|
+
super(getOfflineResolutionConflictParseErrorMessage(args));
|
|
272
|
+
this.name = "OfflineResolutionConflictParseError";
|
|
273
|
+
this.code = args.code;
|
|
274
|
+
this.operation = args.operation;
|
|
275
|
+
this.kind = args.kind;
|
|
276
|
+
this.rawValue = args.rawValue;
|
|
277
|
+
this.validationError = args.validationError;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
//#endregion
|
|
281
|
+
//#region src/persistentStorage/persistenceUtils.ts
|
|
282
|
+
/**
|
|
283
|
+
* Creates a key set that auto-clears entries after a microtask.
|
|
284
|
+
* Used to deduplicate sync storage reads within the same event loop tick.
|
|
285
|
+
*/
|
|
286
|
+
function createTimedKeySet() {
|
|
287
|
+
const keys = /* @__PURE__ */ new Set();
|
|
288
|
+
let clearScheduled = false;
|
|
289
|
+
function scheduleClear() {
|
|
290
|
+
if (clearScheduled) return;
|
|
291
|
+
clearScheduled = true;
|
|
292
|
+
queueMicrotask(() => {
|
|
293
|
+
clearScheduled = false;
|
|
294
|
+
keys.clear();
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
return {
|
|
298
|
+
has: (key) => keys.has(key),
|
|
299
|
+
remember: (key) => {
|
|
300
|
+
keys.add(key);
|
|
301
|
+
scheduleClear();
|
|
302
|
+
},
|
|
303
|
+
clear: (key) => {
|
|
304
|
+
keys.delete(key);
|
|
305
|
+
},
|
|
306
|
+
clearAll: () => {
|
|
307
|
+
keys.clear();
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
function createShouldIgnoreItemPredicate(ignoreItems, resolveItemKey) {
|
|
312
|
+
if (!ignoreItems) return () => false;
|
|
313
|
+
if (typeof ignoreItems === "function") return ignoreItems;
|
|
314
|
+
const ignoredItemKeys = new Set(ignoreItems.map(resolveItemKey));
|
|
315
|
+
return (payload) => ignoredItemKeys.has(resolveItemKey(payload));
|
|
316
|
+
}
|
|
317
|
+
function getSerializedStringSize(value) {
|
|
318
|
+
return value.length;
|
|
319
|
+
}
|
|
320
|
+
function serializeJsonForStorage(value) {
|
|
321
|
+
const rawValue = JSON.stringify(value);
|
|
322
|
+
return {
|
|
323
|
+
rawValue,
|
|
324
|
+
sizeBytes: getSerializedStringSize(rawValue)
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function keepEntriesWithinByteBudget(args) {
|
|
328
|
+
const keptKeys = /* @__PURE__ */ new Set();
|
|
329
|
+
let unprotectedBytes = 0;
|
|
330
|
+
for (const entry of args.entries) {
|
|
331
|
+
if (args.isProtected(entry)) continue;
|
|
332
|
+
unprotectedBytes += args.getSizeBytes(entry);
|
|
333
|
+
}
|
|
334
|
+
if (unprotectedBytes <= args.maxBytes) {
|
|
335
|
+
for (const entry of args.entries) keptKeys.add(args.getKey(entry));
|
|
336
|
+
return keptKeys;
|
|
337
|
+
}
|
|
338
|
+
const sortedEntries = [...args.entries].sort((a, b) => {
|
|
339
|
+
const aProtected = args.isProtected(a);
|
|
340
|
+
const bProtected = args.isProtected(b);
|
|
341
|
+
if (aProtected && !bProtected) return -1;
|
|
342
|
+
if (!aProtected && bProtected) return 1;
|
|
343
|
+
const aPinned = args.isPinned(a);
|
|
344
|
+
const bPinned = args.isPinned(b);
|
|
345
|
+
if (aPinned && !bPinned) return -1;
|
|
346
|
+
if (!aPinned && bPinned) return 1;
|
|
347
|
+
return args.getLastAccessAt(b) - args.getLastAccessAt(a);
|
|
348
|
+
});
|
|
349
|
+
let keptUnprotectedBytes = 0;
|
|
350
|
+
for (const entry of sortedEntries) {
|
|
351
|
+
const key = args.getKey(entry);
|
|
352
|
+
if (args.isProtected(entry)) {
|
|
353
|
+
keptKeys.add(key);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
const sizeBytes = args.getSizeBytes(entry);
|
|
357
|
+
if (args.isPinned(entry)) {
|
|
358
|
+
keptKeys.add(key);
|
|
359
|
+
keptUnprotectedBytes += sizeBytes;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
if (keptUnprotectedBytes + sizeBytes <= args.maxBytes) {
|
|
363
|
+
keptKeys.add(key);
|
|
364
|
+
keptUnprotectedBytes += sizeBytes;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return keptKeys;
|
|
368
|
+
}
|
|
369
|
+
//#endregion
|
|
370
|
+
//#region src/persistentStorage/persistentStorageDefaults.ts
|
|
371
|
+
const defaultMaxBytes = {
|
|
372
|
+
localSync: {
|
|
373
|
+
collection: 64 * 1024,
|
|
374
|
+
listItem: 64 * 1024,
|
|
375
|
+
listQuery: 32 * 1024
|
|
376
|
+
},
|
|
377
|
+
async: {
|
|
378
|
+
collection: 128 * 1024,
|
|
379
|
+
listItem: 128 * 1024,
|
|
380
|
+
listQuery: 64 * 1024
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
function getDefaultMaxBytesProfile(adapter) {
|
|
384
|
+
return adapter === "local-sync" || adapter === "localSync" ? "localSync" : "async";
|
|
385
|
+
}
|
|
386
|
+
function getDefaultMaxBytesKindForScope(scopeKind) {
|
|
387
|
+
switch (scopeKind) {
|
|
388
|
+
case "collection.item": return "collection";
|
|
389
|
+
case "listQuery.item": return "listItem";
|
|
390
|
+
case "listQuery.query": return "listQuery";
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function getDefaultMaxBytesForAdapter(args) {
|
|
394
|
+
return defaultMaxBytes[getDefaultMaxBytesProfile(args.adapter)][args.kind];
|
|
395
|
+
}
|
|
396
|
+
function getDefaultMaxBytesForScope(args) {
|
|
397
|
+
return getDefaultMaxBytesForAdapter({
|
|
398
|
+
adapter: args.adapter,
|
|
399
|
+
kind: getDefaultMaxBytesKindForScope(args.scopeKind)
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
//#endregion
|
|
403
|
+
//#region src/persistentStorage/types.ts
|
|
404
|
+
function parseAsyncStorageNamespaceKind(value) {
|
|
405
|
+
switch (value) {
|
|
406
|
+
case "document":
|
|
407
|
+
case "collection.item":
|
|
408
|
+
case "listQuery.item":
|
|
409
|
+
case "listQuery.query":
|
|
410
|
+
case "offline.queue":
|
|
411
|
+
case "offline.conflict":
|
|
412
|
+
case "offline.entity":
|
|
413
|
+
case "__internal.protected": return value;
|
|
414
|
+
default: return null;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const ASYNC_STORAGE_MAX_AGE_MS = 336 * 60 * 60 * 1e3;
|
|
418
|
+
const ASYNC_STORAGE_STARTUP_CLEANUP_COOLDOWN_MS = 720 * 60 * 1e3;
|
|
419
|
+
const ASYNC_STORAGE_RECENCY_BUCKET_MS = 360 * 60 * 1e3;
|
|
420
|
+
const ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY = "tsdf._am.g";
|
|
421
|
+
const ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX = "tsdf-async-write:";
|
|
422
|
+
const ASYNC_STORAGE_WRITER_LOCK_WARNING = "[TSDF] navigator.locks is unavailable; async persistentStorage is using unlocked writer coordination.";
|
|
423
|
+
const ASYNC_STARTUP_CLEANUP_LOCK_NAME = "tsdf-async-storage-maintenance";
|
|
424
|
+
const ASYNC_STARTUP_CLEANUP_LOCK_WARNING = "[TSDF] navigator.locks is unavailable; async OPFS startup cleanup is using unlocked coordination.";
|
|
425
|
+
const ASYNC_STORAGE_CACHE_INVALIDATION_CHANNEL_NAME = "tsdf-async-storage-cache-v1";
|
|
426
|
+
const ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE = 500;
|
|
427
|
+
const ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE = 5e3;
|
|
428
|
+
function getBucketId(timestamp) {
|
|
429
|
+
return String(Math.floor(timestamp / ASYNC_STORAGE_RECENCY_BUCKET_MS));
|
|
430
|
+
}
|
|
431
|
+
function getRecord(value) {
|
|
432
|
+
if (!isObject(value)) return null;
|
|
433
|
+
return value;
|
|
434
|
+
}
|
|
435
|
+
function isOfflineProtectedMetadata(customMetadata) {
|
|
436
|
+
return customMetadata?.o === true;
|
|
437
|
+
}
|
|
438
|
+
function getProtectedKeysFromMetadata(entries) {
|
|
439
|
+
const keys = /* @__PURE__ */ new Set();
|
|
440
|
+
for (const entry of entries) if (isOfflineProtectedMetadata(entry.customMetadata)) keys.add(entry.key);
|
|
441
|
+
return keys;
|
|
442
|
+
}
|
|
443
|
+
function isSessionOfflineInLocalStorage(sessionKey) {
|
|
444
|
+
if (typeof window === "undefined") return false;
|
|
445
|
+
try {
|
|
446
|
+
return isOfflineModeStatusValue(parseCompactLocalStorageEntry(localStorage.getItem(`tsdf.${sessionKey}._o_.s`))?.value.d ?? null);
|
|
447
|
+
} catch {
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
function setOfflineProtectionMetadata(customMetadata, offlineProtected) {
|
|
452
|
+
if (offlineProtected) return {
|
|
453
|
+
...customMetadata ?? {},
|
|
454
|
+
o: true
|
|
455
|
+
};
|
|
456
|
+
const { o: _ignored, ...withoutOfflineMarker } = customMetadata ?? {};
|
|
457
|
+
return Object.keys(withoutOfflineMarker).length > 0 ? withoutOfflineMarker : void 0;
|
|
458
|
+
}
|
|
459
|
+
function mergeManagedAsyncStorageCustomMetadata(args) {
|
|
460
|
+
const merged = {
|
|
461
|
+
...args.currentCustomMetadata ?? {},
|
|
462
|
+
...args.nextCustomMetadata ?? {}
|
|
463
|
+
};
|
|
464
|
+
const mergedCustomMetadata = Object.keys(merged).length > 0 ? merged : void 0;
|
|
465
|
+
if (args.protectedKeysSnapshotSet !== null) return setOfflineProtectionMetadata(mergedCustomMetadata, args.protectedKeysSnapshotSet?.has(serializeProtectedRef({
|
|
466
|
+
...args.scope,
|
|
467
|
+
key: args.key
|
|
468
|
+
})) === true || isOfflineProtectedMetadata(args.nextCustomMetadata) || isOfflineProtectedMetadata(args.currentCustomMetadata));
|
|
469
|
+
return setOfflineProtectionMetadata(mergedCustomMetadata, isOfflineProtectedMetadata(args.nextCustomMetadata) || isOfflineProtectedMetadata(args.currentCustomMetadata));
|
|
470
|
+
}
|
|
471
|
+
const ASYNC_METADATA_LAST_ACCESS_AT_KEY = "a";
|
|
472
|
+
const ASYNC_METADATA_VERSION_KEY = "v";
|
|
473
|
+
const ASYNC_METADATA_SIZE_BYTES_KEY = "z";
|
|
474
|
+
const persistedStaticPolicySchema = rc_object({
|
|
475
|
+
b: rc_number.optionalKey(),
|
|
476
|
+
k: rc_array(rc_string).optionalKey()
|
|
477
|
+
});
|
|
478
|
+
function getInlineCustomMetadata(record) {
|
|
479
|
+
const customMetadataEntries = Object.entries(record).filter(([key]) => key !== ASYNC_METADATA_LAST_ACCESS_AT_KEY && key !== ASYNC_METADATA_VERSION_KEY && key !== ASYNC_METADATA_SIZE_BYTES_KEY);
|
|
480
|
+
if (customMetadataEntries.length === 0) return void 0;
|
|
481
|
+
return Object.fromEntries(customMetadataEntries);
|
|
482
|
+
}
|
|
483
|
+
function parseInternalManagedMetadataRecord(value) {
|
|
484
|
+
const record = getRecord(value);
|
|
485
|
+
if (record === null || typeof record.a !== "number" || "v" in record && record.v !== void 0 && typeof record.v !== "number" || "z" in record && record.z !== void 0 && typeof record.z !== "number") return null;
|
|
486
|
+
const customMetadata = getInlineCustomMetadata(record);
|
|
487
|
+
return {
|
|
488
|
+
lastAccessAt: record.a,
|
|
489
|
+
...typeof record.z === "number" ? { sizeBytes: record.z } : {},
|
|
490
|
+
version: typeof record.v === "number" ? record.v : 1,
|
|
491
|
+
...customMetadata ? { customMetadata } : {}
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
function serializeInternalManagedMetadataRecord(metadata) {
|
|
495
|
+
const serialized = {
|
|
496
|
+
[ASYNC_METADATA_LAST_ACCESS_AT_KEY]: metadata.lastAccessAt,
|
|
497
|
+
...metadata.sizeBytes !== void 0 ? { [ASYNC_METADATA_SIZE_BYTES_KEY]: metadata.sizeBytes } : {},
|
|
498
|
+
...metadata.version !== 1 ? { [ASYNC_METADATA_VERSION_KEY]: metadata.version } : {}
|
|
499
|
+
};
|
|
500
|
+
const customMetadata = metadata.customMetadata;
|
|
501
|
+
if (customMetadata === void 0) return serialized;
|
|
502
|
+
if (ASYNC_METADATA_LAST_ACCESS_AT_KEY in customMetadata || ASYNC_METADATA_VERSION_KEY in customMetadata || ASYNC_METADATA_SIZE_BYTES_KEY in customMetadata) throw new Error("[TSDF] Async storage custom metadata cannot use reserved keys \"a\", \"v\", or \"z\".");
|
|
503
|
+
return {
|
|
504
|
+
...serialized,
|
|
505
|
+
...customMetadata
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function estimateManagedAsyncStorageEntrySizeBytes(args) {
|
|
509
|
+
return getSerializedStringSize(args.serializedValue) + getSerializedStringSize(JSON.stringify(serializeInternalManagedMetadataRecord({
|
|
510
|
+
lastAccessAt: args.lastAccessAt,
|
|
511
|
+
sizeBytes: void 0,
|
|
512
|
+
version: args.version,
|
|
513
|
+
...args.customMetadata ? { customMetadata: args.customMetadata } : {}
|
|
514
|
+
})));
|
|
515
|
+
}
|
|
516
|
+
function parseIndexEntries(value) {
|
|
517
|
+
const rawEntries = getRecord(value)?.e;
|
|
518
|
+
if (rawEntries === void 0) return value === null ? /* @__PURE__ */ new Map() : null;
|
|
519
|
+
const entriesRecord = getRecord(rawEntries);
|
|
520
|
+
if (entriesRecord === null) return null;
|
|
521
|
+
const entries = /* @__PURE__ */ new Map();
|
|
522
|
+
for (const [key, rawEntry] of Object.entries(entriesRecord)) {
|
|
523
|
+
const parsed = parseInternalManagedMetadataRecord(rawEntry);
|
|
524
|
+
if (parsed === null) return null;
|
|
525
|
+
entries.set(key, parsed);
|
|
526
|
+
}
|
|
527
|
+
return entries;
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Builds a persisted static policy from config values, omitting fields that
|
|
531
|
+
* match the provided default. Returns null when no overrides are needed.
|
|
532
|
+
*/
|
|
533
|
+
function buildPersistedStaticPolicy(maxBytes, defaultMaxBytes, pinnedKeys) {
|
|
534
|
+
return normalizeStaticPolicy({
|
|
535
|
+
...maxBytes !== void 0 && maxBytes !== defaultMaxBytes ? { maxBytes } : {},
|
|
536
|
+
...pinnedKeys.size > 0 ? { pinnedKeys: [...pinnedKeys] } : {}
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
function parseStaticPolicy(value) {
|
|
540
|
+
const parsed = rc_parse(value, persistedStaticPolicySchema).unwrapOrNull();
|
|
541
|
+
if (parsed === null) return null;
|
|
542
|
+
if (parsed.b !== void 0 && (!Number.isInteger(parsed.b) || parsed.b < 0)) return null;
|
|
543
|
+
return normalizeStaticPolicy({
|
|
544
|
+
...parsed.b !== void 0 ? { maxBytes: parsed.b } : {},
|
|
545
|
+
...parsed.k !== void 0 ? { pinnedKeys: parsed.k } : {}
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
function serializeStaticPolicy(policy) {
|
|
549
|
+
if (policy === null) return void 0;
|
|
550
|
+
return {
|
|
551
|
+
...policy.maxBytes !== void 0 ? { b: policy.maxBytes } : {},
|
|
552
|
+
...policy.pinnedKeys !== void 0 && policy.pinnedKeys.length > 0 ? { k: policy.pinnedKeys } : {}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function serializeIndexState(state) {
|
|
556
|
+
const serializedStaticPolicy = serializeStaticPolicy(state.staticPolicy);
|
|
557
|
+
return {
|
|
558
|
+
e: Object.fromEntries([...state.entries.entries()].map(([key, metadata]) => [key, serializeInternalManagedMetadataRecord(metadata)])),
|
|
559
|
+
...serializedStaticPolicy !== void 0 ? { s: serializedStaticPolicy } : {}
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
function getDefaultStaticPolicyForScope(scope) {
|
|
563
|
+
switch (scope.kind) {
|
|
564
|
+
case "collection.item": return { maxBytes: getDefaultMaxBytesForScope({
|
|
565
|
+
adapter: "async",
|
|
566
|
+
scopeKind: "collection.item"
|
|
567
|
+
}) };
|
|
568
|
+
case "listQuery.item": return { maxBytes: getDefaultMaxBytesForScope({
|
|
569
|
+
adapter: "async",
|
|
570
|
+
scopeKind: "listQuery.item"
|
|
571
|
+
}) };
|
|
572
|
+
case "listQuery.query": return { maxBytes: getDefaultMaxBytesForScope({
|
|
573
|
+
adapter: "async",
|
|
574
|
+
scopeKind: "listQuery.query"
|
|
575
|
+
}) };
|
|
576
|
+
default: return null;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Strips fields from a persisted static policy that match the scope's defaults,
|
|
581
|
+
* so only non-default overrides are stored.
|
|
582
|
+
* Expects already-normalized input.
|
|
583
|
+
*/
|
|
584
|
+
function normalizePersistedStaticPolicyForScope(scope, persistedStaticPolicy) {
|
|
585
|
+
if (persistedStaticPolicy === null) return null;
|
|
586
|
+
const defaultPolicy = getDefaultStaticPolicyForScope(scope);
|
|
587
|
+
return normalizeStaticPolicy({
|
|
588
|
+
maxBytes: persistedStaticPolicy.maxBytes !== void 0 && persistedStaticPolicy.maxBytes !== defaultPolicy?.maxBytes ? persistedStaticPolicy.maxBytes : void 0,
|
|
589
|
+
pinnedKeys: persistedStaticPolicy.pinnedKeys
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Merges a persisted static policy (already normalized for scope) with the
|
|
594
|
+
* scope's defaults to produce the effective policy.
|
|
595
|
+
* Expects already-normalized input.
|
|
596
|
+
*/
|
|
597
|
+
function getEffectiveStaticPolicyForScope(scope, normalizedPersistedPolicy) {
|
|
598
|
+
const defaultPolicy = getDefaultStaticPolicyForScope(scope);
|
|
599
|
+
if (defaultPolicy === null) return normalizedPersistedPolicy;
|
|
600
|
+
return normalizeStaticPolicy({
|
|
601
|
+
maxBytes: normalizedPersistedPolicy?.maxBytes ?? defaultPolicy.maxBytes,
|
|
602
|
+
pinnedKeys: normalizedPersistedPolicy?.pinnedKeys
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
async function driverGetManyFrom(driver, scope, keys) {
|
|
606
|
+
if (keys.length === 0) return [];
|
|
607
|
+
return driver.getMany(scope, keys);
|
|
608
|
+
}
|
|
609
|
+
function getManagedDriverCapabilities(driver) {
|
|
610
|
+
return __LEGIT_CAST__(driver).__tsdfManagedStorage ?? null;
|
|
611
|
+
}
|
|
612
|
+
async function readAsyncStorageNamespaceIndexStateUsingDriver(driver, scope, knownRecordKeys) {
|
|
613
|
+
const managedCapabilities = getManagedDriverCapabilities(driver);
|
|
614
|
+
if (managedCapabilities?.readNamespaceIndexState !== void 0) return managedCapabilities.readNamespaceIndexState(scope, knownRecordKeys);
|
|
615
|
+
if (knownRecordKeys != null && !knownRecordKeys.includes("_i")) return {
|
|
616
|
+
entries: null,
|
|
617
|
+
exists: false,
|
|
618
|
+
staticPolicy: null,
|
|
619
|
+
valid: true
|
|
620
|
+
};
|
|
621
|
+
const indexKnownToExist = knownRecordKeys != null;
|
|
622
|
+
const rawIndex = await driver.get(scope, "_i");
|
|
623
|
+
if (rawIndex === null) return indexKnownToExist ? {
|
|
624
|
+
entries: null,
|
|
625
|
+
exists: true,
|
|
626
|
+
staticPolicy: null,
|
|
627
|
+
valid: false
|
|
628
|
+
} : {
|
|
629
|
+
entries: null,
|
|
630
|
+
exists: false,
|
|
631
|
+
staticPolicy: null,
|
|
632
|
+
valid: true
|
|
633
|
+
};
|
|
634
|
+
const record = getRecord(rawIndex);
|
|
635
|
+
const parsed = parseIndexEntries(rawIndex);
|
|
636
|
+
if (parsed === null) return {
|
|
637
|
+
entries: null,
|
|
638
|
+
exists: true,
|
|
639
|
+
staticPolicy: null,
|
|
640
|
+
valid: false
|
|
641
|
+
};
|
|
642
|
+
return {
|
|
643
|
+
entries: parsed,
|
|
644
|
+
exists: true,
|
|
645
|
+
staticPolicy: parseStaticPolicy(record?.s),
|
|
646
|
+
valid: true
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
function cloneStaticPolicy(policy) {
|
|
650
|
+
if (policy === null) return null;
|
|
651
|
+
return {
|
|
652
|
+
maxBytes: policy.maxBytes,
|
|
653
|
+
pinnedKeys: policy.pinnedKeys ? [...policy.pinnedKeys] : void 0
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function cloneManagedMetadataRecord(metadata) {
|
|
657
|
+
return {
|
|
658
|
+
lastAccessAt: metadata.lastAccessAt,
|
|
659
|
+
sizeBytes: metadata.sizeBytes,
|
|
660
|
+
version: metadata.version,
|
|
661
|
+
customMetadata: metadata.customMetadata ? klona(metadata.customMetadata) : void 0
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
function cloneNamespaceIndexReadState(state) {
|
|
665
|
+
let entries = null;
|
|
666
|
+
if (state.entries !== null) {
|
|
667
|
+
entries = /* @__PURE__ */ new Map();
|
|
668
|
+
for (const [key, metadata] of state.entries) entries.set(key, cloneManagedMetadataRecord(metadata));
|
|
669
|
+
}
|
|
670
|
+
return {
|
|
671
|
+
entries,
|
|
672
|
+
exists: state.exists,
|
|
673
|
+
staticPolicy: cloneStaticPolicy(state.staticPolicy),
|
|
674
|
+
valid: state.valid
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
function parseCacheInvalidationReason(value) {
|
|
678
|
+
switch (value) {
|
|
679
|
+
case "clear":
|
|
680
|
+
case "commit":
|
|
681
|
+
case "remove":
|
|
682
|
+
case "startup-cleanup": return value;
|
|
683
|
+
default: return null;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
function parseAsyncStorageCacheInvalidationMessage(value) {
|
|
687
|
+
const record = getRecord(value);
|
|
688
|
+
if (record === null || record.kind !== "namespace-invalidated" || record.protocolVersion !== 1) return null;
|
|
689
|
+
const scopeRecord = getRecord(record.scope);
|
|
690
|
+
if (scopeRecord === null || typeof scopeRecord.kind !== "string" || typeof scopeRecord.sessionKey !== "string" || typeof scopeRecord.storeName !== "string") return null;
|
|
691
|
+
const kind = parseAsyncStorageNamespaceKind(scopeRecord.kind);
|
|
692
|
+
if (kind === null) return null;
|
|
693
|
+
const reason = parseCacheInvalidationReason(record.reason);
|
|
694
|
+
if (reason === null) return null;
|
|
695
|
+
return {
|
|
696
|
+
kind: "namespace-invalidated",
|
|
697
|
+
protocolVersion: 1,
|
|
698
|
+
reason,
|
|
699
|
+
scope: {
|
|
700
|
+
kind,
|
|
701
|
+
sessionKey: scopeRecord.sessionKey,
|
|
702
|
+
storeName: scopeRecord.storeName
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
const asyncStorageReadCacheParticipants = [];
|
|
707
|
+
let asyncStorageCacheInvalidationChannel;
|
|
708
|
+
let asyncStorageReadCacheLifecycleReady = false;
|
|
709
|
+
function getLiveAsyncStorageReadCacheParticipants() {
|
|
710
|
+
const liveParticipants = [];
|
|
711
|
+
const retainedRefs = [];
|
|
712
|
+
for (const ref of asyncStorageReadCacheParticipants) {
|
|
713
|
+
const participant = ref.deref();
|
|
714
|
+
if (participant === void 0) continue;
|
|
715
|
+
liveParticipants.push(participant);
|
|
716
|
+
retainedRefs.push(ref);
|
|
717
|
+
}
|
|
718
|
+
asyncStorageReadCacheParticipants.length = 0;
|
|
719
|
+
asyncStorageReadCacheParticipants.push(...retainedRefs);
|
|
720
|
+
return liveParticipants;
|
|
721
|
+
}
|
|
722
|
+
function clearAllAsyncStorageReadCaches() {
|
|
723
|
+
for (const participant of getLiveAsyncStorageReadCacheParticipants()) participant.clearAllCachedReads();
|
|
724
|
+
}
|
|
725
|
+
function notifyLocalAsyncStorageReadCacheInvalidation(source, message) {
|
|
726
|
+
for (const participant of getLiveAsyncStorageReadCacheParticipants()) {
|
|
727
|
+
if (participant === source) continue;
|
|
728
|
+
participant.onRemoteCacheInvalidation(message);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
function handleAsyncStorageCacheInvalidationEvent(event) {
|
|
732
|
+
const message = parseAsyncStorageCacheInvalidationMessage(event.data);
|
|
733
|
+
if (message === null) return;
|
|
734
|
+
for (const participant of getLiveAsyncStorageReadCacheParticipants()) participant.onRemoteCacheInvalidation(message);
|
|
735
|
+
}
|
|
736
|
+
function ensureAsyncStorageReadCacheLifecycle() {
|
|
737
|
+
if (!asyncStorageReadCacheLifecycleReady) {
|
|
738
|
+
document.addEventListener("visibilitychange", () => {
|
|
739
|
+
if (!document.hidden) clearAllAsyncStorageReadCaches();
|
|
740
|
+
});
|
|
741
|
+
if (typeof window !== "undefined") window.addEventListener("pageshow", () => {
|
|
742
|
+
clearAllAsyncStorageReadCaches();
|
|
743
|
+
});
|
|
744
|
+
asyncStorageReadCacheLifecycleReady = true;
|
|
745
|
+
}
|
|
746
|
+
if (asyncStorageCacheInvalidationChannel !== void 0) return;
|
|
747
|
+
try {
|
|
748
|
+
asyncStorageCacheInvalidationChannel = new BroadcastChannel(ASYNC_STORAGE_CACHE_INVALIDATION_CHANNEL_NAME);
|
|
749
|
+
asyncStorageCacheInvalidationChannel.addEventListener("message", handleAsyncStorageCacheInvalidationEvent);
|
|
750
|
+
} catch {
|
|
751
|
+
asyncStorageCacheInvalidationChannel = null;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
function registerAsyncStorageReadCacheParticipant(participant) {
|
|
755
|
+
ensureAsyncStorageReadCacheLifecycle();
|
|
756
|
+
asyncStorageReadCacheParticipants.push(new WeakRef(participant));
|
|
757
|
+
}
|
|
758
|
+
function parseMaintenanceState(value) {
|
|
759
|
+
const record = getRecord(value);
|
|
760
|
+
if (record === null) return null;
|
|
761
|
+
const lastSuccessfulCleanupAt = record.lca;
|
|
762
|
+
if (lastSuccessfulCleanupAt !== null && typeof lastSuccessfulCleanupAt !== "number") return null;
|
|
763
|
+
return { lastSuccessfulCleanupAt };
|
|
764
|
+
}
|
|
765
|
+
function createDefaultMaintenanceState() {
|
|
766
|
+
return { lastSuccessfulCleanupAt: null };
|
|
767
|
+
}
|
|
768
|
+
var ManagedAsyncStorageNamespaceHandle = class {
|
|
769
|
+
#adapter;
|
|
770
|
+
#scope;
|
|
771
|
+
constructor(adapter, scope) {
|
|
772
|
+
this.#adapter = adapter;
|
|
773
|
+
this.#scope = scope;
|
|
774
|
+
}
|
|
775
|
+
async get(key, options = {}) {
|
|
776
|
+
await this.#adapter.flushPendingNamespaceCommit(this.#scope, [key]);
|
|
777
|
+
const entry = (await this.#adapter.readManagedEntries(this.#scope, [key])).get(key) ?? null;
|
|
778
|
+
if (!entry) return null;
|
|
779
|
+
const now = Date.now();
|
|
780
|
+
const touchMode = options.touch ?? "coarse";
|
|
781
|
+
if (this.#adapter.shouldEnqueueTouch(this.#scope, key, entry.metadata.lastAccessAt, touchMode, now)) this.commit({ touches: [{
|
|
782
|
+
key,
|
|
783
|
+
lastAccessAt: now
|
|
784
|
+
}] }).catch(() => {});
|
|
785
|
+
return entry;
|
|
786
|
+
}
|
|
787
|
+
async getMany(keys, options = {}) {
|
|
788
|
+
if (keys.length === 0) return [];
|
|
789
|
+
const uniqueKeys = [...new Set(keys)];
|
|
790
|
+
await this.#adapter.flushPendingNamespaceCommit(this.#scope, uniqueKeys);
|
|
791
|
+
const entries = await this.#adapter.readManagedEntries(this.#scope, uniqueKeys);
|
|
792
|
+
const entryByKey = /* @__PURE__ */ new Map();
|
|
793
|
+
const touches = [];
|
|
794
|
+
const now = Date.now();
|
|
795
|
+
const touchMode = options.touch ?? "coarse";
|
|
796
|
+
for (const key of uniqueKeys) {
|
|
797
|
+
const entry = entries.get(key) ?? null;
|
|
798
|
+
entryByKey.set(key, entry);
|
|
799
|
+
if (entry !== null && this.#adapter.shouldEnqueueTouch(this.#scope, key, entry.metadata.lastAccessAt, touchMode, now)) touches.push(key);
|
|
800
|
+
}
|
|
801
|
+
if (touches.length > 0) this.commit({ touches: touches.map((key) => ({
|
|
802
|
+
key,
|
|
803
|
+
lastAccessAt: now
|
|
804
|
+
})) }).catch(() => {});
|
|
805
|
+
return keys.map((key) => entryByKey.get(key) ?? null);
|
|
806
|
+
}
|
|
807
|
+
commit(args) {
|
|
808
|
+
return this.#adapter.queueCommitToNamespace(this.#scope, args);
|
|
809
|
+
}
|
|
810
|
+
async listKeys() {
|
|
811
|
+
await this.#adapter.flushPendingNamespaceCommit(this.#scope);
|
|
812
|
+
return this.#adapter.listManagedKeys(this.#scope);
|
|
813
|
+
}
|
|
814
|
+
async listMetadata(args = {}) {
|
|
815
|
+
await this.#adapter.flushPendingNamespaceCommit(this.#scope);
|
|
816
|
+
return this.#adapter.listManagedMetadata(this.#scope, args);
|
|
817
|
+
}
|
|
818
|
+
async listMetadataByFilter(args) {
|
|
819
|
+
await this.#adapter.flushPendingNamespaceCommit(this.#scope);
|
|
820
|
+
return this.#adapter.listManagedMetadata(this.#scope, args);
|
|
821
|
+
}
|
|
822
|
+
async clear() {
|
|
823
|
+
await this.#adapter.flushPendingNamespaceCommit(this.#scope);
|
|
824
|
+
await this.#adapter.clearManagedNamespace(this.#scope);
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
const registeredAsyncStartupStoreCleanupCallbacks = /* @__PURE__ */ new WeakMap();
|
|
828
|
+
function getStoreRegistryKey(sessionKey, storeName) {
|
|
829
|
+
return JSON.stringify([sessionKey, storeName]);
|
|
830
|
+
}
|
|
831
|
+
function registerAsyncStartupStoreCleanup(adapter, sessionKey, storeName, callback) {
|
|
832
|
+
const registry = registeredAsyncStartupStoreCleanupCallbacks.get(adapter) ?? /* @__PURE__ */ new Map();
|
|
833
|
+
registry.set(getStoreRegistryKey(sessionKey, storeName), callback);
|
|
834
|
+
registeredAsyncStartupStoreCleanupCallbacks.set(adapter, registry);
|
|
835
|
+
}
|
|
836
|
+
function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
|
|
837
|
+
const registry = registeredAsyncStartupStoreCleanupCallbacks.get(adapter);
|
|
838
|
+
if (registry === void 0) return;
|
|
839
|
+
registry.delete(getStoreRegistryKey(sessionKey, storeName));
|
|
840
|
+
if (registry.size === 0) registeredAsyncStartupStoreCleanupCallbacks.delete(adapter);
|
|
841
|
+
}
|
|
842
|
+
var ManagedAsyncStorageAdapter = class {
|
|
843
|
+
kind = "async";
|
|
844
|
+
#driver;
|
|
845
|
+
#cachedNamespaceIndexReads = createCache({ maxCacheSize: ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE });
|
|
846
|
+
#cachedPayloadReads = createCache({ maxCacheSize: ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE });
|
|
847
|
+
#namespaceReadCacheGenerations = /* @__PURE__ */ new Map();
|
|
848
|
+
#observedScopes = /* @__PURE__ */ new Map();
|
|
849
|
+
#pendingNamespaceCommits = /* @__PURE__ */ new Map();
|
|
850
|
+
#readCacheGeneration = 0;
|
|
851
|
+
#recentTouchedBuckets = /* @__PURE__ */ new Map();
|
|
852
|
+
#startupCleanupScheduled = false;
|
|
853
|
+
constructor(driver) {
|
|
854
|
+
this.#driver = driver;
|
|
855
|
+
registerAsyncStorageReadCacheParticipant(this);
|
|
856
|
+
}
|
|
857
|
+
async #runWithSessionWriterLock(sessionKey, callback) {
|
|
858
|
+
return runWithNavigatorLock(`${ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX}${sessionKey}`, ASYNC_STORAGE_WRITER_LOCK_WARNING, callback);
|
|
859
|
+
}
|
|
860
|
+
openNamespace(scope) {
|
|
861
|
+
this.#observedScopes.set(getNamespaceId(scope), scope);
|
|
862
|
+
this.#scheduleStartupCleanupIfNeeded();
|
|
863
|
+
return new ManagedAsyncStorageNamespaceHandle(this, scope);
|
|
864
|
+
}
|
|
865
|
+
async clearSession(sessionKey) {
|
|
866
|
+
await this.#runWithSessionWriterLock(sessionKey, async () => {
|
|
867
|
+
await this.#flushPendingNamespaceCommitsForSessionUnlocked(sessionKey);
|
|
868
|
+
const scopesToClear = await this.#listDiscoveredScopes(sessionKey);
|
|
869
|
+
await Promise.all(scopesToClear.map((scope) => this.#clearManagedNamespaceUnlocked(scope)));
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
async readProtectedStorageKeys(sessionKey, driver = this.#driver) {
|
|
873
|
+
const protectedKeysSnapshot = getSessionProtectedKeysSnapshot(sessionKey);
|
|
874
|
+
if (protectedKeysSnapshot !== null && protectedKeysSnapshot.size > 0) return new Set(protectedKeysSnapshot);
|
|
875
|
+
const managedCapabilities = getManagedDriverCapabilities(driver);
|
|
876
|
+
if (managedCapabilities?.readProtectedStorageKeys !== void 0) return new Set(await managedCapabilities.readProtectedStorageKeys(sessionKey));
|
|
877
|
+
const discovered = await this.#listDiscoveredCleanupScopes(driver, sessionKey);
|
|
878
|
+
const protectedRefSets = await Promise.all(discovered.map(async ({ knownRecordKeys, scope }) => {
|
|
879
|
+
const metadataEntries = await this.#listManagedMetadataUsingDriver(driver, scope, {
|
|
880
|
+
knownRecordKeys,
|
|
881
|
+
order: "key"
|
|
882
|
+
});
|
|
883
|
+
const refs = [];
|
|
884
|
+
for (const entry of metadataEntries) if (isOfflineProtectedMetadata(entry.customMetadata)) refs.push(serializeProtectedRef({
|
|
885
|
+
...scope,
|
|
886
|
+
key: entry.key
|
|
887
|
+
}));
|
|
888
|
+
return refs;
|
|
889
|
+
}));
|
|
890
|
+
return new Set(protectedRefSets.flat());
|
|
891
|
+
}
|
|
892
|
+
async syncSessionProtectedKeys(sessionKey, protectedKeys, previousProtectedKeys = []) {
|
|
893
|
+
const nextProtectedRefSet = new Set(protectedKeys);
|
|
894
|
+
const previousProtectedRefSet = new Set(previousProtectedKeys);
|
|
895
|
+
const changedProtectedRefs = [...[...nextProtectedRefSet].filter((entryRef) => !previousProtectedRefSet.has(entryRef)), ...[...previousProtectedRefSet].filter((entryRef) => !nextProtectedRefSet.has(entryRef))];
|
|
896
|
+
if (changedProtectedRefs.length === 0) return;
|
|
897
|
+
const updatesByScope = /* @__PURE__ */ new Map();
|
|
898
|
+
for (const entryRef of changedProtectedRefs) {
|
|
899
|
+
const parsedRef = parseProtectedRef(entryRef);
|
|
900
|
+
if (parsedRef === null || parsedRef.sessionKey !== sessionKey) continue;
|
|
901
|
+
const scope = {
|
|
902
|
+
sessionKey: parsedRef.sessionKey,
|
|
903
|
+
storeName: parsedRef.storeName,
|
|
904
|
+
kind: parsedRef.kind
|
|
905
|
+
};
|
|
906
|
+
const namespaceId = getNamespaceId(scope);
|
|
907
|
+
const existingScopeUpdate = updatesByScope.get(namespaceId);
|
|
908
|
+
if (existingScopeUpdate !== void 0) {
|
|
909
|
+
existingScopeUpdate.protectionByKey.set(parsedRef.key, nextProtectedRefSet.has(entryRef));
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
updatesByScope.set(namespaceId, {
|
|
913
|
+
scope,
|
|
914
|
+
protectionByKey: new Map([[parsedRef.key, nextProtectedRefSet.has(entryRef)]])
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
await this.#runWithSessionWriterLock(sessionKey, async () => {
|
|
918
|
+
await this.#flushPendingNamespaceCommitsForSessionUnlocked(sessionKey);
|
|
919
|
+
const managedCapabilities = getManagedDriverCapabilities(this.#driver);
|
|
920
|
+
if (managedCapabilities?.syncSessionProtectedKeys !== void 0) {
|
|
921
|
+
await managedCapabilities.syncSessionProtectedKeys(sessionKey, nextProtectedRefSet);
|
|
922
|
+
for (const { scope } of updatesByScope.values()) {
|
|
923
|
+
this.#invalidateCachedNamespace(scope);
|
|
924
|
+
this.#broadcastNamespaceInvalidation(scope, "commit");
|
|
925
|
+
}
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
await Promise.all([...updatesByScope.values()].map(async ({ scope, protectionByKey }) => {
|
|
929
|
+
const indexState = await this.#readNamespaceIndexStateUsingDriver(this.#driver, scope);
|
|
930
|
+
const indexEntries = indexState.valid && indexState.entries !== null ? indexState.entries : /* @__PURE__ */ new Map();
|
|
931
|
+
let changed = false;
|
|
932
|
+
for (const [key, shouldProtect] of protectionByKey.entries()) {
|
|
933
|
+
const existingMetadata = indexEntries.get(key);
|
|
934
|
+
if (existingMetadata === void 0) continue;
|
|
935
|
+
if (isOfflineProtectedMetadata(existingMetadata.customMetadata) === shouldProtect) continue;
|
|
936
|
+
const nextCustomMetadata = setOfflineProtectionMetadata(existingMetadata.customMetadata, shouldProtect);
|
|
937
|
+
const nextMetadata = { ...existingMetadata };
|
|
938
|
+
if (nextCustomMetadata !== void 0) nextMetadata.customMetadata = nextCustomMetadata;
|
|
939
|
+
else delete nextMetadata.customMetadata;
|
|
940
|
+
indexEntries.set(key, nextMetadata);
|
|
941
|
+
changed = true;
|
|
942
|
+
}
|
|
943
|
+
if (changed) {
|
|
944
|
+
await this.#persistNamespaceIndexUsingDriver(this.#driver, scope, {
|
|
945
|
+
entries: indexEntries,
|
|
946
|
+
staticPolicy: normalizeStaticPolicy(indexState.staticPolicy)
|
|
947
|
+
});
|
|
948
|
+
this.#invalidateCachedNamespace(scope);
|
|
949
|
+
this.#broadcastNamespaceInvalidation(scope, "commit");
|
|
950
|
+
}
|
|
951
|
+
}));
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
resetForTests() {
|
|
955
|
+
for (const pending of this.#pendingNamespaceCommits.values()) pending.cancelFlush?.();
|
|
956
|
+
this.clearAllCachedReads();
|
|
957
|
+
this.#namespaceReadCacheGenerations.clear();
|
|
958
|
+
this.#observedScopes.clear();
|
|
959
|
+
this.#pendingNamespaceCommits.clear();
|
|
960
|
+
this.#recentTouchedBuckets.clear();
|
|
961
|
+
this.#startupCleanupScheduled = false;
|
|
962
|
+
this.#driver.__resetForTests?.();
|
|
963
|
+
}
|
|
964
|
+
shouldEnqueueTouch(scope, key, lastAccessAt, touchMode, now) {
|
|
965
|
+
if (touchMode === "never") return false;
|
|
966
|
+
const currentBucket = getBucketId(now);
|
|
967
|
+
if (touchMode !== "force" && getBucketId(lastAccessAt) === currentBucket) return false;
|
|
968
|
+
const namespaceKey = getNamespaceId(scope);
|
|
969
|
+
const touchGuardKey = `${namespaceKey}::${key}`;
|
|
970
|
+
if (this.#recentTouchedBuckets.get(touchGuardKey) === currentBucket) return false;
|
|
971
|
+
const pendingTouch = this.#pendingNamespaceCommits.get(namespaceKey)?.touches.get(key);
|
|
972
|
+
return pendingTouch === void 0 || getBucketId(pendingTouch) !== currentBucket;
|
|
973
|
+
}
|
|
974
|
+
#hasPendingBarrierForKeys(pending, keys) {
|
|
975
|
+
return keys.some((key) => {
|
|
976
|
+
return pending.upserts.has(key) || pending.removes.has(key) || pending.inFlightBarrierKeys?.has(key) === true;
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
async queueCommitToNamespace(scope, args) {
|
|
980
|
+
const pending = this.#getOrCreatePendingNamespaceCommit(scope);
|
|
981
|
+
const now = Date.now();
|
|
982
|
+
for (const touch of args.touches ?? []) pending.touches.set(touch.key, touch.lastAccessAt ?? now);
|
|
983
|
+
for (const remove of args.removes ?? []) {
|
|
984
|
+
pending.upserts.delete(remove);
|
|
985
|
+
pending.touches.delete(remove);
|
|
986
|
+
pending.removes.add(remove);
|
|
987
|
+
}
|
|
988
|
+
if ("staticPolicy" in args) {
|
|
989
|
+
pending.hasStaticPolicyUpdate = true;
|
|
990
|
+
pending.staticPolicy = args.staticPolicy ?? null;
|
|
991
|
+
}
|
|
992
|
+
for (const upsert of args.upserts ?? []) {
|
|
993
|
+
pending.removes.delete(upsert.key);
|
|
994
|
+
pending.upserts.set(upsert.key, __LEGIT_CAST__(upsert));
|
|
995
|
+
}
|
|
996
|
+
this.#schedulePendingNamespaceFlush(pending);
|
|
997
|
+
return new Promise((resolve, reject) => {
|
|
998
|
+
pending.waiters.push({
|
|
999
|
+
resolve,
|
|
1000
|
+
reject
|
|
1001
|
+
});
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
async flushPendingNamespaceCommit(scope, keys) {
|
|
1005
|
+
const namespaceKey = getNamespaceId(scope);
|
|
1006
|
+
const pending = this.#pendingNamespaceCommits.get(namespaceKey);
|
|
1007
|
+
if (!pending) return;
|
|
1008
|
+
if (keys !== void 0 && keys.length > 0 && !this.#hasPendingBarrierForKeys(pending, keys)) return;
|
|
1009
|
+
await this.#runWithSessionWriterLock(scope.sessionKey, async () => {
|
|
1010
|
+
await this.#flushPendingNamespaceCommitUnlocked(scope, keys);
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
async #flushPendingNamespaceCommitUnlocked(scope, keys) {
|
|
1014
|
+
const namespaceKey = getNamespaceId(scope);
|
|
1015
|
+
const pending = this.#pendingNamespaceCommits.get(namespaceKey);
|
|
1016
|
+
if (!pending) return;
|
|
1017
|
+
if (keys !== void 0 && keys.length > 0 && !this.#hasPendingBarrierForKeys(pending, keys)) return;
|
|
1018
|
+
if (pending.flushPromise) {
|
|
1019
|
+
await pending.flushPromise;
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
pending.cancelFlush?.();
|
|
1023
|
+
pending.cancelFlush = null;
|
|
1024
|
+
const upserts = [...pending.upserts.values()];
|
|
1025
|
+
const removes = [...pending.removes];
|
|
1026
|
+
const hasStaticPolicyUpdate = pending.hasStaticPolicyUpdate;
|
|
1027
|
+
const staticPolicy = pending.staticPolicy;
|
|
1028
|
+
const touches = [...pending.touches.entries()].map(([key, lastAccessAt]) => ({
|
|
1029
|
+
key,
|
|
1030
|
+
lastAccessAt
|
|
1031
|
+
}));
|
|
1032
|
+
const inFlightBarrierKeys = new Set([...pending.upserts.keys(), ...pending.removes]);
|
|
1033
|
+
const waiters = [...pending.waiters];
|
|
1034
|
+
pending.hasStaticPolicyUpdate = false;
|
|
1035
|
+
pending.upserts = /* @__PURE__ */ new Map();
|
|
1036
|
+
pending.removes = /* @__PURE__ */ new Set();
|
|
1037
|
+
pending.staticPolicy = null;
|
|
1038
|
+
pending.touches = /* @__PURE__ */ new Map();
|
|
1039
|
+
pending.waiters = [];
|
|
1040
|
+
pending.inFlightBarrierKeys = inFlightBarrierKeys.size > 0 ? inFlightBarrierKeys : null;
|
|
1041
|
+
if (upserts.length === 0 && removes.length === 0 && touches.length === 0 && !hasStaticPolicyUpdate) {
|
|
1042
|
+
this.#pendingNamespaceCommits.delete(namespaceKey);
|
|
1043
|
+
for (const waiter of waiters) waiter.resolve();
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
pending.flushPromise = this.#applyManagedCommit(scope, {
|
|
1047
|
+
upserts,
|
|
1048
|
+
removes,
|
|
1049
|
+
...hasStaticPolicyUpdate ? { staticPolicy } : {},
|
|
1050
|
+
touches
|
|
1051
|
+
}).then(() => {
|
|
1052
|
+
const currentBucket = getBucketId(Date.now());
|
|
1053
|
+
for (const touch of touches) this.#recentTouchedBuckets.set(`${namespaceKey}::${touch.key}`, getBucketId(touch.lastAccessAt));
|
|
1054
|
+
for (const upsert of upserts) this.#recentTouchedBuckets.set(`${namespaceKey}::${upsert.key}`, currentBucket);
|
|
1055
|
+
this.#pruneRecentTouchedBuckets(currentBucket);
|
|
1056
|
+
for (const waiter of waiters) waiter.resolve();
|
|
1057
|
+
}).catch((error) => {
|
|
1058
|
+
for (const waiter of waiters) waiter.reject(error);
|
|
1059
|
+
throw error;
|
|
1060
|
+
}).finally(() => {
|
|
1061
|
+
pending.inFlightBarrierKeys = null;
|
|
1062
|
+
pending.flushPromise = null;
|
|
1063
|
+
if (pending.waiters.length === 0) {
|
|
1064
|
+
this.#pendingNamespaceCommits.delete(namespaceKey);
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
this.#schedulePendingNamespaceFlush(pending);
|
|
1068
|
+
});
|
|
1069
|
+
await pending.flushPromise;
|
|
1070
|
+
}
|
|
1071
|
+
async flushAllPendingNamespaceCommits() {
|
|
1072
|
+
await Promise.all([...this.#pendingNamespaceCommits.values()].map((pending) => this.flushPendingNamespaceCommit(pending.scope)));
|
|
1073
|
+
}
|
|
1074
|
+
async #flushPendingNamespaceCommitsForSessionUnlocked(sessionKey) {
|
|
1075
|
+
await Promise.all([...this.#pendingNamespaceCommits.values()].filter((pending) => pending.scope.sessionKey === sessionKey).map((pending) => this.#flushPendingNamespaceCommitUnlocked(pending.scope)));
|
|
1076
|
+
}
|
|
1077
|
+
clearRecentTouchedBucketsForNamespace(scope) {
|
|
1078
|
+
const keyPrefix = `${getNamespaceId(scope)}::`;
|
|
1079
|
+
for (const key of this.#recentTouchedBuckets.keys()) if (key.startsWith(keyPrefix)) this.#recentTouchedBuckets.delete(key);
|
|
1080
|
+
}
|
|
1081
|
+
async #readNamespaceIndexEntriesUsingDriver(driver, scope, knownRecordKeys) {
|
|
1082
|
+
const state = await this.#readNamespaceIndexStateUsingDriver(driver, scope, { knownRecordKeys });
|
|
1083
|
+
return state.valid && state.entries !== null ? state.entries : /* @__PURE__ */ new Map();
|
|
1084
|
+
}
|
|
1085
|
+
async #readNamespaceIndexStaticPolicyUsingDriver(driver, scope, knownRecordKeys) {
|
|
1086
|
+
const state = await this.#readNamespaceIndexStateUsingDriver(driver, scope, { knownRecordKeys });
|
|
1087
|
+
return state.valid ? normalizeStaticPolicy(state.staticPolicy) : null;
|
|
1088
|
+
}
|
|
1089
|
+
async #readNamespaceIndexStateUsingDriver(driver, scope, args = {}) {
|
|
1090
|
+
const knownRecordKeys = args.knownRecordKeys;
|
|
1091
|
+
const namespaceKey = getNamespaceId(scope);
|
|
1092
|
+
const shouldUseCache = driver === this.#driver;
|
|
1093
|
+
if (knownRecordKeys != null) {
|
|
1094
|
+
if (!knownRecordKeys.includes("_i")) {
|
|
1095
|
+
this.#invalidateCachedNamespace(scope);
|
|
1096
|
+
return {
|
|
1097
|
+
entries: null,
|
|
1098
|
+
exists: false,
|
|
1099
|
+
staticPolicy: null,
|
|
1100
|
+
valid: true
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
if (shouldUseCache) {
|
|
1104
|
+
const existing = await this.#cachedNamespaceIndexReads.getAsync(namespaceKey);
|
|
1105
|
+
if (existing !== void 0) return cloneNamespaceIndexReadState(existing);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
if (!shouldUseCache) return readAsyncStorageNamespaceIndexStateUsingDriver(driver, scope, knownRecordKeys);
|
|
1109
|
+
const cacheGeneration = this.#getReadCacheGenerationSnapshot(scope);
|
|
1110
|
+
return cloneNamespaceIndexReadState(await this.#cachedNamespaceIndexReads.getOrInsertAsync(namespaceKey, async ({ skipCaching }) => {
|
|
1111
|
+
const nextState = await readAsyncStorageNamespaceIndexStateUsingDriver(driver, scope, knownRecordKeys);
|
|
1112
|
+
if (!this.#isReadCacheGenerationSnapshotCurrent(cacheGeneration)) return skipCaching(nextState);
|
|
1113
|
+
return this.#shouldCacheNamespaceIndexState(nextState) ? cloneNamespaceIndexReadState(nextState) : skipCaching(nextState);
|
|
1114
|
+
}));
|
|
1115
|
+
}
|
|
1116
|
+
async #persistNamespaceIndexUsingDriver(driver, scope, state, advanceGeneration = true) {
|
|
1117
|
+
if (advanceGeneration) this.#advanceNamespaceReadCacheGeneration(scope);
|
|
1118
|
+
const managedCapabilities = getManagedDriverCapabilities(driver);
|
|
1119
|
+
if (managedCapabilities?.persistNamespaceIndexState !== void 0) {
|
|
1120
|
+
await managedCapabilities.persistNamespaceIndexState(scope, state);
|
|
1121
|
+
if (state.entries.size === 0) this.#invalidateCachedNamespaceIndexState(scope);
|
|
1122
|
+
else this.#setCachedNamespaceIndexState(scope, {
|
|
1123
|
+
entries: state.entries,
|
|
1124
|
+
exists: true,
|
|
1125
|
+
staticPolicy: state.staticPolicy,
|
|
1126
|
+
valid: true
|
|
1127
|
+
});
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (state.entries.size === 0) {
|
|
1131
|
+
await this.#driverRemoveManyFrom(driver, scope, ["_i"]);
|
|
1132
|
+
this.#invalidateCachedNamespaceIndexState(scope);
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
await this.#driverSetManyFrom(driver, scope, [{
|
|
1136
|
+
key: "_i",
|
|
1137
|
+
value: serializeIndexState(state)
|
|
1138
|
+
}]);
|
|
1139
|
+
this.#setCachedNamespaceIndexState(scope, {
|
|
1140
|
+
entries: state.entries,
|
|
1141
|
+
exists: true,
|
|
1142
|
+
staticPolicy: state.staticPolicy,
|
|
1143
|
+
valid: true
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
async readManagedEntries(scope, keys) {
|
|
1147
|
+
const managedCapabilities = getManagedDriverCapabilities(this.#driver);
|
|
1148
|
+
if (managedCapabilities?.readManagedEntries !== void 0) return __LEGIT_CAST__(await managedCapabilities.readManagedEntries(scope, keys));
|
|
1149
|
+
const metadataByKey = await this.#readNamespaceIndexEntriesUsingDriver(this.#driver, scope);
|
|
1150
|
+
const payloadKeys = keys.filter((key) => metadataByKey.has(key));
|
|
1151
|
+
const payloadValues = await this.#readPayloadValuesUsingDriver(this.#driver, scope, payloadKeys);
|
|
1152
|
+
const payloadByKey = /* @__PURE__ */ new Map();
|
|
1153
|
+
for (const [index, key] of payloadKeys.entries()) payloadByKey.set(key, payloadValues[index] ?? null);
|
|
1154
|
+
const result = /* @__PURE__ */ new Map();
|
|
1155
|
+
const orphanedKeys = [];
|
|
1156
|
+
for (const key of keys) {
|
|
1157
|
+
const metadata = metadataByKey.get(key);
|
|
1158
|
+
if (metadata === void 0) {
|
|
1159
|
+
result.set(key, null);
|
|
1160
|
+
continue;
|
|
1161
|
+
}
|
|
1162
|
+
const rawPayload = payloadByKey.get(key) ?? null;
|
|
1163
|
+
if (rawPayload === null) {
|
|
1164
|
+
orphanedKeys.push(key);
|
|
1165
|
+
result.set(key, null);
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
result.set(key, {
|
|
1169
|
+
value: __LEGIT_CAST__(rawPayload),
|
|
1170
|
+
metadata: __LEGIT_CAST__(this.#toPublicMetadata(key, metadata))
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
if (orphanedKeys.length > 0) await this.#removeManagedKeysUsingDriver(this.#driver, scope, orphanedKeys);
|
|
1174
|
+
return result;
|
|
1175
|
+
}
|
|
1176
|
+
async listManagedMetadata(scope, args = {}) {
|
|
1177
|
+
return this.#listManagedMetadataUsingDriver(this.#driver, scope, args);
|
|
1178
|
+
}
|
|
1179
|
+
async #listManagedMetadataUsingDriver(driver, scope, args = {}) {
|
|
1180
|
+
const managedCapabilities = getManagedDriverCapabilities(driver);
|
|
1181
|
+
if (managedCapabilities?.listManagedMetadata !== void 0) return __LEGIT_CAST__(await managedCapabilities.listManagedMetadata(scope, args));
|
|
1182
|
+
const metadataEntries = await this.#readNamespaceIndexEntriesUsingDriver(driver, scope, args.knownRecordKeys);
|
|
1183
|
+
const validEntries = [];
|
|
1184
|
+
for (const [key, metadata] of metadataEntries.entries()) validEntries.push(this.#toPublicMetadata(key, metadata));
|
|
1185
|
+
if (args.filter !== void 0) {
|
|
1186
|
+
const { filter } = args;
|
|
1187
|
+
return __LEGIT_CAST__(validEntries.filter((entry) => entry.customMetadata[filter.key] === filter.equals).sort((left, right) => compareMetadata(left, right, args.order ?? "key")));
|
|
1188
|
+
}
|
|
1189
|
+
validEntries.sort((left, right) => compareMetadata(left, right, args.order ?? "key"));
|
|
1190
|
+
return __LEGIT_CAST__(validEntries);
|
|
1191
|
+
}
|
|
1192
|
+
async listManagedKeys(scope) {
|
|
1193
|
+
const managedCapabilities = getManagedDriverCapabilities(this.#driver);
|
|
1194
|
+
if (managedCapabilities?.listManagedKeys !== void 0) return managedCapabilities.listManagedKeys(scope);
|
|
1195
|
+
return [...(await this.#readNamespaceIndexEntriesUsingDriver(this.#driver, scope)).keys()].sort((left, right) => left.localeCompare(right));
|
|
1196
|
+
}
|
|
1197
|
+
async clearManagedNamespace(scope) {
|
|
1198
|
+
await this.#runWithSessionWriterLock(scope.sessionKey, async () => {
|
|
1199
|
+
await this.#clearManagedNamespaceUnlocked(scope);
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
async #clearManagedNamespaceUnlocked(scope) {
|
|
1203
|
+
const managedCapabilities = getManagedDriverCapabilities(this.#driver);
|
|
1204
|
+
if (managedCapabilities?.clearManagedNamespace !== void 0) await managedCapabilities.clearManagedNamespace(scope);
|
|
1205
|
+
else await this.#driver.clear(scope);
|
|
1206
|
+
this.#invalidateCachedNamespace(scope);
|
|
1207
|
+
this.#broadcastNamespaceInvalidation(scope, "clear");
|
|
1208
|
+
const namespaceKey = getNamespaceId(scope);
|
|
1209
|
+
this.#observedScopes.delete(namespaceKey);
|
|
1210
|
+
this.#pendingNamespaceCommits.delete(namespaceKey);
|
|
1211
|
+
this.clearRecentTouchedBucketsForNamespace(scope);
|
|
1212
|
+
}
|
|
1213
|
+
#toPublicMetadata(key, metadata) {
|
|
1214
|
+
return {
|
|
1215
|
+
key,
|
|
1216
|
+
payloadRef: getPayloadRecordKey(key),
|
|
1217
|
+
writtenAt: metadata.lastAccessAt,
|
|
1218
|
+
lastAccessAt: metadata.lastAccessAt,
|
|
1219
|
+
sizeBytes: metadata.sizeBytes,
|
|
1220
|
+
version: metadata.version,
|
|
1221
|
+
customMetadata: metadata.customMetadata ?? {}
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
async #applyManagedCommit(scope, args) {
|
|
1225
|
+
const upserts = args.upserts ?? [];
|
|
1226
|
+
const removes = [...new Set(args.removes ?? [])];
|
|
1227
|
+
const touches = args.touches ?? [];
|
|
1228
|
+
const touchedKeys = [...new Set(touches.map((touch) => touch.key))];
|
|
1229
|
+
const managedCapabilities = getManagedDriverCapabilities(this.#driver);
|
|
1230
|
+
if (managedCapabilities?.applyManagedCommit !== void 0) {
|
|
1231
|
+
await managedCapabilities.applyManagedCommit(scope, args, { mergeOfflineProtectionMetadata: (key, nextCustomMetadata, currentCustomMetadata) => mergeManagedAsyncStorageCustomMetadata({
|
|
1232
|
+
currentCustomMetadata,
|
|
1233
|
+
key,
|
|
1234
|
+
nextCustomMetadata,
|
|
1235
|
+
protectedKeysSnapshotSet: getSessionProtectedKeysSnapshot(scope.sessionKey),
|
|
1236
|
+
scope
|
|
1237
|
+
}) });
|
|
1238
|
+
this.#advanceNamespaceReadCacheGeneration(scope);
|
|
1239
|
+
this.#invalidateCachedNamespaceIndexState(scope);
|
|
1240
|
+
for (const key of removes) this.#invalidateCachedPayloadValue(scope, key);
|
|
1241
|
+
for (const upsert of upserts) this.#setCachedPayloadValue(scope, upsert.key, { value: upsert.value });
|
|
1242
|
+
this.#broadcastNamespaceInvalidation(scope, "commit");
|
|
1243
|
+
return;
|
|
1244
|
+
}
|
|
1245
|
+
const currentIndexState = await this.#readNamespaceIndexStateUsingDriver(this.#driver, scope);
|
|
1246
|
+
const indexEntries = currentIndexState.valid && currentIndexState.entries !== null ? currentIndexState.entries : /* @__PURE__ */ new Map();
|
|
1247
|
+
const now = Date.now();
|
|
1248
|
+
const touchesByKey = new Map(touches.map((touch) => [touch.key, touch.lastAccessAt ?? now]));
|
|
1249
|
+
const setEntries = [];
|
|
1250
|
+
const removeEntries = removes.map((key) => getPayloadRecordKey(key));
|
|
1251
|
+
let indexChanged = false;
|
|
1252
|
+
let nextStaticPolicy = normalizeStaticPolicy(currentIndexState.staticPolicy);
|
|
1253
|
+
for (const key of removes) indexChanged = indexEntries.delete(key) || indexChanged;
|
|
1254
|
+
if ("staticPolicy" in args) {
|
|
1255
|
+
const normalizedNextStaticPolicy = normalizeStaticPolicy(args.staticPolicy ?? null);
|
|
1256
|
+
if (!deepEqual(nextStaticPolicy, normalizedNextStaticPolicy)) {
|
|
1257
|
+
nextStaticPolicy = normalizedNextStaticPolicy;
|
|
1258
|
+
indexChanged = true;
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
const protectedKeysSnapshotSet = getSessionProtectedKeysSnapshot(scope.sessionKey);
|
|
1262
|
+
for (const upsert of upserts) {
|
|
1263
|
+
const existingMetadata = indexEntries.get(upsert.key);
|
|
1264
|
+
const customMetadata = mergeManagedAsyncStorageCustomMetadata({
|
|
1265
|
+
currentCustomMetadata: existingMetadata?.customMetadata,
|
|
1266
|
+
key: upsert.key,
|
|
1267
|
+
nextCustomMetadata: upsert.metadata,
|
|
1268
|
+
protectedKeysSnapshotSet,
|
|
1269
|
+
scope
|
|
1270
|
+
});
|
|
1271
|
+
const nextLastAccessAt = touchesByKey.get(upsert.key) ?? existingMetadata?.lastAccessAt ?? now;
|
|
1272
|
+
const serializedValue = upsert.serializedValue !== void 0 ? { rawValue: upsert.serializedValue } : serializeJsonForStorage(upsert.value);
|
|
1273
|
+
const nextSizeBytes = scope.kind !== "document" ? estimateManagedAsyncStorageEntrySizeBytes({
|
|
1274
|
+
customMetadata,
|
|
1275
|
+
lastAccessAt: nextLastAccessAt,
|
|
1276
|
+
serializedValue: serializedValue.rawValue,
|
|
1277
|
+
version: upsert.version
|
|
1278
|
+
}) : void 0;
|
|
1279
|
+
const nextMetadata = {
|
|
1280
|
+
lastAccessAt: nextLastAccessAt,
|
|
1281
|
+
version: upsert.version,
|
|
1282
|
+
...nextSizeBytes !== void 0 ? { sizeBytes: nextSizeBytes } : {},
|
|
1283
|
+
...customMetadata ? { customMetadata } : {}
|
|
1284
|
+
};
|
|
1285
|
+
setEntries.push({
|
|
1286
|
+
key: getPayloadRecordKey(upsert.key),
|
|
1287
|
+
serializedValue: serializedValue.rawValue,
|
|
1288
|
+
...nextSizeBytes !== void 0 ? { sizeBytes: nextSizeBytes } : {},
|
|
1289
|
+
value: upsert.value
|
|
1290
|
+
});
|
|
1291
|
+
if (existingMetadata !== void 0 && existingMetadata.lastAccessAt === nextMetadata.lastAccessAt && existingMetadata.sizeBytes === nextMetadata.sizeBytes && existingMetadata.version === nextMetadata.version && deepEqual(existingMetadata.customMetadata, nextMetadata.customMetadata)) continue;
|
|
1292
|
+
indexEntries.set(upsert.key, nextMetadata);
|
|
1293
|
+
indexChanged = true;
|
|
1294
|
+
}
|
|
1295
|
+
if (touchedKeys.length > 0) {
|
|
1296
|
+
const upsertKeySet = new Set(upserts.map((upsert) => upsert.key));
|
|
1297
|
+
for (const key of touchedKeys) {
|
|
1298
|
+
if (upsertKeySet.has(key)) continue;
|
|
1299
|
+
const metadata = indexEntries.get(key);
|
|
1300
|
+
if (!metadata) continue;
|
|
1301
|
+
const nextLastAccessAt = touchesByKey.get(key) ?? now;
|
|
1302
|
+
if (metadata.lastAccessAt === nextLastAccessAt) continue;
|
|
1303
|
+
indexEntries.set(key, {
|
|
1304
|
+
...metadata,
|
|
1305
|
+
lastAccessAt: nextLastAccessAt
|
|
1306
|
+
});
|
|
1307
|
+
indexChanged = true;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
await Promise.all([removeEntries.length > 0 ? this.#driverRemoveManyFrom(this.#driver, scope, removeEntries) : Promise.resolve(), setEntries.length > 0 ? this.#driverSetManyFrom(this.#driver, scope, setEntries) : Promise.resolve()]);
|
|
1311
|
+
this.#advanceNamespaceReadCacheGeneration(scope);
|
|
1312
|
+
for (const key of removes) this.#invalidateCachedPayloadValue(scope, key);
|
|
1313
|
+
for (const upsert of upserts) this.#setCachedPayloadValue(scope, upsert.key, { value: upsert.value });
|
|
1314
|
+
if (indexChanged) await this.#persistNamespaceIndexUsingDriver(this.#driver, scope, {
|
|
1315
|
+
entries: indexEntries,
|
|
1316
|
+
staticPolicy: nextStaticPolicy
|
|
1317
|
+
}, false);
|
|
1318
|
+
else this.#setCachedNamespaceIndexState(scope, {
|
|
1319
|
+
entries: currentIndexState.valid ? indexEntries : null,
|
|
1320
|
+
exists: currentIndexState.exists,
|
|
1321
|
+
staticPolicy: currentIndexState.staticPolicy,
|
|
1322
|
+
valid: currentIndexState.valid
|
|
1323
|
+
});
|
|
1324
|
+
this.#broadcastNamespaceInvalidation(scope, "commit");
|
|
1325
|
+
}
|
|
1326
|
+
async #removeManagedKeysUsingDriver(driver, scope, keys) {
|
|
1327
|
+
const uniqueKeys = [...new Set(keys)];
|
|
1328
|
+
if (uniqueKeys.length === 0) return;
|
|
1329
|
+
await this.#runWithSessionWriterLock(scope.sessionKey, async () => {
|
|
1330
|
+
const indexState = await this.#readNamespaceIndexStateUsingDriver(driver, scope);
|
|
1331
|
+
await this.#driverRemoveManyFrom(driver, scope, uniqueKeys.map((key) => getPayloadRecordKey(key)));
|
|
1332
|
+
for (const key of uniqueKeys) this.#invalidateCachedPayloadValue(scope, key);
|
|
1333
|
+
if (indexState.valid && indexState.entries !== null) {
|
|
1334
|
+
let changed = false;
|
|
1335
|
+
for (const key of uniqueKeys) changed = indexState.entries.delete(key) || changed;
|
|
1336
|
+
if (changed) await this.#persistNamespaceIndexUsingDriver(driver, scope, {
|
|
1337
|
+
entries: indexState.entries,
|
|
1338
|
+
staticPolicy: normalizeStaticPolicy(indexState.staticPolicy)
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
this.#broadcastNamespaceInvalidation(scope, "remove");
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
async #driverSetManyFrom(driver, scope, entries) {
|
|
1345
|
+
if (entries.length === 0) return;
|
|
1346
|
+
await driver.setMany(scope, entries);
|
|
1347
|
+
}
|
|
1348
|
+
async #driverRemoveManyFrom(driver, scope, keys) {
|
|
1349
|
+
if (keys.length === 0) return;
|
|
1350
|
+
await driver.removeMany(scope, keys);
|
|
1351
|
+
}
|
|
1352
|
+
#readMaintenanceState() {
|
|
1353
|
+
const raw = localStorage.getItem(ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY);
|
|
1354
|
+
if (raw === null) return createDefaultMaintenanceState();
|
|
1355
|
+
try {
|
|
1356
|
+
return parseMaintenanceState(JSON.parse(raw)) ?? createDefaultMaintenanceState();
|
|
1357
|
+
} catch {
|
|
1358
|
+
return createDefaultMaintenanceState();
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
#writeMaintenanceState(state) {
|
|
1362
|
+
localStorage.setItem(ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY, JSON.stringify({ lca: state.lastSuccessfulCleanupAt }));
|
|
1363
|
+
}
|
|
1364
|
+
clearAllCachedReads() {
|
|
1365
|
+
this.#readCacheGeneration += 1;
|
|
1366
|
+
this.#cachedNamespaceIndexReads.clear();
|
|
1367
|
+
this.#cachedPayloadReads.clear();
|
|
1368
|
+
}
|
|
1369
|
+
onRemoteCacheInvalidation(message) {
|
|
1370
|
+
this.#invalidateCachedNamespace(message.scope);
|
|
1371
|
+
}
|
|
1372
|
+
async #readPayloadValuesUsingDriver(driver, scope, keys) {
|
|
1373
|
+
if (keys.length === 0) return [];
|
|
1374
|
+
if (!(driver === this.#driver)) return driverGetManyFrom(driver, scope, keys.map((key) => getPayloadRecordKey(key)));
|
|
1375
|
+
const cacheGeneration = this.#getReadCacheGenerationSnapshot(scope);
|
|
1376
|
+
const promisesByKey = /* @__PURE__ */ new Map();
|
|
1377
|
+
const uncachedKeys = [];
|
|
1378
|
+
for (const key of keys) {
|
|
1379
|
+
const payloadCacheKey = this.#getPayloadCacheKey(scope, key);
|
|
1380
|
+
if (this.#cachedPayloadReads.has(payloadCacheKey)) {
|
|
1381
|
+
promisesByKey.set(key, this.#cachedPayloadReads.getAsync(payloadCacheKey).then((state) => state ?? null));
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
uncachedKeys.push(key);
|
|
1385
|
+
}
|
|
1386
|
+
if (uncachedKeys.length > 0) {
|
|
1387
|
+
const readPromise = driverGetManyFrom(driver, scope, uncachedKeys.map((key) => getPayloadRecordKey(key)));
|
|
1388
|
+
for (const [index, key] of uncachedKeys.entries()) {
|
|
1389
|
+
const payloadCacheKey = this.#getPayloadCacheKey(scope, key);
|
|
1390
|
+
const keyPromise = this.#cachedPayloadReads.setAsync(payloadCacheKey, async ({ skipCaching }) => {
|
|
1391
|
+
const value = (await readPromise)[index] ?? null;
|
|
1392
|
+
const nextState = value === null ? null : { value: klona(value) };
|
|
1393
|
+
if (!this.#isReadCacheGenerationSnapshotCurrent(cacheGeneration)) return skipCaching(nextState);
|
|
1394
|
+
return nextState === null ? skipCaching(null) : nextState;
|
|
1395
|
+
});
|
|
1396
|
+
promisesByKey.set(key, keyPromise);
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
return Promise.all(keys.map(async (key) => {
|
|
1400
|
+
const state = await promisesByKey.get(key);
|
|
1401
|
+
return state === null || state === void 0 ? null : klona(state.value);
|
|
1402
|
+
}));
|
|
1403
|
+
}
|
|
1404
|
+
#setCachedNamespaceIndexState(scope, state) {
|
|
1405
|
+
if (!this.#shouldCacheNamespaceIndexState(state)) {
|
|
1406
|
+
this.#cachedNamespaceIndexReads.delete(getNamespaceId(scope));
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
this.#cachedNamespaceIndexReads.set(getNamespaceId(scope), cloneNamespaceIndexReadState(state));
|
|
1410
|
+
}
|
|
1411
|
+
#setCachedPayloadValue(scope, key, state) {
|
|
1412
|
+
this.#cachedPayloadReads.set(this.#getPayloadCacheKey(scope, key), { value: klona(state.value) });
|
|
1413
|
+
}
|
|
1414
|
+
#invalidateCachedNamespaceIndexState(scope) {
|
|
1415
|
+
this.#cachedNamespaceIndexReads.delete(getNamespaceId(scope));
|
|
1416
|
+
}
|
|
1417
|
+
#invalidateCachedPayloadValue(scope, key) {
|
|
1418
|
+
this.#cachedPayloadReads.delete(this.#getPayloadCacheKey(scope, key));
|
|
1419
|
+
}
|
|
1420
|
+
#invalidateCachedNamespace(scope) {
|
|
1421
|
+
const namespaceKey = `${getNamespaceId(scope)}::`;
|
|
1422
|
+
this.#advanceNamespaceReadCacheGeneration(scope);
|
|
1423
|
+
this.#invalidateCachedNamespaceIndexState(scope);
|
|
1424
|
+
for (const key of this.#cachedPayloadReads[" cache"].map.keys()) if (key.startsWith(namespaceKey)) this.#cachedPayloadReads.delete(key);
|
|
1425
|
+
}
|
|
1426
|
+
#getPayloadCacheKey(scope, key) {
|
|
1427
|
+
return `${getNamespaceId(scope)}::${key}`;
|
|
1428
|
+
}
|
|
1429
|
+
#getNamespaceReadCacheGeneration(namespaceId) {
|
|
1430
|
+
return this.#namespaceReadCacheGenerations.get(namespaceId) ?? 0;
|
|
1431
|
+
}
|
|
1432
|
+
#advanceNamespaceReadCacheGeneration(scope) {
|
|
1433
|
+
const namespaceId = getNamespaceId(scope);
|
|
1434
|
+
this.#namespaceReadCacheGenerations.set(namespaceId, this.#getNamespaceReadCacheGeneration(namespaceId) + 1);
|
|
1435
|
+
}
|
|
1436
|
+
#getReadCacheGenerationSnapshot(scope) {
|
|
1437
|
+
const namespaceId = getNamespaceId(scope);
|
|
1438
|
+
return {
|
|
1439
|
+
globalGeneration: this.#readCacheGeneration,
|
|
1440
|
+
namespaceGeneration: this.#getNamespaceReadCacheGeneration(namespaceId),
|
|
1441
|
+
namespaceId
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
#isReadCacheGenerationSnapshotCurrent(snapshot) {
|
|
1445
|
+
return snapshot.globalGeneration === this.#readCacheGeneration && snapshot.namespaceGeneration === this.#getNamespaceReadCacheGeneration(snapshot.namespaceId);
|
|
1446
|
+
}
|
|
1447
|
+
#shouldCacheNamespaceIndexState(state) {
|
|
1448
|
+
return state.valid && state.exists && state.entries !== null;
|
|
1449
|
+
}
|
|
1450
|
+
#broadcastNamespaceInvalidation(scope, reason) {
|
|
1451
|
+
const message = {
|
|
1452
|
+
kind: "namespace-invalidated",
|
|
1453
|
+
protocolVersion: 1,
|
|
1454
|
+
reason,
|
|
1455
|
+
scope
|
|
1456
|
+
};
|
|
1457
|
+
notifyLocalAsyncStorageReadCacheInvalidation(this, message);
|
|
1458
|
+
asyncStorageCacheInvalidationChannel?.postMessage(message);
|
|
1459
|
+
}
|
|
1460
|
+
async #listDiscoveredScopes(sessionKey, driver = this.#driver) {
|
|
1461
|
+
return (await driver.listScopes(sessionKey)).filter((scope) => scope.kind !== "__internal.protected");
|
|
1462
|
+
}
|
|
1463
|
+
#getOrCreatePendingNamespaceCommit(scope) {
|
|
1464
|
+
const namespaceKey = getNamespaceId(scope);
|
|
1465
|
+
const existing = this.#pendingNamespaceCommits.get(namespaceKey);
|
|
1466
|
+
if (existing) return existing;
|
|
1467
|
+
const created = {
|
|
1468
|
+
scope,
|
|
1469
|
+
cancelFlush: null,
|
|
1470
|
+
inFlightBarrierKeys: null,
|
|
1471
|
+
flushPromise: null,
|
|
1472
|
+
hasStaticPolicyUpdate: false,
|
|
1473
|
+
removes: /* @__PURE__ */ new Set(),
|
|
1474
|
+
staticPolicy: null,
|
|
1475
|
+
touches: /* @__PURE__ */ new Map(),
|
|
1476
|
+
upserts: /* @__PURE__ */ new Map(),
|
|
1477
|
+
waiters: []
|
|
1478
|
+
};
|
|
1479
|
+
this.#pendingNamespaceCommits.set(namespaceKey, created);
|
|
1480
|
+
return created;
|
|
1481
|
+
}
|
|
1482
|
+
#schedulePendingNamespaceFlush(pending) {
|
|
1483
|
+
if (pending.cancelFlush !== null || pending.flushPromise !== null) return;
|
|
1484
|
+
const timeoutId = setTimeout(() => {
|
|
1485
|
+
pending.cancelFlush = null;
|
|
1486
|
+
this.flushPendingNamespaceCommit(pending.scope);
|
|
1487
|
+
}, 40);
|
|
1488
|
+
pending.cancelFlush = () => clearTimeout(timeoutId);
|
|
1489
|
+
}
|
|
1490
|
+
#pruneRecentTouchedBuckets(currentBucket) {
|
|
1491
|
+
for (const [key, bucket] of this.#recentTouchedBuckets) if (bucket !== currentBucket) this.#recentTouchedBuckets.delete(key);
|
|
1492
|
+
}
|
|
1493
|
+
#scheduleStartupCleanupIfNeeded() {
|
|
1494
|
+
if (this.#startupCleanupScheduled) return;
|
|
1495
|
+
this.#startupCleanupScheduled = true;
|
|
1496
|
+
scheduleIdleCleanup(() => {
|
|
1497
|
+
this.#runStartupCleanupIfDue().catch(() => {});
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
async #runStartupCleanupIfDue() {
|
|
1501
|
+
if (document.hidden) await sleep(2e3);
|
|
1502
|
+
await runWithNavigatorLock(ASYNC_STARTUP_CLEANUP_LOCK_NAME, ASYNC_STARTUP_CLEANUP_LOCK_WARNING, async () => {
|
|
1503
|
+
const maintenance = this.#readMaintenanceState();
|
|
1504
|
+
const now = Date.now();
|
|
1505
|
+
if (maintenance.lastSuccessfulCleanupAt !== null && now - maintenance.lastSuccessfulCleanupAt < ASYNC_STORAGE_STARTUP_CLEANUP_COOLDOWN_MS) return;
|
|
1506
|
+
await this.#performStartupCleanup();
|
|
1507
|
+
this.#writeMaintenanceState({ lastSuccessfulCleanupAt: Date.now() });
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
async #performStartupCleanup() {
|
|
1511
|
+
await this.flushAllPendingNamespaceCommits();
|
|
1512
|
+
const scopesToInvalidate = await this.#withCleanupDriver(async (driver) => {
|
|
1513
|
+
const discoveredScopes = await this.#listDiscoveredCleanupScopes(driver);
|
|
1514
|
+
const discoveredScopesBySession = /* @__PURE__ */ new Map();
|
|
1515
|
+
for (const discoveredScope of discoveredScopes) {
|
|
1516
|
+
const existing = discoveredScopesBySession.get(discoveredScope.scope.sessionKey);
|
|
1517
|
+
if (existing !== void 0) existing.push(discoveredScope);
|
|
1518
|
+
else discoveredScopesBySession.set(discoveredScope.scope.sessionKey, [discoveredScope]);
|
|
1519
|
+
}
|
|
1520
|
+
return (await Promise.all([...discoveredScopesBySession.entries()].map(async ([sessionKey, sessionDiscoveredScopes]) => this.#runWithSessionWriterLock(sessionKey, async () => {
|
|
1521
|
+
await this.#flushPendingNamespaceCommitsForSessionUnlocked(sessionKey);
|
|
1522
|
+
return this.#performStartupCleanupWithDriver(driver, {
|
|
1523
|
+
discoveredScopes: sessionDiscoveredScopes,
|
|
1524
|
+
sessionKey
|
|
1525
|
+
});
|
|
1526
|
+
})))).flat();
|
|
1527
|
+
});
|
|
1528
|
+
for (const scope of scopesToInvalidate) {
|
|
1529
|
+
this.#invalidateCachedNamespace(scope);
|
|
1530
|
+
this.#broadcastNamespaceInvalidation(scope, "startup-cleanup");
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
async #performStartupCleanupWithDriver(driver, args = {}) {
|
|
1534
|
+
const cleanupActionDriver = __LEGIT_CAST__(driver);
|
|
1535
|
+
const discoveredScopes = args.discoveredScopes ?? await this.#listDiscoveredCleanupScopes(driver, args.sessionKey);
|
|
1536
|
+
const now = Date.now();
|
|
1537
|
+
const uniqueSessionKeys = [...new Set(discoveredScopes.map(({ scope }) => scope.sessionKey))];
|
|
1538
|
+
const offlineSessions = new Set(uniqueSessionKeys.filter((sessionKey) => isSessionOfflineInLocalStorage(sessionKey)));
|
|
1539
|
+
const protectedRefsBySession = new Map(uniqueSessionKeys.map((sessionKey) => [sessionKey, getSessionProtectedKeysSnapshot(sessionKey)]));
|
|
1540
|
+
const customStartupCallbacks = registeredAsyncStartupStoreCleanupCallbacks.get(this) ?? /* @__PURE__ */ new Map();
|
|
1541
|
+
const discoveredScopesByStore = /* @__PURE__ */ new Map();
|
|
1542
|
+
for (const discoveredScope of discoveredScopes) {
|
|
1543
|
+
const storeKey = getStoreRegistryKey(discoveredScope.scope.sessionKey, discoveredScope.scope.storeName);
|
|
1544
|
+
const existing = discoveredScopesByStore.get(storeKey);
|
|
1545
|
+
if (existing !== void 0) existing.push(discoveredScope);
|
|
1546
|
+
else discoveredScopesByStore.set(storeKey, [discoveredScope]);
|
|
1547
|
+
}
|
|
1548
|
+
const callbackEntries = [];
|
|
1549
|
+
for (const [storeKey, storeDiscoveredScopes] of discoveredScopesByStore) {
|
|
1550
|
+
const callback = customStartupCallbacks.get(storeKey);
|
|
1551
|
+
if (callback === void 0) continue;
|
|
1552
|
+
callbackEntries.push({
|
|
1553
|
+
callback,
|
|
1554
|
+
scopes: storeDiscoveredScopes,
|
|
1555
|
+
storeKey
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
const [callbackResults, genericScopePlans] = await Promise.all([Promise.all(callbackEntries.map(({ callback, scopes }) => callback({
|
|
1559
|
+
discoveredScopes: scopes,
|
|
1560
|
+
driver,
|
|
1561
|
+
now
|
|
1562
|
+
}))), Promise.all(discoveredScopes.map(async ({ knownRecordKeys, scope }) => this.#planStartupCleanupForScope({
|
|
1563
|
+
driver,
|
|
1564
|
+
knownRecordKeys,
|
|
1565
|
+
now,
|
|
1566
|
+
protectedRefs: protectedRefsBySession.get(scope.sessionKey) ?? void 0,
|
|
1567
|
+
skipExpiration: offlineSessions.has(scope.sessionKey),
|
|
1568
|
+
scope
|
|
1569
|
+
})))]);
|
|
1570
|
+
const scopePlansByNamespaceId = new Map(genericScopePlans.map((plan) => [getNamespaceId(plan.scope), plan]));
|
|
1571
|
+
const customStoreDeletePlans = [];
|
|
1572
|
+
for (const result of callbackResults) {
|
|
1573
|
+
for (const scopePlan of result.scopePlans) {
|
|
1574
|
+
const namespaceId = getNamespaceId(scopePlan.scope);
|
|
1575
|
+
const existing = scopePlansByNamespaceId.get(namespaceId);
|
|
1576
|
+
scopePlansByNamespaceId.set(namespaceId, this.#mergeStartupCleanupScopePlan(existing ?? {
|
|
1577
|
+
deleteAction: null,
|
|
1578
|
+
persistEntries: null,
|
|
1579
|
+
scope: scopePlan.scope
|
|
1580
|
+
}, {
|
|
1581
|
+
deleteAction: scopePlan.deleteKeys.length === 0 ? null : this.#createStartupCleanupDeleteAction({
|
|
1582
|
+
keys: scopePlan.deleteKeys,
|
|
1583
|
+
scope: scopePlan.scope
|
|
1584
|
+
}),
|
|
1585
|
+
persistEntries: scopePlan.persistEntries ?? null,
|
|
1586
|
+
persistStaticPolicy: scopePlan.persistStaticPolicy,
|
|
1587
|
+
scope: scopePlan.scope
|
|
1588
|
+
}));
|
|
1589
|
+
}
|
|
1590
|
+
for (const storeDeletePlan of result.storeDeletePlans ?? []) customStoreDeletePlans.push(storeDeletePlan);
|
|
1591
|
+
}
|
|
1592
|
+
const scopePlans = [...scopePlansByNamespaceId.values()];
|
|
1593
|
+
const genericStoreDeletePlans = cleanupActionDriver.cleanupRemoveKnownStoreDir === void 0 ? [] : this.#planStartupCleanupStoreDeletes({
|
|
1594
|
+
customStoreDeletePlanStoreKeys: new Set(customStoreDeletePlans.map((storeDeletePlan) => getStoreRegistryKey(storeDeletePlan.representativeScope.sessionKey, storeDeletePlan.representativeScope.storeName))),
|
|
1595
|
+
discoveredScopesByStore,
|
|
1596
|
+
scopePlansByNamespaceId
|
|
1597
|
+
});
|
|
1598
|
+
const storeDeletePlans = [...customStoreDeletePlans, ...genericStoreDeletePlans];
|
|
1599
|
+
const persistPlans = [];
|
|
1600
|
+
const invalidatedScopesByNamespaceId = /* @__PURE__ */ new Map();
|
|
1601
|
+
const successfulStoreDeleteSessions = /* @__PURE__ */ new Set();
|
|
1602
|
+
const successfulStoreDeleteScopes = /* @__PURE__ */ new Set();
|
|
1603
|
+
const skippedScopeIds = new Set(genericStoreDeletePlans.flatMap((storeDeletePlan) => storeDeletePlan.removedKeysByScope.map(({ scope }) => getNamespaceId(scope))));
|
|
1604
|
+
if (cleanupActionDriver.cleanupRemoveKnownStoreDir !== void 0) {
|
|
1605
|
+
const removeStoreDir = cleanupActionDriver.cleanupRemoveKnownStoreDir;
|
|
1606
|
+
const storeDeleteResults = await Promise.all(storeDeletePlans.map(async (storeDeletePlan) => {
|
|
1607
|
+
const deleteKeys = [...new Set(storeDeletePlan.removedKeysByScope.flatMap(({ keys }) => keys))];
|
|
1608
|
+
return {
|
|
1609
|
+
removed: await removeStoreDir(storeDeletePlan.representativeScope, deleteKeys),
|
|
1610
|
+
storeDeletePlan
|
|
1611
|
+
};
|
|
1612
|
+
}));
|
|
1613
|
+
for (const { removed, storeDeletePlan } of storeDeleteResults) {
|
|
1614
|
+
if (!removed) continue;
|
|
1615
|
+
for (const { keys, scope } of storeDeletePlan.removedKeysByScope) cleanupActionDriver.cleanupFinalizeRemovedRecords?.(scope, keys);
|
|
1616
|
+
cleanupActionDriver.cleanupFinalizeRemovedStoreDir?.(storeDeletePlan.representativeScope, []);
|
|
1617
|
+
successfulStoreDeleteSessions.add(storeDeletePlan.representativeScope.sessionKey);
|
|
1618
|
+
for (const { scope } of storeDeletePlan.removedKeysByScope) {
|
|
1619
|
+
const namespaceId = getNamespaceId(scope);
|
|
1620
|
+
invalidatedScopesByNamespaceId.set(namespaceId, scope);
|
|
1621
|
+
successfulStoreDeleteScopes.add(namespaceId);
|
|
1622
|
+
skippedScopeIds.add(namespaceId);
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
const deleteResults = await Promise.allSettled(scopePlans.flatMap((plan) => {
|
|
1627
|
+
if (skippedScopeIds.has(getNamespaceId(plan.scope))) return [];
|
|
1628
|
+
return plan.deleteAction === null ? [] : [this.#runStartupCleanupDeleteAction(cleanupActionDriver, plan.deleteAction)];
|
|
1629
|
+
}));
|
|
1630
|
+
for (const settledResult of deleteResults) {
|
|
1631
|
+
if (settledResult.status !== "fulfilled") continue;
|
|
1632
|
+
const result = settledResult.value;
|
|
1633
|
+
switch (result.kind) {
|
|
1634
|
+
case "removeRecords": {
|
|
1635
|
+
if (result.removedKeys.length > 0) {
|
|
1636
|
+
cleanupActionDriver.cleanupFinalizeRemovedRecords?.(result.action.scope, result.removedKeys);
|
|
1637
|
+
invalidatedScopesByNamespaceId.set(getNamespaceId(result.action.scope), result.action.scope);
|
|
1638
|
+
}
|
|
1639
|
+
if (!result.allSucceeded) continue;
|
|
1640
|
+
const scopePlan = scopePlansByNamespaceId.get(getNamespaceId(result.action.scope));
|
|
1641
|
+
if (scopePlan !== void 0 && scopePlan.persistEntries !== null) persistPlans.push({
|
|
1642
|
+
entries: scopePlan.persistEntries,
|
|
1643
|
+
staticPolicy: scopePlan.persistStaticPolicy,
|
|
1644
|
+
scope: scopePlan.scope
|
|
1645
|
+
});
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
case "removeStoreDir":
|
|
1649
|
+
if (!result.removed) continue;
|
|
1650
|
+
cleanupActionDriver.cleanupFinalizeRemovedStoreDir?.(result.action.scope, result.action.keys);
|
|
1651
|
+
successfulStoreDeleteSessions.add(result.action.scope.sessionKey);
|
|
1652
|
+
successfulStoreDeleteScopes.add(getNamespaceId(result.action.scope));
|
|
1653
|
+
continue;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
for (const scopePlan of scopePlans) {
|
|
1657
|
+
if (skippedScopeIds.has(getNamespaceId(scopePlan.scope)) || scopePlan.deleteAction !== null || scopePlan.persistEntries === null) continue;
|
|
1658
|
+
persistPlans.push({
|
|
1659
|
+
entries: scopePlan.persistEntries,
|
|
1660
|
+
staticPolicy: scopePlan.persistStaticPolicy,
|
|
1661
|
+
scope: scopePlan.scope
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
const sessionDeletePlans = [...successfulStoreDeleteSessions].flatMap((sessionKey) => this.#shouldPlanStartupCleanupSessionDelete(cleanupActionDriver, scopePlans, successfulStoreDeleteScopes, sessionKey) ? [{
|
|
1665
|
+
kind: "removeSessionDir",
|
|
1666
|
+
sessionKey
|
|
1667
|
+
}] : []);
|
|
1668
|
+
const sessionDeletePromise = Promise.allSettled(sessionDeletePlans.map((action) => this.#runStartupCleanupDeleteAction(cleanupActionDriver, action)));
|
|
1669
|
+
const persistPromise = Promise.all(persistPlans.map(async ({ entries, scope, staticPolicy }) => {
|
|
1670
|
+
if (entries !== null) await this.#persistNamespaceIndexUsingDriver(driver, scope, {
|
|
1671
|
+
entries,
|
|
1672
|
+
staticPolicy: staticPolicy !== void 0 ? staticPolicy : await this.#readNamespaceIndexStaticPolicyUsingDriver(driver, scope)
|
|
1673
|
+
});
|
|
1674
|
+
}));
|
|
1675
|
+
const [sessionDeleteResults] = await Promise.all([sessionDeletePromise, persistPromise]);
|
|
1676
|
+
for (const { scope } of persistPlans) invalidatedScopesByNamespaceId.set(getNamespaceId(scope), scope);
|
|
1677
|
+
for (const settledResult of sessionDeleteResults) {
|
|
1678
|
+
if (settledResult.status !== "fulfilled") continue;
|
|
1679
|
+
const result = settledResult.value;
|
|
1680
|
+
if (result.kind !== "removeSessionDir" || !result.removed) continue;
|
|
1681
|
+
cleanupActionDriver.cleanupFinalizeRemovedSessionDir?.(result.action.sessionKey);
|
|
1682
|
+
}
|
|
1683
|
+
return [...invalidatedScopesByNamespaceId.values()];
|
|
1684
|
+
}
|
|
1685
|
+
#intersectPersistEntries(left, right) {
|
|
1686
|
+
if (left === null) return right;
|
|
1687
|
+
if (right === null) return left;
|
|
1688
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1689
|
+
for (const [key, metadata] of left.entries()) if (right.has(key)) merged.set(key, metadata);
|
|
1690
|
+
return merged.size > 0 ? merged : null;
|
|
1691
|
+
}
|
|
1692
|
+
#mergeStartupCleanupScopePlan(left, right) {
|
|
1693
|
+
const mergedPersistEntries = this.#intersectPersistEntries(left.persistEntries, right.persistEntries);
|
|
1694
|
+
const getDeleteKeys = (action) => action !== null && action.kind !== "removeSessionDir" ? action.keys : [];
|
|
1695
|
+
const mergedDeleteKeys = [...new Set([...getDeleteKeys(left.deleteAction), ...getDeleteKeys(right.deleteAction)])].filter((key) => mergedPersistEntries === null || key !== "_i");
|
|
1696
|
+
return {
|
|
1697
|
+
deleteAction: mergedDeleteKeys.length === 0 ? null : this.#createStartupCleanupDeleteAction({
|
|
1698
|
+
keys: mergedDeleteKeys,
|
|
1699
|
+
scope: left.scope
|
|
1700
|
+
}),
|
|
1701
|
+
persistEntries: mergedPersistEntries,
|
|
1702
|
+
persistStaticPolicy: right.persistStaticPolicy !== void 0 ? right.persistStaticPolicy : left.persistStaticPolicy,
|
|
1703
|
+
scope: left.scope
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
#planStartupCleanupStoreDeletes(args) {
|
|
1707
|
+
const storeDeletePlans = [];
|
|
1708
|
+
for (const [storeKey, discoveredScopes] of args.discoveredScopesByStore) {
|
|
1709
|
+
if (args.customStoreDeletePlanStoreKeys.has(storeKey)) continue;
|
|
1710
|
+
const removedKeysByScope = [];
|
|
1711
|
+
const discoveredKnownKeys = /* @__PURE__ */ new Set();
|
|
1712
|
+
let shouldDeleteWholeStore = discoveredScopes.length > 0;
|
|
1713
|
+
for (const discoveredScope of discoveredScopes) {
|
|
1714
|
+
const knownRecordKeys = discoveredScope.knownRecordKeys;
|
|
1715
|
+
const scopePlan = args.scopePlansByNamespaceId.get(getNamespaceId(discoveredScope.scope));
|
|
1716
|
+
if (knownRecordKeys === null || scopePlan === void 0 || scopePlan.persistEntries !== null || scopePlan.deleteAction === null) {
|
|
1717
|
+
shouldDeleteWholeStore = false;
|
|
1718
|
+
break;
|
|
1719
|
+
}
|
|
1720
|
+
const plannedDeleteKeys = new Set(scopePlan.deleteAction.kind !== "removeSessionDir" ? scopePlan.deleteAction.keys : []);
|
|
1721
|
+
if (!knownRecordKeys.every((knownKey) => plannedDeleteKeys.has(knownKey))) {
|
|
1722
|
+
shouldDeleteWholeStore = false;
|
|
1723
|
+
break;
|
|
1724
|
+
}
|
|
1725
|
+
for (const knownKey of knownRecordKeys) discoveredKnownKeys.add(knownKey);
|
|
1726
|
+
removedKeysByScope.push({
|
|
1727
|
+
keys: [...plannedDeleteKeys],
|
|
1728
|
+
scope: discoveredScope.scope
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
if (!shouldDeleteWholeStore) continue;
|
|
1732
|
+
const plannedDeleteKeys = new Set(removedKeysByScope.flatMap(({ keys }) => keys));
|
|
1733
|
+
if (plannedDeleteKeys.size !== discoveredKnownKeys.size || [...discoveredKnownKeys].some((knownKey) => !plannedDeleteKeys.has(knownKey))) continue;
|
|
1734
|
+
const representativeScope = discoveredScopes[0]?.scope;
|
|
1735
|
+
if (representativeScope === void 0) continue;
|
|
1736
|
+
storeDeletePlans.push({
|
|
1737
|
+
removedKeysByScope,
|
|
1738
|
+
representativeScope
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
return storeDeletePlans;
|
|
1742
|
+
}
|
|
1743
|
+
async #planStartupCleanupForScope(args) {
|
|
1744
|
+
const rawKeys = args.knownRecordKeys ?? await args.driver.listKeys(args.scope);
|
|
1745
|
+
const indexState = await readAsyncStorageNamespaceIndexStateUsingDriver(args.driver, args.scope, rawKeys);
|
|
1746
|
+
const payloadKeys = /* @__PURE__ */ new Set();
|
|
1747
|
+
const rawKeysToRemove = [];
|
|
1748
|
+
for (const key of rawKeys) if (key.startsWith("__tsdf_payload__:")) payloadKeys.add(key.slice(17));
|
|
1749
|
+
else if (key !== "_i") rawKeysToRemove.push(key);
|
|
1750
|
+
if (!indexState.valid || indexState.entries === null) {
|
|
1751
|
+
const keysToRemove = rawKeys.filter((key) => key !== "_i" || indexState.exists);
|
|
1752
|
+
return {
|
|
1753
|
+
deleteAction: keysToRemove.length === 0 ? null : this.#createStartupCleanupDeleteAction({
|
|
1754
|
+
keys: keysToRemove,
|
|
1755
|
+
scope: args.scope
|
|
1756
|
+
}),
|
|
1757
|
+
persistEntries: null,
|
|
1758
|
+
persistStaticPolicy: null,
|
|
1759
|
+
scope: args.scope
|
|
1760
|
+
};
|
|
1761
|
+
}
|
|
1762
|
+
const nextEntries = /* @__PURE__ */ new Map();
|
|
1763
|
+
const currentPersistedStaticPolicy = normalizeStaticPolicy(indexState.staticPolicy);
|
|
1764
|
+
const nextPersistedStaticPolicy = normalizePersistedStaticPolicyForScope(args.scope, currentPersistedStaticPolicy);
|
|
1765
|
+
const effectiveStaticPolicy = getEffectiveStaticPolicyForScope(args.scope, nextPersistedStaticPolicy);
|
|
1766
|
+
const payloadRecordKeysToRemove = new Set(rawKeysToRemove);
|
|
1767
|
+
const candidateEntries = [];
|
|
1768
|
+
for (const [key, metadata] of indexState.entries.entries()) {
|
|
1769
|
+
const isProtected = isOfflineProtectedMetadata(metadata.customMetadata) || args.protectedRefs?.has(serializeProtectedRef({
|
|
1770
|
+
...args.scope,
|
|
1771
|
+
key
|
|
1772
|
+
})) === true;
|
|
1773
|
+
if (!payloadKeys.has(key)) continue;
|
|
1774
|
+
if (!isProtected && !args.skipExpiration && args.now - metadata.lastAccessAt > 12096e5) {
|
|
1775
|
+
payloadRecordKeysToRemove.add(getPayloadRecordKey(key));
|
|
1776
|
+
continue;
|
|
1777
|
+
}
|
|
1778
|
+
nextEntries.set(key, metadata);
|
|
1779
|
+
candidateEntries.push({
|
|
1780
|
+
itemKey: key,
|
|
1781
|
+
lastAccessAt: metadata.lastAccessAt,
|
|
1782
|
+
protected: isProtected,
|
|
1783
|
+
sizeBytes: metadata.sizeBytes ?? 0
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
for (const payloadKey of payloadKeys) if (!indexState.entries.has(payloadKey)) payloadRecordKeysToRemove.add(getPayloadRecordKey(payloadKey));
|
|
1787
|
+
if (effectiveStaticPolicy?.maxBytes !== void 0) {
|
|
1788
|
+
const pinnedKeys = new Set(effectiveStaticPolicy.pinnedKeys ?? []);
|
|
1789
|
+
const keptKeys = keepEntriesWithinByteBudget({
|
|
1790
|
+
entries: candidateEntries,
|
|
1791
|
+
getKey: (entry) => entry.itemKey,
|
|
1792
|
+
getLastAccessAt: (entry) => entry.lastAccessAt,
|
|
1793
|
+
getSizeBytes: (entry) => entry.sizeBytes,
|
|
1794
|
+
isPinned: (entry) => pinnedKeys.has(entry.itemKey),
|
|
1795
|
+
isProtected: (entry) => entry.protected,
|
|
1796
|
+
maxBytes: effectiveStaticPolicy.maxBytes
|
|
1797
|
+
});
|
|
1798
|
+
for (const { itemKey } of candidateEntries) {
|
|
1799
|
+
if (keptKeys.has(itemKey)) continue;
|
|
1800
|
+
payloadRecordKeysToRemove.add(getPayloadRecordKey(itemKey));
|
|
1801
|
+
nextEntries.delete(itemKey);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
const indexChanged = nextEntries.size !== indexState.entries.size || rawKeysToRemove.length > 0 || !deepEqual(currentPersistedStaticPolicy, nextPersistedStaticPolicy);
|
|
1805
|
+
const deleteKeys = [...payloadRecordKeysToRemove];
|
|
1806
|
+
if (indexChanged && nextEntries.size === 0) deleteKeys.push("_i");
|
|
1807
|
+
return {
|
|
1808
|
+
deleteAction: deleteKeys.length === 0 ? null : this.#createStartupCleanupDeleteAction({
|
|
1809
|
+
keys: deleteKeys,
|
|
1810
|
+
scope: args.scope
|
|
1811
|
+
}),
|
|
1812
|
+
persistEntries: indexChanged && nextEntries.size > 0 ? nextEntries : null,
|
|
1813
|
+
persistStaticPolicy: indexChanged && nextEntries.size > 0 ? nextPersistedStaticPolicy : void 0,
|
|
1814
|
+
scope: args.scope
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
#createStartupCleanupDeleteAction(args) {
|
|
1818
|
+
return {
|
|
1819
|
+
kind: "removeRecords",
|
|
1820
|
+
keys: [...new Set(args.keys)],
|
|
1821
|
+
scope: args.scope
|
|
1822
|
+
};
|
|
1823
|
+
}
|
|
1824
|
+
async #runStartupCleanupDeleteAction(cleanupActionDriver, action) {
|
|
1825
|
+
switch (action.kind) {
|
|
1826
|
+
case "removeRecords": {
|
|
1827
|
+
const removedKeys = cleanupActionDriver.cleanupRemoveKnownRecords !== void 0 ? await cleanupActionDriver.cleanupRemoveKnownRecords(action.scope, action.keys) : await this.#driverRemoveManyFrom(cleanupActionDriver, action.scope, action.keys).then(() => action.keys);
|
|
1828
|
+
return {
|
|
1829
|
+
action,
|
|
1830
|
+
allSucceeded: removedKeys.length === action.keys.length,
|
|
1831
|
+
kind: "removeRecords",
|
|
1832
|
+
removedKeys
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
case "removeStoreDir": return {
|
|
1836
|
+
action,
|
|
1837
|
+
kind: "removeStoreDir",
|
|
1838
|
+
removed: cleanupActionDriver.cleanupRemoveKnownStoreDir === void 0 ? false : await cleanupActionDriver.cleanupRemoveKnownStoreDir(action.scope, action.keys)
|
|
1839
|
+
};
|
|
1840
|
+
case "removeSessionDir": return {
|
|
1841
|
+
action,
|
|
1842
|
+
kind: "removeSessionDir",
|
|
1843
|
+
removed: cleanupActionDriver.cleanupRemoveKnownSessionDir === void 0 ? false : await cleanupActionDriver.cleanupRemoveKnownSessionDir(action.sessionKey)
|
|
1844
|
+
};
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
#shouldPlanStartupCleanupSessionDelete(cleanupActionDriver, scopePlans, successfulStoreDeleteScopes, sessionKey) {
|
|
1848
|
+
if (cleanupActionDriver.cleanupRemoveKnownSessionDir === void 0) return false;
|
|
1849
|
+
const sessionScopePlans = scopePlans.filter((plan) => plan.scope.sessionKey === sessionKey);
|
|
1850
|
+
return sessionScopePlans.length > 0 && sessionScopePlans.every((plan) => successfulStoreDeleteScopes.has(getNamespaceId(plan.scope)));
|
|
1851
|
+
}
|
|
1852
|
+
async #listDiscoveredCleanupScopes(driver, sessionKey) {
|
|
1853
|
+
return (await driver.listScopesWithKnownRecordKeys(sessionKey)).filter(({ scope }) => scope.kind !== "__internal.protected");
|
|
1854
|
+
}
|
|
1855
|
+
async #withCleanupDriver(callback) {
|
|
1856
|
+
const maybeCleanupCapableDriver = __LEGIT_CAST__(this.#driver);
|
|
1857
|
+
if (typeof maybeCleanupCapableDriver.withIsolatedCleanupDriver === "function") return maybeCleanupCapableDriver.withIsolatedCleanupDriver(callback);
|
|
1858
|
+
return callback(this.#driver);
|
|
1859
|
+
}
|
|
1860
|
+
};
|
|
1861
|
+
function createAsyncStorageAdapter(driver) {
|
|
1862
|
+
return new ManagedAsyncStorageAdapter(driver);
|
|
1863
|
+
}
|
|
1864
|
+
function serializeProtectedRef(ref) {
|
|
1865
|
+
return serializeProtectedRef$1(ref);
|
|
1866
|
+
}
|
|
1867
|
+
//#endregion
|
|
1868
|
+
export { getNavigatorLockManager as A, parseAsyncStorageRecordKey as B, isModeEffectivelyActive as C, clearSessionProtectedKeysSnapshot as D, offlineResolutionRecordSchema as E, encodePersistedAsyncNamespaceKind as F, serializeProtectedRef$1 as H, getNamespaceId as I, getPayloadRecordKey as L, createCompactLocalStorageEntry as M, parseCompactLocalStorageEntry as N, getSessionProtectedKeysSnapshot as O, compareMetadata as P, getPersistedNamespaceId as R, getIsOfflineModeFromStatus as S, offlineItemEntityRefSchema as T, scheduleIdleCleanup as U, parsePersistedAsyncNamespaceKind as V, keepEntriesWithinByteBudget as _, estimateManagedAsyncStorageEntrySizeBytes as a, compactOfflineStatusSnapshotSchema as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, getSerializedStringSize as g, createTimedKeySet as h, createAsyncStorageAdapter as i, warnIfNavigatorLockUnavailable as j, setSessionProtectedKeysSnapshot as k, registerAsyncStartupStoreCleanup as l, createShouldIgnoreItemPredicate as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, getDefaultMaxBytesForScope as p, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, serializeJsonForStorage as v, isOfflineModeStatusValue as w, defaultOfflineRuntimeConfig as x, OfflineResolutionConflictParseError as y, normalizeStaticPolicy as z };
|