tricache 0.7.1 → 0.8.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.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +87 -1371
  3. package/dashboards/tricache-alerts.yaml +54 -0
  4. package/dashboards/tricache-grafana.json +548 -0
  5. package/dist/cache-service-5MZXFIGK.js +12 -0
  6. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  7. package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  10. package/dist/chunk-QNU7B43J.js +687 -0
  11. package/dist/chunk-UGD4VEPD.js +138 -0
  12. package/dist/chunk-XZL45ABR.js +108 -0
  13. package/dist/chunk-ZTSWCFYO.js +135 -0
  14. package/dist/cli.cjs +2790 -471
  15. package/dist/cli.d.ts +1 -0
  16. package/dist/cli.js +103 -5
  17. package/dist/dashboard/index.cjs +1065 -0
  18. package/dist/dashboard/index.d.ts +183 -0
  19. package/dist/dashboard/index.js +22 -0
  20. package/dist/drizzle/index.cjs +2553 -470
  21. package/dist/drizzle/index.d.ts +3 -1
  22. package/dist/drizzle/index.js +1 -1
  23. package/dist/edge/index.cjs +1498 -0
  24. package/dist/edge/index.d.ts +127 -0
  25. package/dist/edge/index.js +1109 -0
  26. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  27. package/dist/http/index.cjs +2926 -562
  28. package/dist/http/index.d.ts +109 -23
  29. package/dist/http/index.js +220 -72
  30. package/dist/index.cjs +6936 -2518
  31. package/dist/index.d.ts +547 -30
  32. package/dist/index.js +104 -5
  33. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  34. package/dist/nestjs/index.cjs +2494 -463
  35. package/dist/nestjs/index.d.ts +3 -1
  36. package/dist/nestjs/index.js +6 -3
  37. package/dist/next/index.cjs +2517 -483
  38. package/dist/next/index.d.ts +4 -2
  39. package/dist/next/index.js +14 -10
  40. package/dist/prisma/index.d.ts +3 -1
  41. package/dist/serialize-worker.cjs +5 -4
  42. package/dist/serialize-worker.js +1 -1
  43. package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
  44. package/package.json +34 -6
  45. package/src/adapters/auto-pipeliner.ts +206 -0
  46. package/src/adapters/node-redis.ts +370 -0
  47. package/src/cache-service.ts +1339 -402
  48. package/src/cli.ts +120 -2
  49. package/src/codec.ts +72 -0
  50. package/src/cross-region.ts +245 -0
  51. package/src/dashboard/handler.ts +392 -0
  52. package/src/dashboard/html.ts +594 -0
  53. package/src/dashboard/index.ts +195 -0
  54. package/src/dashboard/types.ts +96 -0
  55. package/src/disk-tier.ts +449 -47
  56. package/src/drizzle/index.ts +86 -86
  57. package/src/edge/adapters/cloudflare-do.ts +130 -0
  58. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  59. package/src/edge/adapters/upstash.ts +143 -0
  60. package/src/edge/cache.ts +797 -0
  61. package/src/edge/crypto.ts +182 -0
  62. package/src/edge/hono.ts +203 -0
  63. package/src/edge/index.ts +37 -0
  64. package/src/edge/types.ts +230 -0
  65. package/src/edge/utils/base64.ts +63 -0
  66. package/src/edge/utils/murmur3.ts +179 -0
  67. package/src/encryption.ts +127 -5
  68. package/src/http/express.ts +195 -0
  69. package/src/http/fastify.ts +260 -0
  70. package/src/http/index.ts +39 -258
  71. package/src/http/utils.ts +92 -0
  72. package/src/index.ts +149 -47
  73. package/src/ipc-telemetry.ts +481 -0
  74. package/src/latency-watchdog.ts +282 -0
  75. package/src/nestjs/decorators.ts +161 -161
  76. package/src/nestjs/index.ts +23 -23
  77. package/src/nestjs/tricache.module.ts +104 -104
  78. package/src/nestjs/tricache.store.ts +97 -97
  79. package/src/nestjs/types.ts +79 -79
  80. package/src/next/cache-handler.ts +12 -9
  81. package/src/next/index.ts +37 -37
  82. package/src/next/isr-handler.ts +105 -105
  83. package/src/next/types.ts +130 -130
  84. package/src/remote-snapshot.ts +153 -0
  85. package/src/serialize-worker.ts +120 -120
  86. package/src/sigv4-snapshot-adapter.ts +260 -0
  87. package/src/smart-memory-cache.ts +91 -8
  88. package/src/types.ts +290 -2
  89. package/src/utils/cgroup.ts +100 -0
  90. package/src/utils/tracing.ts +54 -0
  91. package/src/wasm/bloom-filter-wasm.ts +109 -102
  92. package/src/worker-pool.ts +299 -299
  93. package/src/wtiny-lfu.ts +624 -0
  94. package/dist/cache-service-5GATUYAK.js +0 -7
  95. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -12,8 +12,9 @@
12
12
  * - Process-level singleton via globalThis (survives Next.js hot reloads)
13
13
  */
14
14
 
15
- import { pack, unpack } from 'msgpackr';
16
- import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason } from './types';
15
+ import { CacheCodec, defaultCodec } from './codec.js';
16
+ import type { CacheHit, CachePriority, CategoryLimit, SmartCacheEntry, ILogger, EvictionReason, WTinyLfuStats } from './types';
17
+ import { WTinyLfuPolicy } from './wtiny-lfu.js';
17
18
 
18
19
  /**
19
20
  * Packed-byte threshold above which the live JS object is NOT stored alongside the
@@ -257,16 +258,27 @@ export interface SmartMemoryCacheOptions {
257
258
  logger: ILogger;
258
259
  /** Fraction of maxEntries / maxBytes at which proactive eviction fires (default 0.9). */
259
260
  evictionWatermark?: number;
261
+ /** Custom binary codec (defaults to defaultCodec with record structures and rich types enabled). */
262
+ codec?: CacheCodec;
263
+ /**
264
+ * Admission policy:
265
+ * - 'wtinylfu': Window TinyLFU segmented admission with mathematical scan resistance.
266
+ * - 'adaptive': Adaptive LFU x LRU x priority reservoir sampling.
267
+ * Default: 'adaptive' (unless explicitly set to 'wtinylfu')
268
+ */
269
+ admissionPolicy?: 'wtinylfu' | 'adaptive';
260
270
  }
261
271
 
262
272
  export class SmartMemoryCache {
263
273
  private readonly cache = new Map<string, SmartCacheEntry>();
264
274
  private readonly opts: SmartMemoryCacheOptions;
275
+ private readonly codec: CacheCodec;
265
276
  private bloom: AnyBloomFilter;
266
277
  /** Non-default category prefixes pre-extracted to avoid Object.keys() allocation on every call. */
267
278
  private readonly categoryPrefixes: string[];
268
279
  /** Historical frequency sketch — survives eviction, closes same-priority burst-flood gap. */
269
280
  private readonly sketch = new CountMinSketch();
281
+ private readonly wtinyPolicy?: WTinyLfuPolicy;
270
282
  private totalSize = 0;
271
283
  private categoryCount = new Map<string, number>();
272
284
  private categorySize = new Map<string, number>();
@@ -294,8 +306,12 @@ export class SmartMemoryCache {
294
306
 
295
307
  constructor(opts: SmartMemoryCacheOptions, existing?: Map<string, SmartCacheEntry>) {
296
308
  this.opts = opts;
309
+ this.codec = opts.codec ?? defaultCodec;
297
310
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
298
311
  this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
312
+ if (opts.admissionPolicy === 'wtinylfu') {
313
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
314
+ }
299
315
 
300
316
  if (existing) {
301
317
  for (const [k, v] of existing) this.cache.set(k, v);
@@ -311,6 +327,12 @@ export class SmartMemoryCache {
311
327
  this.categoryCount.clear();
312
328
  this.categorySize.clear();
313
329
  this.categoryKeys.clear();
330
+ if (this.wtinyPolicy) {
331
+ this.wtinyPolicy.clear();
332
+ for (const key of this.cache.keys()) {
333
+ this.wtinyPolicy.onSet(key, false);
334
+ }
335
+ }
314
336
  for (const [key, entry] of this.cache) {
315
337
  this.totalSize += entry.size;
316
338
  const cat = this.getCategory(key);
@@ -336,6 +358,7 @@ export class SmartMemoryCache {
336
358
  private _delete(key: string, reason: EvictionReason = 'manual'): boolean {
337
359
  const entry = this.cache.get(key);
338
360
  if (!entry) return false;
361
+ this.wtinyPolicy?.onDelete(key);
339
362
  const cat = this.getCategory(key);
340
363
  this.totalSize -= entry.size;
341
364
  this.categoryCount.set(cat, (this.categoryCount.get(cat) ?? 1) - 1);
@@ -524,9 +547,10 @@ export class SmartMemoryCache {
524
547
  entry.lastAccess = now;
525
548
  // Sample sketch at 25 % — eviction scoring only needs relative frequency, not exact counts.
526
549
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
550
+ this.wtinyPolicy?.onAccess(key);
527
551
  // value is cached at write time — hot reads return the live object directly,
528
552
  // skipping unpack. Falls back to decode for entries restored from disk/snapshot.
529
- const value = entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
553
+ const value = entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
530
554
  // Fresh object per call — never a shared/reusable one. Callers hold this result
531
555
  // across await boundaries (CacheService.get() awaits tag-version checks between
532
556
  // the L1 hit and the return); a shared object would let a concurrent get()
@@ -555,7 +579,7 @@ export class SmartMemoryCache {
555
579
  ): void {
556
580
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
557
581
  // "size probe" that was discarded for large payloads (the double-pass).
558
- const packed = pack(data);
582
+ const packed = this.codec.encode(data);
559
583
  const size = packed.byteLength;
560
584
  this.compressions++;
561
585
  this.sketch.increment(key);
@@ -576,7 +600,57 @@ export class SmartMemoryCache {
576
600
  this.categorySize.set(cat, (this.categorySize.get(cat) ?? existingEntry.size) - existingEntry.size);
577
601
  this.cache.delete(key);
578
602
  }
579
- this.ensureCapacity(cat, size);
603
+
604
+ if (this.wtinyPolicy) {
605
+ const decision = this.wtinyPolicy.onSet(key, Boolean(existingEntry));
606
+ if (!decision.admit) {
607
+ if (decision.candidateKey === key) {
608
+ // Candidate itself was rejected by TinyLFU admission gate
609
+ if (this.opts.diskSpill) {
610
+ const now = Date.now();
611
+ const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
612
+ this.opts.diskSpill(key, {
613
+ data: packed,
614
+ value: liveValue,
615
+ isCompressed: true,
616
+ expiresAt: now + ttlMs,
617
+ staleAt,
618
+ size,
619
+ hits: 1,
620
+ lastAccess: now,
621
+ priority,
622
+ ttlMs,
623
+ delta,
624
+ setAt: now,
625
+ tagVersions,
626
+ });
627
+ }
628
+ return;
629
+ } else if (decision.candidateKey) {
630
+ // An older window candidate was rejected to make room for key
631
+ const candEntry = this.cache.get(decision.candidateKey);
632
+ if (candEntry && this.opts.diskSpill) {
633
+ this.opts.diskSpill(decision.candidateKey, candEntry);
634
+ }
635
+ this._delete(decision.candidateKey, 'capacity');
636
+ }
637
+ } else if (decision.evictKey) {
638
+ // Main cache victim evicted to admit candidate
639
+ const victimEntry = this.cache.get(decision.evictKey);
640
+ if (victimEntry && this.opts.diskSpill) {
641
+ this.opts.diskSpill(decision.evictKey, victimEntry);
642
+ }
643
+ this._delete(decision.evictKey, 'capacity');
644
+ }
645
+
646
+ // Check category byte limit or total byte limit
647
+ const catSz = this.categorySize.get(cat) ?? 0;
648
+ if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
649
+ this.ensureCapacity(cat, size);
650
+ }
651
+ } else {
652
+ this.ensureCapacity(cat, size);
653
+ }
580
654
 
581
655
  const now = Date.now();
582
656
  // Only cache the live object for small entries — large entries would store the packed
@@ -656,6 +730,7 @@ export class SmartMemoryCache {
656
730
  }
657
731
  const count = this.cache.size;
658
732
  this.cache.clear();
733
+ this.wtinyPolicy?.clear();
659
734
  this.totalSize = 0;
660
735
  this.categoryCount.clear();
661
736
  this.categorySize.clear();
@@ -840,12 +915,12 @@ export class SmartMemoryCache {
840
915
  const rawData = entry.data;
841
916
  // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
842
917
  const data: Buffer = !entry.isCompressed
843
- ? pack(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
918
+ ? this.codec.encode(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
844
919
  : rawData instanceof Uint8Array
845
920
  ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
846
921
  : rawData as Buffer; // already a Buffer
847
922
  // Cache the live object for small entries only — large entries skip double-heap storage.
848
- const value = entry.size <= LARGE_VALUE_BYTES ? unpack(data) : undefined;
923
+ const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
849
924
  this.cache.set(key, { ...entry, data, value, isCompressed: true });
850
925
  this.bloom.add(key);
851
926
  loaded++;
@@ -922,7 +997,7 @@ export class SmartMemoryCache {
922
997
  * if the live object was not cached (large-entry optimisation or disk-restored entry).
923
998
  */
924
999
  resolveValue(entry: SmartCacheEntry): unknown {
925
- return entry.value !== undefined ? entry.value : unpack(entry.data as Buffer);
1000
+ return entry.value !== undefined ? entry.value : this.codec.decode(entry.data as Buffer);
926
1001
  }
927
1002
 
928
1003
  // ── Stats ─────────────────────────────────────────────────────────────────
@@ -1023,4 +1098,12 @@ export class SmartMemoryCache {
1023
1098
  out.sort((a, b) => b.hits - a.hits);
1024
1099
  return out.slice(0, n);
1025
1100
  }
1101
+
1102
+ /**
1103
+ * Return real-time metrics and telemetry for the Window TinyLFU admission policy.
1104
+ * Returns `undefined` when running under default adaptive eviction.
1105
+ */
1106
+ getWTinyLfuStats(): WTinyLfuStats | undefined {
1107
+ return this.wtinyPolicy?.getStats();
1108
+ }
1026
1109
  }
package/src/types.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import type { RemoteSnapshotOptions } from './remote-snapshot';
2
+ import type { CrossRegionRelayOptions } from './cross-region';
3
+
1
4
  /**
2
5
  * tricache — shared types and interfaces
3
6
  */
@@ -10,9 +13,18 @@
10
13
  * Minimal span interface — structurally compatible with `@opentelemetry/api` Span.
11
14
  * Pass your existing OTEL tracer; no extra package required.
12
15
  */
16
+ export interface ICacheSpanLink {
17
+ context: {
18
+ traceId: string;
19
+ spanId: string;
20
+ traceFlags?: number;
21
+ };
22
+ }
23
+
13
24
  export interface ICacheSpan {
14
25
  setAttribute(key: string, value: string | number | boolean): this;
15
26
  setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
27
+ recordException?(err: Error | unknown): this;
16
28
  end(): void;
17
29
  }
18
30
 
@@ -20,7 +32,7 @@ export interface ICacheSpan {
20
32
  * Minimal tracer interface — structurally compatible with `@opentelemetry/api` Tracer.
21
33
  */
22
34
  export interface ICacheTracer {
23
- startSpan(name: string): ICacheSpan;
35
+ startSpan(name: string, options?: { links?: ICacheSpanLink[] }): ICacheSpan;
24
36
  }
25
37
 
26
38
  /** Minimal logger interface — plug in any logger (pino, winston, console, etc.) */
@@ -250,8 +262,55 @@ export interface CacheMetrics {
250
262
  lastTriggeredAt: number | null;
251
263
  };
252
264
 
265
+ /** Remote snapshot statistics — present when remoteSnapshot is configured */
266
+ remoteSnapshot?: {
267
+ enabled: boolean;
268
+ uploads: number;
269
+ downloads: number;
270
+ errors: number;
271
+ lastUploadedAt: number | null;
272
+ lastDownloadedAt: number | null;
273
+ };
274
+
275
+ /** Cross-region invalidation relay statistics — present when crossRegion is configured */
276
+ crossRegion?: {
277
+ enabled: boolean;
278
+ currentRegion: string;
279
+ sent: number;
280
+ received: number;
281
+ deduplicated: number;
282
+ errors: number;
283
+ };
284
+
285
+ /** Auto-pipelining statistics — present when autoPipeline is enabled */
286
+ pipelining?: {
287
+ batchesDispatched: number;
288
+ operationsBatched: number;
289
+ pendingQueueSize: number;
290
+ };
291
+
253
292
  l1: { entries: number; sizeBytes: number; maxBytes: number };
254
- disk: { files: number; sizeKB: number; maxKB: number; disabled: boolean };
293
+ disk: {
294
+ files: number;
295
+ sizeKB: number;
296
+ maxKB: number;
297
+ disabled: boolean;
298
+ latencyWatchdog?: {
299
+ bypassActive: boolean;
300
+ bypassStage: 0 | 1 | 2 | 3;
301
+ diskP95Ms: number;
302
+ redisP95Ms: number;
303
+ redisDampened: boolean;
304
+ bypassedTotal: number;
305
+ };
306
+ pruning?: {
307
+ active: boolean;
308
+ pruneRounds: number;
309
+ entriesPruned: number;
310
+ spillsShedTotal: number;
311
+ hostVolumeLowSpacePauses: number;
312
+ };
313
+ };
255
314
 
256
315
  /** Adaptive TTL statistics — present only when `adaptiveTtl` is enabled */
257
316
  adaptiveTtl?: {
@@ -267,6 +326,20 @@ export interface CacheMetrics {
267
326
  };
268
327
  }
269
328
 
329
+ /**
330
+ * Result returned by cache.health()
331
+ *
332
+ * NOTE: Intended strictly for Kubernetes Readiness probes (/ready).
333
+ * Do NOT hook into Liveness probes (/healthz), as degraded caches should shed ingress
334
+ * traffic while keeping the container alive to heal local storage and drain in-flight tasks.
335
+ */
336
+ export interface CacheHealthStatus {
337
+ healthy: boolean;
338
+ degraded: boolean;
339
+ reasons: string[];
340
+ details?: Record<string, unknown>;
341
+ }
342
+
270
343
  // ─── Configuration ───────────────────────────────────────────────────────────
271
344
 
272
345
  /** Per-category memory limits for L1 */
@@ -275,6 +348,11 @@ export interface CategoryLimit {
275
348
  maxSizeBytes: number;
276
349
  }
277
350
 
351
+ /**
352
+ * Supported opinionated pre-configurations for CacheService.preset()
353
+ */
354
+ export type CachePresetType = 'nextjs' | 'microservice' | 'serverless' | 'enterprise-hardened';
355
+
278
356
  /**
279
357
  * Options accepted by CacheService.create()
280
358
  *
@@ -308,6 +386,14 @@ export interface CacheOptions {
308
386
  * Default: ['auth:', 'session:', 'mfa:', 'rate_limit:']
309
387
  */
310
388
  forbiddenSnapshotPrefixes?: string[];
389
+ /**
390
+ * L1 cache admission and eviction policy:
391
+ * - `'wtinylfu'`: Window TinyLFU admission policy (popularized by Caffeine) providing
392
+ * mathematical scan resistance and burst recency absorption.
393
+ * - `'adaptive'`: Adaptive LFU x LRU x priority reservoir sampling.
394
+ * Default: `'wtinylfu'`
395
+ */
396
+ l1AdmissionPolicy?: 'wtinylfu' | 'adaptive';
311
397
 
312
398
  // ── L1.5 (disk tier) ────────────────────────────────────────────────────
313
399
  /** Directory used for L1.5 disk-spill files. Default: os.tmpdir()/tricache-disk */
@@ -316,6 +402,61 @@ export interface CacheOptions {
316
402
  diskMaxBytes?: number;
317
403
  /** Max bytes for a single disk entry. Default: 10 MB */
318
404
  diskEntryMaxBytes?: number;
405
+ /**
406
+ * Maximum concurrent asynchronous filesystem writes permitted in-flight for disk spills.
407
+ * Protects against libuv threadpool (UV_THREADPOOL_SIZE=4) saturation during cloud I/O throttling.
408
+ * Default: Math.min(4, Math.max(1, Math.floor(os.availableParallelism() / 4)))
409
+ */
410
+ diskMaxConcurrentWrites?: number;
411
+ /**
412
+ * Maximum queued spill writes awaiting execution before shedding kicks in.
413
+ * Once pending writes hit this limit, incoming spills are dropped without touching libuv.
414
+ * Default: 512
415
+ */
416
+ diskMaxPendingWrites?: number;
417
+ /**
418
+ * Maximum time permitted for an individual write before timing out and tripping backpressure.
419
+ * Default: 500 ms
420
+ */
421
+ diskWriteTimeoutMs?: number;
422
+ /**
423
+ * Number of consecutive slow or failed disk writes before tripping the disk circuit breaker to OPEN.
424
+ * Default: 5
425
+ */
426
+ diskCircuitBreakerThreshold?: number;
427
+ /**
428
+ * Cooldown time in ms before transitioning the disk circuit breaker from OPEN to HALF-OPEN for canary probing.
429
+ * Default: 5000 ms
430
+ */
431
+ diskCircuitBreakerCooldownMs?: number;
432
+ /**
433
+ * Enable dynamic tier latency watchdog.
434
+ * Compares disk read latency against Redis and automatically sheds traffic to Redis when disk slows down.
435
+ * Default: true
436
+ */
437
+ diskLatencyWatchdog?: boolean;
438
+ /**
439
+ * Ratio of disk p95 latency to Redis p95 latency required to trip bypass.
440
+ * Default: 1.5
441
+ */
442
+ diskLatencyBypassRatio?: number;
443
+ /**
444
+ * Minimum disk p95 latency floor in ms before bypass can be considered.
445
+ * Default: 10 ms
446
+ */
447
+ diskLatencyBypassMinMs?: number;
448
+ /**
449
+ * Cooldown time in ms before probing canary during Stage 3 bypass.
450
+ * Subject to ±30% anti-synchronicity jitter.
451
+ * Default: 30_000 ms
452
+ */
453
+ diskLatencyBypassCooldownMs?: number;
454
+ /**
455
+ * When true, cache.health().healthy returns false when degraded, causing
456
+ * Kubernetes readiness probes to fail and route traffic away from this pod.
457
+ * Default: false (graceful local degradation without failing readiness)
458
+ */
459
+ failReadinessOnDegraded?: boolean;
319
460
 
320
461
  // ── L2 (Redis) ────────────────────────────────────────────────────────────
321
462
  /**
@@ -326,6 +467,29 @@ export interface CacheOptions {
326
467
  redisHost?: string;
327
468
  /** Redis port. Default: 6379 */
328
469
  redisPort?: number;
470
+ /**
471
+ * Strict per-command timeout for Redis operations.
472
+ * When expired, triggers connection reset / socket destruction to prevent RESP multiplexing desync.
473
+ * Default: 2500 ms
474
+ */
475
+ redisCommandTimeoutMs?: number;
476
+ /**
477
+ * Coalesce Redis operations executed within the identical synchronous tick into a single pipeline round-trip via queueMicrotask.
478
+ * Eliminates syscall and network overhead under heavy concurrent traffic with 0ms event-loop delay.
479
+ * Default: false
480
+ */
481
+ autoPipeline?: boolean;
482
+ /**
483
+ * Maximum batch size for auto-pipelined Redis requests before forcing an immediate dispatch.
484
+ * Default: 100
485
+ */
486
+ maxPipelineBatchSize?: number;
487
+ /**
488
+ * Clock skew tolerance window in milliseconds across cluster nodes / containers.
489
+ * Allows timestamps within this tolerance ahead of the local clock to prevent premature eviction anomalies.
490
+ * Default: 250 ms
491
+ */
492
+ clockSkewToleranceMs?: number;
329
493
  /**
330
494
  * Whether to enable TLS for the Redis connection. Default: true in production,
331
495
  * false otherwise.
@@ -343,6 +507,19 @@ export interface CacheOptions {
343
507
  */
344
508
  disableRedis?: boolean;
345
509
 
510
+ /**
511
+ * Pre-existing or custom Redis client or driver adapter (e.g. `NodeRedisAdapter` wrapping
512
+ * `@redis/client`, or a pre-configured `ioredis` instance).
513
+ * When supplied, TriCache bypasses internal connection construction and uses this client directly.
514
+ */
515
+ redisClient?: IRedisDriver | any;
516
+
517
+ /**
518
+ * Dedicated subscriber client for Redis Pub/Sub invalidation backplane.
519
+ * If omitted and `redisClient` supports `.duplicate()`, TriCache will duplicate `redisClient`.
520
+ */
521
+ redisSubClient?: IRedisDriver | any;
522
+
346
523
  // ── Encryption ────────────────────────────────────────────────────────────
347
524
  /**
348
525
  * Base64-encoded 32-byte AES-256-GCM key for encrypting L2 (Redis) values and
@@ -380,6 +557,15 @@ export interface CacheOptions {
380
557
  */
381
558
  strictKeyValidation?: boolean;
382
559
 
560
+ // ── Serialization & Codec (msgpackr) ────────────────────────────────────
561
+ /**
562
+ * Whether to call `.toJSON()` when serializing objects into binary cache buffers.
563
+ * - `true` (default): Honors `.toJSON()`, matching standard JSON serialization conventions.
564
+ * - `false`: Preserves the object's own internal properties (msgpackr 2.1.0+ durable state feature),
565
+ * avoiding accidental API response projections on cached domain entities.
566
+ */
567
+ serializeToJSON?: boolean;
568
+
383
569
  // ── Compression ──────────────────────────────────────────────────────────
384
570
  /**
385
571
  * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
@@ -406,6 +592,11 @@ export interface CacheOptions {
406
592
  * Max age (ms) of a snapshot file before it is rejected. Default: 2 hours
407
593
  */
408
594
  snapshotMaxAgeMs?: number;
595
+ /**
596
+ * Optional remote blob storage snapshot configuration for stateless containers (S3, GCS, R2, HTTP).
597
+ * Enables persisting and hydrating L1 RAM cache snapshots across Kubernetes / container deployments.
598
+ */
599
+ remoteSnapshot?: RemoteSnapshotOptions;
409
600
 
410
601
  /**
411
602
  * Optional namespace prefix for all cache keys.
@@ -484,6 +675,15 @@ export interface CacheOptions {
484
675
  */
485
676
  useShardedPubSub?: boolean;
486
677
 
678
+ // ── Multi-Region / Cross-Cluster Invalidation Relay ─────────────────────
679
+ /**
680
+ * Optional cross-region invalidation relay configuration for geo-distributed deployments.
681
+ * Synchronizes `delete()` and `invalidateTag()` events across separate regional Redis clusters
682
+ * (e.g. `us-east-1` and `eu-central-1`) via HTTP mesh or custom message brokers (SNS, SQS, EventBridge)
683
+ * with automatic origin deduplication to prevent invalidation loops.
684
+ */
685
+ crossRegion?: CrossRegionRelayOptions;
686
+
487
687
  // ── OOM protection ──────────────────────────────────────────────────────
488
688
  /**
489
689
  * Enable the GC-aware OOM guard. When heap utilisation crosses
@@ -516,6 +716,18 @@ export interface CacheOptions {
516
716
  /** How often the `onMetrics` callback fires (ms). Default: 60 000 ms */
517
717
  metricsIntervalMs?: number;
518
718
 
719
+ /**
720
+ * Enable local IPC telemetry server (Unix domain socket on POSIX, Windows Named Pipe on win32)
721
+ * allowing external monitors like `tricache top` to inspect this instance.
722
+ * Default: `false`.
723
+ */
724
+ enableIpc?: boolean;
725
+ /**
726
+ * Custom socket path or Windows named pipe path for the IPC telemetry server.
727
+ * Default: `/tmp/tricache-<pid>.sock` (POSIX) or `\\.\pipe\tricache-<pid>` (Windows).
728
+ */
729
+ ipcSocketPath?: string;
730
+
519
731
  /**
520
732
  * OpenTelemetry-compatible tracer. When provided, `get()`, `set()`, and
521
733
  * `delete()` are each wrapped in a span with attributes:
@@ -909,3 +1121,79 @@ export interface ICacheMeter {
909
1121
  createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
910
1122
  addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
911
1123
  }
1124
+
1125
+ /**
1126
+ * Common pipeline / transaction interface matching ioredis and adapted drivers.
1127
+ */
1128
+ export interface IRedisPipeline {
1129
+ get(key: string): this;
1130
+ set(key: string, value: string, ...args: (string | number)[]): this;
1131
+ setex(key: string, seconds: number, value: string): this;
1132
+ del(...keys: string[]): this;
1133
+ expire(key: string, seconds: number): this;
1134
+ incr(key: string): this;
1135
+ sadd(key: string, ...members: string[]): this;
1136
+ smembers(key: string): this;
1137
+ hset(key: string, value: Record<string, string>): this;
1138
+ exec(): Promise<Array<[Error | null, any]> | null>;
1139
+ }
1140
+
1141
+ /**
1142
+ * Pluggable contract for external Redis drivers (e.g. `@redis/client` / `node-redis`,
1143
+ * custom connection pools, or pre-configured `ioredis` instances).
1144
+ */
1145
+ export interface IRedisDriver {
1146
+ get(key: string): Promise<string | null>;
1147
+ set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
1148
+ setex?(key: string, seconds: number, value: string): Promise<unknown>;
1149
+ del(...keys: string[]): Promise<number>;
1150
+ ping(): Promise<string>;
1151
+ expire(key: string, seconds: number): Promise<number | boolean>;
1152
+ incr(key: string): Promise<number>;
1153
+ eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
1154
+ multi(): IRedisPipeline;
1155
+ pipeline?(): IRedisPipeline;
1156
+ smembers?(key: string): Promise<string[]>;
1157
+ sadd?(key: string, ...members: string[]): Promise<number>;
1158
+ scan?(cursor: string, ...args: (string | number)[]): Promise<[string, string[]]>;
1159
+ scanStream?(options?: { match?: string; count?: number }): any;
1160
+ hset?(key: string, value: Record<string, string>): Promise<unknown>;
1161
+ publish?(channel: string, message: string): Promise<number>;
1162
+ subscribe?(...channels: string[]): Promise<unknown>;
1163
+ disconnect(): Promise<void> | void;
1164
+ quit?(): Promise<void> | void;
1165
+ duplicate?(): IRedisDriver;
1166
+ on?(event: string, listener: (...args: any[]) => void): this | unknown;
1167
+ once?(event: string, listener: (...args: any[]) => void): this | unknown;
1168
+ isOpen?: boolean;
1169
+ connect?(): Promise<unknown>;
1170
+ }
1171
+
1172
+ /**
1173
+ * Real-time telemetry and state for the disk tier backpressure queue.
1174
+ */
1175
+ export interface DiskBackpressureStats {
1176
+ activeWrites: number;
1177
+ pendingWrites: number;
1178
+ spillsDropped: number;
1179
+ circuitState: 'closed' | 'open' | 'half-open';
1180
+ lastTripTimestamp: number;
1181
+ }
1182
+
1183
+ /**
1184
+ * Telemetry metrics and counters for Window TinyLFU cache admission.
1185
+ */
1186
+ export interface WTinyLfuStats {
1187
+ capacity: number;
1188
+ size: number;
1189
+ windowSize: number;
1190
+ probationSize: number;
1191
+ protectedSize: number;
1192
+ hits: number;
1193
+ misses: number;
1194
+ hitRate: number;
1195
+ admissions: number;
1196
+ rejections: number;
1197
+ demotions: number;
1198
+ promotions: number;
1199
+ }
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs';
2
+ import v8 from 'node:v8';
3
+
4
+ /** Unbounded / sentinel limit threshold for cgroup memory (e.g. 9223372036854771712 or MAX_INT) */
5
+ const UNBOUNDED_CGROUP_THRESHOLD = 9_000_000_000_000_000_000;
6
+
7
+ /** Default safety ceiling for autonomous L1 memory allocations: 512 MB */
8
+ export const DEFAULT_AUTONOMOUS_L1_CEILING_BYTES = 512 * 1024 * 1024;
9
+
10
+ /** Minimum floor for autonomous L1 allocations: 16 MB */
11
+ export const MIN_AUTONOMOUS_L1_FLOOR_BYTES = 16 * 1024 * 1024;
12
+
13
+ /**
14
+ * Reads the container memory limit from Linux cgroups (v2 or v1).
15
+ *
16
+ * Defaults to `Infinity` when running outside Linux, when cgroup limits are unset ('max'),
17
+ * or when permission errors (EACCES / ENOENT) occur in hardened distroless environments.
18
+ */
19
+ export function readCgroupMemoryLimit(): number {
20
+ if (process.platform !== 'linux') {
21
+ return Infinity;
22
+ }
23
+
24
+ // 1. Probe cgroup v2: /sys/fs/cgroup/memory.max
25
+ try {
26
+ if (fs.existsSync('/sys/fs/cgroup/memory.max')) {
27
+ const raw = fs.readFileSync('/sys/fs/cgroup/memory.max', 'utf8').trim();
28
+ if (raw === 'max') {
29
+ return Infinity;
30
+ }
31
+ const bytes = parseInt(raw, 10);
32
+ if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
33
+ return bytes;
34
+ }
35
+ }
36
+ } catch {
37
+ // EACCES, ENOENT, or unreadable — fall through to cgroup v1 or Infinity
38
+ }
39
+
40
+ // 2. Probe cgroup v1: /sys/fs/cgroup/memory/memory.limit_in_bytes
41
+ try {
42
+ if (fs.existsSync('/sys/fs/cgroup/memory/memory.limit_in_bytes')) {
43
+ const raw = fs.readFileSync('/sys/fs/cgroup/memory/memory.limit_in_bytes', 'utf8').trim();
44
+ const bytes = parseInt(raw, 10);
45
+ if (Number.isFinite(bytes) && bytes > 0 && bytes < UNBOUNDED_CGROUP_THRESHOLD) {
46
+ return bytes;
47
+ }
48
+ }
49
+ } catch {
50
+ // EACCES, ENOENT, or unreadable
51
+ }
52
+
53
+ return Infinity;
54
+ }
55
+
56
+ /**
57
+ * Returns the V8 JavaScript heap size limit in bytes.
58
+ * Safely guards against missing or mock environments.
59
+ */
60
+ export function getV8HeapLimit(): number {
61
+ try {
62
+ const stats = v8.getHeapStatistics();
63
+ if (stats && Number.isFinite(stats.heap_size_limit) && stats.heap_size_limit > 0) {
64
+ return stats.heap_size_limit;
65
+ }
66
+ } catch {
67
+ // Fallback if v8 module is mocked or unavailable
68
+ }
69
+ return Infinity;
70
+ }
71
+
72
+ export interface AutonomousL1Options {
73
+ cgroupLimit?: number;
74
+ v8HeapLimit?: number;
75
+ defaultCeilingBytes?: number;
76
+ }
77
+
78
+ /**
79
+ * Computes an autonomous, safe memory bound for TriCache L1 RAM.
80
+ *
81
+ * Evaluates both the container cgroup limit (max 40% of container RAM)
82
+ * and the V8 heap limit (max 50% of V8 heap limit from --max-old-space-size),
83
+ * capped at a default 512MB ceiling.
84
+ */
85
+ export function resolveAutonomousL1MaxBytes(options?: AutonomousL1Options): number {
86
+ const cgroup = options?.cgroupLimit !== undefined ? options.cgroupLimit : readCgroupMemoryLimit();
87
+ const v8Limit = options?.v8HeapLimit !== undefined ? options.v8HeapLimit : getV8HeapLimit();
88
+ const ceiling = options?.defaultCeilingBytes ?? DEFAULT_AUTONOMOUS_L1_CEILING_BYTES;
89
+
90
+ const cgroupCap = Number.isFinite(cgroup) && cgroup > 0 ? cgroup * 0.40 : Infinity;
91
+ const v8Cap = Number.isFinite(v8Limit) && v8Limit > 0 ? v8Limit * 0.50 : Infinity;
92
+
93
+ const resolved = Math.min(cgroupCap, v8Cap, ceiling);
94
+
95
+ if (!Number.isFinite(resolved) || resolved <= 0) {
96
+ return ceiling;
97
+ }
98
+
99
+ return Math.max(MIN_AUTONOMOUS_L1_FLOOR_BYTES, Math.floor(resolved));
100
+ }