tricache 0.6.4 → 0.6.6

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/README.md CHANGED
@@ -20,7 +20,7 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
20
20
  | Feature | Detail |
21
21
  |---|---|
22
22
  | **Adaptive eviction** | LFU × LRU × priority score + Count-Min Sketch cross-eviction frequency; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
23
- | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **78 % survival rate** in benchmark flood tests |
23
+ | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **84 % survival rate** in benchmark flood tests |
24
24
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
25
25
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
26
26
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
@@ -243,6 +243,15 @@ CacheService.create({
243
243
  adaptiveTtlMax: 86400, // ceiling: never exceed 24 h (default)
244
244
  adaptiveTtlMultiplier: 20, // p95Ms × 20 = TTL in seconds (default)
245
245
 
246
+ // ── Singleton + rate-limit safety ──────────────────────────────────────
247
+ // strictSingleton: when true, a later create() for an existing namespace
248
+ // whose options differ from the first call THROWS instead of silently
249
+ // returning the existing instance. Guards against conflicting init points.
250
+ strictSingleton: false,
251
+ // failClosed: when true, increment() re-throws on a Redis error instead of
252
+ // failing open (returning 0). Enforces the rate-limit guard during outages.
253
+ failClosed: false,
254
+
246
255
  // ── OpenTelemetry tracer ──────────────────────────────────────────────
247
256
  // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
248
257
  // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
@@ -310,7 +319,7 @@ CacheService.create({
310
319
 
311
320
  ### `CacheService.create(options?)` → `CacheService`
312
321
 
313
- Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance.
322
+ Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance. When the new options differ from what the existing singleton was built with, this is a **silent no-op by default** (a one-time warning is logged and the `singletonDivergences` metric is incremented). Set `strictSingleton: true` on the first call to instead **throw** on a divergent later call — use this when multiple init points could pass conflicting Redis credentials or TTLs.
314
323
 
315
324
  ### `CacheService.createAsync(optionsOrPromise)` → `Promise<CacheService>`
316
325
 
@@ -334,7 +343,7 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
334
343
  |---|---|---|---|
335
344
  | `key` | `string` | — | Cache key |
336
345
  | `fetchFn` | `() => Promise<T>` | — | Called on a miss; result is cached |
337
- | `ttlSeconds` | `number` | `300` | Hard TTL in seconds |
346
+ | `ttlSeconds` | `number` | `300` | Hard TTL in seconds. **When `adaptiveTtl` is enabled, this is only authoritative until ≥ 5 samples are collected for the key — after that the library derives TTL from the p95 fetch latency** (see Adaptive TTL config). Use `opts` or a separate cache instance if you need a hard floor. |
338
347
  | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
339
348
  | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
340
349
  | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
@@ -361,7 +370,7 @@ await cache.delete('org:42'); // org:42:members is evicted too
361
370
 
362
371
  ### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
363
372
 
364
- Batch read. Returns L1-cached values for hot keys; calls `fetchFn` only with the keys that missed. Preserves input ordering.
373
+ Batch read. Checks **all three tiers** for each key — L1 (RAM), then L2 (Redis, in one pipelined `MGET`), then the L1.5 disk spill — and calls `fetchFn` only for keys that miss every tier. Preserves input ordering and counts exactly one hit per key (no double-counting across tiers).
365
374
 
366
375
  `ttl` accepts a **plain number** (uniform TTL) or a **function `(key: string) => number`** (per-key TTL). The function is only called for miss keys — L1 hits are unaffected.
367
376
 
@@ -528,7 +537,9 @@ cache.rebalance();
528
537
 
529
538
  ### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
530
539
 
531
- Redis `INCR` — atomically increments a counter, setting TTL on first write. When Redis is disabled, maintains an in-process counter with the same TTL semantics so rate-limiting works in dev/test.
540
+ Distributed counter. With Redis active, atomically increments via `INCR` and returns the fleet-wide value. **By default it fails OPEN on a Redis error** — it returns `0`, so a caller's `if (count > LIMIT) reject()` guard will NOT reject during an outage. Set `failClosed: true` to re-throw the error instead, enforcing the limit even when Redis is unavailable. Track failures via `cache.metrics().counters.errors`.
541
+
542
+ When Redis is disabled, it maintains an **in-process** counter with the same TTL semantics so dev/test rate-limiting works — but rate-limiting is then per-instance, **not fleet-wide**. A one-time warning is logged the first time this fallback is used.
532
543
 
533
544
  ### `cache.metrics()` → `CacheMetrics`
534
545
 
@@ -834,10 +845,13 @@ ioredis monitors the current master via the Sentinel topology and transparently
834
845
 
835
846
  ## ⚡ WASM Bloom filter
836
847
 
837
- A 100,000-bit filter with k=7 hash probes:
848
+ A 100,000-bit filter with k=7 hash probes is used when it is large enough for the
849
+ configured `l1MaxEntries`; otherwise a right-sized pure-JS filter is instantiated
850
+ automatically (see `createBloomFilter`). For the default 100K-bit filter:
838
851
 
839
- - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.01%**
840
- - At rated capacity (~18,000 entries) — false-positive rate ≈ **1%**
852
+ - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.00007%** (m=100,000, k=7)
853
+ - At its rated capacity (~10,400 entries) — false-positive rate ≈ **1%**
854
+ - When `l1MaxEntries` exceeds the WASM filter's ~10,400-entry capacity, a JS filter sized via the optimal formula (m = ⌈–n·ln p / (ln 2)²⌉, k = round(ln 2 · m / n) clamped to [4, 10]) is used instead — no capacity cliff.
841
855
  - The filter rebuilds automatically when stale bits from deleted/expired entries accumulate
842
856
 
843
857
  Mechanics:
@@ -858,12 +872,12 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
858
872
  |---|---|---|---|
859
873
  | `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
860
874
  | `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
861
- | `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
862
- | `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
863
- | `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
864
- | `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
875
+ | `set` — tiny payload | 1.06 M/s | 944 ns | pack() + Map.set + bloom.add |
876
+ | `set` — small payload (< 512 B) | 574.1 K/s | 1.74 µs | pack() same unified path, larger payload |
877
+ | `set` — large payload (≥ 512 B) | 228.6 K/s | 4.37 µs | pack() larger payload |
878
+ | `set` — CRITICAL priority | 843.6 K/s | 1.19 µs | same set path; skipped in eviction sort |
865
879
  | `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
866
- | `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
880
+ | `deletePattern` — glob wildcard | 18.7 K/s | 53.48 µs | O(n) Map scan |
867
881
  | Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
868
882
 
869
883
  **Iterator interface (L1 live entries, 500 entries)**
@@ -1,10 +1,3 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
1
  // src/encryption.ts
9
2
  import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync } from "crypto";
10
3
  var IV_BYTES = 12;
@@ -155,6 +148,20 @@ var CacheEncryption = class {
155
148
  get isEnabled() {
156
149
  return this._key !== null;
157
150
  }
151
+ /**
152
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
153
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
154
+ * cast in cache-service.ts — the worker pool reads these via this accessor
155
+ * instead of reaching into underscore-prefixed internals.
156
+ */
157
+ toWorkerInit() {
158
+ return {
159
+ keyBase64: this._key ? this._key.toString("base64") : "",
160
+ mode: this._mode,
161
+ prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
162
+ prevMode: this._prevMode
163
+ };
164
+ }
158
165
  // ── String (Redis) ────────────────────────────────────────────────────────
159
166
  /**
160
167
  * Encrypt a string for Redis storage.
@@ -197,18 +204,18 @@ var CacheEncryption = class {
197
204
  */
198
205
  decrypt(value) {
199
206
  try {
200
- return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
207
+ return this._decryptWithKey(value, this._key, this._keyObj);
201
208
  } catch (primaryErr) {
202
209
  if (this._prevKey) {
203
210
  try {
204
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
211
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
205
212
  } catch {
206
213
  }
207
214
  }
208
215
  throw primaryErr;
209
216
  }
210
217
  }
211
- _decryptWithKey(value, key, keyObj, mode) {
218
+ _decryptWithKey(value, key, keyObj) {
212
219
  if (value.startsWith(PREFIX_XOR)) {
213
220
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
214
221
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -243,8 +250,6 @@ var CacheEncryption = class {
243
250
  const plain = d.update(ct);
244
251
  d.final();
245
252
  return plain.toString("utf8");
246
- void mode;
247
- void key;
248
253
  }
249
254
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
250
255
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
@@ -337,6 +342,5 @@ var CacheEncryption = class {
337
342
  };
338
343
 
339
344
  export {
340
- __require,
341
345
  CacheEncryption
342
346
  };