@blaze-cache/core 0.3.0 → 0.4.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/dist/cache.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CacheEventBus } from './events.js';
2
- import { initBlazeWasm, keyScratch, WasmCache } from './wasm.js';
2
+ import { CacheSubscriptions } from './reactivity.js';
3
+ import { loadBlazeWasm, keyScratch, WasmCache } from './wasm.js';
3
4
  import { indexedDbPersistence } from './persistence/indexeddb.js';
4
5
  /** Entries held when `capacity` is not given. */
5
6
  export const DEFAULT_CAPACITY = 500;
@@ -20,6 +21,20 @@ const MAX_FAILED_FLUSHES = 3;
20
21
  * a fresh `[]` per `set`. Never mutated.
21
22
  */
22
23
  const NO_TAGS = [];
24
+ /**
25
+ * Reads one persistence option that exists under a new name **and** a legacy alias
26
+ * (`debounceMs`/`flushDelayMs`, `maxEntries`/`maxRecords`).
27
+ *
28
+ * Either spelling works on its own; given both, they must agree — a silent "new name
29
+ * wins" would leave the old one rotting in a caller's config with no hint that it stopped
30
+ * having an effect. Returns the value to validate, or `undefined` when neither was given.
31
+ */
32
+ function pickPaired(primary, legacy, primaryName, legacyName) {
33
+ if (primary !== undefined && legacy !== undefined && primary !== legacy) {
34
+ throw new RangeError(`[blaze-cache] persistence.${primaryName} (${String(primary)}) and persistence.${legacyName} (${String(legacy)}) were both given and disagree — keep one spelling.`);
35
+ }
36
+ return primary ?? legacy;
37
+ }
23
38
  /**
24
39
  * The client-side cache: WebAssembly storage and eviction, optional write-through persistence.
25
40
  *
@@ -135,22 +150,94 @@ export class BlazeCache {
135
150
  #timer = null;
136
151
  #chain = Promise.resolve();
137
152
  #disposed = false;
153
+ /** The configured namespace, for {@link BlazeCache.persistence.stats}. */
154
+ #namespace = '';
155
+ /**
156
+ * The current session generation — the token rotated on logout/login. `''` means "no
157
+ * generation", i.e. the plain namespace.
158
+ */
159
+ #generation = '';
160
+ /**
161
+ * Monotonic session counter, bumped by {@link PersistenceControl.rotate}.
162
+ *
163
+ * Every asynchronous persistence pass (flush, hydrate) snapshots it before its first
164
+ * `await` and re-checks it after each one: a mismatch means the session changed
165
+ * underneath the pass, which then **drops its claimed work** instead of writing the
166
+ * previous account's records into the next account's storage — or requeueing them,
167
+ * where they would surface one flush later. Clearing memory alone never did this; a
168
+ * save already handed to the adapter cannot be un-handed, which is why the adapter
169
+ * snapshots its bucket too (see `indexedDbPersistence`).
170
+ */
171
+ #epoch = 0;
172
+ #restoreExpired = false;
173
+ #writeMode = 'debounce';
174
+ /** Observer for contained failures — replaces the default `console.error` reporting. */
175
+ #onError;
176
+ /** Observer for persistence activity (hydrate/flush/rotate/error). */
177
+ #onActivity;
178
+ // --- persistence counters behind `persistence.stats()` ---
179
+ #statHydrates = 0;
180
+ #statRestored = 0;
181
+ #statSkipped = 0;
182
+ #statFlushes = 0;
183
+ #statRecordsWritten = 0;
184
+ #statAborted = 0;
185
+ #statRotations = 0;
186
+ #statErrors = 0;
187
+ #statLastError = null;
188
+ #statLastFlushAt = null;
189
+ #statLastHydrateAt = null;
138
190
  /** The single in-flight teardown — overlapping {@link BlazeCache.dispose} calls share it. */
139
191
  #disposePromise = null;
140
192
  /** Consecutive failed flushes per dirty key; a key that keeps failing is dropped, not queued forever. */
141
193
  #failedFlushes = new Map();
194
+ /**
195
+ * The reactivity layer behind {@link BlazeCache.subscribe} and friends — `null` until the
196
+ * first subscription, so a cache nobody subscribes to never allocates it and never pays
197
+ * for it. Created once and reused: an empty layer is a detached layer.
198
+ */
199
+ #subs = null;
200
+ /**
201
+ * The {@link PersistenceControl} handed out by {@link BlazeCache.persistence} — built
202
+ * once, because every method is a closure over this instance and the state it reads
203
+ * (adapter presence, generation, counters) is only known at call time. That is also
204
+ * what lets the surface exist on a memory-only cache: the methods simply resolve as
205
+ * no-ops instead of forcing callers to branch on an option they may not remember.
206
+ */
207
+ #control;
142
208
  constructor(wasm) {
143
209
  this.#wasm = wasm;
144
210
  this.#raw = keyScratch.enabled;
211
+ // The getters below need *the instance* for private-field access: inside an object
212
+ // literal `this` would be the control object itself.
213
+ const self = this;
214
+ this.#control = {
215
+ get enabled() {
216
+ return self.#persist !== null;
217
+ },
218
+ get generation() {
219
+ return self.#generation;
220
+ },
221
+ flush: () => this.flush(),
222
+ clear: () => this.#controlClear(),
223
+ hydrate: () => this.#controlHydrate(),
224
+ rotate: (generation) => this.#rotate(generation),
225
+ stats: () => this.#persistenceStats(),
226
+ };
145
227
  }
146
228
  /**
147
229
  * Loads the wasm module, builds the cache and — if requested — hydrates it from storage.
148
230
  *
231
+ * The binary comes from the one source option given ({@link WasmLoadOptions.wasmUrl},
232
+ * {@link WasmLoadOptions.module} or {@link WasmLoadOptions.instantiate}), or from the
233
+ * asset shipped with this package when none is. Loading happens once per page: concurrent
234
+ * `create()` calls share one download and one instantiation.
235
+ *
149
236
  * Storage failures (blocked IndexedDB, quota, private mode) degrade to memory-only with a
150
237
  * console warning instead of rejecting.
151
238
  */
152
239
  static async create(options = {}) {
153
- await initBlazeWasm(options.wasm);
240
+ await loadBlazeWasm(options);
154
241
  const cache = new BlazeCache(new WasmCache(options.capacity ?? DEFAULT_CAPACITY));
155
242
  await cache.#setupPersistence(options.persistence);
156
243
  return cache;
@@ -461,6 +548,104 @@ export class BlazeCache {
461
548
  this.#events.off(typeOrListener);
462
549
  else
463
550
  this.#events.off(typeOrListener, listener);
551
+ // `off()` can only ever reach the layer's listeners *through* the bus, so this is the
552
+ // one place that has to put them back. A no-op with nothing subscribed.
553
+ this.#subs?.rebind();
554
+ }
555
+ /**
556
+ * Watches one key and runs `listener` with its **current value** every time the cache
557
+ * changes it. Returns the unsubscribe function — idempotent, and safe to call from
558
+ * inside the listener itself.
559
+ *
560
+ * This is the value-oriented front end of the event system: no `hit`/`miss`, no wildcard,
561
+ * just the key you asked for. `value` is what the cache holds *now* — the new value after
562
+ * `set`, the unchanged one after `touch`, and `undefined` after `delete`, `evict`,
563
+ * `expire`, `invalidate`, `prune` or `clear` (for `evict`/`expire` the dropped reference
564
+ * is still on `change.value`). The second argument is the mutation itself, so a listener
565
+ * can tell a renewal from a replacement without a second lookup.
566
+ *
567
+ * Everything is opt-in: with no subscription the layer does not exist and `get`/`set`
568
+ * are untouched. The first call attaches eight typed listeners to the event bus and
569
+ * snapshots the live keys; while a subscription lives, a write crosses the boundary once
570
+ * more to re-read that key's tags — and only when a {@link BlazeCache.subscribeTag}
571
+ * subscription exists. A listener that throws is isolated: the failure is logged with
572
+ * `console.error`, the mutation stands, and the other subscribers still run.
573
+ *
574
+ * @example
575
+ * ```ts
576
+ * const stop = cache.subscribe('user:42', (user, change) => {
577
+ * if (change.type === 'delete') console.log('gone');
578
+ * else console.log(change.type, user);
579
+ * });
580
+ *
581
+ * const stopOnce = cache.subscribe('ready', (v) => console.log('first change', v), { once: true });
582
+ *
583
+ * stop();
584
+ * stopOnce(); // already fired — a no-op
585
+ * ```
586
+ */
587
+ subscribe(key, listener, options) {
588
+ return (this.#subs ??= new CacheSubscriptions(this)).subscribe(key, listener, options);
589
+ }
590
+ /**
591
+ * Watches several keys with one listener, which is told **which** key changed:
592
+ * `(key, value, change)`. Duplicates collapse, an empty list subscribes to nothing (it
593
+ * never attaches and returns a no-op handle), and everything else — opt-in cost, error
594
+ * isolation, the `once` option — matches {@link BlazeCache.subscribe}.
595
+ *
596
+ * @example
597
+ * ```ts
598
+ * const stop = cache.subscribeMany(['a', 'b'], (key, value, change) => {
599
+ * console.log(`${key} is now`, value, `after a ${change.type}`);
600
+ * });
601
+ * ```
602
+ */
603
+ subscribeMany(keys, listener, options) {
604
+ return (this.#subs ??= new CacheSubscriptions(this)).subscribeMany(keys, listener, options);
605
+ }
606
+ /**
607
+ * Watches one tag and runs `listener` whenever an entry carrying it changes — including
608
+ * entries removed by an unrelated `invalidateTags` call, an eviction or a TTL that ran
609
+ * out, which is the part the raw events cannot tell you on their own.
610
+ *
611
+ * The listener receives `{ tag, keys, change }`: the tag that woke it, the keys of *that
612
+ * tag* the mutation touched (a write reports the key that entered or stayed in the tag,
613
+ * a removal reports the keys that left it), and the mutation itself. Keys are attributed
614
+ * from a per-tag mirror the layer keeps while anybody watches, so removals need no extra
615
+ * lookup. Opt-in cost, error isolation and `once` match {@link BlazeCache.subscribe}.
616
+ *
617
+ * @example
618
+ * ```ts
619
+ * const stop = cache.subscribeTag('user', ({ keys, change }) => {
620
+ * console.log(change.type, keys); // 'invalidate', ['user:42', 'user:43']
621
+ * });
622
+ * ```
623
+ */
624
+ subscribeTag(tag, listener, options) {
625
+ return (this.#subs ??= new CacheSubscriptions(this)).subscribeTag(tag, listener, options);
626
+ }
627
+ /**
628
+ * The persistence control surface: `flush()`, `clear()`, `hydrate()`, `stats()` and
629
+ * `rotate()` — see {@link PersistenceControl}.
630
+ *
631
+ * Always present, even on a memory-only cache (the methods resolve as no-ops and
632
+ * `stats().enabled` is `false`), so callers never have to remember which flavour of
633
+ * `create` they are holding.
634
+ *
635
+ * ```ts
636
+ * await cache.persistence.flush(); // same as cache.flush()
637
+ * await cache.persistence.clear(); // wipe this namespace in storage (memory stays)
638
+ * await cache.persistence.hydrate(); // reload stored records into memory
639
+ * cache.persistence.stats(); // counters: hydrates, flushes, errors, pending…
640
+ *
641
+ * // logout → login:
642
+ * await cache.persistence.rotate('user-43'); // invalidate the previous session
643
+ * cache.clear(); // drop its entries from memory
644
+ * await cache.persistence.hydrate(); // load the new session's records
645
+ * ```
646
+ */
647
+ get persistence() {
648
+ return this.#control;
464
649
  }
465
650
  /**
466
651
  * Writes pending changes to storage immediately.
@@ -471,7 +656,9 @@ export class BlazeCache {
471
656
  * When the write itself fails — quota, a blocked or transient IndexedDB error — the pass
472
657
  * rejects **and hands every record it had claimed back onto the queue**, so the next flush
473
658
  * (a later mutation's timer, an explicit call, `pagehide`, `dispose`) retries them instead
474
- * of losing them.
659
+ * of losing them. A pass invalidated by {@link PersistenceControl.rotate} is the
660
+ * exception: its claimed work belongs to a session that no longer exists, so it is
661
+ * dropped and the flush resolves without writing.
475
662
  */
476
663
  flush() {
477
664
  if (this.#disposed)
@@ -518,6 +705,7 @@ export class BlazeCache {
518
705
  }
519
706
  for (const unbind of this.#unbind.splice(0))
520
707
  unbind();
708
+ this.#subs?.dispose(); // drops the subscription layer's listeners and mirrors
521
709
  this.#events.clear(); // the change hook skips the wasm sync (`#disposed` is already true)
522
710
  this.#dropTracking = false;
523
711
  try {
@@ -536,40 +724,54 @@ export class BlazeCache {
536
724
  async #setupPersistence(spec) {
537
725
  if (!spec)
538
726
  return;
539
- let adapter;
540
- let flushDelayMs;
541
- let maxRecords;
542
- if ('adapter' in spec) {
543
- adapter = spec.adapter;
544
- flushDelayMs = spec.flushDelayMs;
545
- maxRecords = spec.maxRecords;
727
+ // ---- validate everything before touching storage or the adapter ----------
728
+ // Validated, not defaulted silently: a `debounceMs` of NaN would make every debounce
729
+ // fire immediately, and `maxEntries: 0` would persist *everything* — `slice(-0)` is
730
+ // the whole array, not the empty one. A caller who passes a bad number gets a loud
731
+ // failure at `create` rather than a mysterious persistence behaviour later.
732
+ const debounceMs = pickPaired(spec.debounceMs, spec.flushDelayMs, 'debounceMs', 'flushDelayMs');
733
+ if (debounceMs !== undefined && (!Number.isFinite(debounceMs) || debounceMs < 0)) {
734
+ throw new RangeError(`[blaze-cache] persistence.debounceMs must be a finite number >= 0, got ${String(debounceMs)}.`);
546
735
  }
547
- else {
548
- adapter = indexedDbPersistence(spec);
549
- flushDelayMs = spec.flushDelayMs;
550
- maxRecords = spec.maxRecords;
736
+ const maxEntries = pickPaired(spec.maxEntries, spec.maxRecords, 'maxEntries', 'maxRecords');
737
+ if (maxEntries !== undefined && (!Number.isInteger(maxEntries) || maxEntries < 1)) {
738
+ throw new RangeError(`[blaze-cache] persistence.maxEntries must be an integer >= 1, got ${String(maxEntries)}.`);
551
739
  }
552
- this.#persist = adapter;
553
- // Validated, not defaulted silently: `flushDelayMs: NaN` would make every debounce fire
554
- // immediately, and `maxRecords: 0` would persist *everything* — `slice(-0)` is the whole
555
- // array, not the empty one. A caller who passes a number gets a loud failure at `create`
556
- // rather than a mysterious persistence behaviour later.
557
- if (flushDelayMs !== undefined && (!Number.isFinite(flushDelayMs) || flushDelayMs < 0)) {
558
- this.#persist = null;
559
- throw new RangeError(`[blaze-cache] persistence.flushDelayMs must be a finite number >= 0, got ${String(flushDelayMs)}.`);
740
+ const writeMode = spec.writeMode ?? 'debounce';
741
+ if (writeMode !== 'debounce' && writeMode !== 'immediate') {
742
+ throw new RangeError(`[blaze-cache] persistence.writeMode must be "debounce" or "immediate", got ${String(writeMode)}.`);
560
743
  }
561
- if (maxRecords !== undefined && (!Number.isInteger(maxRecords) || maxRecords < 1)) {
562
- this.#persist = null;
563
- throw new RangeError(`[blaze-cache] persistence.maxRecords must be an integer >= 1, got ${String(maxRecords)}.`);
744
+ if (spec.restoreExpired !== undefined && typeof spec.restoreExpired !== 'boolean') {
745
+ throw new RangeError(`[blaze-cache] persistence.restoreExpired must be a boolean, got ${String(spec.restoreExpired)}.`);
564
746
  }
565
- this.#flushDelayMs = flushDelayMs ?? DEFAULT_FLUSH_DELAY_MS;
566
- this.#maxRecords = maxRecords ?? DEFAULT_MAX_RECORDS;
747
+ // ---- attach --------------------------------------------------------------
748
+ // A custom adapter takes precedence; otherwise the built-in IndexedDB one — which
749
+ // validates `namespace`/`generation` (no NUL characters) and throws from here, so a
750
+ // bad isolation setup fails `create` loudly instead of misbehaving later.
751
+ const adapter = spec.adapter ?? indexedDbPersistence(spec);
752
+ this.#persist = adapter;
753
+ this.#namespace = spec.namespace ?? 'default';
754
+ this.#generation = spec.generation ?? '';
755
+ this.#flushDelayMs = debounceMs ?? DEFAULT_FLUSH_DELAY_MS;
756
+ this.#maxRecords = maxEntries ?? DEFAULT_MAX_RECORDS;
757
+ this.#restoreExpired = spec.restoreExpired ?? false;
758
+ this.#writeMode = writeMode;
759
+ this.#onError = spec.onError;
760
+ this.#onActivity = spec.onActivity;
567
761
  try {
568
762
  await this.#hydrate(adapter);
569
763
  }
570
764
  catch (error) {
765
+ // Contained: an adapter that cannot open at all (private mode, enterprise policy)
766
+ // degrades to memory-only instead of breaking `create`. The failure is still
767
+ // recorded and handed to `onError`, so an operator watching persistence hears it.
571
768
  this.#persist = null;
769
+ this.#recordError('hydrate', error);
572
770
  console.warn('[blaze-cache] persistence unavailable — running memory-only.', error);
771
+ // The console.warn above already announced the degrade; `onError` only fires when
772
+ // somebody asked to hear about failures, so the two never double-report.
773
+ if (this.#onError)
774
+ this.#notifyError(error);
573
775
  return;
574
776
  }
575
777
  this.#bindPageLifecycle();
@@ -584,12 +786,40 @@ export class BlazeCache {
584
786
  * must cost exactly that row: every record is shape-checked (and its wasm `set` guarded)
585
787
  * individually, so the remaining records still hydrate. The complaint is a single
586
788
  * `console.warn` per run, not one per bad row.
789
+ *
790
+ * Two further guards make an explicit re-hydrate (`cache.persistence.hydrate()`, the
791
+ * login half of an account switch) safe:
792
+ *
793
+ * * **Generation** — the pass snapshots the session before `load()` and discards the
794
+ * whole result if it changed while the read was in flight, so the previous account's
795
+ * records can never land in the next account's memory.
796
+ * * **`restoreExpired: false`** (the default) keeps records that expired while the tab
797
+ * was away out of memory; `true` restores them with their original TTL window
798
+ * restarted from now — never with the non-positive remainder, which the wasm core
799
+ * would read as "never expires".
800
+ *
801
+ * A full-clear queued *before* this hydrate would erase exactly what was just loaded,
802
+ * so it is dropped once the records land.
587
803
  */
588
804
  async #hydrate(adapter) {
805
+ const epoch = this.#epoch;
806
+ const generation = this.#generation;
807
+ const startedAt = Date.now();
808
+ this.#activity({ type: 'hydrate-start', generation });
589
809
  const records = await adapter.load();
810
+ if (epoch !== this.#epoch) {
811
+ // The session changed under the read: these rows belong to a generation that no
812
+ // longer exists. Discard them — storage still holds them for their own owner.
813
+ this.#statAborted += 1;
814
+ this.#activity({ type: 'hydrate-abort', generation });
815
+ return;
816
+ }
590
817
  const now = Date.now();
818
+ let restored = 0;
819
+ let skipped = 0;
591
820
  let reported = false;
592
821
  const skip = (reason, record, error) => {
822
+ skipped += 1;
593
823
  if (reported)
594
824
  return;
595
825
  reported = true;
@@ -615,23 +845,45 @@ export class BlazeCache {
615
845
  }
616
846
  try {
617
847
  const remaining = record.ttlMs === null ? null : record.ttlMs - (now - record.storedAt);
618
- if (remaining !== null && remaining <= 0)
848
+ if (remaining !== null && remaining <= 0) {
849
+ if (!this.#restoreExpired) {
850
+ skipped += 1; // expired on purpose — not a malformed record, so no warning
851
+ continue;
852
+ }
853
+ // Opt-in resurrection: the original TTL window, restarted from now. Fresh but
854
+ // not forever — and never the dead remainder, which reads as "never expires".
855
+ this.#wasm.set(record.key, record.value, record.ttlMs, record.tags);
856
+ restored += 1;
619
857
  continue;
858
+ }
620
859
  // Direct wasm call: hydration is not a user write, so it emits no event — nor any
621
860
  // change for persistence (the adapter it came from is already up to date).
622
861
  this.#wasm.set(record.key, record.value, remaining, record.tags);
862
+ restored += 1;
623
863
  }
624
864
  catch (error) {
625
865
  skip('the wasm core refused the write', record, error);
626
866
  }
627
867
  }
868
+ this.#clearAll = false;
869
+ this.#statHydrates += 1;
870
+ this.#statRestored += restored;
871
+ this.#statSkipped += skipped;
872
+ this.#statLastHydrateAt = Date.now();
873
+ this.#activity({
874
+ type: 'hydrate-finish',
875
+ generation,
876
+ restored,
877
+ skipped,
878
+ durationMs: Date.now() - startedAt,
879
+ });
628
880
  }
629
881
  #bindPageLifecycle() {
630
882
  if (typeof window === 'undefined')
631
883
  return;
632
884
  const flush = () => {
633
885
  void this.flush().catch((error) => {
634
- console.error('[blaze-cache] flush on page hide failed.', error);
886
+ this.#notifyError(error, '[blaze-cache] flush on page hide failed.');
635
887
  });
636
888
  };
637
889
  const onVisibility = () => {
@@ -646,19 +898,29 @@ export class BlazeCache {
646
898
  });
647
899
  }
648
900
  #scheduleFlush() {
649
- if (this.#timer !== null)
901
+ if (this.#disposed || this.#timer !== null)
650
902
  return;
903
+ // `immediate` collapses the current task into one pass (a `setMany` of 100 entries
904
+ // still writes once) instead of chaining one flush per mutation; `debounce` waits
905
+ // out the window so a burst of writes coalesces by key.
906
+ const delay = this.#writeMode === 'immediate' ? 0 : this.#flushDelayMs;
651
907
  this.#timer = setTimeout(() => {
652
908
  this.#timer = null;
653
909
  void this.flush().catch((error) => {
654
- console.error('[blaze-cache] background flush failed.', error);
910
+ this.#notifyError(error, '[blaze-cache] background flush failed.');
655
911
  });
656
- }, this.#flushDelayMs);
912
+ }, delay);
657
913
  }
658
914
  async #runFlush() {
659
915
  const persist = this.#persist;
660
916
  if (!persist || this.#disposed)
661
917
  return;
918
+ // Snapshot the session *now*: work claimed under an older generation than the one
919
+ // currently active is dropped at every checkpoint below instead of being written,
920
+ // requeued or reconciled (see `#epoch`).
921
+ const epoch = this.#epoch;
922
+ const generation = this.#generation;
923
+ const startedAt = Date.now();
662
924
  // Take ownership of the pending work up front, so a `set` racing with the awaits below
663
925
  // lands in the *next* pass instead of being written twice. The claimed records stay in
664
926
  // these locals for the whole pass: if the adapter rejects — quota, a transient
@@ -672,27 +934,13 @@ export class BlazeCache {
672
934
  this.#clearAll = false;
673
935
  this.#dirty.clear();
674
936
  this.#deleted.clear();
937
+ this.#activity({
938
+ type: 'flush-start',
939
+ generation,
940
+ records: dirty.length + deleted.length,
941
+ });
675
942
  let toRemove = deleted;
676
943
  try {
677
- if (clearAll)
678
- await persist.clear();
679
- if (dirty.length > 0) {
680
- const records = [];
681
- for (const key of dirty.slice(-this.#maxRecords)) {
682
- const entry = this.#wasm.entry(key);
683
- if (!entry)
684
- continue;
685
- records.push({
686
- key,
687
- value: entry.value,
688
- tags: entry.tags,
689
- ttlMs: entry.ttlMs,
690
- storedAt: Date.now(),
691
- });
692
- }
693
- if (records.length > 0)
694
- await persist.save(records);
695
- }
696
944
  // Reconcile the rows the wasm core dropped on its own. A capacity eviction inside
697
945
  // `set` and a lapsed TTL never queue a delete for persistence — the `evict`/`expire`
698
946
  // events they emit reach subscribers only, and `prune`/`remove` callers may not have
@@ -701,27 +949,77 @@ export class BlazeCache {
701
949
  // `QuotaExceededError` kills persistence outright.
702
950
  // Any key storage still holds that the wasm core no longer lists is stale. Skipped
703
951
  // after `clear()` (storage was just emptied) and for adapters without `keys()`.
952
+ // It runs *before* the write: a row the upcoming `save` would add belongs to a live
953
+ // key (that is why it is dirty), so it can never come back stale here.
704
954
  if (!clearAll && typeof persist.keys === 'function') {
705
955
  const persisted = await persist.keys();
956
+ if (epoch !== this.#epoch)
957
+ return this.#abortPass(generation);
706
958
  // Read the live set *after* the await, so a `set` landing mid-pass counts as live
707
- // and keeps its row — and nothing awaits before `remove`, so the diff cannot go
959
+ // and keeps its row — and nothing awaits before the write, so the diff cannot go
708
960
  // stale under our feet.
709
961
  const live = new Set(this.#wasm.keys());
710
962
  const stale = persisted.filter((key) => !live.has(key));
711
963
  if (stale.length > 0)
712
964
  toRemove = [...new Set([...deleted, ...stale])];
713
965
  }
966
+ const records = [];
967
+ for (const key of dirty.slice(-this.#maxRecords)) {
968
+ const entry = this.#wasm.entry(key);
969
+ if (!entry)
970
+ continue;
971
+ records.push({
972
+ key,
973
+ value: entry.value,
974
+ tags: entry.tags,
975
+ ttlMs: entry.ttlMs,
976
+ storedAt: Date.now(),
977
+ });
978
+ }
714
979
  // One last synchronous guard: a key re-`set` while the pass was awaiting belongs to
715
980
  // the *next* pass's `save`, so removing its row here would only open a window where
716
981
  // memory and storage disagree.
717
982
  const targets = toRemove.filter((key) => !this.#dirty.has(key));
718
- if (targets.length > 0)
719
- await persist.remove(targets);
983
+ if (clearAll || records.length > 0 || targets.length > 0) {
984
+ if (typeof persist.write === 'function') {
985
+ // One batch, one transaction: `clear` + upserts + deletes commit together
986
+ // instead of serialising as up to three separate round trips.
987
+ await persist.write({ clear: clearAll, save: records, remove: targets });
988
+ }
989
+ else {
990
+ if (clearAll)
991
+ await persist.clear();
992
+ if (records.length > 0)
993
+ await persist.save(records);
994
+ if (targets.length > 0)
995
+ await persist.remove(targets);
996
+ }
997
+ }
998
+ if (epoch !== this.#epoch)
999
+ return this.#abortPass(generation);
720
1000
  // The pass completed — every strike from earlier failures is forgiven (a temporary
721
1001
  // quota pinch must not accumulate toward dropping a key).
722
1002
  this.#failedFlushes.clear();
1003
+ this.#statFlushes += 1;
1004
+ this.#statRecordsWritten += records.length;
1005
+ this.#statLastFlushAt = Date.now();
1006
+ this.#activity({
1007
+ type: 'flush-finish',
1008
+ generation,
1009
+ records: records.length,
1010
+ durationMs: Date.now() - startedAt,
1011
+ });
723
1012
  }
724
1013
  catch (error) {
1014
+ // The session changed while the adapter was failing: the error belongs to a
1015
+ // generation that no longer exists, and so does the work it was doing. Drop both —
1016
+ // requeueing would write the previous account's records into the next account's
1017
+ // storage on some later flush.
1018
+ if (epoch !== this.#epoch)
1019
+ return this.#abortPass(generation);
1020
+ // Recorded for `stats()`/`onActivity`; the rejection below still reaches whoever
1021
+ // awaited this flush (background passes route it to `onError` in their `catch`).
1022
+ this.#recordError('flush', error);
725
1023
  // Hand back exactly what this pass claimed. Concurrent work that landed during the
726
1024
  // awaits is kept as-is, and the two queues stay disjoint — a key the runner may have
727
1025
  // touched in the meantime belongs to whoever claimed it last.
@@ -758,6 +1056,195 @@ export class BlazeCache {
758
1056
  throw error;
759
1057
  }
760
1058
  }
1059
+ /**
1060
+ * Ends a pass whose session disappeared mid-flight: the claimed work is discarded (it
1061
+ * was never requeued), nothing else runs, and the flush resolves — a stale write must
1062
+ * not surface as an error to whoever awaited it, nor as one to the new session.
1063
+ */
1064
+ #abortPass(generation) {
1065
+ this.#statAborted += 1;
1066
+ this.#activity({ type: 'flush-abort', generation });
1067
+ }
1068
+ // ------------------------------------------------------- persistence control
1069
+ /**
1070
+ * `persistence.clear()` — empties this namespace in storage and drops every queued
1071
+ * write, without touching the cache's memory.
1072
+ *
1073
+ * Queues are dropped twice: once synchronously (so work nobody claimed yet never
1074
+ * reaches storage) and again inside the serialised pass (because an in-flight flush
1075
+ * that *fails* hands its claimed records back after our first drop). The storage wipe
1076
+ * runs on the same chain, so it always lands after writes already in flight — the
1077
+ * final state of storage is empty, not "empty, then rewritten by the pass that was
1078
+ * already running".
1079
+ */
1080
+ async #controlClear() {
1081
+ const persist = this.#persist;
1082
+ if (!persist || this.#disposed)
1083
+ return;
1084
+ const dropQueued = () => {
1085
+ this.#dirty.clear();
1086
+ this.#deleted.clear();
1087
+ this.#clearAll = false;
1088
+ this.#failedFlushes.clear();
1089
+ if (this.#timer !== null) {
1090
+ clearTimeout(this.#timer);
1091
+ this.#timer = null;
1092
+ }
1093
+ };
1094
+ dropQueued();
1095
+ const run = async () => {
1096
+ dropQueued();
1097
+ try {
1098
+ await persist.clear();
1099
+ }
1100
+ catch (error) {
1101
+ this.#recordError('clear', error);
1102
+ throw error;
1103
+ }
1104
+ };
1105
+ // Chain instead of guarding: clearing while a flush is in flight must serialise
1106
+ // behind it, exactly like two `flush()` calls do. A rejection leaves the chain
1107
+ // rejected, which the next `flush()` recovers from (it attaches both handlers).
1108
+ this.#chain = this.#chain.then(run, run);
1109
+ return this.#chain;
1110
+ }
1111
+ /**
1112
+ * `persistence.hydrate()` — reloads stored records into memory, serialised behind any
1113
+ * write already in flight. Merge, not replace: memory-only entries survive, which is
1114
+ * what makes it usable as a "storage caught up, pull it in" call. A failure rejects
1115
+ * *this* promise (the caller asked for the read) while leaving persistence attached
1116
+ * and the chain healthy — core reads and writes are never affected.
1117
+ */
1118
+ #controlHydrate() {
1119
+ const persist = this.#persist;
1120
+ if (!persist || this.#disposed)
1121
+ return Promise.resolve();
1122
+ const run = async () => {
1123
+ try {
1124
+ await this.#hydrate(persist);
1125
+ }
1126
+ catch (error) {
1127
+ this.#recordError('hydrate', error);
1128
+ throw error;
1129
+ }
1130
+ };
1131
+ const result = this.#chain.then(run, run);
1132
+ // The chain must outlive a rejected hydrate: swallow the failure *there* while the
1133
+ // caller still receives the original rejection from `result`.
1134
+ this.#chain = result.then(() => { }, () => { });
1135
+ return result;
1136
+ }
1137
+ /**
1138
+ * `persistence.rotate(generation)` — the logout/login switch.
1139
+ *
1140
+ * The epoch bump, the queue drop and the timer cancel all happen **synchronously**,
1141
+ * before the first `await`: from this instant every pass still in flight fails its
1142
+ * next epoch check and drops its claimed work, and every queued write belongs to a
1143
+ * session that no longer exists. The adapter then adopts the new generation — its
1144
+ * already-running operations keep the bucket they snapshotted, so a save that lands
1145
+ * after this call writes into the *previous* generation's rows, which the new
1146
+ * generation can never load.
1147
+ *
1148
+ * Memory is deliberately untouched: entries left behind by the old session are the
1149
+ * caller's to drop (`cache.clear()`), and a full-clear queued by that call is already
1150
+ * neutralised here — the queues it would have set are gone.
1151
+ */
1152
+ async #rotate(generation) {
1153
+ if (typeof generation !== 'string') {
1154
+ throw new TypeError(`[blaze-cache] persistence.rotate expects a string generation, got ${typeof generation}.`);
1155
+ }
1156
+ if (generation.includes('\0')) {
1157
+ throw new RangeError('[blaze-cache] persistence.rotate: a generation must not contain a NUL character ("\\0").');
1158
+ }
1159
+ if (this.#disposed)
1160
+ return;
1161
+ // --- synchronous invalidation: everything below runs before any await ---
1162
+ this.#epoch += 1;
1163
+ this.#generation = generation;
1164
+ this.#dirty.clear();
1165
+ this.#deleted.clear();
1166
+ this.#clearAll = false;
1167
+ this.#failedFlushes.clear();
1168
+ if (this.#timer !== null) {
1169
+ clearTimeout(this.#timer);
1170
+ this.#timer = null;
1171
+ }
1172
+ const persist = this.#persist;
1173
+ if (persist?.rotate) {
1174
+ try {
1175
+ await persist.rotate(generation);
1176
+ }
1177
+ catch (error) {
1178
+ // The cache-side isolation is already active (epoch + dropped queues); only the
1179
+ // adapter's bucket switch failed, so report it and let the caller decide.
1180
+ this.#recordError('rotate', error);
1181
+ throw error;
1182
+ }
1183
+ }
1184
+ this.#statRotations += 1;
1185
+ this.#activity({ type: 'rotate', generation });
1186
+ }
1187
+ /** A fresh snapshot of the counters behind `persistence.stats()`. */
1188
+ #persistenceStats() {
1189
+ return {
1190
+ enabled: this.#persist !== null,
1191
+ namespace: this.#namespace,
1192
+ generation: this.#generation,
1193
+ pending: this.#dirty.size + this.#deleted.size + (this.#clearAll ? 1 : 0),
1194
+ hydrates: this.#statHydrates,
1195
+ restored: this.#statRestored,
1196
+ skipped: this.#statSkipped,
1197
+ flushes: this.#statFlushes,
1198
+ recordsWritten: this.#statRecordsWritten,
1199
+ aborted: this.#statAborted,
1200
+ rotations: this.#statRotations,
1201
+ errors: this.#statErrors,
1202
+ lastError: this.#statLastError,
1203
+ lastFlushAt: this.#statLastFlushAt,
1204
+ lastHydrateAt: this.#statLastHydrateAt,
1205
+ };
1206
+ }
1207
+ /**
1208
+ * Hands one failure to the `onActivity` observer. Never throws: a broken observer must
1209
+ * not be able to take down the persistence layer it is observing.
1210
+ */
1211
+ #activity(activity) {
1212
+ const onActivity = this.#onActivity;
1213
+ if (!onActivity)
1214
+ return;
1215
+ try {
1216
+ onActivity(activity);
1217
+ }
1218
+ catch (error) {
1219
+ console.error('[blaze-cache] persistence onActivity observer failed.', error);
1220
+ }
1221
+ }
1222
+ /** Counts one failure for `stats()` and the activity stream. */
1223
+ #recordError(phase, error) {
1224
+ this.#statErrors += 1;
1225
+ this.#statLastError = error;
1226
+ this.#activity({ type: 'error', phase, error });
1227
+ }
1228
+ /**
1229
+ * Routes a failure **nobody awaited** — the debounced timer's flush, the pagehide
1230
+ * flush, the startup degrade — to `onError`, falling back to `console.error` when no
1231
+ * observer was given. Awaited calls (`flush()`, `hydrate()`, `clear()`, `rotate()`)
1232
+ * reject instead and never come through here; they are already recorded for
1233
+ * `stats()`/`onActivity` by whoever failed.
1234
+ */
1235
+ #notifyError(error, message = '[blaze-cache] persistence failed.') {
1236
+ const onError = this.#onError;
1237
+ if (!onError) {
1238
+ console.error(message, error);
1239
+ return;
1240
+ }
1241
+ try {
1242
+ onError(error);
1243
+ }
1244
+ catch (observerError) {
1245
+ console.error('[blaze-cache] persistence onError observer failed.', observerError);
1246
+ }
1247
+ }
761
1248
  /**
762
1249
  * `true` when a change event would actually reach someone — persistence bookkeeping or at
763
1250
  * least one event listener (wildcard or typed).