@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.
@@ -13,6 +13,21 @@ export interface PersistedRecord<V = unknown> {
13
13
  /** `Date.now()` at the moment the record was written. */
14
14
  storedAt: number;
15
15
  }
16
+ /**
17
+ * The batch one flush wants to apply — what {@link CachePersistence.write} receives.
18
+ *
19
+ * The three parts are disjoint by construction (`remove` never contains a key the same
20
+ * pass also saves), so an adapter may apply them in any order it likes as long as `clear`
21
+ * is honoured **before** the other two.
22
+ */
23
+ export interface PersistenceWriteOps {
24
+ /** `true` when the namespace must be emptied before `save` lands. */
25
+ clear?: boolean;
26
+ /** Records to upsert (last write wins per key). */
27
+ save: PersistedRecord[];
28
+ /** Keys whose rows must be deleted. */
29
+ remove: string[];
30
+ }
16
31
  /**
17
32
  * Pluggable storage backend used for write-through persistence.
18
33
  *
@@ -40,9 +55,164 @@ export interface CachePersistence {
40
55
  * diff, and any explicit `delete`/`invalidateTags`/`prune` still reaches `remove`.
41
56
  */
42
57
  keys?(): Promise<string[]>;
58
+ /**
59
+ * Applies a whole flush — `clear` + `save` + `remove` — as **one unit of work**.
60
+ *
61
+ * Optional. When present the cache hands the entire batch over instead of calling
62
+ * `clear`/`save`/`remove` separately, which turns a flush of up to three IndexedDB
63
+ * transactions into one. The adapter must make the batch atomic: either every part
64
+ * lands or none does (the built-in adapter aborts its transaction on failure).
65
+ */
66
+ write?(ops: PersistenceWriteOps): Promise<void>;
67
+ /**
68
+ * Adopts a new persistence **generation** — the session/account token that isolates
69
+ * one login from the next. Optional.
70
+ *
71
+ * Called by `cache.persistence.rotate(generation)` *after* the cache has already
72
+ * invalidated every queued and in-flight operation from the previous generation.
73
+ * Implementations must guarantee that an operation already in flight continues to
74
+ * read and write the **previous** generation's bucket (the built-in adapter snapshots
75
+ * its effective namespace per operation, so a late write lands there and is invisible
76
+ * to the new generation). Rows already stored are left alone — call `clear()` before
77
+ * `rotate()` to wipe them.
78
+ *
79
+ * Adapters without it still get the cache-level protection (queued and in-flight
80
+ * flushes are dropped on rotation), but their stored rows are not namespaced by
81
+ * generation.
82
+ */
83
+ rotate?(generation: string): void | Promise<void>;
43
84
  /** Releases any underlying handle. */
44
85
  close?(): void | Promise<void>;
45
86
  }
87
+ /** How queued writes reach storage. */
88
+ export type PersistenceWriteMode =
89
+ /** Coalesce writes and flush once the debounce window (`debounceMs`) elapses. */
90
+ 'debounce'
91
+ /** Flush on the next task after a mutation — no debounce window. */
92
+ | 'immediate';
93
+ /** The phase a {@link PersistenceActivity} `error` event belongs to. */
94
+ export type PersistenceErrorPhase = 'hydrate' | 'flush' | 'clear' | 'rotate';
95
+ /**
96
+ * Persistence activity, as reported by the `onActivity` option.
97
+ *
98
+ * The observability channel for the write-through layer: hydrate start/finish, flush
99
+ * start/finish, a flush invalidated by a generation change, and contained errors. It is
100
+ * deliberately separate from the cache's event bus — persistence activity is not a cache
101
+ * mutation, and wildcard listeners must not start waking up for it.
102
+ */
103
+ export type PersistenceActivity = {
104
+ type: 'hydrate-start';
105
+ generation: string;
106
+ } | {
107
+ type: 'hydrate-finish';
108
+ generation: string;
109
+ /** Records that made it into memory. */
110
+ restored: number;
111
+ /** Records skipped (malformed, expired, unreadable). */
112
+ skipped: number;
113
+ durationMs: number;
114
+ }
115
+ /** The generation changed while a hydrate was loading — its records were discarded. */
116
+ | {
117
+ type: 'hydrate-abort';
118
+ generation: string;
119
+ } | {
120
+ type: 'flush-start';
121
+ generation: string;
122
+ records: number;
123
+ } | {
124
+ type: 'flush-finish';
125
+ generation: string;
126
+ records: number;
127
+ durationMs: number;
128
+ }
129
+ /** The generation changed mid-flush — the pass' claimed work was dropped. */
130
+ | {
131
+ type: 'flush-abort';
132
+ generation: string;
133
+ } | {
134
+ type: 'rotate';
135
+ generation: string;
136
+ } | {
137
+ type: 'error';
138
+ phase: PersistenceErrorPhase;
139
+ error: unknown;
140
+ };
141
+ /**
142
+ * A snapshot of persistence's current state and cumulative counters — what
143
+ * `cache.persistence.stats()` returns.
144
+ *
145
+ * The counters are cumulative for the lifetime of the cache instance; the `last*`
146
+ * timestamps are `Date.now()` values (or `null` when the phase has not run yet).
147
+ */
148
+ export interface PersistenceStats {
149
+ /** `false` when persistence was never attached (or was disabled after a startup failure). */
150
+ enabled: boolean;
151
+ /** The configured namespace — `'default'` when none was given. */
152
+ namespace: string;
153
+ /** The current session generation; `''` when no generation is in use. */
154
+ generation: string;
155
+ /** Writes queued right now: dirty keys + pending deletes (+1 for a pending full clear). */
156
+ pending: number;
157
+ /** Hydrates that completed. */
158
+ hydrates: number;
159
+ /** Records restored into memory across all hydrates. */
160
+ restored: number;
161
+ /** Records skipped across all hydrates — malformed, expired or unreadable. */
162
+ skipped: number;
163
+ /** Flush passes that completed. */
164
+ flushes: number;
165
+ /** Records written across all completed flushes. */
166
+ recordsWritten: number;
167
+ /** Flushes/hydrates dropped because the generation changed mid-flight. */
168
+ aborted: number;
169
+ /** Successful {@link PersistenceControl.rotate} calls. */
170
+ rotations: number;
171
+ /** Failures the cache saw (they still reject the awaited call, when there is one). */
172
+ errors: number;
173
+ /** The most recent failure, or `null`. */
174
+ lastError: unknown;
175
+ /** `Date.now()` of the last completed flush, or `null`. */
176
+ lastFlushAt: number | null;
177
+ /** `Date.now()` of the last completed hydrate, or `null`. */
178
+ lastHydrateAt: number | null;
179
+ }
180
+ /**
181
+ * The persistence control surface — `cache.persistence`.
182
+ *
183
+ * Every method is safe to call on a cache created without persistence: they resolve as
184
+ * no-ops and `stats()` reports `enabled: false`, so application code never has to branch.
185
+ */
186
+ export interface PersistenceControl {
187
+ /** `true` while a storage adapter is attached. */
188
+ readonly enabled: boolean;
189
+ /** The current session generation; `''` when none is in use. */
190
+ readonly generation: string;
191
+ /** Writes pending changes to storage now — same as `cache.flush()`. */
192
+ flush(): Promise<void>;
193
+ /**
194
+ * Empties this namespace in storage **and** drops every queued write, without touching
195
+ * the cache's memory. Rows written by other namespaces are left alone.
196
+ */
197
+ clear(): Promise<void>;
198
+ /**
199
+ * Reloads stored records into memory (merge, not replace: memory-only entries survive).
200
+ * A queued full-clear that predates the call is dropped — storage was just adopted
201
+ * as-is, and clearing it again would contradict that.
202
+ */
203
+ hydrate(): Promise<void>;
204
+ /** A snapshot of persistence's state and counters. */
205
+ stats(): PersistenceStats;
206
+ /**
207
+ * Rotates the persistence generation — call this on logout/login.
208
+ *
209
+ * Invalidates every write queued by the previous session **and** every operation still
210
+ * in flight (a late save can no longer repopulate the next session's storage), then
211
+ * hands the new generation to the adapter. Memory is left alone: pair it with
212
+ * `cache.clear()` for a full account switch.
213
+ */
214
+ rotate(generation: string): Promise<void>;
215
+ }
46
216
  /** IndexedDB connection settings. */
47
217
  export interface IndexedDbOptions {
48
218
  /** Database name. Default `'blaze-cache'`. */
@@ -52,7 +222,108 @@ export interface IndexedDbOptions {
52
222
  /**
53
223
  * Key prefix isolating this cache from other caches in the same store.
54
224
  * Default `'default'`.
225
+ *
226
+ * Must not contain a NUL character (`\0`) — it is the separator the composite primary
227
+ * key is built from. For per-account isolation prefer {@link generation}, which can be
228
+ * rotated in place; baking the account into the namespace also works but orphans the
229
+ * previous account's rows instead of keeping them one rotation away.
55
230
  */
56
231
  namespace?: string;
232
+ /**
233
+ * Session/account token folded into the stored key space, isolating one login from the
234
+ * next. Default `''` (the plain namespace, exactly as before generations existed).
235
+ *
236
+ * Rows written under one generation are invisible to every other: `load`, `keys`,
237
+ * `clear` and a late in-flight write all stay inside the bucket they started in.
238
+ * Change it through `cache.persistence.rotate()` rather than by hand.
239
+ */
240
+ generation?: string;
241
+ }
242
+ /**
243
+ * Every option `createCache({ persistence })` accepts — one shape for the built-in
244
+ * IndexedDB adapter and for custom {@link CachePersistence} adapters alike.
245
+ *
246
+ * ```ts
247
+ * const cache = await createCache({
248
+ * persistence: {
249
+ * namespace: 'app:v1', // isolate this cache from others in the database
250
+ * debounceMs: 50, // coalesce writes for 50 ms before hitting storage
251
+ * maxEntries: 2000, // cap on records written by a single flush
252
+ * restoreExpired: false, // never resurrect records that expired while away
253
+ * writeMode: 'debounce', // or 'immediate' — flush on the next task
254
+ * onError: (err) => report(err), // failures nobody awaited
255
+ * onActivity: (a) => debug(a), // hydrate/flush/rotate lifecycle
256
+ * },
257
+ * });
258
+ * ```
259
+ */
260
+ export interface PersistenceOptions extends IndexedDbOptions {
261
+ /**
262
+ * Custom storage implementation. Omit it (keeping `namespace`/`database`/…) to use the
263
+ * built-in IndexedDB adapter.
264
+ */
265
+ adapter?: CachePersistence;
266
+ /**
267
+ * How long a write waits for more writes before reaching storage. Default `400`.
268
+ * Must be a finite number `>= 0`.
269
+ *
270
+ * The window is where write coalescing happens: repeated writes to the same key inside
271
+ * it produce **one** row, with the final value.
272
+ */
273
+ debounceMs?: number;
274
+ /**
275
+ * Legacy spelling of {@link debounceMs}. Keep one of the two — passing both with
276
+ * different values throws a `RangeError` from `create`.
277
+ *
278
+ * @deprecated Rename to `debounceMs`; this alias still works and will keep working.
279
+ */
280
+ flushDelayMs?: number;
281
+ /**
282
+ * Upper bound on the records a single flush writes (the newest `maxEntries` dirty keys
283
+ * win). Default `2000`. Must be an integer `>= 1`.
284
+ */
285
+ maxEntries?: number;
286
+ /**
287
+ * Legacy spelling of {@link maxEntries}. Keep one of the two — passing both with
288
+ * different values throws a `RangeError` from `create`.
289
+ *
290
+ * @deprecated Rename to `maxEntries`; this alias still works and will keep working.
291
+ */
292
+ maxRecords?: number;
293
+ /**
294
+ * Whether records whose TTL elapsed while the tab was away are restored on hydrate.
295
+ * Default `false` — an expired record stays gone.
296
+ *
297
+ * `true` restores them with their **original TTL window restarted from now** (fresh,
298
+ * but not forever). It is never restored with the expired remainder: a non-positive
299
+ * TTL reads as "never expires" to the wasm core, which would turn a dead record into
300
+ * an immortal one.
301
+ */
302
+ restoreExpired?: boolean;
303
+ /**
304
+ * `'debounce'` (default) waits {@link debounceMs} before writing;
305
+ * `'immediate'` flushes on the next task after a mutation — no debounce window, while
306
+ * still coalescing everything written within the current task into one pass.
307
+ */
308
+ writeMode?: PersistenceWriteMode;
309
+ /**
310
+ * Called for persistence failures **nobody awaited** — the debounced timer's flush, the
311
+ * pagehide flush, and a startup that had to fall back to memory-only. Awaited calls
312
+ * (`flush()`, `clear()`, `hydrate()`, `rotate()`) still reject with the same error, so
313
+ * treat this as an observability hook rather than the only error path.
314
+ *
315
+ * When absent, those failures go to `console.error` as before.
316
+ */
317
+ onError?: (error: unknown) => void;
318
+ /**
319
+ * Called for persistence activity: hydrate start/finish, flush start/finish, passes
320
+ * aborted by a {@link PersistenceControl.rotate}, rotations and errors. See
321
+ * {@link PersistenceActivity} for the exact shapes.
322
+ *
323
+ * This channel is separate from the cache's event bus on purpose: persistence activity
324
+ * is not a cache mutation, and a wildcard `cache.on(listener)` must not start waking
325
+ * up for it. An observer that throws is isolated (logged, never propagated).
326
+ */
327
+ onActivity?: (activity: PersistenceActivity) => void;
57
328
  }
58
329
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/persistence/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,WAAW,eAAe,CAAC,CAAC,GAAG,OAAO;IAC1C,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,CAAC,CAAC;IACT,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,mFAAmF;IACnF,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,yDAAyD;IACzD,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,kFAAkF;IAClF,IAAI,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC,CAAC;IACnC,yDAAyD;IACzD,IAAI,CAAC,OAAO,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,8BAA8B;IAC9B,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE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CAAC,EAAE,CAAC,QAAQ,EAAE,mBAAmB,KAAK,IAAI,CAAC;CACtD"}
@@ -0,0 +1,63 @@
1
+ import type { BlazeCache } from './cache.js';
2
+ import type { CacheManySubscriber, CacheKeySubscriber, CacheSubscribeOptions, CacheTagSubscriber } from './types.js';
3
+ /**
4
+ * The opt-in reactivity layer behind {@link BlazeCache.subscribe} / `subscribeTag` /
5
+ * `subscribeMany`.
6
+ *
7
+ * ## Design
8
+ *
9
+ * Nothing here runs until the first `subscribe` call. That call attaches the layer to the
10
+ * event bus — eight **typed** listeners, one per change type — and snapshots the live keys
11
+ * so `clear` (which names nothing) can still be reported precisely. From then on every
12
+ * mutation is dispatched twice over: the mirrors first, so a subscriber always observes a
13
+ * cache the layer already agrees with, and the subscribers second.
14
+ *
15
+ * Two mirrors, both dropped the moment the last subscription stops:
16
+ *
17
+ * * `#live` — the live keys, kept in step by the events themselves (a `set` adds, a
18
+ * removal deletes, `clear` empties). It is what proves a key was present when `clear`
19
+ * hit, so a subscription for an absent key is never woken by one.
20
+ * * `#tagged` — per *watched* tag, the live keys carrying it, hydrated straight from
21
+ * {@link BlazeCache.keysWithTag} the first time somebody subscribes to that tag. Removal
22
+ * events carry no tags, so this is what attributes a `delete`/`evict`/`expire`/
23
+ * `invalidate`/`prune`/`clear` to the tag subscriptions it concerns — without it the
24
+ * layer would have to guess, or poll the cache.
25
+ *
26
+ * The cost of a subscription is therefore bounded and paid only while one exists: one
27
+ * `keys()` crossing at attach, one `keysWithTag()` per watched tag, one `tagsOf()` per
28
+ * write *only while a tag subscription is live*, and a `peek()` per change to a key
29
+ * somebody actually subscribed to. With no subscription the layer does not exist and the
30
+ * hot path is untouched.
31
+ *
32
+ * Delivery mirrors the event bus: a snapshot of the subscriber set is taken before each
33
+ * notification and membership re-checked per subscriber, so one that unsubscribes mid-event
34
+ * — by its own handle, or because a `{ once: true }` sibling fired — is never visited for
35
+ * that event. A subscriber that throws is isolated with `console.error`; the mutation it
36
+ * was told about stands and the remaining subscribers still run.
37
+ */
38
+ export declare class CacheSubscriptions<V = any> {
39
+ #private;
40
+ constructor(cache: BlazeCache<V>);
41
+ /**
42
+ * Watches one key. The listener receives the key's **current** value — `undefined` once
43
+ * the change removed it or it expired — plus the mutation that woke it.
44
+ */
45
+ subscribe(key: string, listener: CacheKeySubscriber<V>, options?: CacheSubscribeOptions): () => void;
46
+ /**
47
+ * Watches several keys with one listener, which is told *which* key changed. Duplicates
48
+ * collapse, and an empty list subscribes to nothing — it never attaches and returns a
49
+ * no-op handle.
50
+ */
51
+ subscribeMany(keys: string[], listener: CacheManySubscriber<V>, options?: CacheSubscribeOptions): () => void;
52
+ /**
53
+ * Watches one tag. The listener is told which of that tag's keys the mutation touched —
54
+ * a write reports the key that entered or stayed in the tag, a removal reports the keys
55
+ * that left it — and what the mutation was.
56
+ */
57
+ subscribeTag(tag: string, listener: CacheTagSubscriber<V>, options?: CacheSubscribeOptions): () => void;
58
+ /** Re-registers the eight bus listeners after `cache.off()` dropped them. See `rebind`. */
59
+ rebind(): void;
60
+ /** Drops every subscription and detaches from the bus — `BlazeCache.dispose` calls this. */
61
+ dispose(): void;
62
+ }
63
+ //# sourceMappingURL=reactivity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reactivity.d.ts","sourceRoot":"","sources":["../src/reactivity.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAEV,mBAAmB,EACnB,kBAAkB,EAElB,qBAAqB,EAErB,kBAAkB,EACnB,MAAM,YAAY,CAAC;AA8CpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,qBAAa,kBAAkB,CAAC,CAAC,GAAG,GAAG;;gBAezB,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;IAMhC;;;OAGG;IACH,SAAS,CACP,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,kBAAkB,CAAC,CAAC,CAAC,EAC/B,OAAO,CAAC,EAAE,qBAAqB,GAC9B,MAAM,IAAI;IAUb;;;;OAIG;IACH,aAAa,CACX,IAAI,EAAE,MAAM,EAAE,EACd,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAChC,OAAO,CAAC,EAAE,qBAAqB,GAC9B,MAAM,IAAI;IAYb;;;;OAIG;IACH,YAAY,CACV,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,kBAAkB,CAAC,CAAC,CAAC,EAC/B,OAAO,CAAC,EAAE,qBAAqB,GAC9B,MAAM,IAAI;IAwBb,2FAA2F;IAC3F,MAAM,IAAI,IAAI;IAMd,4FAA4F;IAC5F,OAAO,IAAI,IAAI;CAqRhB"}