@blaze-cache/core 0.4.0-beta.0 → 0.4.0-beta.2

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,6 +1,6 @@
1
1
  import { CacheEventBus } from './events.js';
2
2
  import { CacheSubscriptions } from './reactivity.js';
3
- import { initBlazeWasm, keyScratch, WasmCache } from './wasm.js';
3
+ import { loadBlazeWasm, keyScratch, WasmCache } from './wasm.js';
4
4
  import { indexedDbPersistence } from './persistence/indexeddb.js';
5
5
  /** Entries held when `capacity` is not given. */
6
6
  export const DEFAULT_CAPACITY = 500;
@@ -21,6 +21,20 @@ const MAX_FAILED_FLUSHES = 3;
21
21
  * a fresh `[]` per `set`. Never mutated.
22
22
  */
23
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
+ }
24
38
  /**
25
39
  * The client-side cache: WebAssembly storage and eviction, optional write-through persistence.
26
40
  *
@@ -136,6 +150,43 @@ export class BlazeCache {
136
150
  #timer = null;
137
151
  #chain = Promise.resolve();
138
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;
139
190
  /** The single in-flight teardown — overlapping {@link BlazeCache.dispose} calls share it. */
140
191
  #disposePromise = null;
141
192
  /** Consecutive failed flushes per dirty key; a key that keeps failing is dropped, not queued forever. */
@@ -146,18 +197,47 @@ export class BlazeCache {
146
197
  * for it. Created once and reused: an empty layer is a detached layer.
147
198
  */
148
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;
149
208
  constructor(wasm) {
150
209
  this.#wasm = wasm;
151
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
+ };
152
227
  }
153
228
  /**
154
229
  * Loads the wasm module, builds the cache and — if requested — hydrates it from storage.
155
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
+ *
156
236
  * Storage failures (blocked IndexedDB, quota, private mode) degrade to memory-only with a
157
237
  * console warning instead of rejecting.
158
238
  */
159
239
  static async create(options = {}) {
160
- await initBlazeWasm(options.wasm);
240
+ await loadBlazeWasm(options);
161
241
  const cache = new BlazeCache(new WasmCache(options.capacity ?? DEFAULT_CAPACITY));
162
242
  await cache.#setupPersistence(options.persistence);
163
243
  return cache;
@@ -544,6 +624,29 @@ export class BlazeCache {
544
624
  subscribeTag(tag, listener, options) {
545
625
  return (this.#subs ??= new CacheSubscriptions(this)).subscribeTag(tag, listener, options);
546
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;
649
+ }
547
650
  /**
548
651
  * Writes pending changes to storage immediately.
549
652
  *
@@ -553,7 +656,9 @@ export class BlazeCache {
553
656
  * When the write itself fails — quota, a blocked or transient IndexedDB error — the pass
554
657
  * rejects **and hands every record it had claimed back onto the queue**, so the next flush
555
658
  * (a later mutation's timer, an explicit call, `pagehide`, `dispose`) retries them instead
556
- * 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.
557
662
  */
558
663
  flush() {
559
664
  if (this.#disposed)
@@ -619,40 +724,54 @@ export class BlazeCache {
619
724
  async #setupPersistence(spec) {
620
725
  if (!spec)
621
726
  return;
622
- let adapter;
623
- let flushDelayMs;
624
- let maxRecords;
625
- if ('adapter' in spec) {
626
- adapter = spec.adapter;
627
- flushDelayMs = spec.flushDelayMs;
628
- 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)}.`);
629
735
  }
630
- else {
631
- adapter = indexedDbPersistence(spec);
632
- flushDelayMs = spec.flushDelayMs;
633
- 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)}.`);
634
739
  }
635
- this.#persist = adapter;
636
- // Validated, not defaulted silently: `flushDelayMs: NaN` would make every debounce fire
637
- // immediately, and `maxRecords: 0` would persist *everything* — `slice(-0)` is the whole
638
- // array, not the empty one. A caller who passes a number gets a loud failure at `create`
639
- // rather than a mysterious persistence behaviour later.
640
- if (flushDelayMs !== undefined && (!Number.isFinite(flushDelayMs) || flushDelayMs < 0)) {
641
- this.#persist = null;
642
- 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)}.`);
643
743
  }
644
- if (maxRecords !== undefined && (!Number.isInteger(maxRecords) || maxRecords < 1)) {
645
- this.#persist = null;
646
- 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)}.`);
647
746
  }
648
- this.#flushDelayMs = flushDelayMs ?? DEFAULT_FLUSH_DELAY_MS;
649
- 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;
650
761
  try {
651
762
  await this.#hydrate(adapter);
652
763
  }
653
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.
654
768
  this.#persist = null;
769
+ this.#recordError('hydrate', error);
655
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);
656
775
  return;
657
776
  }
658
777
  this.#bindPageLifecycle();
@@ -667,12 +786,40 @@ export class BlazeCache {
667
786
  * must cost exactly that row: every record is shape-checked (and its wasm `set` guarded)
668
787
  * individually, so the remaining records still hydrate. The complaint is a single
669
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.
670
803
  */
671
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 });
672
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
+ }
673
817
  const now = Date.now();
818
+ let restored = 0;
819
+ let skipped = 0;
674
820
  let reported = false;
675
821
  const skip = (reason, record, error) => {
822
+ skipped += 1;
676
823
  if (reported)
677
824
  return;
678
825
  reported = true;
@@ -696,25 +843,56 @@ export class BlazeCache {
696
843
  skip(reason, record);
697
844
  continue;
698
845
  }
846
+ // A delete queued before this hydrate is still an intent to remove the key. Loading
847
+ // the row back into memory here would undo that delete, while the queued delete
848
+ // would then erase the row from storage on the next flush — leaving memory and
849
+ // storage disagreeing. Storage is the source being adopted, but a pending delete
850
+ // wins over it; the delete stays queued so storage is cleaned as well.
851
+ if (this.#deleted.has(record.key)) {
852
+ skipped += 1;
853
+ continue;
854
+ }
699
855
  try {
700
856
  const remaining = record.ttlMs === null ? null : record.ttlMs - (now - record.storedAt);
701
- if (remaining !== null && remaining <= 0)
857
+ if (remaining !== null && remaining <= 0) {
858
+ if (!this.#restoreExpired) {
859
+ skipped += 1; // expired on purpose — not a malformed record, so no warning
860
+ continue;
861
+ }
862
+ // Opt-in resurrection: the original TTL window, restarted from now. Fresh but
863
+ // not forever — and never the dead remainder, which reads as "never expires".
864
+ this.#wasm.set(record.key, record.value, record.ttlMs, record.tags);
865
+ restored += 1;
702
866
  continue;
867
+ }
703
868
  // Direct wasm call: hydration is not a user write, so it emits no event — nor any
704
869
  // change for persistence (the adapter it came from is already up to date).
705
870
  this.#wasm.set(record.key, record.value, remaining, record.tags);
871
+ restored += 1;
706
872
  }
707
873
  catch (error) {
708
874
  skip('the wasm core refused the write', record, error);
709
875
  }
710
876
  }
877
+ this.#clearAll = false;
878
+ this.#statHydrates += 1;
879
+ this.#statRestored += restored;
880
+ this.#statSkipped += skipped;
881
+ this.#statLastHydrateAt = Date.now();
882
+ this.#activity({
883
+ type: 'hydrate-finish',
884
+ generation,
885
+ restored,
886
+ skipped,
887
+ durationMs: Date.now() - startedAt,
888
+ });
711
889
  }
712
890
  #bindPageLifecycle() {
713
891
  if (typeof window === 'undefined')
714
892
  return;
715
893
  const flush = () => {
716
894
  void this.flush().catch((error) => {
717
- console.error('[blaze-cache] flush on page hide failed.', error);
895
+ this.#notifyError(error, '[blaze-cache] flush on page hide failed.');
718
896
  });
719
897
  };
720
898
  const onVisibility = () => {
@@ -729,19 +907,29 @@ export class BlazeCache {
729
907
  });
730
908
  }
731
909
  #scheduleFlush() {
732
- if (this.#timer !== null)
910
+ if (this.#disposed || this.#timer !== null)
733
911
  return;
912
+ // `immediate` collapses the current task into one pass (a `setMany` of 100 entries
913
+ // still writes once) instead of chaining one flush per mutation; `debounce` waits
914
+ // out the window so a burst of writes coalesces by key.
915
+ const delay = this.#writeMode === 'immediate' ? 0 : this.#flushDelayMs;
734
916
  this.#timer = setTimeout(() => {
735
917
  this.#timer = null;
736
918
  void this.flush().catch((error) => {
737
- console.error('[blaze-cache] background flush failed.', error);
919
+ this.#notifyError(error, '[blaze-cache] background flush failed.');
738
920
  });
739
- }, this.#flushDelayMs);
921
+ }, delay);
740
922
  }
741
923
  async #runFlush() {
742
924
  const persist = this.#persist;
743
925
  if (!persist || this.#disposed)
744
926
  return;
927
+ // Snapshot the session *now*: work claimed under an older generation than the one
928
+ // currently active is dropped at every checkpoint below instead of being written,
929
+ // requeued or reconciled (see `#epoch`).
930
+ const epoch = this.#epoch;
931
+ const generation = this.#generation;
932
+ const startedAt = Date.now();
745
933
  // Take ownership of the pending work up front, so a `set` racing with the awaits below
746
934
  // lands in the *next* pass instead of being written twice. The claimed records stay in
747
935
  // these locals for the whole pass: if the adapter rejects — quota, a transient
@@ -755,27 +943,13 @@ export class BlazeCache {
755
943
  this.#clearAll = false;
756
944
  this.#dirty.clear();
757
945
  this.#deleted.clear();
946
+ this.#activity({
947
+ type: 'flush-start',
948
+ generation,
949
+ records: dirty.length + deleted.length,
950
+ });
758
951
  let toRemove = deleted;
759
952
  try {
760
- if (clearAll)
761
- await persist.clear();
762
- if (dirty.length > 0) {
763
- const records = [];
764
- for (const key of dirty.slice(-this.#maxRecords)) {
765
- const entry = this.#wasm.entry(key);
766
- if (!entry)
767
- continue;
768
- records.push({
769
- key,
770
- value: entry.value,
771
- tags: entry.tags,
772
- ttlMs: entry.ttlMs,
773
- storedAt: Date.now(),
774
- });
775
- }
776
- if (records.length > 0)
777
- await persist.save(records);
778
- }
779
953
  // Reconcile the rows the wasm core dropped on its own. A capacity eviction inside
780
954
  // `set` and a lapsed TTL never queue a delete for persistence — the `evict`/`expire`
781
955
  // events they emit reach subscribers only, and `prune`/`remove` callers may not have
@@ -784,27 +958,77 @@ export class BlazeCache {
784
958
  // `QuotaExceededError` kills persistence outright.
785
959
  // Any key storage still holds that the wasm core no longer lists is stale. Skipped
786
960
  // after `clear()` (storage was just emptied) and for adapters without `keys()`.
961
+ // It runs *before* the write: a row the upcoming `save` would add belongs to a live
962
+ // key (that is why it is dirty), so it can never come back stale here.
787
963
  if (!clearAll && typeof persist.keys === 'function') {
788
964
  const persisted = await persist.keys();
965
+ if (epoch !== this.#epoch)
966
+ return this.#abortPass(generation);
789
967
  // Read the live set *after* the await, so a `set` landing mid-pass counts as live
790
- // and keeps its row — and nothing awaits before `remove`, so the diff cannot go
968
+ // and keeps its row — and nothing awaits before the write, so the diff cannot go
791
969
  // stale under our feet.
792
970
  const live = new Set(this.#wasm.keys());
793
971
  const stale = persisted.filter((key) => !live.has(key));
794
972
  if (stale.length > 0)
795
973
  toRemove = [...new Set([...deleted, ...stale])];
796
974
  }
975
+ const records = [];
976
+ for (const key of dirty.slice(-this.#maxRecords)) {
977
+ const entry = this.#wasm.entry(key);
978
+ if (!entry)
979
+ continue;
980
+ records.push({
981
+ key,
982
+ value: entry.value,
983
+ tags: entry.tags,
984
+ ttlMs: entry.ttlMs,
985
+ storedAt: Date.now(),
986
+ });
987
+ }
797
988
  // One last synchronous guard: a key re-`set` while the pass was awaiting belongs to
798
989
  // the *next* pass's `save`, so removing its row here would only open a window where
799
990
  // memory and storage disagree.
800
991
  const targets = toRemove.filter((key) => !this.#dirty.has(key));
801
- if (targets.length > 0)
802
- await persist.remove(targets);
992
+ if (clearAll || records.length > 0 || targets.length > 0) {
993
+ if (typeof persist.write === 'function') {
994
+ // One batch, one transaction: `clear` + upserts + deletes commit together
995
+ // instead of serialising as up to three separate round trips.
996
+ await persist.write({ clear: clearAll, save: records, remove: targets });
997
+ }
998
+ else {
999
+ if (clearAll)
1000
+ await persist.clear();
1001
+ if (records.length > 0)
1002
+ await persist.save(records);
1003
+ if (targets.length > 0)
1004
+ await persist.remove(targets);
1005
+ }
1006
+ }
1007
+ if (epoch !== this.#epoch)
1008
+ return this.#abortPass(generation);
803
1009
  // The pass completed — every strike from earlier failures is forgiven (a temporary
804
1010
  // quota pinch must not accumulate toward dropping a key).
805
1011
  this.#failedFlushes.clear();
1012
+ this.#statFlushes += 1;
1013
+ this.#statRecordsWritten += records.length;
1014
+ this.#statLastFlushAt = Date.now();
1015
+ this.#activity({
1016
+ type: 'flush-finish',
1017
+ generation,
1018
+ records: records.length,
1019
+ durationMs: Date.now() - startedAt,
1020
+ });
806
1021
  }
807
1022
  catch (error) {
1023
+ // The session changed while the adapter was failing: the error belongs to a
1024
+ // generation that no longer exists, and so does the work it was doing. Drop both —
1025
+ // requeueing would write the previous account's records into the next account's
1026
+ // storage on some later flush.
1027
+ if (epoch !== this.#epoch)
1028
+ return this.#abortPass(generation);
1029
+ // Recorded for `stats()`/`onActivity`; the rejection below still reaches whoever
1030
+ // awaited this flush (background passes route it to `onError` in their `catch`).
1031
+ this.#recordError('flush', error);
808
1032
  // Hand back exactly what this pass claimed. Concurrent work that landed during the
809
1033
  // awaits is kept as-is, and the two queues stay disjoint — a key the runner may have
810
1034
  // touched in the meantime belongs to whoever claimed it last.
@@ -841,6 +1065,195 @@ export class BlazeCache {
841
1065
  throw error;
842
1066
  }
843
1067
  }
1068
+ /**
1069
+ * Ends a pass whose session disappeared mid-flight: the claimed work is discarded (it
1070
+ * was never requeued), nothing else runs, and the flush resolves — a stale write must
1071
+ * not surface as an error to whoever awaited it, nor as one to the new session.
1072
+ */
1073
+ #abortPass(generation) {
1074
+ this.#statAborted += 1;
1075
+ this.#activity({ type: 'flush-abort', generation });
1076
+ }
1077
+ // ------------------------------------------------------- persistence control
1078
+ /**
1079
+ * `persistence.clear()` — empties this namespace in storage and drops every queued
1080
+ * write, without touching the cache's memory.
1081
+ *
1082
+ * Queues are dropped twice: once synchronously (so work nobody claimed yet never
1083
+ * reaches storage) and again inside the serialised pass (because an in-flight flush
1084
+ * that *fails* hands its claimed records back after our first drop). The storage wipe
1085
+ * runs on the same chain, so it always lands after writes already in flight — the
1086
+ * final state of storage is empty, not "empty, then rewritten by the pass that was
1087
+ * already running".
1088
+ */
1089
+ async #controlClear() {
1090
+ const persist = this.#persist;
1091
+ if (!persist || this.#disposed)
1092
+ return;
1093
+ const dropQueued = () => {
1094
+ this.#dirty.clear();
1095
+ this.#deleted.clear();
1096
+ this.#clearAll = false;
1097
+ this.#failedFlushes.clear();
1098
+ if (this.#timer !== null) {
1099
+ clearTimeout(this.#timer);
1100
+ this.#timer = null;
1101
+ }
1102
+ };
1103
+ dropQueued();
1104
+ const run = async () => {
1105
+ dropQueued();
1106
+ try {
1107
+ await persist.clear();
1108
+ }
1109
+ catch (error) {
1110
+ this.#recordError('clear', error);
1111
+ throw error;
1112
+ }
1113
+ };
1114
+ // Chain instead of guarding: clearing while a flush is in flight must serialise
1115
+ // behind it, exactly like two `flush()` calls do. A rejection leaves the chain
1116
+ // rejected, which the next `flush()` recovers from (it attaches both handlers).
1117
+ this.#chain = this.#chain.then(run, run);
1118
+ return this.#chain;
1119
+ }
1120
+ /**
1121
+ * `persistence.hydrate()` — reloads stored records into memory, serialised behind any
1122
+ * write already in flight. Merge, not replace: memory-only entries survive, which is
1123
+ * what makes it usable as a "storage caught up, pull it in" call. A failure rejects
1124
+ * *this* promise (the caller asked for the read) while leaving persistence attached
1125
+ * and the chain healthy — core reads and writes are never affected.
1126
+ */
1127
+ #controlHydrate() {
1128
+ const persist = this.#persist;
1129
+ if (!persist || this.#disposed)
1130
+ return Promise.resolve();
1131
+ const run = async () => {
1132
+ try {
1133
+ await this.#hydrate(persist);
1134
+ }
1135
+ catch (error) {
1136
+ this.#recordError('hydrate', error);
1137
+ throw error;
1138
+ }
1139
+ };
1140
+ const result = this.#chain.then(run, run);
1141
+ // The chain must outlive a rejected hydrate: swallow the failure *there* while the
1142
+ // caller still receives the original rejection from `result`.
1143
+ this.#chain = result.then(() => { }, () => { });
1144
+ return result;
1145
+ }
1146
+ /**
1147
+ * `persistence.rotate(generation)` — the logout/login switch.
1148
+ *
1149
+ * The epoch bump, the queue drop and the timer cancel all happen **synchronously**,
1150
+ * before the first `await`: from this instant every pass still in flight fails its
1151
+ * next epoch check and drops its claimed work, and every queued write belongs to a
1152
+ * session that no longer exists. The adapter then adopts the new generation — its
1153
+ * already-running operations keep the bucket they snapshotted, so a save that lands
1154
+ * after this call writes into the *previous* generation's rows, which the new
1155
+ * generation can never load.
1156
+ *
1157
+ * Memory is deliberately untouched: entries left behind by the old session are the
1158
+ * caller's to drop (`cache.clear()`), and a full-clear queued by that call is already
1159
+ * neutralised here — the queues it would have set are gone.
1160
+ */
1161
+ async #rotate(generation) {
1162
+ if (typeof generation !== 'string') {
1163
+ throw new TypeError(`[blaze-cache] persistence.rotate expects a string generation, got ${typeof generation}.`);
1164
+ }
1165
+ if (generation.includes('\0')) {
1166
+ throw new RangeError('[blaze-cache] persistence.rotate: a generation must not contain a NUL character ("\\0").');
1167
+ }
1168
+ if (this.#disposed)
1169
+ return;
1170
+ // --- synchronous invalidation: everything below runs before any await ---
1171
+ this.#epoch += 1;
1172
+ this.#generation = generation;
1173
+ this.#dirty.clear();
1174
+ this.#deleted.clear();
1175
+ this.#clearAll = false;
1176
+ this.#failedFlushes.clear();
1177
+ if (this.#timer !== null) {
1178
+ clearTimeout(this.#timer);
1179
+ this.#timer = null;
1180
+ }
1181
+ const persist = this.#persist;
1182
+ if (persist?.rotate) {
1183
+ try {
1184
+ await persist.rotate(generation);
1185
+ }
1186
+ catch (error) {
1187
+ // The cache-side isolation is already active (epoch + dropped queues); only the
1188
+ // adapter's bucket switch failed, so report it and let the caller decide.
1189
+ this.#recordError('rotate', error);
1190
+ throw error;
1191
+ }
1192
+ }
1193
+ this.#statRotations += 1;
1194
+ this.#activity({ type: 'rotate', generation });
1195
+ }
1196
+ /** A fresh snapshot of the counters behind `persistence.stats()`. */
1197
+ #persistenceStats() {
1198
+ return {
1199
+ enabled: this.#persist !== null,
1200
+ namespace: this.#namespace,
1201
+ generation: this.#generation,
1202
+ pending: this.#dirty.size + this.#deleted.size + (this.#clearAll ? 1 : 0),
1203
+ hydrates: this.#statHydrates,
1204
+ restored: this.#statRestored,
1205
+ skipped: this.#statSkipped,
1206
+ flushes: this.#statFlushes,
1207
+ recordsWritten: this.#statRecordsWritten,
1208
+ aborted: this.#statAborted,
1209
+ rotations: this.#statRotations,
1210
+ errors: this.#statErrors,
1211
+ lastError: this.#statLastError,
1212
+ lastFlushAt: this.#statLastFlushAt,
1213
+ lastHydrateAt: this.#statLastHydrateAt,
1214
+ };
1215
+ }
1216
+ /**
1217
+ * Hands one failure to the `onActivity` observer. Never throws: a broken observer must
1218
+ * not be able to take down the persistence layer it is observing.
1219
+ */
1220
+ #activity(activity) {
1221
+ const onActivity = this.#onActivity;
1222
+ if (!onActivity)
1223
+ return;
1224
+ try {
1225
+ onActivity(activity);
1226
+ }
1227
+ catch (error) {
1228
+ console.error('[blaze-cache] persistence onActivity observer failed.', error);
1229
+ }
1230
+ }
1231
+ /** Counts one failure for `stats()` and the activity stream. */
1232
+ #recordError(phase, error) {
1233
+ this.#statErrors += 1;
1234
+ this.#statLastError = error;
1235
+ this.#activity({ type: 'error', phase, error });
1236
+ }
1237
+ /**
1238
+ * Routes a failure **nobody awaited** — the debounced timer's flush, the pagehide
1239
+ * flush, the startup degrade — to `onError`, falling back to `console.error` when no
1240
+ * observer was given. Awaited calls (`flush()`, `hydrate()`, `clear()`, `rotate()`)
1241
+ * reject instead and never come through here; they are already recorded for
1242
+ * `stats()`/`onActivity` by whoever failed.
1243
+ */
1244
+ #notifyError(error, message = '[blaze-cache] persistence failed.') {
1245
+ const onError = this.#onError;
1246
+ if (!onError) {
1247
+ console.error(message, error);
1248
+ return;
1249
+ }
1250
+ try {
1251
+ onError(error);
1252
+ }
1253
+ catch (observerError) {
1254
+ console.error('[blaze-cache] persistence onError observer failed.', observerError);
1255
+ }
1256
+ }
844
1257
  /**
845
1258
  * `true` when a change event would actually reach someone — persistence bookkeeping or at
846
1259
  * least one event listener (wildcard or typed).