tricache 0.4.0 → 0.5.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bloom-filter-wasm.js","sourceRoot":"","sources":["../../src/wasm/bloom-filter-wasm.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAE3B;;;;;;;;;;;;;GAaG;AAEH,MAAM,iBAAiB,GACrB,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,8EAA8E;IAC9E,sEAAsE,CAAC;AAEzE,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,aAAa,GAAG,GAAG,CAAC;AAU1B,SAAS,eAAe;IACtB,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;IAC3D,MAAM,QAAQ,GAAG,IAAI,WAAW,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACnD,OAAO,IAAI,WAAW,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,OAAO,eAAe;IACT,OAAO,CAAmB;IAC1B,GAAG,CAAa;IAChB,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAC5B,OAAO,GAAG,OAAO,CAAC;IACnC,+FAA+F;IAC9E,YAAY,CAAS;IACtC,uFAAuF;IAC/E,eAAe,GAAG,CAAC,CAAC;IAE5B;QACE,MAAM,QAAQ,GAAG,eAAe,EAAE,CAAC;QACnC,IAAI,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAsC,CAAC;QAC/D,IAAI,CAAC,GAAG,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACtD,MAAM,CAAC,GAAG,CAAC,EAAE,C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IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC;QAC1C,IAAI,CAAC,eAAe,EAAE,CAAC;IACzB,CAAC;IAED,YAAY,CAAC,GAAW;QACtB,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,GAAG,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QAC3B,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,kBAAkB,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,KAAW,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,eAAe,GAAG,CAAC,CAAC,CAAC,CAAC;IAEjE,OAAO,CAAC,IAAsB;QAC5B,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,KAAK,MAAM,GAAG,IAAI,IAAI;YAAE,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,KAAK;QACP,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;QACzC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;IACzD,CAAC;IAED,sDAAsD;IACtD,IAAI,UAAU,KAAa,OAAO,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;IAEzD;;;;OAIG;IACH,IAAI,WAAW,KAAa,OAAO,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;CACxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tricache",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
5
5
  "keywords": [
6
6
  "cache",
@@ -18,7 +18,6 @@
18
18
  "nodejs"
19
19
  ],
20
20
  "license": "MIT",
21
- "packageManager": "pnpm@11.0.9",
22
21
  "type": "module",
23
22
  "main": "./dist/index.js",
24
23
  "module": "./dist/index.js",
@@ -36,14 +35,6 @@
36
35
  "README.md",
37
36
  "LICENSE"
38
37
  ],
39
- "scripts": {
40
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
41
- "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
42
- "typecheck": "tsc --noEmit",
43
- "test": "vitest run",
44
- "test:watch": "vitest",
45
- "bench": "node --import tsx/esm bench/benchmark.ts"
46
- },
47
38
  "dependencies": {
48
39
  "ioredis": "^5.3.2",
49
40
  "msgpackr": "^2.0.1"
@@ -62,5 +53,13 @@
62
53
  "repository": {
63
54
  "type": "git",
64
55
  "url": "git+https://github.com/Kareem411/TriCache.git"
56
+ },
57
+ "scripts": {
58
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
59
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "vitest run",
62
+ "test:watch": "vitest",
63
+ "bench": "node --import tsx/esm bench/benchmark.ts"
65
64
  }
66
- }
65
+ }
@@ -150,6 +150,7 @@ export class CacheService {
150
150
  ttlJitterFactor: number;
151
151
  tracer: ICacheTracer | undefined;
152
152
  notFoundTtl: number;
153
+ warmKeys: string | undefined;
153
154
  };
154
155
  /** Pre-computed once — opts.namespace never changes after construction. */
155
156
  private readonly _namespace: string;
@@ -169,6 +170,7 @@ export class CacheService {
169
170
  private redisConnecting: Promise<RedisClient> | null = null;
170
171
  private readonly cb: L2CircuitBreaker;
171
172
  private snapshotLoaded = false;
173
+ private _readyPromise: Promise<void> = Promise.resolve();
172
174
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;
173
175
  private oomInterval: ReturnType<typeof setInterval> | null = null;
174
176
  private metricsInterval: ReturnType<typeof setInterval> | null = null;
@@ -255,6 +257,7 @@ export class CacheService {
255
257
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
256
258
  tracer: options.tracer,
257
259
  notFoundTtl: options.notFoundTtl ?? 0,
260
+ warmKeys: options.warmKeys,
258
261
  };
259
262
 
260
263
  // Circuit breaker for L2 Redis
@@ -337,6 +340,11 @@ export class CacheService {
337
340
  this.instanceId = crypto.randomBytes(8).toString('hex');
338
341
  this.backplaneChannel = `tricache:inv${ns ? ':' + ns : ''}`;
339
342
  this.initBackplane();
343
+
344
+ // Auto-warm from L2 if warmKeys is configured; ready() waits for completion.
345
+ if (this.opts.warmKeys) {
346
+ this._readyPromise = this.warmFromL2(this.opts.warmKeys).then(() => undefined);
347
+ }
340
348
  }
341
349
 
342
350
  // ── Singleton factory ─────────────────────────────────────────────────────
@@ -460,6 +468,11 @@ export class CacheService {
460
468
  // message returns immediately without blocking hot get() calls.
461
469
  this.l1.delete(msg.key);
462
470
  setImmediate(() => this.disk.delete(msg.key));
471
+ // Cascade: evict dependents registered on this instance for the
472
+ // deleted key — same logic the local delete() path runs, now also
473
+ // applied to peer-originated invalidations so fleet-wide deletes
474
+ // propagate dependency cascades to every node.
475
+ this._cascadeDependencies(msg.key);
463
476
  } else if (msg.op === 'del-glob') {
464
477
  // Glob patterns clean L1 only — disk entries expire naturally via
465
478
  // the background purge timer or are bypassed on the next L1 miss.
@@ -661,7 +674,6 @@ export class CacheService {
661
674
  const now = Date.now();
662
675
  const remaining = l1Hit.expiresAt - now;
663
676
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
664
- const priority = opts.priority ?? inferPriority(cacheKey);
665
677
 
666
678
  const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0
667
679
  ? remaining <= entryTtl * (1 - opts.refreshAhead)
@@ -674,6 +686,9 @@ export class CacheService {
674
686
  : false;
675
687
 
676
688
  if (shouldRefreshAhead || shouldXFetch) {
689
+ // Defer inferPriority until we actually need it — avoids 3× string.includes()
690
+ // scans on every warm hit when the threshold check is false (the common case).
691
+ const priority = opts.priority ?? inferPriority(cacheKey);
677
692
  this.revalidating.add(k);
678
693
  void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
679
694
  this.counters.swrRevalidations++;
@@ -1127,12 +1142,13 @@ export class CacheService {
1127
1142
  *
1128
1143
  * @param keys - Array of cache keys.
1129
1144
  * @param fetchFn - Called with only the keys that missed L1.
1130
- * @param ttl - TTL in seconds for newly fetched values.
1145
+ * @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
1146
+ * `(key) => number` so heterogeneous TTLs can be batched in one call.
1131
1147
  */
1132
1148
  async mget<T>(
1133
1149
  keys: string[],
1134
1150
  fetchFn: (missKeys: string[]) => Promise<Record<string, T>>,
1135
- ttl = 300,
1151
+ ttl: number | ((key: string) => number) = 300,
1136
1152
  priority?: CachePriority,
1137
1153
  ): Promise<(T | undefined)[]> {
1138
1154
  const result: (T | undefined)[] = new Array(keys.length);
@@ -1156,7 +1172,8 @@ export class CacheService {
1156
1172
  const v = fetched[missKeys[j]];
1157
1173
  result[missIndexes[j]] = v;
1158
1174
  if (v !== undefined) {
1159
- await this.set(missKeys[j], v, ttl, priority);
1175
+ const resolvedTtl = typeof ttl === 'function' ? ttl(missKeys[j]) : ttl;
1176
+ await this.set(missKeys[j], v, resolvedTtl, priority);
1160
1177
  }
1161
1178
  }
1162
1179
  }
@@ -1164,6 +1181,21 @@ export class CacheService {
1164
1181
  return result;
1165
1182
  }
1166
1183
 
1184
+ /**
1185
+ * Returns a Promise that resolves once the cache is fully initialised and any
1186
+ * startup warming configured via `warmKeys` has completed.
1187
+ *
1188
+ * Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once
1189
+ * `warmFromL2(warmKeys)` finishes — ideal for k8s readiness probes.
1190
+ *
1191
+ * @example
1192
+ * const cache = CacheService.create({ warmKeys: 'user:*' });
1193
+ * await cache.ready(); // gate traffic until warm
1194
+ */
1195
+ ready(): Promise<void> {
1196
+ return this._readyPromise;
1197
+ }
1198
+
1167
1199
  /**
1168
1200
  * Batch write — set multiple entries in a single call.
1169
1201
  * TTL jitter is applied per-entry when `ttlJitterFactor` > 0.
@@ -14,6 +14,10 @@
14
14
 
15
15
  import { pack, unpack } from 'msgpackr';
16
16
  import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
17
+
18
+ // Reusable return object for get() — eliminates one heap allocation per hot read.
19
+ // Safe because JS is single-threaded: callers consume all fields before the next get().
20
+ const _hit: CacheHit = { value: undefined, isStale: false, expiresAt: 0, ttlMs: undefined, delta: undefined };
17
21
  import { WasmBloomFilter } from './wasm/bloom-filter-wasm';
18
22
 
19
23
 
@@ -133,36 +137,38 @@ class CountMinSketch {
133
137
  return h;
134
138
  }
135
139
 
136
- /** Four independent bit-mixes from one FNV-1a seed. */
137
- private hashes(key: string): [number, number, number, number] {
138
- const h = this.fnv32(key);
139
- const h1 = (h ^ (h >>> 16)) >>> 0;
140
- const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
141
- const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
142
- const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
143
- return [h1, h2, h3, h4];
144
- }
145
-
146
140
  /** Record one access. Decays all counters when the insertion threshold is crossed. */
147
141
  increment(key: string): void {
148
- const [h1, h2, h3, h4] = this.hashes(key);
149
- const t = this.table;
150
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] = Math.min(0xffff, (t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)] + 1));
151
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] = Math.min(0xffff, (t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)] + 1));
152
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] = Math.min(0xffff, (t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)] + 1));
153
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] = Math.min(0xffff, (t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)] + 1));
142
+ const h = this.fnv32(key);
143
+ const h1 = (h ^ (h >>> 16)) >>> 0;
144
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
145
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
146
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
147
+ const t = this.table;
148
+ const i0 = h1 & SKETCH_MASK;
149
+ const i1 = SKETCH_WIDTH + (h2 & SKETCH_MASK);
150
+ const i2 = 2 * SKETCH_WIDTH + (h3 & SKETCH_MASK);
151
+ const i3 = 3 * SKETCH_WIDTH + (h4 & SKETCH_MASK);
152
+ if (t[i0] < 0xffff) t[i0]++;
153
+ if (t[i1] < 0xffff) t[i1]++;
154
+ if (t[i2] < 0xffff) t[i2]++;
155
+ if (t[i3] < 0xffff) t[i3]++;
154
156
  if (++this.inserts >= SKETCH_DECAY_THRESHOLD) this.decay();
155
157
  }
156
158
 
157
159
  /** Minimum-across-rows frequency estimate. */
158
160
  estimate(key: string): number {
159
- const [h1, h2, h3, h4] = this.hashes(key);
160
- const t = this.table;
161
+ const h = this.fnv32(key);
162
+ const h1 = (h ^ (h >>> 16)) >>> 0;
163
+ const h2 = (Math.imul(h1, 0x45d9f3b) ^ (h1 >>> 16)) >>> 0;
164
+ const h3 = (Math.imul(h2, 0x7fb9b7a1) ^ (h2 >>> 16)) >>> 0;
165
+ const h4 = (Math.imul(h3, 0x1b873593) ^ (h3 >>> 16)) >>> 0;
166
+ const t = this.table;
161
167
  return Math.min(
162
- t[0 * SKETCH_WIDTH + (h1 & SKETCH_MASK)],
163
- t[1 * SKETCH_WIDTH + (h2 & SKETCH_MASK)],
164
- t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
165
- t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
168
+ t[h1 & SKETCH_MASK],
169
+ t[SKETCH_WIDTH + (h2 & SKETCH_MASK)],
170
+ t[2 * SKETCH_WIDTH + (h3 & SKETCH_MASK)],
171
+ t[3 * SKETCH_WIDTH + (h4 & SKETCH_MASK)],
166
172
  );
167
173
  }
168
174
 
@@ -384,14 +390,17 @@ export class SmartMemoryCache {
384
390
  if (entry.expiresAt < now) { this._delete(key, 'ttl'); return null; }
385
391
  entry.hits++;
386
392
  entry.lastAccess = now;
387
- this.sketch.increment(key);
388
- const cat = this.getCategory(key);
389
- this.categoryHits.set(cat, (this.categoryHits.get(cat) ?? 0) + 1);
393
+ // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
394
+ if ((entry.hits & 3) === 0) this.sketch.increment(key);
390
395
  // value is cached at write time — hot reads return the live object directly,
391
396
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
392
397
  const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
393
- const isStale = entry.staleAt !== undefined && now > entry.staleAt;
394
- return { value, isStale, expiresAt: entry.expiresAt, ttlMs: entry.ttlMs, delta: entry.delta };
398
+ _hit.value = value;
399
+ _hit.isStale = entry.staleAt !== undefined && now > entry.staleAt;
400
+ _hit.expiresAt = entry.expiresAt;
401
+ _hit.ttlMs = entry.ttlMs;
402
+ _hit.delta = entry.delta;
403
+ return _hit;
395
404
  }
396
405
 
397
406
  set(
package/src/types.ts CHANGED
@@ -472,4 +472,10 @@ export interface CacheOptions {
472
472
  * Default: `30 000` ms (30 s).
473
473
  */
474
474
  l2CircuitBreakerCooldownMs?: number;
475
+ /**
476
+ * Redis key pattern to automatically warm L1 from at startup (e.g. `'user:*'`).
477
+ * `cache.ready()` returns a Promise that resolves once this warm-up completes.
478
+ * No-op when Redis is disabled or unreachable — safe to set unconditionally.
479
+ */
480
+ warmKeys?: string;
475
481
  }