@blaze-cache/core 0.4.0-beta.2 → 0.5.0-beta.1
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/README.md +131 -44
- package/dist/cache.d.ts +67 -0
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +608 -28
- package/dist/cache.js.map +1 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/multitab.d.ts +140 -0
- package/dist/multitab.d.ts.map +1 -0
- package/dist/multitab.js +306 -0
- package/dist/multitab.js.map +1 -0
- package/dist/persistence/indexeddb.d.ts.map +1 -1
- package/dist/persistence/indexeddb.js +8 -2
- package/dist/persistence/indexeddb.js.map +1 -1
- package/dist/query.d.ts +102 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +116 -0
- package/dist/query.js.map +1 -0
- package/dist/reactivity.d.ts.map +1 -1
- package/dist/shared.d.ts +52 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +100 -0
- package/dist/shared.js.map +1 -0
- package/dist/types.d.ts +48 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +16 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +31 -0
- package/dist/utils.js.map +1 -1
- package/dist/wasm.d.ts +38 -0
- package/dist/wasm.d.ts.map +1 -1
- package/dist/wasm.js +189 -5
- package/dist/wasm.js.map +1 -1
- package/package.json +6 -2
- package/pkg/blaze_cache_wasm.d.ts +157 -0
- package/pkg/blaze_cache_wasm.js +460 -0
- package/pkg/blaze_cache_wasm_bg.wasm +0 -0
- package/pkg/blaze_cache_wasm_bg.wasm.d.ts +23 -0
- package/pkg/package.json +1 -1
package/dist/cache.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { assertQueryOptions, estimateValueBytes } from './query.js';
|
|
1
2
|
import { CacheEventBus } from './events.js';
|
|
3
|
+
import { MultiTabSync } from './multitab.js';
|
|
2
4
|
import { CacheSubscriptions } from './reactivity.js';
|
|
3
|
-
import { loadBlazeWasm, keyScratch, WasmCache } from './wasm.js';
|
|
5
|
+
import { loadBlazeWasm, keyScratch, tagScratch, wasmLinearMemory, WasmCache } from './wasm.js';
|
|
4
6
|
import { indexedDbPersistence } from './persistence/indexeddb.js';
|
|
5
7
|
/** Entries held when `capacity` is not given. */
|
|
6
8
|
export const DEFAULT_CAPACITY = 500;
|
|
@@ -134,6 +136,16 @@ export class BlazeCache {
|
|
|
134
136
|
* ordinary string path.
|
|
135
137
|
*/
|
|
136
138
|
#raw;
|
|
139
|
+
/** Opt-in cross-tab sync. `null` unless `multiTab.enabled` is set. */
|
|
140
|
+
#multiTab = null;
|
|
141
|
+
/** Last version seen for each key — the stale-message guard. */
|
|
142
|
+
#versions = new Map();
|
|
143
|
+
/** Where values live. See {@link BlazeCacheOptions.storage}. */
|
|
144
|
+
#storage;
|
|
145
|
+
/** `key → stable id`, only populated in `storage: 'js'` mode. */
|
|
146
|
+
#ids = new Map();
|
|
147
|
+
/** `id → value`, only populated in `storage: 'js'` mode. */
|
|
148
|
+
#values = new Map();
|
|
137
149
|
#events = new CacheEventBus(() => this.#syncDropTracking());
|
|
138
150
|
/**
|
|
139
151
|
* Mirrors {@link CacheEventBus.wantsDrops} onto the wasm core: `true` while the Rust
|
|
@@ -205,9 +217,23 @@ export class BlazeCache {
|
|
|
205
217
|
* no-ops instead of forcing callers to branch on an option they may not remember.
|
|
206
218
|
*/
|
|
207
219
|
#control;
|
|
208
|
-
|
|
220
|
+
/** Whether the opt-in query indexes were built. Never changes during the cache's life. */
|
|
221
|
+
#indexes;
|
|
222
|
+
constructor(wasm, storage = 'wasm', indexes = false) {
|
|
209
223
|
this.#wasm = wasm;
|
|
210
224
|
this.#raw = keyScratch.enabled;
|
|
225
|
+
this.#storage = storage;
|
|
226
|
+
this.#indexes = indexes;
|
|
227
|
+
if (indexes)
|
|
228
|
+
this.#wasm.enableIndexes();
|
|
229
|
+
// JS-authoritative mode needs the drop log permanently on: self-initiated evictions and
|
|
230
|
+
// expirations are how JS learns which ids to delete from its value Map.
|
|
231
|
+
if (storage === 'js') {
|
|
232
|
+
// Both indexes are opt-in in the Rust core: the default path pays nothing for them.
|
|
233
|
+
this.#wasm.enableIds();
|
|
234
|
+
this.#wasm.setDropTracking(true);
|
|
235
|
+
this.#dropTracking = true;
|
|
236
|
+
}
|
|
211
237
|
// The getters below need *the instance* for private-field access: inside an object
|
|
212
238
|
// literal `this` would be the control object itself.
|
|
213
239
|
const self = this;
|
|
@@ -238,8 +264,13 @@ export class BlazeCache {
|
|
|
238
264
|
*/
|
|
239
265
|
static async create(options = {}) {
|
|
240
266
|
await loadBlazeWasm(options);
|
|
241
|
-
const
|
|
267
|
+
const storage = options.storage ?? 'wasm';
|
|
268
|
+
if (storage !== 'wasm' && storage !== 'js') {
|
|
269
|
+
throw new TypeError(`[blaze-cache] storage must be "wasm" or "js", got ${String(storage)}.`);
|
|
270
|
+
}
|
|
271
|
+
const cache = new BlazeCache(new WasmCache(options.capacity ?? DEFAULT_CAPACITY), storage, options.indexes === true);
|
|
242
272
|
await cache.#setupPersistence(options.persistence);
|
|
273
|
+
cache.#setupMultiTab(options.multiTab);
|
|
243
274
|
return cache;
|
|
244
275
|
}
|
|
245
276
|
// ------------------------------------------------------------------ reads
|
|
@@ -253,7 +284,20 @@ export class BlazeCache {
|
|
|
253
284
|
*/
|
|
254
285
|
get(key) {
|
|
255
286
|
let value;
|
|
256
|
-
if (this.#
|
|
287
|
+
if (this.#storage === 'js') {
|
|
288
|
+
const id = this.#ids.get(key);
|
|
289
|
+
// Hot path: no key string crosses the boundary — wasm only answers "is this id alive?".
|
|
290
|
+
if (id === undefined) {
|
|
291
|
+
this.#wasm.recordMiss();
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
const alive = this.#wasm.getById(id);
|
|
295
|
+
value = alive ? this.#values.get(id) : undefined;
|
|
296
|
+
// An expired id is reclaimed inside wasm; #drainDrops releases its value and hands
|
|
297
|
+
// listeners the real reference, so do not delete it here first.
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
else if (this.#raw) {
|
|
257
301
|
// Pre-encode into the shared scratch: a repeated key costs one identity check instead
|
|
258
302
|
// of a wasm-side malloc + copy + free (see `KeyScratch`).
|
|
259
303
|
keyScratch.encode(key);
|
|
@@ -284,7 +328,16 @@ export class BlazeCache {
|
|
|
284
328
|
* emits one `hit`/`miss` event per key.
|
|
285
329
|
*/
|
|
286
330
|
getMany(keys) {
|
|
287
|
-
const values = this.#
|
|
331
|
+
const values = this.#storage === 'js'
|
|
332
|
+
? keys.map((key) => {
|
|
333
|
+
const id = this.#ids.get(key);
|
|
334
|
+
if (id === undefined) {
|
|
335
|
+
this.#wasm.recordMiss();
|
|
336
|
+
return undefined;
|
|
337
|
+
}
|
|
338
|
+
return this.#wasm.getById(id) ? this.#values.get(id) : undefined;
|
|
339
|
+
})
|
|
340
|
+
: this.#wasm.getMany(keys);
|
|
288
341
|
const wantsHit = this.#events.hears('hit');
|
|
289
342
|
const wantsMiss = this.#events.hears('miss');
|
|
290
343
|
if (wantsHit || wantsMiss) {
|
|
@@ -313,6 +366,10 @@ export class BlazeCache {
|
|
|
313
366
|
* exactly like {@link BlazeCache.get}.
|
|
314
367
|
*/
|
|
315
368
|
peek(key) {
|
|
369
|
+
if (this.#storage === 'js') {
|
|
370
|
+
const id = this.#ids.get(key);
|
|
371
|
+
return id !== undefined && this.#wasm.peekById(id) ? this.#values.get(id) : undefined;
|
|
372
|
+
}
|
|
316
373
|
return this.#wasm.peek(key);
|
|
317
374
|
}
|
|
318
375
|
/**
|
|
@@ -327,6 +384,10 @@ export class BlazeCache {
|
|
|
327
384
|
}
|
|
328
385
|
/** `true` when `key` is present and not expired. Never changes eviction state. */
|
|
329
386
|
has(key) {
|
|
387
|
+
if (this.#storage === 'js') {
|
|
388
|
+
const id = this.#ids.get(key);
|
|
389
|
+
return id !== undefined && this.#wasm.hasById(id);
|
|
390
|
+
}
|
|
330
391
|
return this.#wasm.has(key);
|
|
331
392
|
}
|
|
332
393
|
/**
|
|
@@ -334,6 +395,12 @@ export class BlazeCache {
|
|
|
334
395
|
* Crosses the wasm boundary once instead of once per key.
|
|
335
396
|
*/
|
|
336
397
|
hasMany(keys) {
|
|
398
|
+
if (this.#storage === 'js') {
|
|
399
|
+
return keys.map((key) => {
|
|
400
|
+
const id = this.#ids.get(key);
|
|
401
|
+
return id !== undefined && this.#wasm.hasById(id);
|
|
402
|
+
});
|
|
403
|
+
}
|
|
337
404
|
const flags = this.#wasm.hasMany(keys);
|
|
338
405
|
const result = new Array(flags.length);
|
|
339
406
|
for (let i = 0; i < flags.length; i += 1)
|
|
@@ -345,13 +412,22 @@ export class BlazeCache {
|
|
|
345
412
|
* field is the cache's live reference — see *Value ownership* on the class.
|
|
346
413
|
*/
|
|
347
414
|
entry(key) {
|
|
348
|
-
return this.#
|
|
415
|
+
return this.#entryFor(key);
|
|
349
416
|
}
|
|
350
417
|
/**
|
|
351
418
|
* Snapshot of every live entry, oldest first. The `value` fields are the cache's live
|
|
352
419
|
* references — see *Value ownership* on the class.
|
|
353
420
|
*/
|
|
354
421
|
entries() {
|
|
422
|
+
if (this.#storage === 'js') {
|
|
423
|
+
const metas = this.#wasm.entriesMeta();
|
|
424
|
+
return metas.map(({ key, id, ttlMs, tags }) => ({
|
|
425
|
+
key,
|
|
426
|
+
value: this.#values.get(id),
|
|
427
|
+
ttlMs,
|
|
428
|
+
tags,
|
|
429
|
+
}));
|
|
430
|
+
}
|
|
355
431
|
return this.#wasm.entries();
|
|
356
432
|
}
|
|
357
433
|
/** Live keys, oldest first. */
|
|
@@ -389,6 +465,139 @@ export class BlazeCache {
|
|
|
389
465
|
const total = base.hits + base.misses;
|
|
390
466
|
return { ...base, hitRate: total === 0 ? 0 : base.hits / total };
|
|
391
467
|
}
|
|
468
|
+
// ------------------------------------------------------------------ queries
|
|
469
|
+
/**
|
|
470
|
+
* Bounded, indexed query. Returns metadata only unless `includeValues` is set (which
|
|
471
|
+
* requires both caps and hands back live by-reference values).
|
|
472
|
+
*
|
|
473
|
+
* Throws a setup error without `createCache({ indexes: true })`; an explicit
|
|
474
|
+
* `fullScan: true` with no other constraints is the only O(n) path.
|
|
475
|
+
*/
|
|
476
|
+
query(filter) {
|
|
477
|
+
assertQueryOptions(filter);
|
|
478
|
+
if (!this.#indexes && !filter.fullScan) {
|
|
479
|
+
throw new Error('[blaze-cache] query() requires createCache({ indexes: true }) (or an explicit fullScan: true).');
|
|
480
|
+
}
|
|
481
|
+
let rows;
|
|
482
|
+
let nextCursor;
|
|
483
|
+
let total;
|
|
484
|
+
if (filter.fullScan) {
|
|
485
|
+
const limit = filter.withTotal ? Number.MAX_SAFE_INTEGER : filter.limit;
|
|
486
|
+
const scanned = this.#scanSummaries(filter, limit);
|
|
487
|
+
total = filter.withTotal ? scanned.length : undefined;
|
|
488
|
+
rows = scanned.slice(0, filter.limit);
|
|
489
|
+
nextCursor = scanned.length > filter.limit ? (rows[rows.length - 1]?.key ?? null) : null;
|
|
490
|
+
}
|
|
491
|
+
else {
|
|
492
|
+
const page = this.#wasm.queryKeys(filter.prefix ?? null, [...(filter.tags?.any ?? [])], [...(filter.tags?.all ?? [])], [...(filter.tags?.none ?? [])], filter.ttlRange?.min ?? null, filter.ttlRange?.max ?? null, filter.keys ? [...filter.keys] : null, filter.limit, filter.cursor ?? null, filter.withTotal === true);
|
|
493
|
+
// serde-wasm-bindgen maps Rust `None` to `undefined`; the public API uses `null`.
|
|
494
|
+
rows = page.rows.map((row) => ({ ...row, ttlMs: row.ttlMs ?? null }));
|
|
495
|
+
nextCursor = page.nextCursor ?? null;
|
|
496
|
+
total = filter.withTotal ? page.total : undefined;
|
|
497
|
+
}
|
|
498
|
+
// `maxEntries` bounds both shapes, so one place reports the cut and re-anchors the
|
|
499
|
+
// cursor. It never truncates to an empty page (`assertQueryOptions` requires >= 1), so
|
|
500
|
+
// the new anchor always exists and a `loadMore` loop can always make progress.
|
|
501
|
+
let truncated = false;
|
|
502
|
+
if (filter.maxEntries !== undefined && filter.maxEntries < rows.length) {
|
|
503
|
+
rows = rows.slice(0, filter.maxEntries);
|
|
504
|
+
truncated = true;
|
|
505
|
+
nextCursor = rows[rows.length - 1].key;
|
|
506
|
+
}
|
|
507
|
+
if (!filter.includeValues) {
|
|
508
|
+
return { items: rows, nextCursor, total, ...(truncated ? { truncated: true } : {}) };
|
|
509
|
+
}
|
|
510
|
+
// Include live values, capped by both row count and estimated bytes. `entry()` is used
|
|
511
|
+
// instead of `peek()` so a stored `undefined` stays a real row — `peek` cannot tell it
|
|
512
|
+
// from a key that vanished — and `get()` is avoided so a devtools read never moves
|
|
513
|
+
// SIEVE state or the hit rate.
|
|
514
|
+
const items = [];
|
|
515
|
+
let bytes = 0;
|
|
516
|
+
let capped = false;
|
|
517
|
+
for (const row of rows) {
|
|
518
|
+
const live = this.entry(row.key);
|
|
519
|
+
if (live === undefined)
|
|
520
|
+
continue; // expired or deleted since the page was read
|
|
521
|
+
const value = live.value;
|
|
522
|
+
const size = row.size ?? estimateValueBytes(value);
|
|
523
|
+
if (bytes + size > filter.maxValueBytes) {
|
|
524
|
+
capped = true;
|
|
525
|
+
break;
|
|
526
|
+
}
|
|
527
|
+
bytes += size;
|
|
528
|
+
items.push({ ...row, value, size });
|
|
529
|
+
}
|
|
530
|
+
if (capped) {
|
|
531
|
+
truncated = true;
|
|
532
|
+
// Only a cap can leave rows unseen; a key that vanished needs no re-anchor.
|
|
533
|
+
if (items.length > 0)
|
|
534
|
+
nextCursor = items[items.length - 1].key;
|
|
535
|
+
}
|
|
536
|
+
return { items, nextCursor, total, ...(truncated ? { truncated: true } : {}) };
|
|
537
|
+
}
|
|
538
|
+
/** Key-only form of {@link BlazeCache.query}, with the same cursor semantics. */
|
|
539
|
+
queryKeys(filter) {
|
|
540
|
+
assertQueryOptions({ ...filter, includeValues: false });
|
|
541
|
+
if (!this.#indexes && !filter.fullScan) {
|
|
542
|
+
throw new Error('[blaze-cache] queryKeys() requires createCache({ indexes: true }) (or an explicit fullScan: true).');
|
|
543
|
+
}
|
|
544
|
+
if (filter.fullScan) {
|
|
545
|
+
const limit = filter.withTotal ? Number.MAX_SAFE_INTEGER : filter.limit;
|
|
546
|
+
const scanned = this.#scanSummaries(filter, limit);
|
|
547
|
+
return {
|
|
548
|
+
keys: scanned.slice(0, filter.limit).map((row) => row.key),
|
|
549
|
+
nextCursor: scanned.length > filter.limit ? (scanned[filter.limit - 1]?.key ?? null) : null,
|
|
550
|
+
...(filter.withTotal ? { total: scanned.length } : {}),
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
const page = this.#wasm.queryKeys(filter.prefix ?? null, [...(filter.tags?.any ?? [])], [...(filter.tags?.all ?? [])], [...(filter.tags?.none ?? [])], filter.ttlRange?.min ?? null, filter.ttlRange?.max ?? null, filter.keys ? [...filter.keys] : null, filter.limit, filter.cursor ?? null, filter.withTotal === true);
|
|
554
|
+
return {
|
|
555
|
+
keys: page.rows.map((row) => row.key),
|
|
556
|
+
nextCursor: page.nextCursor ?? null,
|
|
557
|
+
...(filter.withTotal ? { total: page.total } : {}),
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
/** Number of matching entries. Requires `indexes: true`; never an implicit full scan. */
|
|
561
|
+
count(filter = {}) {
|
|
562
|
+
if (filter.where) {
|
|
563
|
+
throw new TypeError('[blaze-cache] count() does not support `where`.');
|
|
564
|
+
}
|
|
565
|
+
if (!this.#indexes) {
|
|
566
|
+
throw new Error('[blaze-cache] count() requires createCache({ indexes: true }).');
|
|
567
|
+
}
|
|
568
|
+
return this.#wasm.queryCount(filter.prefix ?? null, [...(filter.tags?.any ?? [])], [...(filter.tags?.all ?? [])], [...(filter.tags?.none ?? [])], filter.ttlRange?.min ?? null, filter.ttlRange?.max ?? null, filter.keys ? [...filter.keys] : null);
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Full-scan building block used only when the caller opts in explicitly.
|
|
572
|
+
*
|
|
573
|
+
* Applies the same anchor rule as the indexed path (`cursor` is a last-key position in
|
|
574
|
+
* ascending order), so a full scan paginates exactly like an indexed one. `keys()` hands
|
|
575
|
+
* back a fresh array, so the sort needs no defensive copy.
|
|
576
|
+
*/
|
|
577
|
+
#scanSummaries(filter, limit) {
|
|
578
|
+
const keys = this.keys().sort();
|
|
579
|
+
const cursor = filter.cursor;
|
|
580
|
+
const summaries = [];
|
|
581
|
+
for (const key of keys) {
|
|
582
|
+
if (cursor !== undefined && key <= cursor)
|
|
583
|
+
continue;
|
|
584
|
+
const entry = this.entry(key);
|
|
585
|
+
if (!entry)
|
|
586
|
+
continue;
|
|
587
|
+
const summary = {
|
|
588
|
+
key,
|
|
589
|
+
ttlMs: entry.ttlMs,
|
|
590
|
+
tags: entry.tags,
|
|
591
|
+
size: estimateValueBytes(entry.value),
|
|
592
|
+
};
|
|
593
|
+
if (filter.where && !filter.where(summary))
|
|
594
|
+
continue;
|
|
595
|
+
summaries.push(summary);
|
|
596
|
+
if (summaries.length > limit)
|
|
597
|
+
break;
|
|
598
|
+
}
|
|
599
|
+
return summaries;
|
|
600
|
+
}
|
|
392
601
|
// ----------------------------------------------------------------- writes
|
|
393
602
|
/**
|
|
394
603
|
* Stores (or replaces) `key`. Replacing refreshes the TTL and replaces the tags.
|
|
@@ -402,7 +611,27 @@ export class BlazeCache {
|
|
|
402
611
|
// Untagged writes share `NO_TAGS` (see its doc).
|
|
403
612
|
const tags = (options?.tags ?? NO_TAGS);
|
|
404
613
|
const ttlMs = options?.ttlMs ?? null;
|
|
405
|
-
if (this.#
|
|
614
|
+
if (this.#storage === 'js') {
|
|
615
|
+
// wasm keeps metadata and hands back a stable id; the value itself never crosses the
|
|
616
|
+
// boundary. An overwrite keeps its id, so this is one Map.set rather than two.
|
|
617
|
+
const id = this.#wasm.setMeta(key, ttlMs, tags);
|
|
618
|
+
this.#values.set(id, value);
|
|
619
|
+
this.#ids.set(key, id);
|
|
620
|
+
}
|
|
621
|
+
else if (this.#raw && tagScratch.enabled && tags.length === 1) {
|
|
622
|
+
// Single-tag fast path: no offset table and no cache-key allocation on the host.
|
|
623
|
+
keyScratch.encode(key);
|
|
624
|
+
const encoded = tagScratch.encodeOne(tags[0]);
|
|
625
|
+
this.#wasm.setRawWithOneTag(keyScratch.ptr, keyScratch.len, value, ttlMs, encoded.ptr, encoded.len);
|
|
626
|
+
}
|
|
627
|
+
else if (this.#raw && tagScratch.enabled && tags.length > 0) {
|
|
628
|
+
// Tagged raw path: key and tag bytes are already in Wasm memory, so neither is
|
|
629
|
+
// marshalled per write. Offsets are validated again inside the binding.
|
|
630
|
+
keyScratch.encode(key);
|
|
631
|
+
const encoded = tagScratch.encode(tags);
|
|
632
|
+
this.#wasm.setRawWithTags(keyScratch.ptr, keyScratch.len, value, ttlMs, encoded.ptr, encoded.len, encoded.offsetsView);
|
|
633
|
+
}
|
|
634
|
+
else if (this.#raw && tags.length === 0) {
|
|
406
635
|
// Untagged write via the pre-encoded-key path: skips both the key allocation and the
|
|
407
636
|
// empty-tags array crossing — the two avoidable costs of the string `set`.
|
|
408
637
|
keyScratch.encode(key);
|
|
@@ -445,7 +674,25 @@ export class BlazeCache {
|
|
|
445
674
|
}
|
|
446
675
|
tagOffsets[i + 1] = tagsFlat.length;
|
|
447
676
|
}
|
|
448
|
-
this.#
|
|
677
|
+
if (this.#storage === 'js') {
|
|
678
|
+
const ids = this.#wasm.setManyMeta(keys, ttlMs, tagsFlat, tagOffsets);
|
|
679
|
+
for (let i = 0; i < n; i += 1) {
|
|
680
|
+
const id = ids[i];
|
|
681
|
+
this.#values.set(id, entries[i].value);
|
|
682
|
+
this.#ids.set(entries[i].key, id);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
else if (this.#raw && tagScratch.enabled) {
|
|
686
|
+
// Keys and tags are encoded into the two scratch buffers; only the values array crosses
|
|
687
|
+
// the boundary. This is the batched counterpart of the tagged raw write path.
|
|
688
|
+
const encodedKeys = keyScratch.encodeMany(keys);
|
|
689
|
+
const groups = entries.map((entry) => entry.options?.tags ?? []);
|
|
690
|
+
const encodedTags = tagScratch.encodeRanges(groups);
|
|
691
|
+
this.#wasm.setManyRaw(encodedKeys.ptr, encodedKeys.offsets, encodedKeys.lengths, values, ttlMs, encodedTags.ptr, encodedTags.len, encodedTags.offsetsView);
|
|
692
|
+
}
|
|
693
|
+
else {
|
|
694
|
+
this.#wasm.setMany(keys, values, ttlMs, tagsFlat, tagOffsets);
|
|
695
|
+
}
|
|
449
696
|
if (this.#hasChangeConsumers) {
|
|
450
697
|
for (let i = 0; i < n; i += 1)
|
|
451
698
|
this.#notify({ type: 'set', key: entries[i].key });
|
|
@@ -454,6 +701,95 @@ export class BlazeCache {
|
|
|
454
701
|
if (this.#dropTracking)
|
|
455
702
|
this.#drainDrops();
|
|
456
703
|
}
|
|
704
|
+
// ------------------------------------------------------------- binary value mode (opt-in)
|
|
705
|
+
/**
|
|
706
|
+
* Stores raw bytes **directly in Wasm linear memory** and reads them back as a zero-copy
|
|
707
|
+
* `Uint8Array` view. Only available in the default `storage: 'wasm'` mode.
|
|
708
|
+
*
|
|
709
|
+
* The payload is copied once into a reserved arena region (a raw byte copy, not JS object
|
|
710
|
+
* serialisation); `getBytes` then returns a view onto that region with no copy at all. This
|
|
711
|
+
* is the only genuine zero-copy value path, because arbitrary JS objects cannot live in
|
|
712
|
+
* linear memory. Prefer `getBytesCopy` when a view must outlive the next write or eviction.
|
|
713
|
+
*/
|
|
714
|
+
setBytes(key, value, options) {
|
|
715
|
+
if (this.#storage !== 'wasm') {
|
|
716
|
+
throw new Error('[blaze-cache] setBytes requires storage: "wasm" (the default).');
|
|
717
|
+
}
|
|
718
|
+
const source = ArrayBuffer.isView(value)
|
|
719
|
+
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
|
|
720
|
+
: new Uint8Array(value);
|
|
721
|
+
const length = source.byteLength;
|
|
722
|
+
const ptr = WasmCache.bytesReserve(length);
|
|
723
|
+
const memory = wasmLinearMemory();
|
|
724
|
+
new Uint8Array(memory.buffer, ptr, length).set(source);
|
|
725
|
+
const tags = (options?.tags ?? NO_TAGS);
|
|
726
|
+
const ttlMs = options?.ttlMs ?? null;
|
|
727
|
+
const stored = this.#wasm.setBytes(key, ptr, length, ttlMs, tags);
|
|
728
|
+
if (stored && this.#hasChangeConsumers)
|
|
729
|
+
this.#notify({ type: 'set', key });
|
|
730
|
+
if (this.#dropTracking)
|
|
731
|
+
this.#drainDrops();
|
|
732
|
+
return stored;
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* A zero-copy view of a byte value, or `undefined` when the key is missing or was written
|
|
736
|
+
* with `set`. Counts a hit/miss exactly like {@link BlazeCache.get}.
|
|
737
|
+
*
|
|
738
|
+
* The view is valid until the next Wasm allocation: `memory.grow` detaches the old
|
|
739
|
+
* `ArrayBuffer`, and an evicted region may be reused. Read it promptly, or use
|
|
740
|
+
* {@link BlazeCache.getBytesCopy} for a long-lived snapshot.
|
|
741
|
+
*/
|
|
742
|
+
getBytes(key) {
|
|
743
|
+
const coordinates = this.#wasm.getBytes(key);
|
|
744
|
+
if (!coordinates) {
|
|
745
|
+
if (this.#events.hears('miss'))
|
|
746
|
+
this.#events.emit('miss', { type: 'miss', key });
|
|
747
|
+
if (this.#dropTracking)
|
|
748
|
+
this.#drainDrops();
|
|
749
|
+
return undefined;
|
|
750
|
+
}
|
|
751
|
+
const value = new Uint8Array(wasmLinearMemory().buffer, coordinates[0], coordinates[1]);
|
|
752
|
+
if (this.#events.hears('hit'))
|
|
753
|
+
this.#events.emit('hit', { type: 'hit', key, value: value });
|
|
754
|
+
if (this.#dropTracking)
|
|
755
|
+
this.#drainDrops();
|
|
756
|
+
return value;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Advanced bytes-producer path: stores an already-reserved arena region by its `(ptr, len)`
|
|
760
|
+
* coordinates, with no JS→Wasm copy. Obtain `ptr` from `WasmCache.bytesReserve(len)` and write
|
|
761
|
+
* the payload into `new Uint8Array(wasmLinearMemory().buffer, ptr, len)` first — a decoder can
|
|
762
|
+
* therefore write straight into Wasm memory and hand the region to the cache. A rejected or
|
|
763
|
+
* stale pointer stores nothing and returns `false`. The public `setBytes` remains the safe
|
|
764
|
+
* default; this entry point is opt-in and shares its view-lifetime contract.
|
|
765
|
+
*/
|
|
766
|
+
setBytesReserved(key, ptr, length, options) {
|
|
767
|
+
if (this.#storage !== 'wasm') {
|
|
768
|
+
throw new Error('[blaze-cache] setBytesReserved requires storage: "wasm" (the default).');
|
|
769
|
+
}
|
|
770
|
+
const tags = (options?.tags ?? NO_TAGS);
|
|
771
|
+
const ttlMs = options?.ttlMs ?? null;
|
|
772
|
+
const stored = this.#wasm.setBytes(key, ptr, length, ttlMs, tags);
|
|
773
|
+
if (stored && this.#hasChangeConsumers)
|
|
774
|
+
this.#notify({ type: 'set', key });
|
|
775
|
+
if (this.#dropTracking)
|
|
776
|
+
this.#drainDrops();
|
|
777
|
+
return stored;
|
|
778
|
+
}
|
|
779
|
+
/** An owned copy of a byte value — safe to retain across writes, eviction and `memory.grow`. */
|
|
780
|
+
getBytesCopy(key) {
|
|
781
|
+
const value = this.#wasm.getBytesCopy(key);
|
|
782
|
+
if (value === undefined) {
|
|
783
|
+
if (this.#events.hears('miss'))
|
|
784
|
+
this.#events.emit('miss', { type: 'miss', key });
|
|
785
|
+
}
|
|
786
|
+
else if (this.#events.hears('hit')) {
|
|
787
|
+
this.#events.emit('hit', { type: 'hit', key, value: value });
|
|
788
|
+
}
|
|
789
|
+
if (this.#dropTracking)
|
|
790
|
+
this.#drainDrops();
|
|
791
|
+
return value;
|
|
792
|
+
}
|
|
457
793
|
/**
|
|
458
794
|
* Marks `key` as recently used for eviction and optionally renews its TTL — the stored
|
|
459
795
|
* value is never changed.
|
|
@@ -472,14 +808,7 @@ export class BlazeCache {
|
|
|
472
808
|
}
|
|
473
809
|
/** Removes `key`, returning whether it was there. */
|
|
474
810
|
delete(key) {
|
|
475
|
-
|
|
476
|
-
if (this.#raw) {
|
|
477
|
-
keyScratch.encode(key);
|
|
478
|
-
removed = this.#wasm.deleteRaw(keyScratch.ptr, keyScratch.len);
|
|
479
|
-
}
|
|
480
|
-
else {
|
|
481
|
-
removed = this.#wasm.delete(key);
|
|
482
|
-
}
|
|
811
|
+
const removed = this.#deleteLocal(key);
|
|
483
812
|
if (removed && this.#hasChangeConsumers)
|
|
484
813
|
this.#notify({ type: 'delete', key });
|
|
485
814
|
return removed;
|
|
@@ -491,8 +820,15 @@ export class BlazeCache {
|
|
|
491
820
|
deleteMany(keys) {
|
|
492
821
|
const removed = this.#wasm.deleteMany(keys);
|
|
493
822
|
const result = new Array(removed.length);
|
|
494
|
-
for (let i = 0; i < removed.length; i += 1)
|
|
823
|
+
for (let i = 0; i < removed.length; i += 1) {
|
|
495
824
|
result[i] = removed[i] === 1;
|
|
825
|
+
if (result[i] && this.#storage === 'js') {
|
|
826
|
+
const id = this.#ids.get(keys[i]);
|
|
827
|
+
if (id !== undefined)
|
|
828
|
+
this.#values.delete(id);
|
|
829
|
+
this.#ids.delete(keys[i]);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
496
832
|
if (this.#hasChangeConsumers) {
|
|
497
833
|
for (let i = 0; i < removed.length; i += 1) {
|
|
498
834
|
if (result[i])
|
|
@@ -506,14 +842,22 @@ export class BlazeCache {
|
|
|
506
842
|
if (tags.length === 0)
|
|
507
843
|
return [];
|
|
508
844
|
const removed = this.#wasm.invalidateTags(tags);
|
|
845
|
+
if (this.#storage === 'js')
|
|
846
|
+
this.#forgetKeys(removed);
|
|
509
847
|
if (removed.length > 0 && this.#hasChangeConsumers) {
|
|
510
|
-
|
|
848
|
+
// `tags` is additive (0.5.0): listeners see the original names even though the
|
|
849
|
+
// entries — and therefore `tagsOf(key)` — are already gone.
|
|
850
|
+
this.#notify({ type: 'invalidate', keys: removed, tags });
|
|
851
|
+
this.#multiTab?.publishInvalidateTags(tags);
|
|
852
|
+
this.#multiTab?.markEpoch();
|
|
511
853
|
}
|
|
512
854
|
return removed;
|
|
513
855
|
}
|
|
514
856
|
/** Removes every expired entry, returning the removed keys. */
|
|
515
857
|
prune() {
|
|
516
858
|
const removed = this.#wasm.prune();
|
|
859
|
+
if (this.#storage === 'js')
|
|
860
|
+
this.#forgetKeys(removed);
|
|
517
861
|
if (removed.length > 0 && this.#hasChangeConsumers) {
|
|
518
862
|
this.#notify({ type: 'prune', keys: removed });
|
|
519
863
|
}
|
|
@@ -522,6 +866,10 @@ export class BlazeCache {
|
|
|
522
866
|
/** Empties the cache. */
|
|
523
867
|
clear() {
|
|
524
868
|
this.#wasm.clear();
|
|
869
|
+
if (this.#storage === 'js') {
|
|
870
|
+
this.#ids.clear();
|
|
871
|
+
this.#values.clear();
|
|
872
|
+
}
|
|
525
873
|
if (this.#hasChangeConsumers)
|
|
526
874
|
this.#notify({ type: 'clear' });
|
|
527
875
|
}
|
|
@@ -667,7 +1015,17 @@ export class BlazeCache {
|
|
|
667
1015
|
clearTimeout(this.#timer);
|
|
668
1016
|
this.#timer = null;
|
|
669
1017
|
}
|
|
670
|
-
//
|
|
1018
|
+
// With sync on, IndexedDB writes are serialised across tabs by a Web Lock. A tab that is
|
|
1019
|
+
// still hidden cannot commit a stale snapshot over a peer's newer row: remote mutations
|
|
1020
|
+
// update this tab's queues first, and only the lock holder writes.
|
|
1021
|
+
const locks = globalThis.navigator?.locks;
|
|
1022
|
+
if (this.#multiTab?.active && locks) {
|
|
1023
|
+
return locks.request(this.#multiTab.channelName, () => this.#flushChain());
|
|
1024
|
+
}
|
|
1025
|
+
return this.#flushChain();
|
|
1026
|
+
}
|
|
1027
|
+
/** The serialised flush chain, without the optional cross-tab Web Lock. */
|
|
1028
|
+
#flushChain() {
|
|
671
1029
|
this.#chain = this.#chain.then(() => this.#runFlush(), () => this.#runFlush());
|
|
672
1030
|
return this.#chain;
|
|
673
1031
|
}
|
|
@@ -694,6 +1052,8 @@ export class BlazeCache {
|
|
|
694
1052
|
}
|
|
695
1053
|
/** The one teardown pass: flush, unbind, close storage, free wasm. See {@link BlazeCache.dispose}. */
|
|
696
1054
|
async #teardown() {
|
|
1055
|
+
// Stop listening first: a dispose handshake must not be mistaken for a live peer.
|
|
1056
|
+
this.#multiTab?.close();
|
|
697
1057
|
try {
|
|
698
1058
|
await this.flush();
|
|
699
1059
|
}
|
|
@@ -720,6 +1080,125 @@ export class BlazeCache {
|
|
|
720
1080
|
this.#wasm.free();
|
|
721
1081
|
}
|
|
722
1082
|
}
|
|
1083
|
+
// -------------------------------------------------------------- multi-tab (opt-in)
|
|
1084
|
+
/**
|
|
1085
|
+
* Attaches the optional cross-tab channel. Runs *after* persistence hydration so a tab that
|
|
1086
|
+
* woke up from IndexedDB can answer a peer's `hello` with its real state.
|
|
1087
|
+
*/
|
|
1088
|
+
#setupMultiTab(spec) {
|
|
1089
|
+
if (!spec?.enabled)
|
|
1090
|
+
return;
|
|
1091
|
+
if (typeof spec.channel === 'string' &&
|
|
1092
|
+
(spec.channel.length === 0 || spec.channel.includes('\0'))) {
|
|
1093
|
+
throw new RangeError('[blaze-cache] multiTab.channel must be a non-empty string without NUL.');
|
|
1094
|
+
}
|
|
1095
|
+
const strategy = spec.strategy ?? 'value';
|
|
1096
|
+
if (strategy !== 'value' && strategy !== 'invalidate') {
|
|
1097
|
+
throw new TypeError(`[blaze-cache] multiTab.strategy must be "value" or "invalidate", got ${String(strategy)}.`);
|
|
1098
|
+
}
|
|
1099
|
+
const self = this;
|
|
1100
|
+
this.#multiTab = new MultiTabSync({
|
|
1101
|
+
channel: spec.channel ?? `blaze-cache:${this.#namespace}\0${this.#generation}`,
|
|
1102
|
+
generation: this.#generation,
|
|
1103
|
+
strategy,
|
|
1104
|
+
bridge: {
|
|
1105
|
+
applySet(key, value, ttlMs, tags) {
|
|
1106
|
+
self.#writeDirect(key, value, ttlMs, tags);
|
|
1107
|
+
if (self.#hasChangeConsumers)
|
|
1108
|
+
self.#notify({ type: 'set', key }, false);
|
|
1109
|
+
},
|
|
1110
|
+
applyDelete(key) {
|
|
1111
|
+
if (self.#deleteLocal(key) && self.#hasChangeConsumers) {
|
|
1112
|
+
self.#notify({ type: 'delete', key }, false);
|
|
1113
|
+
}
|
|
1114
|
+
},
|
|
1115
|
+
applyClear() {
|
|
1116
|
+
self.#wasm.clear();
|
|
1117
|
+
self.#ids.clear();
|
|
1118
|
+
self.#values.clear();
|
|
1119
|
+
self.#versions.clear();
|
|
1120
|
+
if (self.#hasChangeConsumers)
|
|
1121
|
+
self.#notify({ type: 'clear' }, false);
|
|
1122
|
+
},
|
|
1123
|
+
applyInvalidateTags(tags) {
|
|
1124
|
+
const removed = self.#wasm.invalidateTags(tags);
|
|
1125
|
+
self.#forgetKeys(removed);
|
|
1126
|
+
if (removed.length > 0 && self.#hasChangeConsumers) {
|
|
1127
|
+
self.#notify({ type: 'invalidate', keys: removed, tags }, false);
|
|
1128
|
+
}
|
|
1129
|
+
},
|
|
1130
|
+
applyRotate(generation) {
|
|
1131
|
+
void self.#rotate(generation, false).catch((error) => {
|
|
1132
|
+
self.#notifyError(error, '[blaze-cache] remote rotate failed.');
|
|
1133
|
+
});
|
|
1134
|
+
},
|
|
1135
|
+
emitRemote(type, key, value) {
|
|
1136
|
+
self.#emitRemote(type, key, value);
|
|
1137
|
+
},
|
|
1138
|
+
snapshot() {
|
|
1139
|
+
return self.#wasm.entries().map((entry) => ({
|
|
1140
|
+
key: entry.key,
|
|
1141
|
+
value: entry.value,
|
|
1142
|
+
ttlMs: entry.ttlMs,
|
|
1143
|
+
tags: entry.tags,
|
|
1144
|
+
version: self.#versions.get(entry.key),
|
|
1145
|
+
}));
|
|
1146
|
+
},
|
|
1147
|
+
versionOf(key) {
|
|
1148
|
+
return self.#versions.get(key);
|
|
1149
|
+
},
|
|
1150
|
+
setVersion(key, version) {
|
|
1151
|
+
self.#versions.set(key, version);
|
|
1152
|
+
},
|
|
1153
|
+
resetVersions() {
|
|
1154
|
+
self.#versions.clear();
|
|
1155
|
+
},
|
|
1156
|
+
},
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
/** Emits a `remote-*` event, isolated by the bus exactly like every other listener. */
|
|
1160
|
+
#emitRemote(type, key, value) {
|
|
1161
|
+
if (!this.#events.hears(type))
|
|
1162
|
+
return;
|
|
1163
|
+
switch (type) {
|
|
1164
|
+
case 'remote-set':
|
|
1165
|
+
this.#events.emit('remote-set', { type: 'remote-set', key: key, value: value });
|
|
1166
|
+
break;
|
|
1167
|
+
case 'remote-delete':
|
|
1168
|
+
this.#events.emit('remote-delete', { type: 'remote-delete', key: key });
|
|
1169
|
+
break;
|
|
1170
|
+
case 'remote-clear':
|
|
1171
|
+
this.#events.emit('remote-clear', { type: 'remote-clear' });
|
|
1172
|
+
break;
|
|
1173
|
+
case 'remote-invalidate':
|
|
1174
|
+
this.#events.emit('remote-invalidate', { type: 'remote-invalidate' });
|
|
1175
|
+
break;
|
|
1176
|
+
case 'remote-rotate':
|
|
1177
|
+
this.#events.emit('remote-rotate', { type: 'remote-rotate' });
|
|
1178
|
+
break;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
/** The un-notified half of `delete()`, shared with the remote-apply path. */
|
|
1182
|
+
#deleteLocal(key) {
|
|
1183
|
+
let removed;
|
|
1184
|
+
if (this.#storage === 'js') {
|
|
1185
|
+
removed = this.#wasm.delete(key);
|
|
1186
|
+
if (removed) {
|
|
1187
|
+
const id = this.#ids.get(key);
|
|
1188
|
+
if (id !== undefined)
|
|
1189
|
+
this.#values.delete(id);
|
|
1190
|
+
this.#ids.delete(key);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
else if (this.#raw) {
|
|
1194
|
+
keyScratch.encode(key);
|
|
1195
|
+
removed = this.#wasm.deleteRaw(keyScratch.ptr, keyScratch.len);
|
|
1196
|
+
}
|
|
1197
|
+
else {
|
|
1198
|
+
removed = this.#wasm.delete(key);
|
|
1199
|
+
}
|
|
1200
|
+
return removed;
|
|
1201
|
+
}
|
|
723
1202
|
// ----------------------------------------------------------- persistence
|
|
724
1203
|
async #setupPersistence(spec) {
|
|
725
1204
|
if (!spec)
|
|
@@ -830,7 +1309,8 @@ export class BlazeCache {
|
|
|
830
1309
|
if (typeof record?.key !== 'string') {
|
|
831
1310
|
reason = 'key is missing or not a string';
|
|
832
1311
|
}
|
|
833
|
-
else if (!Array.isArray(record.tags) ||
|
|
1312
|
+
else if (!Array.isArray(record.tags) ||
|
|
1313
|
+
record.tags.some((tag) => typeof tag !== 'string')) {
|
|
834
1314
|
reason = 'tags are not an array of strings';
|
|
835
1315
|
}
|
|
836
1316
|
else if (record.ttlMs !== null &&
|
|
@@ -861,13 +1341,13 @@ export class BlazeCache {
|
|
|
861
1341
|
}
|
|
862
1342
|
// Opt-in resurrection: the original TTL window, restarted from now. Fresh but
|
|
863
1343
|
// not forever — and never the dead remainder, which reads as "never expires".
|
|
864
|
-
this.#
|
|
1344
|
+
this.#writeDirect(record.key, record.value, record.ttlMs, record.tags);
|
|
865
1345
|
restored += 1;
|
|
866
1346
|
continue;
|
|
867
1347
|
}
|
|
868
1348
|
// Direct wasm call: hydration is not a user write, so it emits no event — nor any
|
|
869
1349
|
// change for persistence (the adapter it came from is already up to date).
|
|
870
|
-
this.#
|
|
1350
|
+
this.#writeDirect(record.key, record.value, remaining, record.tags);
|
|
871
1351
|
restored += 1;
|
|
872
1352
|
}
|
|
873
1353
|
catch (error) {
|
|
@@ -974,7 +1454,7 @@ export class BlazeCache {
|
|
|
974
1454
|
}
|
|
975
1455
|
const records = [];
|
|
976
1456
|
for (const key of dirty.slice(-this.#maxRecords)) {
|
|
977
|
-
const entry = this.#
|
|
1457
|
+
const entry = this.#entryFor(key);
|
|
978
1458
|
if (!entry)
|
|
979
1459
|
continue;
|
|
980
1460
|
records.push({
|
|
@@ -1158,7 +1638,7 @@ export class BlazeCache {
|
|
|
1158
1638
|
* caller's to drop (`cache.clear()`), and a full-clear queued by that call is already
|
|
1159
1639
|
* neutralised here — the queues it would have set are gone.
|
|
1160
1640
|
*/
|
|
1161
|
-
async #rotate(generation) {
|
|
1641
|
+
async #rotate(generation, publish = true) {
|
|
1162
1642
|
if (typeof generation !== 'string') {
|
|
1163
1643
|
throw new TypeError(`[blaze-cache] persistence.rotate expects a string generation, got ${typeof generation}.`);
|
|
1164
1644
|
}
|
|
@@ -1192,6 +1672,10 @@ export class BlazeCache {
|
|
|
1192
1672
|
}
|
|
1193
1673
|
this.#statRotations += 1;
|
|
1194
1674
|
this.#activity({ type: 'rotate', generation });
|
|
1675
|
+
if (publish) {
|
|
1676
|
+
this.#multiTab?.publishRotate(generation);
|
|
1677
|
+
this.#multiTab?.markEpoch();
|
|
1678
|
+
}
|
|
1195
1679
|
}
|
|
1196
1680
|
/** A fresh snapshot of the counters behind `persistence.stats()`. */
|
|
1197
1681
|
#persistenceStats() {
|
|
@@ -1264,9 +1748,56 @@ export class BlazeCache {
|
|
|
1264
1748
|
* the `!#disposed` check inside `#notify` cannot change the outcome here.
|
|
1265
1749
|
*/
|
|
1266
1750
|
get #hasChangeConsumers() {
|
|
1267
|
-
return this.#events.size > 0 || this.#persist !== null;
|
|
1751
|
+
return this.#events.size > 0 || this.#persist !== null || this.#multiTab?.active === true;
|
|
1268
1752
|
}
|
|
1269
|
-
|
|
1753
|
+
/**
|
|
1754
|
+
* Bookkeeping + event delivery for a mutation.
|
|
1755
|
+
*
|
|
1756
|
+
* `publish` is `false` only for mutations applied *from* another tab: those still wake local
|
|
1757
|
+
* listeners and the persistence queue, but are never sent back to the channel. That single
|
|
1758
|
+
* flag is what makes echo storms impossible.
|
|
1759
|
+
*/
|
|
1760
|
+
#notify(change, publish = true) {
|
|
1761
|
+
const sync = this.#multiTab;
|
|
1762
|
+
if (publish && sync?.active) {
|
|
1763
|
+
switch (change.type) {
|
|
1764
|
+
case 'set': {
|
|
1765
|
+
const entry = this.#entryFor(change.key);
|
|
1766
|
+
sync.publishSet(change.key, entry?.value, entry?.ttlMs ?? null, entry?.tags ?? []);
|
|
1767
|
+
const version = sync.lastVersion;
|
|
1768
|
+
if (version)
|
|
1769
|
+
this.#versions.set(change.key, version);
|
|
1770
|
+
break;
|
|
1771
|
+
}
|
|
1772
|
+
case 'touch': {
|
|
1773
|
+
const entry = this.#entryFor(change.key);
|
|
1774
|
+
sync.publishSet(change.key, entry?.value, entry?.ttlMs ?? null, entry?.tags ?? []);
|
|
1775
|
+
const version = sync.lastVersion;
|
|
1776
|
+
if (version)
|
|
1777
|
+
this.#versions.set(change.key, version);
|
|
1778
|
+
break;
|
|
1779
|
+
}
|
|
1780
|
+
case 'delete': {
|
|
1781
|
+
sync.publishDelete(change.key);
|
|
1782
|
+
const version = sync.lastVersion;
|
|
1783
|
+
if (version)
|
|
1784
|
+
this.#versions.set(change.key, version);
|
|
1785
|
+
break;
|
|
1786
|
+
}
|
|
1787
|
+
case 'clear':
|
|
1788
|
+
sync.publishClear();
|
|
1789
|
+
sync.markEpoch();
|
|
1790
|
+
this.#versions.clear();
|
|
1791
|
+
break;
|
|
1792
|
+
case 'invalidate':
|
|
1793
|
+
// The change now carries `tags` too, but `invalidateTags()` already published the
|
|
1794
|
+
// original list; publishing again would send a duplicate message to other tabs.
|
|
1795
|
+
break;
|
|
1796
|
+
case 'prune':
|
|
1797
|
+
// A local reclamation — no peer needs it.
|
|
1798
|
+
break;
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1270
1801
|
if (this.#persist && !this.#disposed) {
|
|
1271
1802
|
switch (change.type) {
|
|
1272
1803
|
case 'set':
|
|
@@ -1297,6 +1828,47 @@ export class BlazeCache {
|
|
|
1297
1828
|
// siblings (see `events.ts`).
|
|
1298
1829
|
this.#events.emit(change);
|
|
1299
1830
|
}
|
|
1831
|
+
// ------------------------------------------------- JS-authoritative internals (storage: 'js')
|
|
1832
|
+
/** Drops a key/id pair from the local value store. Idempotent. */
|
|
1833
|
+
#forget(key, id) {
|
|
1834
|
+
this.#values.delete(id);
|
|
1835
|
+
this.#ids.delete(key);
|
|
1836
|
+
}
|
|
1837
|
+
/** Same, for a batch of keys returned by wasm. */
|
|
1838
|
+
#forgetKeys(keys) {
|
|
1839
|
+
for (const key of keys) {
|
|
1840
|
+
const id = this.#ids.get(key);
|
|
1841
|
+
if (id !== undefined)
|
|
1842
|
+
this.#values.delete(id);
|
|
1843
|
+
this.#ids.delete(key);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
/** Full entry with the value from the right store — used by `entry()` and persistence. */
|
|
1847
|
+
#entryFor(key) {
|
|
1848
|
+
if (this.#storage === 'js') {
|
|
1849
|
+
const meta = this.#wasm.entryMeta(key);
|
|
1850
|
+
if (!meta)
|
|
1851
|
+
return undefined;
|
|
1852
|
+
return {
|
|
1853
|
+
key: meta.key,
|
|
1854
|
+
value: this.#values.get(meta.id),
|
|
1855
|
+
ttlMs: meta.ttlMs,
|
|
1856
|
+
tags: meta.tags,
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
return this.#wasm.entry(key);
|
|
1860
|
+
}
|
|
1861
|
+
/** A write from hydrate: metadata + value, with no event or persistence bookkeeping. */
|
|
1862
|
+
#writeDirect(key, value, ttlMs, tags) {
|
|
1863
|
+
if (this.#storage === 'js') {
|
|
1864
|
+
const id = this.#wasm.setMeta(key, ttlMs, tags);
|
|
1865
|
+
this.#values.set(id, value);
|
|
1866
|
+
this.#ids.set(key, id);
|
|
1867
|
+
}
|
|
1868
|
+
else {
|
|
1869
|
+
this.#wasm.set(key, value, ttlMs, tags);
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1300
1872
|
/**
|
|
1301
1873
|
* Emits `evict`/`expire` for every entry the Rust core reclaimed during the operation
|
|
1302
1874
|
* that just ran — a capacity sweep inside `set`, or lazy TTL reclamation inside `get`.
|
|
@@ -1308,7 +1880,13 @@ export class BlazeCache {
|
|
|
1308
1880
|
#drainDrops() {
|
|
1309
1881
|
const drops = this.#wasm.drainDrops();
|
|
1310
1882
|
for (let i = 0; i < drops.length; i += 1) {
|
|
1311
|
-
const {
|
|
1883
|
+
const { id, key, reason } = drops[i];
|
|
1884
|
+
// The wasm drop's `value` is a sentinel in JS-authoritative mode; the real value lives
|
|
1885
|
+
// in `#values` under the id the core now reports. Release it and deliver it to listeners
|
|
1886
|
+
// exactly as in wasm mode, so `evict`/`expire` stay indistinguishable to callers.
|
|
1887
|
+
const value = (this.#storage === 'js' ? this.#values.get(id) : drops[i].value);
|
|
1888
|
+
if (this.#storage === 'js')
|
|
1889
|
+
this.#forget(key, id);
|
|
1312
1890
|
if (reason === 'evict')
|
|
1313
1891
|
this.#events.emit('evict', { type: 'evict', key, value });
|
|
1314
1892
|
else
|
|
@@ -1328,7 +1906,9 @@ export class BlazeCache {
|
|
|
1328
1906
|
#syncDropTracking() {
|
|
1329
1907
|
if (this.#disposed)
|
|
1330
1908
|
return;
|
|
1331
|
-
|
|
1909
|
+
// In JS-authoritative mode the drop log is structural (it drives Map cleanup), not just
|
|
1910
|
+
// an observer convenience — it must stay on even with zero event listeners.
|
|
1911
|
+
const wanted = this.#storage === 'js' || this.#events.wantsDrops;
|
|
1332
1912
|
if (wanted === this.#dropTracking)
|
|
1333
1913
|
return;
|
|
1334
1914
|
this.#dropTracking = wanted;
|