@blaze-cache/core 0.2.0-beta → 0.2.3-beta

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/dist/cache.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CacheEventBus } from './events.js';
1
2
  import { initBlazeWasm, WasmCache } from './wasm.js';
2
3
  import { indexedDbPersistence } from './persistence/indexeddb.js';
3
4
  /** Entries held when `capacity` is not given. */
@@ -30,12 +31,88 @@ const NO_TAGS = [];
30
31
  * await cache.dispose();
31
32
  * ```
32
33
  *
34
+ * ### Value ownership
35
+ *
36
+ * Values are held — and handed back — **by reference**. The object you pass to
37
+ * {@link BlazeCache.set} is the very object {@link BlazeCache.get}, {@link BlazeCache.peek},
38
+ * {@link BlazeCache.entry} and {@link BlazeCache.entries} return later: mutating either one
39
+ * silently rewrites the cache — and, after the next flush, the persisted row — with no error
40
+ * and no warning. Treat values living in the cache as read-only: clone on the way *out*
41
+ * (`structuredClone(cache.get(key))`) before editing, or clone on the way *in* if you want
42
+ * to keep mutating your own copy. The sharing is deliberate, not an oversight — the Rust
43
+ * core promises allocation-free `get`/`set` precisely *because* values are never cloned or
44
+ * serialised on the hot path, and cloning on read would only close one half of the alias
45
+ * anyway (your original reference from `set` survives either way). The contract is
46
+ * ownership transfer, not deep-copy semantics.
47
+ *
48
+ * ### Events
49
+ *
50
+ * {@link BlazeCache.on} subscribes to one {@link CacheEventType} — `on('set', listener)` —
51
+ * or, without a type, to **every** event; `once` fires a single time, `off` removes
52
+ * listeners without a subscription handle, and every `on`/`once` call returns its own
53
+ * unsubscribe function.
54
+ *
55
+ * Eight event types are raised here in TypeScript, describing the operation you just made.
56
+ * `evict` and `expire` are the exception: capacity sweeps and TTL reclamation happen
57
+ * *inside* the Rust core — mid-`set`, or lazily during a `get` — where no JavaScript
58
+ * exists to observe them. For those the core keeps an opt-in **drop log**. The first
59
+ * listener interested in `evict`/`expire` (a typed one, or any wildcard) switches the log
60
+ * on through the wasm binding, and after every operation that can reclaim memory (`get`,
61
+ * `getMany`, `set`, `setMany`) this class drains it and emits one event per dropped entry:
62
+ * `{ type: 'evict' | 'expire', key, value }`, with `value` coming back as the cache's live
63
+ * reference — exactly what you would have got from `get` one moment earlier. While no such
64
+ * listener exists the log stays off and the hot path pays a single predictable branch at
65
+ * the moment an entry dies — never per read or write.
66
+ *
67
+ * ```ts
68
+ * const offEvict = cache.on('evict', ({ key, value }) => {
69
+ * console.log('the cache dropped', key, value);
70
+ * });
71
+ *
72
+ * const offAll = cache.on((event) => { // wildcard — every event type
73
+ * if (event.type === 'hit') console.log('hit', event.key);
74
+ * });
75
+ *
76
+ * cache.once('clear', () => console.log('first clear, only once'));
77
+ *
78
+ * offEvict(); // unsubscribe one handle
79
+ * cache.off('evict'); // …or drop every `evict` listener
80
+ * cache.off(); // …or every listener, period
81
+ * ```
82
+ *
83
+ * Wildcard listeners receive the full {@link CacheEvent} union, so narrow on
84
+ * `event.type` before reading fields. A listener that throws is isolated: the failure is
85
+ * logged with `console.error`, the mutation it was told about stands, and the remaining
86
+ * listeners still run. Listeners run synchronously, in registration order per type (typed
87
+ * listeners first, wildcards last) — an event is never delivered to a listener that
88
+ * unsubscribed before its turn.
89
+ *
90
+ * Code written against the original `on(listener)` API keeps working: that form *is* the
91
+ * wildcard now, so such listeners additionally see `hit`/`miss`/`evict`/`expire`.
92
+ *
93
+ * ### Multiple tabs
94
+ *
95
+ * Tabs share one IndexedDB namespace but nothing else: each one holds its own WebAssembly
96
+ * instance, hydrated once at startup, and each flushes the keys it wrote. There is no
97
+ * coordination between them — writes are last-writer-wins per key. For ordinary use that is
98
+ * what you want (the tab in the foreground refetches on focus and rewrites its own fresh
99
+ * copy), but a tab that keeps working while hidden — a timer, a background sync — can flush
100
+ * a value older than the one the focused tab just wrote, and after a reload that older
101
+ * value is what hydration paints until revalidation corrects it. If that matters, use a
102
+ * short `ttlMs` on records written from background tabs, or filter on a timestamp you store
103
+ * inside the value itself.
104
+ *
33
105
  * All reads and writes are synchronous — the wasm module is instantiated during `create`, so
34
106
  * the hot path never touches a `Promise`.
35
107
  */
36
108
  export class BlazeCache {
37
109
  #wasm;
38
- #listeners = new Set();
110
+ #events = new CacheEventBus(() => this.#syncDropTracking());
111
+ /**
112
+ * Mirrors {@link CacheEventBus.wantsDrops} onto the wasm core: `true` while the Rust
113
+ * side records evictions/expirations for us to drain. `false` costs nothing.
114
+ */
115
+ #dropTracking = false;
39
116
  #unbind = [];
40
117
  #persist = null;
41
118
  #flushDelayMs = DEFAULT_FLUSH_DELAY_MS;
@@ -62,16 +139,65 @@ export class BlazeCache {
62
139
  return cache;
63
140
  }
64
141
  // ------------------------------------------------------------------ reads
65
- /** Value stored under `key`, or `undefined` when missing or expired. Counts a hit/miss. */
142
+ /**
143
+ * Value stored under `key`, or `undefined` when missing or expired. Counts a hit/miss.
144
+ *
145
+ * The value comes back as the cache's **live reference** — see *Value ownership* on the
146
+ * class before mutating it. Emits {@link CacheEventMap.hit} / {@link CacheEventMap.miss}
147
+ * when someone listens, and an entry whose stored value *is* `undefined` counts as a
148
+ * miss — from the caller's side there is no way to tell it apart from absence anyway.
149
+ */
66
150
  get(key) {
67
- return this.#wasm.get(key);
151
+ const value = this.#wasm.get(key);
152
+ // `hears` first: the payload (and the boundary-crossing bookkeeping around it) is only
153
+ // built when a listener of that exact type — or a wildcard — exists.
154
+ if (value === undefined) {
155
+ if (this.#events.hears('miss'))
156
+ this.#events.emit('miss', { type: 'miss', key });
157
+ }
158
+ else if (this.#events.hears('hit')) {
159
+ this.#events.emit('hit', { type: 'hit', key, value });
160
+ }
161
+ // The core may have reclaimed an expired entry during this very lookup.
162
+ if (this.#dropTracking)
163
+ this.#drainDrops();
164
+ return value;
165
+ }
166
+ /**
167
+ * Batch lookup: returns the value for each key, or `undefined` when missing/expired.
168
+ * Crosses the wasm boundary once instead of once per key.
169
+ *
170
+ * Each hit marks the entry visited for SIEVE, exactly like {@link BlazeCache.get} — and
171
+ * emits one `hit`/`miss` event per key.
172
+ */
173
+ getMany(keys) {
174
+ const values = this.#wasm.getMany(keys);
175
+ const wantsHit = this.#events.hears('hit');
176
+ const wantsMiss = this.#events.hears('miss');
177
+ if (wantsHit || wantsMiss) {
178
+ for (let i = 0; i < keys.length; i += 1) {
179
+ const key = keys[i];
180
+ const value = values[i];
181
+ if (value === undefined) {
182
+ if (wantsMiss)
183
+ this.#events.emit('miss', { type: 'miss', key });
184
+ }
185
+ else if (wantsHit) {
186
+ this.#events.emit('hit', { type: 'hit', key, value });
187
+ }
188
+ }
189
+ }
190
+ if (this.#dropTracking)
191
+ this.#drainDrops();
192
+ return values;
68
193
  }
69
194
  /**
70
195
  * The same lookup as {@link BlazeCache.get}, minus every side effect: no hit or miss is
71
196
  * recorded, the entry is not marked used for eviction, and nothing is reclaimed.
72
197
  *
73
198
  * The read for "is this here?" questions — a UI check must not be able to move the hit
74
- * rate or decide who gets evicted next.
199
+ * rate or decide who gets evicted next. The value is still the cache's **live reference**,
200
+ * exactly like {@link BlazeCache.get}.
75
201
  */
76
202
  peek(key) {
77
203
  return this.#wasm.peek(key);
@@ -90,11 +216,28 @@ export class BlazeCache {
90
216
  has(key) {
91
217
  return this.#wasm.has(key);
92
218
  }
93
- /** Live entry — value, remaining TTL and tags — without touching statistics. */
219
+ /**
220
+ * Batch existence check: returns `true` for each key that is present and not expired.
221
+ * Crosses the wasm boundary once instead of once per key.
222
+ */
223
+ hasMany(keys) {
224
+ const flags = this.#wasm.hasMany(keys);
225
+ const result = new Array(flags.length);
226
+ for (let i = 0; i < flags.length; i += 1)
227
+ result[i] = flags[i] === 1;
228
+ return result;
229
+ }
230
+ /**
231
+ * Live entry — value, remaining TTL and tags — without touching statistics. The `value`
232
+ * field is the cache's live reference — see *Value ownership* on the class.
233
+ */
94
234
  entry(key) {
95
235
  return this.#wasm.entry(key);
96
236
  }
97
- /** Snapshot of every live entry, oldest first. */
237
+ /**
238
+ * Snapshot of every live entry, oldest first. The `value` fields are the cache's live
239
+ * references — see *Value ownership* on the class.
240
+ */
98
241
  entries() {
99
242
  return this.#wasm.entries();
100
243
  }
@@ -134,7 +277,12 @@ export class BlazeCache {
134
277
  return { ...base, hitRate: total === 0 ? 0 : base.hits / total };
135
278
  }
136
279
  // ----------------------------------------------------------------- writes
137
- /** Stores (or replaces) `key`. Replacing refreshes the TTL and replaces the tags. */
280
+ /**
281
+ * Stores (or replaces) `key`. Replacing refreshes the TTL and replaces the tags.
282
+ *
283
+ * The value is stored **by reference** — the cache takes ownership for the lifetime of the
284
+ * entry, so mutating it afterwards rewrites the cache (see *Value ownership* on the class).
285
+ */
138
286
  set(key, value, options) {
139
287
  // No defensive copy of `tags`: the binding reads the array synchronously while building
140
288
  // the wasm call and never retains it, so the `readonly`→`string[]` cast below is safe.
@@ -142,6 +290,46 @@ export class BlazeCache {
142
290
  this.#wasm.set(key, value, options?.ttlMs ?? null, (options?.tags ?? NO_TAGS));
143
291
  if (this.#hasChangeConsumers)
144
292
  this.#notify({ type: 'set', key });
293
+ // Capacity pressure is applied inside the wasm call: entries it dropped surface here.
294
+ if (this.#dropTracking)
295
+ this.#drainDrops();
296
+ }
297
+ /**
298
+ * Batch write: stores every key/value pair in one wasm boundary crossing.
299
+ *
300
+ * Each entry's `ttlMs` and `tags` are applied independently. A negative `ttlMs` means
301
+ * "no expiry". Crosses the boundary once instead of once per entry.
302
+ *
303
+ * Listeners are notified for each entry when change consumers exist.
304
+ */
305
+ setMany(entries) {
306
+ const n = entries.length;
307
+ const keys = new Array(n);
308
+ const values = new Array(n);
309
+ const ttlMs = new Float64Array(n);
310
+ const tagsFlat = [];
311
+ const tagOffsets = new Uint32Array(n + 1);
312
+ tagOffsets[0] = 0;
313
+ for (let i = 0; i < n; i += 1) {
314
+ const entry = entries[i];
315
+ keys[i] = entry.key;
316
+ values[i] = entry.value;
317
+ ttlMs[i] = entry.options?.ttlMs ?? -1;
318
+ const tags = entry.options?.tags;
319
+ if (tags) {
320
+ for (const tag of tags)
321
+ tagsFlat.push(tag);
322
+ }
323
+ tagOffsets[i + 1] = tagsFlat.length;
324
+ }
325
+ this.#wasm.setMany(keys, values, ttlMs, tagsFlat, tagOffsets);
326
+ if (this.#hasChangeConsumers) {
327
+ for (let i = 0; i < n; i += 1)
328
+ this.#notify({ type: 'set', key: entries[i].key });
329
+ }
330
+ // One sweep can span the whole batch — drain once, after every write landed.
331
+ if (this.#dropTracking)
332
+ this.#drainDrops();
145
333
  }
146
334
  /**
147
335
  * Marks `key` as recently used for eviction and optionally renews its TTL — the stored
@@ -166,6 +354,23 @@ export class BlazeCache {
166
354
  this.#notify({ type: 'delete', key });
167
355
  return removed;
168
356
  }
357
+ /**
358
+ * Batch delete: removes every key, returning `true` for each key that was present.
359
+ * Crosses the wasm boundary once instead of once per key.
360
+ */
361
+ deleteMany(keys) {
362
+ const removed = this.#wasm.deleteMany(keys);
363
+ const result = new Array(removed.length);
364
+ for (let i = 0; i < removed.length; i += 1)
365
+ result[i] = removed[i] === 1;
366
+ if (this.#hasChangeConsumers) {
367
+ for (let i = 0; i < removed.length; i += 1) {
368
+ if (result[i])
369
+ this.#notify({ type: 'delete', key: keys[i] });
370
+ }
371
+ }
372
+ return result;
373
+ }
169
374
  /** Removes every entry carrying any of `tags`, returning the removed keys. */
170
375
  invalidateTags(...tags) {
171
376
  if (tags.length === 0)
@@ -194,24 +399,36 @@ export class BlazeCache {
194
399
  resetStats() {
195
400
  this.#wasm.resetStats();
196
401
  }
197
- // ------------------------------------------------------------- observers
198
- /**
199
- * Subscribes to mutations. Returns the unsubscribe function.
200
- *
201
- * Persistence uses this internally, so listeners fire for every change regardless of
202
- * whether storage is enabled.
203
- */
204
- on(listener) {
205
- this.#listeners.add(listener);
206
- return () => {
207
- this.#listeners.delete(listener);
208
- };
402
+ on(typeOrListener, maybeListener) {
403
+ // The bus's change hook keeps `#dropTracking` in step with the subscriber set, so
404
+ // neither registration nor the returned unsubscribe has to remember the wasm call.
405
+ return maybeListener === undefined
406
+ ? this.#events.on(typeOrListener)
407
+ : this.#events.on(typeOrListener, maybeListener);
408
+ }
409
+ once(typeOrListener, maybeListener) {
410
+ return maybeListener === undefined
411
+ ? this.#events.once(typeOrListener)
412
+ : this.#events.once(typeOrListener, maybeListener);
413
+ }
414
+ off(typeOrListener, listener) {
415
+ if (typeOrListener === undefined)
416
+ this.#events.off();
417
+ else if (listener === undefined)
418
+ this.#events.off(typeOrListener);
419
+ else
420
+ this.#events.off(typeOrListener, listener);
209
421
  }
210
422
  /**
211
423
  * Writes pending changes to storage immediately.
212
424
  *
213
425
  * Resolves once the underlying transaction commits. Concurrent calls are serialised, so
214
426
  * this is safe to call from a `beforeunload` handler while a debounced flush is pending.
427
+ *
428
+ * When the write itself fails — quota, a blocked or transient IndexedDB error — the pass
429
+ * rejects **and hands every record it had claimed back onto the queue**, so the next flush
430
+ * (a later mutation's timer, an explicit call, `pagehide`, `dispose`) retries them instead
431
+ * of losing them.
215
432
  */
216
433
  flush() {
217
434
  if (this.#disposed)
@@ -228,23 +445,37 @@ export class BlazeCache {
228
445
  * Flushes, unbinds page-lifecycle listeners and frees the wasm memory.
229
446
  *
230
447
  * The cache is unusable afterwards. A failed flush still rejects — the caller may retry or
231
- * report it.
448
+ * report it — but teardown happens in a `finally`, so a storage outage can never leak the
449
+ * wasm instance, the timers or the `pagehide`/`visibilitychange` listeners behind a
450
+ * rejected promise.
232
451
  */
233
452
  async dispose() {
234
453
  if (this.#disposed)
235
454
  return;
236
- await this.flush();
237
- this.#disposed = true;
238
- if (this.#timer !== null) {
239
- clearTimeout(this.#timer);
240
- this.#timer = null;
455
+ try {
456
+ await this.flush();
457
+ }
458
+ finally {
459
+ this.#disposed = true;
460
+ if (this.#timer !== null) {
461
+ clearTimeout(this.#timer);
462
+ this.#timer = null;
463
+ }
464
+ for (const unbind of this.#unbind.splice(0))
465
+ unbind();
466
+ this.#events.clear(); // the change hook skips the wasm sync (`#disposed` is already true)
467
+ this.#dropTracking = false;
468
+ try {
469
+ await this.#persist?.close?.();
470
+ }
471
+ catch (error) {
472
+ // Closing is best-effort (the IndexedDB adapter says as much): a failing adapter
473
+ // must neither break disposal nor mask the flush error this `finally` rethrows.
474
+ console.error('[blaze-cache] closing the persistence adapter failed.', error);
475
+ }
476
+ this.#persist = null;
477
+ this.#wasm.free();
241
478
  }
242
- for (const unbind of this.#unbind.splice(0))
243
- unbind();
244
- this.#listeners.clear();
245
- await this.#persist?.close?.();
246
- this.#persist = null;
247
- this.#wasm.free();
248
479
  }
249
480
  // ----------------------------------------------------------- persistence
250
481
  async #setupPersistence(spec) {
@@ -276,16 +507,56 @@ export class BlazeCache {
276
507
  }
277
508
  this.#bindPageLifecycle();
278
509
  }
279
- /** Fills the cache from storage, dropping records whose TTL elapsed while we were away. */
510
+ /**
511
+ * Fills the cache from storage, dropping records whose TTL elapsed while we were away —
512
+ * and records no well-formed write could ever have produced.
513
+ *
514
+ * `load()` hands back whatever sits on disk: an older package version, another tab or a
515
+ * flaky adapter may have left a row that no longer matches {@link PersistedRecord} — a
516
+ * missing key, `tags` that are not an array, a deadline that is not a number. One such row
517
+ * must cost exactly that row: every record is shape-checked (and its wasm `set` guarded)
518
+ * individually, so the remaining records still hydrate. The complaint is a single
519
+ * `console.warn` per run, not one per bad row.
520
+ */
280
521
  async #hydrate(adapter) {
281
522
  const records = await adapter.load();
282
523
  const now = Date.now();
524
+ let reported = false;
525
+ const skip = (reason, record, error) => {
526
+ if (reported)
527
+ return;
528
+ reported = true;
529
+ console.warn(`[blaze-cache] skipping malformed persisted record — ${reason}.`, record, ...(error === undefined ? [] : [error]));
530
+ };
283
531
  for (const record of records) {
284
- const remaining = record.ttlMs === null ? null : record.ttlMs - (now - record.storedAt);
285
- if (remaining !== null && remaining <= 0)
532
+ let reason = null;
533
+ if (typeof record?.key !== 'string') {
534
+ reason = 'key is missing or not a string';
535
+ }
536
+ else if (!Array.isArray(record.tags) || record.tags.some((tag) => typeof tag !== 'string')) {
537
+ reason = 'tags are not an array of strings';
538
+ }
539
+ else if (record.ttlMs !== null &&
540
+ (!Number.isFinite(record.ttlMs) || !Number.isFinite(record.storedAt))) {
541
+ // With a TTL present, both halves of the deadline must be real numbers — anything
542
+ // else yields a `NaN` that would masquerade as "never expires".
543
+ reason = 'ttl or storedAt is not a finite number';
544
+ }
545
+ if (reason !== null) {
546
+ skip(reason, record);
286
547
  continue;
287
- // Direct wasm call: hydration is not a user write, so it emits no change event.
288
- this.#wasm.set(record.key, record.value, remaining, record.tags);
548
+ }
549
+ try {
550
+ const remaining = record.ttlMs === null ? null : record.ttlMs - (now - record.storedAt);
551
+ if (remaining !== null && remaining <= 0)
552
+ continue;
553
+ // Direct wasm call: hydration is not a user write, so it emits no event — nor any
554
+ // change for persistence (the adapter it came from is already up to date).
555
+ this.#wasm.set(record.key, record.value, remaining, record.tags);
556
+ }
557
+ catch (error) {
558
+ skip('the wasm core refused the write', record, error);
559
+ }
289
560
  }
290
561
  }
291
562
  #bindPageLifecycle() {
@@ -322,38 +593,88 @@ export class BlazeCache {
322
593
  if (!persist || this.#disposed)
323
594
  return;
324
595
  // Take ownership of the pending work up front, so a `set` racing with the awaits below
325
- // lands in the *next* pass instead of being written twice.
596
+ // lands in the *next* pass instead of being written twice. The claimed records stay in
597
+ // these locals for the whole pass: if the adapter rejects — quota, a transient
598
+ // IndexedDB failure — the catch below hands every one of them back to the queues, so a
599
+ // failed flush delays work rather than destroying it. Single-flight still holds: this
600
+ // run is chained on `#chain`, and the next `flush()` chains onto *our* settled promise,
601
+ // requeued work included.
326
602
  const clearAll = this.#clearAll;
327
603
  const deleted = [...this.#deleted];
328
604
  const dirty = [...this.#dirty].filter((key) => !this.#deleted.has(key));
329
605
  this.#clearAll = false;
330
606
  this.#dirty.clear();
331
607
  this.#deleted.clear();
332
- if (clearAll)
333
- await persist.clear();
334
- if (dirty.length > 0) {
335
- const records = [];
336
- for (const key of dirty.slice(-this.#maxRecords)) {
337
- const entry = this.#wasm.entry(key);
338
- if (!entry)
339
- continue;
340
- records.push({
341
- key,
342
- value: entry.value,
343
- tags: entry.tags,
344
- ttlMs: entry.ttlMs,
345
- storedAt: Date.now(),
346
- });
608
+ let toRemove = deleted;
609
+ try {
610
+ if (clearAll)
611
+ await persist.clear();
612
+ if (dirty.length > 0) {
613
+ const records = [];
614
+ for (const key of dirty.slice(-this.#maxRecords)) {
615
+ const entry = this.#wasm.entry(key);
616
+ if (!entry)
617
+ continue;
618
+ records.push({
619
+ key,
620
+ value: entry.value,
621
+ tags: entry.tags,
622
+ ttlMs: entry.ttlMs,
623
+ storedAt: Date.now(),
624
+ });
625
+ }
626
+ if (records.length > 0)
627
+ await persist.save(records);
347
628
  }
348
- if (records.length > 0)
349
- await persist.save(records);
629
+ // Reconcile the rows the wasm core dropped on its own. A capacity eviction inside
630
+ // `set` and a lapsed TTL never queue a delete for persistence — the `evict`/`expire`
631
+ // events they emit reach subscribers only, and `prune`/`remove` callers may not have
632
+ // persisted the key either — so without this diff their rows would outlive every
633
+ // flush, be re-hydrated at the next startup, and eat quota until a
634
+ // `QuotaExceededError` kills persistence outright.
635
+ // Any key storage still holds that the wasm core no longer lists is stale. Skipped
636
+ // after `clear()` (storage was just emptied) and for adapters without `keys()`.
637
+ if (!clearAll && typeof persist.keys === 'function') {
638
+ const persisted = await persist.keys();
639
+ // Read the live set *after* the await, so a `set` landing mid-pass counts as live
640
+ // and keeps its row — and nothing awaits before `remove`, so the diff cannot go
641
+ // stale under our feet.
642
+ const live = new Set(this.#wasm.keys());
643
+ const stale = persisted.filter((key) => !live.has(key));
644
+ if (stale.length > 0)
645
+ toRemove = [...new Set([...deleted, ...stale])];
646
+ }
647
+ // One last synchronous guard: a key re-`set` while the pass was awaiting belongs to
648
+ // the *next* pass's `save`, so removing its row here would only open a window where
649
+ // memory and storage disagree.
650
+ const targets = toRemove.filter((key) => !this.#dirty.has(key));
651
+ if (targets.length > 0)
652
+ await persist.remove(targets);
653
+ }
654
+ catch (error) {
655
+ // Hand back exactly what this pass claimed. Concurrent work that landed during the
656
+ // awaits is kept as-is, and the two queues stay disjoint — a key the runner may have
657
+ // touched in the meantime belongs to whoever claimed it last.
658
+ if (clearAll)
659
+ this.#clearAll = true;
660
+ for (const key of dirty) {
661
+ // Deleted while we were awaiting? Its delete bookkeeping is already queued — don't
662
+ // resurrect it on the dirty side.
663
+ if (!this.#deleted.has(key))
664
+ this.#dirty.add(key);
665
+ }
666
+ for (const key of toRemove) {
667
+ // Re-`set` while we were awaiting? Then the next pass must save it, not delete the
668
+ // row that save would write.
669
+ if (!this.#dirty.has(key))
670
+ this.#deleted.add(key);
671
+ }
672
+ throw error;
350
673
  }
351
- if (deleted.length > 0)
352
- await persist.remove(deleted);
353
674
  }
354
675
  /**
355
676
  * `true` when a change event would actually reach someone — persistence bookkeeping or at
356
- * least one listener.
677
+ * least one event listener (wildcard or typed).
357
678
  *
358
679
  * Lets the mutation paths skip building a {@link CacheChange} object altogether when
359
680
  * nothing consumes it (memory-only cache, no subscribers). Equivalent to the conditions
@@ -361,7 +682,7 @@ export class BlazeCache {
361
682
  * the `!#disposed` check inside `#notify` cannot change the outcome here.
362
683
  */
363
684
  get #hasChangeConsumers() {
364
- return this.#listeners.size > 0 || this.#persist !== null;
685
+ return this.#events.size > 0 || this.#persist !== null;
365
686
  }
366
687
  #notify(change) {
367
688
  if (this.#persist && !this.#disposed) {
@@ -390,8 +711,46 @@ export class BlazeCache {
390
711
  }
391
712
  this.#scheduleFlush();
392
713
  }
393
- for (const listener of this.#listeners)
394
- listener(change);
714
+ // Wildcard and typed listeners alike — the bus isolates a throwing listener from its
715
+ // siblings (see `events.ts`).
716
+ this.#events.emit(change);
717
+ }
718
+ /**
719
+ * Emits `evict`/`expire` for every entry the Rust core reclaimed during the operation
720
+ * that just ran — a capacity sweep inside `set`, or lazy TTL reclamation inside `get`.
721
+ *
722
+ * Callers reach this only while `#dropTracking` is on, and the core only *records* drops
723
+ * while tracking is on, so the frequent result is an empty array: one wasm crossing that
724
+ * emits nothing. The `value` handed to listeners is the dropped entry's live reference.
725
+ */
726
+ #drainDrops() {
727
+ const drops = this.#wasm.drainDrops();
728
+ for (let i = 0; i < drops.length; i += 1) {
729
+ const { key, value, reason } = drops[i];
730
+ if (reason === 'evict')
731
+ this.#events.emit('evict', { type: 'evict', key, value });
732
+ else
733
+ this.#events.emit('expire', { type: 'expire', key, value });
734
+ }
735
+ }
736
+ /**
737
+ * Mirrors the subscriber set onto the wasm core: while *any* listener cares about
738
+ * `evict`/`expire` — a typed one or any wildcard — the Rust core's opt-in drop log
739
+ * collects the entries the cache drops by itself; when the last such listener goes away
740
+ * the log is switched off (which also discards anything not yet drained).
741
+ *
742
+ * Driven by the event bus's change hook, so it runs after every `on`/`once`/`off` —
743
+ * including the removal a fired `once` performs — and no call site has to remember it.
744
+ * Skipped after `dispose`: the wasm instance is already gone.
745
+ */
746
+ #syncDropTracking() {
747
+ if (this.#disposed)
748
+ return;
749
+ const wanted = this.#events.wantsDrops;
750
+ if (wanted === this.#dropTracking)
751
+ return;
752
+ this.#dropTracking = wanted;
753
+ this.#wasm.setDropTracking(wanted);
395
754
  }
396
755
  }
397
756
  /** Shorthand for {@link BlazeCache.create}. */