@blaze-cache/core 0.4.0-beta.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,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;
@@ -698,23 +845,45 @@ export class BlazeCache {
698
845
  }
699
846
  try {
700
847
  const remaining = record.ttlMs === null ? null : record.ttlMs - (now - record.storedAt);
701
- 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;
702
857
  continue;
858
+ }
703
859
  // Direct wasm call: hydration is not a user write, so it emits no event — nor any
704
860
  // change for persistence (the adapter it came from is already up to date).
705
861
  this.#wasm.set(record.key, record.value, remaining, record.tags);
862
+ restored += 1;
706
863
  }
707
864
  catch (error) {
708
865
  skip('the wasm core refused the write', record, error);
709
866
  }
710
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
+ });
711
880
  }
712
881
  #bindPageLifecycle() {
713
882
  if (typeof window === 'undefined')
714
883
  return;
715
884
  const flush = () => {
716
885
  void this.flush().catch((error) => {
717
- console.error('[blaze-cache] flush on page hide failed.', error);
886
+ this.#notifyError(error, '[blaze-cache] flush on page hide failed.');
718
887
  });
719
888
  };
720
889
  const onVisibility = () => {
@@ -729,19 +898,29 @@ export class BlazeCache {
729
898
  });
730
899
  }
731
900
  #scheduleFlush() {
732
- if (this.#timer !== null)
901
+ if (this.#disposed || this.#timer !== null)
733
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;
734
907
  this.#timer = setTimeout(() => {
735
908
  this.#timer = null;
736
909
  void this.flush().catch((error) => {
737
- console.error('[blaze-cache] background flush failed.', error);
910
+ this.#notifyError(error, '[blaze-cache] background flush failed.');
738
911
  });
739
- }, this.#flushDelayMs);
912
+ }, delay);
740
913
  }
741
914
  async #runFlush() {
742
915
  const persist = this.#persist;
743
916
  if (!persist || this.#disposed)
744
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();
745
924
  // Take ownership of the pending work up front, so a `set` racing with the awaits below
746
925
  // lands in the *next* pass instead of being written twice. The claimed records stay in
747
926
  // these locals for the whole pass: if the adapter rejects — quota, a transient
@@ -755,27 +934,13 @@ export class BlazeCache {
755
934
  this.#clearAll = false;
756
935
  this.#dirty.clear();
757
936
  this.#deleted.clear();
937
+ this.#activity({
938
+ type: 'flush-start',
939
+ generation,
940
+ records: dirty.length + deleted.length,
941
+ });
758
942
  let toRemove = deleted;
759
943
  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
944
  // Reconcile the rows the wasm core dropped on its own. A capacity eviction inside
780
945
  // `set` and a lapsed TTL never queue a delete for persistence — the `evict`/`expire`
781
946
  // events they emit reach subscribers only, and `prune`/`remove` callers may not have
@@ -784,27 +949,77 @@ export class BlazeCache {
784
949
  // `QuotaExceededError` kills persistence outright.
785
950
  // Any key storage still holds that the wasm core no longer lists is stale. Skipped
786
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.
787
954
  if (!clearAll && typeof persist.keys === 'function') {
788
955
  const persisted = await persist.keys();
956
+ if (epoch !== this.#epoch)
957
+ return this.#abortPass(generation);
789
958
  // 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
959
+ // and keeps its row — and nothing awaits before the write, so the diff cannot go
791
960
  // stale under our feet.
792
961
  const live = new Set(this.#wasm.keys());
793
962
  const stale = persisted.filter((key) => !live.has(key));
794
963
  if (stale.length > 0)
795
964
  toRemove = [...new Set([...deleted, ...stale])];
796
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
+ }
797
979
  // One last synchronous guard: a key re-`set` while the pass was awaiting belongs to
798
980
  // the *next* pass's `save`, so removing its row here would only open a window where
799
981
  // memory and storage disagree.
800
982
  const targets = toRemove.filter((key) => !this.#dirty.has(key));
801
- if (targets.length > 0)
802
- 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);
803
1000
  // The pass completed — every strike from earlier failures is forgiven (a temporary
804
1001
  // quota pinch must not accumulate toward dropping a key).
805
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
+ });
806
1012
  }
807
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);
808
1023
  // Hand back exactly what this pass claimed. Concurrent work that landed during the
809
1024
  // awaits is kept as-is, and the two queues stay disjoint — a key the runner may have
810
1025
  // touched in the meantime belongs to whoever claimed it last.
@@ -841,6 +1056,195 @@ export class BlazeCache {
841
1056
  throw error;
842
1057
  }
843
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
+ }
844
1248
  /**
845
1249
  * `true` when a change event would actually reach someone — persistence bookkeeping or at
846
1250
  * least one event listener (wildcard or typed).