tricache 0.6.6 → 0.7.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 (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +500 -24
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-AJASH5FX.js +7 -0
  5. package/dist/cache-service-BblHuF3i.d.ts +1476 -0
  6. package/dist/chunk-3XQUQBOZ.js +4583 -0
  7. package/dist/{chunk-FKY5R3CE.js → chunk-PFB5FMEY.js} +126 -4
  8. package/dist/chunk-UBSR5UYA.js +0 -0
  9. package/dist/cli.cjs +5181 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5161 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5289 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +172 -0
  18. package/dist/index.cjs +1181 -194
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3697
  21. package/dist/nestjs/index.cjs +5305 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5327 -0
  25. package/dist/next/index.d.ts +204 -0
  26. package/dist/next/index.js +274 -0
  27. package/dist/prisma/index.cjs +122 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +86 -0
  30. package/dist/serialize-worker.cjs +177 -13
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +64 -15
  33. package/src/cache-service.ts +1005 -192
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +63 -0
  36. package/src/disk-tier.ts +71 -7
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +56 -5
  39. package/src/http/index.ts +223 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +244 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +151 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +22 -8
  53. package/src/types.ts +172 -2
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 tricache contributors
3
+ Copyright (c) 2026 Kareem (https://github.com/Kareem411) and TriCache contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -2,30 +2,57 @@
2
2
 
3
3
  [![CI](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml/badge.svg)](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml)
4
4
  [![npm version](https://img.shields.io/npm/v/tricache.svg)](https://www.npmjs.com/package/tricache)
5
- [![npm downloads](https://img.shields.io/npm/dm/tricache.svg)](https://www.npmjs.com/package/tricache)
5
+ [![Tests](https://img.shields.io/badge/tests-484%20passing-brightgreen)](tests)
6
+ [![Code Quality](https://img.shields.io/badge/oxlint-0%20warnings-brightgreen)](src)
6
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
8
  [![Node.js ≥ 22](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org)
8
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.x%20%7C%206.x-blue)](https://www.typescriptlang.org)
9
- [![L1 get](https://img.shields.io/badge/L1%20get-2.81%20M%2Fs-brightgreen)](BENCHMARKS.md)
10
- [![Thundering herd](https://img.shields.io/badge/thundering%20herd-100%25%20coalesced-brightgreen)](BENCHMARKS.md)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20%7C%205.x%20%7C%206.x-blue)](https://www.typescriptlang.org)
10
+ [![npm provenance](https://img.shields.io/badge/provenance-verified-brightgreen)](https://www.npmjs.com/package/tricache)
11
11
 
12
- tricache is an extremely fast three-tier Node.js cache library. It serves warm reads at **2.81 million operations per second** from a single thread — over 100× faster than a localhost Redis round-trip and below any network latency floor. When L1 fills, evicted entries spill to a local NVMe disk tier rather than being dropped, keeping hit rates high without unbounded RAM growth. Cache misses that reach L2 (Redis or Valkey) are automatically coalesced: no matter how many concurrent callers miss the same key, `fetchFn` fires exactly once. See the [performance section](#-performance) for full numbers. Stale-While-Revalidate, AES-256-GCM at-rest encryption, pub/sub fleet-wide invalidation, OOM guard, cold-start snapshots, and Prometheus metrics are also supported through optional configuration — with zero required fields to get started.
12
+ tricache is a three-tier Node.js cache library — in-memory (L1), local disk spill, and Redis/Valkey (L2). Warm L1 reads run at 2.81 million operations per second on a single thread (356 ns/op) — well below any network round-trip, including a local Redis call. When L1 fills, evicted entries spill to disk instead of being dropped, keeping hit rates high without unbounded RAM growth. Misses that reach L2 are coalesced across concurrent callers, so a spike of simultaneous requests for the same key triggers exactly one fetchFn call, not one per caller. See the performance section for full numbers. Optional configuration adds Stale-While-Revalidate, at-rest encryption (AES-256-GCM by default), pub/sub fleet-wide invalidation, an OOM guard, cold-start snapshots, and Prometheus metrics — none of it required to get started.
13
13
 
14
14
  <img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
15
15
 
16
16
  ---
17
17
 
18
+ ## 🏆 What Makes TriCache a "No-Brainer"
19
+
20
+ | Dimension | Industry Standard (`keyv`, `@neshca/cache-handler`, `cache-manager`) | **TriCache v0.7.0** |
21
+ |:---|:---|:---|
22
+ | **Storage Hierarchy** | Single-tier (RAM or Redis or Disk) | **Three-Tier (RAM → NVMe Disk → Redis/Valkey)** |
23
+ | **Thundering-Herd** | Unhandled / requires external single-flight libraries | **Built-in Inflight Promise Coalescing (10k tested)** |
24
+ | **Tag Invalidation** | $O(N)$ bulk key scans or Redis `SMEMBERS` deletions | **$O(1)$ Generational Version Counters (`MULTI/EXEC`)** |
25
+ | **Next.js 16 Support** | Basic key-value handlers, broken RSC stream reuse | **Native 5-Method Bridge with stream re-hydration & `cacheLife`** |
26
+ | **NestJS Support** | Generic `CacheModule` with missing batch/tag methods | **Dynamic `TriCacheModule` + `@Cacheable` & `@CacheEvict` decorators** |
27
+ | **Cluster Invalidation** | At-most-once Pub/Sub (drops messages on network blips) | **Durable Redis Streams (`XADD`/`XREAD`) with reconnect replay** |
28
+ | **Memory Hygiene** | Standard JSON stringification, unconstrained RAM | **WASM Bloom filter, Count-Min Sketch, Zero-Copy `transferList` workers** |
29
+ | **Failure Tolerance** | Cascading 500s when Redis/Upstream flutters | **Circuit Breaker, `staleIfError` SWR grace, monotonic tag guarantees** |
30
+
31
+ ---
32
+
18
33
  ## ✨ Features
19
34
 
20
35
  | Feature | Detail |
21
36
  |---|---|
37
+ | **Next.js 16 & 15 Adapter** | Full `CacheHandler` implementation for Next.js 16 `"use cache"` and legacy ISR; single-use stream re-hydration, dynamic `softTags` checking, and automatic `NEXT_PHASE` build bypass |
38
+ | **NestJS Dynamic Module & Store** | Dedicated `TriCacheModule.register()` dynamic module, `TriCacheStore` adapter for `@nestjs/cache-manager`, and declarative `@Cacheable` / `@CacheEvict` method decorators |
39
+ | **First-Class Prisma Extension** | `withTriCache(options)` for `$extends` with automatic query key hashing, cache options, and write mutation tag invalidation |
40
+ | **First-Class Drizzle Wrapper** | `withCache(query, options)` wrapping Drizzle queries with automatic SQL + params hashing and SWR support |
41
+ | **Distributed Mutex Lock** | `cache.lock(key, fn, options)` with Redis `SET NX EX`, atomic Lua token-release, and local promise-chain fallback |
42
+ | **Native OpenTelemetry Metrics** | Direct `meter` integration publishing monotonic counters and observable gauges without scrapers |
43
+ | **Interactive Developer CLI** | Zero-dependency CLI (`npx tricache inspect`, `ping`, `clear`) with terminal dashboard and latency probes |
44
+ | **Universal `cache.wrap()` Primitive** | Options-object wrapper (`{ ttl, swr, tags, dependsOn, priority }`) for ORMs and service layers |
45
+ | **Generational Tagging** | $O(1)$ tag invalidations via Redis version counters (`INCR tag_ver:<tag>`); atomic `{d, t, tv}` hash schema, pipelined batch `invalidateTags()`, and time-based self-healing reconciliation |
46
+ | **Read Safety (`cloneStrategy`)** | `cloneStrategy: 'structuredClone'` isolates returned objects from caller mutation; sub-microsecond raw reference fallback (`'none'`) |
47
+ | **Redis Streams Backplane** | `backplaneMode: 'stream'` replaces at-most-once Pub/Sub with durable `XADD`/`XREAD` append-only log; cluster hash tag slot safety and zero-drop reconnect replay |
48
+ | **Atomic Disk Writes** | Atomic staging via unique `.tmp` sibling files with Windows NTFS file-lock micro-retries and background `.tmp` janitor sweep |
22
49
  | **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
50
  | **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
51
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
25
52
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
26
53
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
27
54
  | **Stale-if-error** | Extend a stale entry's TTL when SWR revalidation fails — no errors served during upstream outages |
28
- | **Thundering-herd prevention** | Inflight `Promise` registry — only one `fetchFn` call per key regardless of concurrency |
55
+ | **Thundering-herd prevention** | Inflight `Promise` registry — only one `fetchFn` call per key regardless of concurrency (10,000 tested) |
29
56
  | **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
30
57
  | **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
31
58
  | **Batch read** | `mget()` collects L1 hits, calls `fetchFn` only for misses, preserves ordering |
@@ -82,6 +109,13 @@ const user = await cache.get(
82
109
  300,
83
110
  );
84
111
 
112
+ // Universal wrap() with options object (alternative to get)
113
+ const profile = await cache.wrap(
114
+ `user:${userId}:profile`,
115
+ () => db.users.findProfile(userId),
116
+ { ttl: 300, swr: 60, tags: ['users'] },
117
+ );
118
+
85
119
  // Explicit set
86
120
  await cache.set(`user:${userId}`, user, 300);
87
121
 
@@ -120,7 +154,13 @@ await cache.mset({
120
154
 
121
155
  // Batch delete
122
156
  await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
157
+ ```
158
+
159
+ > [!TIP]
160
+ > **In-Memory Reference Semantics & Mutation Safety:**
161
+ > By default, TriCache returns direct in-memory object references from L1 RAM (`cloneStrategy: 'none'`) to achieve sub-microsecond throughput (**2.81M ops/sec / 356 ns**). If your callers mutate returned objects in-place, enable `cloneStrategy: 'structuredClone'` for deep copy isolation, or enable `frozen: true` in non-production environments to catch mutations at runtime.
123
162
 
163
+ ```typescript
124
164
  // Warm L1 from Redis at startup
125
165
  const loaded = await cache.warmFromL2('user:*');
126
166
  console.log(`Pre-warmed ${loaded} user entries`);
@@ -189,12 +229,32 @@ CacheService.create({
189
229
  redisHost: 'my-redis.example.com', // or REDIS_HOST env var
190
230
  redisPort: 6379,
191
231
  redisTls: true, // default: true when NODE_ENV=production
232
+ redisProtocol: 3, // default: 3 (RESP3 in ioredis v6+); set to 2 for RESP2 proxies (Twemproxy/Envoy)
192
233
  disableRedis: false, // default: true when NODE_ENV!=production
193
234
 
235
+ // ── Transparent payload compression ──────────────────────────────────
236
+ // 'none' (default) — raw msgpack/JSON representation
237
+ // 'brotli' | 'gzip' — compress Redis L2 payloads and disk tier binaries
238
+ compression: 'none',
239
+ compressionThresholdBytes: 1024, // only compress entries ≥ 1 KB (default)
240
+
194
241
  // ── Invalidation backplane ───────────────────────────────────────────
195
- // Redis pub/sub channel that propagates deletes to all instances.
196
- // Enabled by default when Redis is active.
197
- invalidationBackplane: true,
242
+ invalidationBackplane: true,
243
+ // 'pubsub' (default) — Ephemeral Redis Pub/Sub (at-most-once delivery)
244
+ // 'stream' — Durable Redis Streams (XADD/XREAD) with replay on reconnect
245
+ backplaneMode: 'pubsub',
246
+ backplaneStreamMaxLen: 10_000, // max entries retained in invalidation stream
247
+ backplaneStreamBlockMs: 2_000, // blocking poll interval for XREAD BLOCK
248
+ // backplaneStreamKey: 'tricache:stream:{my-app}', // custom stream key override
249
+
250
+ // ── Generational tagging & clone strategy ─────────────────────────────
251
+ // 'set' (default) — traditional Redis Set member tracking
252
+ // 'generational' — atomic O(1) integer version counters in Redis + memory
253
+ tagStrategy: 'set',
254
+ tagVersionTtlMs: 5_000, // ms before local generational tag is re-synced from Redis
255
+ // 'none' (default) — raw in-memory references (~350 ns performance)
256
+ // 'structuredClone' — deep-clones returned values to prevent caller mutation
257
+ cloneStrategy: 'none',
198
258
 
199
259
  // ── OOM guard ────────────────────────────────────────────────────────
200
260
  oomProtection: true, // enabled by default
@@ -487,14 +547,17 @@ const hot = cache.hotKeys(5);
487
547
  // ]
488
548
  ```
489
549
 
490
- ### `cache.invalidateTag(tag)` → `Promise<void>`
550
+ ### `cache.invalidateTag(tag)` / `cache.invalidateTags(tags)` → `Promise<void>`
491
551
 
492
- Evict all entries associated with a tag from L1, disk, and Redis.
552
+ Evict all entries associated with one or more tags from L1, disk, and Redis.
553
+ When `tagStrategy: 'generational'` is active, `invalidateTags(tags)` pipelines multi-tag increments in a single network round-trip.
493
554
 
494
555
  ```typescript
495
- await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
496
- await cache.set('product:2', data, 60, undefined, { tags: ['catalog'] });
497
- await cache.invalidateTag('catalog'); // evicts both entries
556
+ await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'electronics'] });
557
+ await cache.set('product:2', data, 60, undefined, { tags: ['catalog', 'deals'] });
558
+
559
+ await cache.invalidateTag('catalog'); // single tag
560
+ await cache.invalidateTags(['electronics', 'deals']); // pipelined batch invalidation
498
561
  ```
499
562
 
500
563
  ### `cache.ping()` → `Promise<CachePingResult>`
@@ -597,7 +660,33 @@ Lazily yields `[key, value]` pairs for every live L1 entry. Key has namespace pr
597
660
  for (const [key, user] of cache.entries<User>()) sync(key, user);
598
661
  ```
599
662
 
600
- > **JIT note:** all three generators iterate `SmartMemoryCache.cache` (a single `Map`). V8 maintains per-call-site type feedback; having three generator functions share the same Map means no single one gets the full monomorphic specialization budget. In practice the throughput impact is ≤5 % relative to each running in isolation. See [BENCHMARKS.md](BENCHMARKS.md) for numbers.
663
+ ### `cache.rotateEncryptionKey(newKeyBase64, newMode?)` → `Promise<void>`
664
+
665
+ Dynamically rotates the active encryption key at runtime with zero downtime:
666
+ - Installs the new key as primary for all subsequent writes.
667
+ - Automatically preserves the previous key for seamless fallback decryption of existing cache entries.
668
+ - Gracefully drains and re-initializes all worker threads in the crypto pool (`WorkerPool.drainAndReinit()`).
669
+
670
+ ```typescript
671
+ await cache.rotateEncryptionKey(newKeyBase64, 'aes-256-gcm');
672
+ ```
673
+
674
+ ### `cache.lock<T>(resourceKey, fn, options?)` → `Promise<T>`
675
+
676
+ Acquire a distributed (or in-process) mutual exclusion lock on `resourceKey`, execute `fn`, and automatically release the lock on return or throw.
677
+ - Prevents concurrent executions of critical tasks across a cluster (e.g. database migrations, nightly syncs, cron jobs).
678
+ - Safe token comparison via Redis Lua script prevents deleting a lock acquired by another worker if execution exceeded the lock TTL.
679
+ - Automatically falls back to an in-process promise-chain mutex in single-process or dev environments.
680
+
681
+ ```typescript
682
+ const result = await cache.lock('cron:nightly-sync', async () => {
683
+ return await runNightlyDatabaseSync();
684
+ }, {
685
+ ttl: 60, // Auto-release TTL in seconds (prevents deadlocks on crash)
686
+ acquireTimeout: 5000, // Maximum wait time to acquire lock in ms
687
+ retryInterval: 100, // Polling retry interval in ms
688
+ });
689
+ ```
601
690
 
602
691
  ### `cache.destroy()` → `Promise<void>`
603
692
 
@@ -605,6 +694,120 @@ Closes the Redis connection, unsubscribes the backplane, and stops all backgroun
605
694
 
606
695
  ---
607
696
 
697
+ ## 🗄️ First-Class ORM Extensions (Prisma & Drizzle)
698
+
699
+ ### Prisma Client Extension (`tricache/prisma`)
700
+
701
+ Add one-line query caching and automatic model tag invalidation to Prisma:
702
+
703
+ ```typescript
704
+ import { PrismaClient } from '@prisma/client';
705
+ import { withTriCache } from 'tricache/prisma';
706
+ import { CacheService } from 'tricache';
707
+
708
+ const cache = CacheService.create({ redisHost: 'localhost' });
709
+
710
+ const prisma = new PrismaClient().$extends(
711
+ withTriCache({
712
+ cache,
713
+ defaultTtl: 300,
714
+ autoInvalidate: true, // Automatically invalidates 'user' tag on user.create / update / delete
715
+ })
716
+ );
717
+
718
+ // Automatic caching with explicit options:
719
+ const activeUsers = await prisma.user.findMany({
720
+ where: { active: true },
721
+ cache: { ttl: 60, tags: ['users'], swr: 30 },
722
+ });
723
+ ```
724
+
725
+ ### Drizzle ORM Wrapper (`tricache/drizzle`)
726
+
727
+ Wrap any Drizzle query builder with automatic SQL + parameter hashing and caching:
728
+
729
+ ```typescript
730
+ import { withCache } from 'tricache/drizzle';
731
+ import { eq } from 'drizzle-orm';
732
+
733
+ const activeUsers = await withCache(
734
+ db.select().from(users).where(eq(users.active, true)),
735
+ { cache, ttl: 300, tags: ['users'] }
736
+ );
737
+ ```
738
+
739
+ ---
740
+
741
+ ## 📊 OpenTelemetry Native Metrics
742
+
743
+ TriCache integrates directly with OpenTelemetry `Meter` (`@opentelemetry/api`) to publish monotonic counters and observable gauges without scrapers:
744
+
745
+ ```typescript
746
+ import { metrics } from '@opentelemetry/api';
747
+ import { CacheService } from 'tricache';
748
+
749
+ const meter = metrics.getMeter('my-service');
750
+
751
+ const cache = CacheService.create({
752
+ redisHost: 'localhost',
753
+ meter, // Native OpenTelemetry meter integration
754
+ });
755
+ ```
756
+
757
+ ---
758
+
759
+ ## 💻 Developer & Troubleshooting CLI (`npx tricache`)
760
+
761
+ Inspect running caches, test latency across tiers, or flush namespaces directly from your terminal:
762
+
763
+ ```bash
764
+ # Display full live dashboard (hit ratios, latencies, Count-Min Sketch hot keys)
765
+ npx tricache inspect --redis redis://localhost:6379 --namespace my-app
766
+
767
+ # Measure 3-tier response latency
768
+ npx tricache ping --redis redis://localhost:6379
769
+
770
+ # Flush namespace or prefix
771
+ npx tricache clear --redis redis://localhost:6379 --namespace my-app --prefix user:
772
+ ```
773
+
774
+ ---
775
+
776
+ ## 🌐 HTTP Caching & 304 ETag Middleware (`tricache/http`)
777
+
778
+ Drop-in HTTP caching with automatic weak ETag generation and RFC-compliant `304 Not Modified` short-circuiting:
779
+
780
+ ### Express & Connect
781
+ ```typescript
782
+ import express from 'express';
783
+ import { expressCache } from 'tricache/http';
784
+ import { CacheService } from 'tricache';
785
+
786
+ const app = express();
787
+ const cache = CacheService.create({ redisHost: 'localhost' });
788
+
789
+ // Automatically caches GET /api/users, emits ETag, and returns 304 on If-None-Match
790
+ app.get('/api/users', expressCache({ cache, ttl: 300, tags: ['users'] }), async (_req, res) => {
791
+ const users = await db.user.findMany();
792
+ res.json(users);
793
+ });
794
+ ```
795
+
796
+ ### Hono & Web Standards
797
+ ```typescript
798
+ import { Hono } from 'hono';
799
+ import { honoCache } from 'tricache/http';
800
+
801
+ const app = new Hono();
802
+
803
+ app.get('/api/users', honoCache({ ttl: 300, tags: ['users'] }), async (c) => {
804
+ const users = await db.user.findMany();
805
+ return c.json(users);
806
+ });
807
+ ```
808
+
809
+ ---
810
+
608
811
  ## 🎯 Priority levels
609
812
 
610
813
  ```typescript
@@ -663,7 +866,7 @@ CacheService.create({
663
866
 
664
867
  ## 🔐 Encryption
665
868
 
666
- AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Three modes are available via `encryptionMode`:
869
+ AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Four modes are available via `encryptionMode`:
667
870
 
668
871
  | Mode | Key length | Notes |
669
872
  |---|---|---|
@@ -750,20 +953,257 @@ CacheService.create({
750
953
 
751
954
  ---
752
955
 
753
- ## 🔁 Backplane staleness fence
956
+ ## 🗜️ Transparent Payload Compression
754
957
 
755
- Redis Pub/Sub has no delivery guarantees — a subscriber disconnect (network blip, Redis failover, container restart) can cause peer invalidation messages to be silently dropped. Entries written to L1 between the disconnect and reconnect may silently serve stale data.
756
-
757
- TriCache tracks when the subscriber disconnects and, on reconnect, compares the gap duration against `backplaneMaxStalenessMs`. If the gap exceeds the threshold, every L1 entry that was written before the disconnect is proactively evicted, forcing a controlled re-fetch from L2 on the next access:
958
+ TriCache includes built-in Brotli and Gzip compression for Redis L2 strings and L1.5 disk tier binary payloads, transparently reducing network bandwidth and storage footprints without manual application encoding.
758
959
 
759
960
  ```typescript
760
961
  CacheService.create({
761
- invalidationBackplane: true,
762
- backplaneMaxStalenessMs: 5_000, // default: evict stale L1 on gaps > 5 s
962
+ compression: 'brotli', // 'brotli' | 'gzip' | 'none' (default: 'none')
963
+ compressionThresholdBytes: 1024, // only compress entries >= 1024 bytes (default)
763
964
  });
764
965
  ```
765
966
 
766
- Setting `backplaneMaxStalenessMs: 0` disables the fence entirely. The eviction count and gap duration are logged at `warn` level on every triggered flush.
967
+ ### Storage Envelope Matrix
968
+
969
+ Entries written to Redis L2 and the disk spill tier use self-describing magic headers, allowing mixed uncompressed, compressed, and encrypted entries to coexist seamlessly during rollout:
970
+
971
+ | Envelope Header | State | Description |
972
+ |---|---|---|
973
+ | `cmp:v1:<data>` | Compressed | Compressed payload (Brotli or Gzip) |
974
+ | `ecp:v1:<data>` | Encrypted + Compressed | Payload compressed before encryption |
975
+ | `enc:v1:<data>` | Encrypted | AES-256-GCM / AES-128 encrypted without compression |
976
+ | `{"d": ...}` / raw | Plaintext | Uncompressed, unencrypted legacy JSON / msgpack |
977
+
978
+ ### Worker Thread Offload
979
+
980
+ When `workerThreads: true` is enabled, compression and decompression for large payloads above `workerThresholdBytes` are offloaded to background worker threads alongside encryption, keeping the V8 main event loop free for concurrent HTTP requests.
981
+
982
+ ---
983
+
984
+ ## ⚡ Next.js 16 & 15 Integration (`tricache/next`)
985
+
986
+ TriCache provides first-class support for Next.js 16 `"use cache"`, React 19 RSC streaming, and Next.js 15/16 ISR via `tricache/next`.
987
+
988
+ ### Setup in `next.config.mjs`
989
+
990
+ ```javascript
991
+ // next.config.mjs
992
+ /** @type {import('next').NextConfig} */
993
+ const nextConfig = {
994
+ // Point Next.js directly to the default export
995
+ cacheHandler: require.resolve('tricache/next'),
996
+ cacheMaxMemorySize: 0, // Disable Next.js default in-memory cache to let TriCache manage RAM
997
+ };
998
+
999
+ export default nextConfig;
1000
+ ```
1001
+
1002
+ ### Custom Options Factory
1003
+
1004
+ To configure TriCache with custom Redis, encryption, or namespace settings:
1005
+
1006
+ ```typescript
1007
+ // cache-handler.mjs
1008
+ import { createNextCacheHandler } from 'tricache/next';
1009
+
1010
+ export default createNextCacheHandler({
1011
+ namespace: 'my-next-app',
1012
+ redisHost: process.env.REDIS_HOST,
1013
+ tagStrategy: 'generational',
1014
+ backplaneMode: 'stream',
1015
+ });
1016
+ ```
1017
+
1018
+ ```javascript
1019
+ // next.config.mjs
1020
+ export default {
1021
+ cacheHandler: require.resolve('./cache-handler.mjs'),
1022
+ };
1023
+ ```
1024
+
1025
+ ### Key Architectural Highlights
1026
+ - **Single-Use Stream Re-hydration:** React 19 RSC streams (`ReadableStream<Uint8Array>`) are drained to contiguous binary buffers on `set()`, and fresh unlocked `ReadableStream` instances are re-hydrated on every `get()` hit.
1027
+ - **Dynamic `softTags` Verification:** In Next.js 16 App Router, layout and route boundary invalidations pass `softTags` into `ctx.softTags` at read time. TriCache dynamically validates them against generational tag versions, triggering misses on invalidated boundaries.
1028
+ - **Stream Error Boundary:** Mid-flight client disconnects or aborted streams are caught safely without throwing or storing corrupted partial payloads.
1029
+ - **Automatic Build Phase Bypass:** Automatically detects `NEXT_PHASE=phase-production-build` during `next build` and runs in-memory without opening Redis network sockets.
1030
+
1031
+ ---
1032
+
1033
+ ## 🦁 NestJS Integration (`tricache/nestjs`)
1034
+
1035
+ TriCache provides an official NestJS dynamic module and `@nestjs/cache-manager` store adapter compatible with `cache-manager` v5/v6:
1036
+
1037
+ ### Synchronous Module Registration
1038
+
1039
+ ```typescript
1040
+ // app.module.ts
1041
+ import { Module } from '@nestjs/common';
1042
+ import { TriCacheModule } from 'tricache/nestjs';
1043
+
1044
+ @Module({
1045
+ imports: [
1046
+ TriCacheModule.register({
1047
+ namespace: 'my-nest-api',
1048
+ redisHost: process.env.REDIS_HOST,
1049
+ encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
1050
+ }),
1051
+ ],
1052
+ })
1053
+ export class AppModule {}
1054
+ ```
1055
+
1056
+ ### Asynchronous Module Registration (with ConfigService)
1057
+
1058
+ ```typescript
1059
+ // app.module.ts
1060
+ import { Module } from '@nestjs/common';
1061
+ import { ConfigModule, ConfigService } from '@nestjs/config';
1062
+ import { TriCacheModule } from 'tricache/nestjs';
1063
+
1064
+ @Module({
1065
+ imports: [
1066
+ ConfigModule.forRoot(),
1067
+ TriCacheModule.registerAsync({
1068
+ imports: [ConfigModule],
1069
+ inject: [ConfigService],
1070
+ useFactory: (config: ConfigService) => ({
1071
+ namespace: config.get<string>('CACHE_NAMESPACE', 'nest-api'),
1072
+ redisHost: config.get<string>('REDIS_HOST'),
1073
+ redisPort: config.get<number>('REDIS_PORT', 6379),
1074
+ tagStrategy: 'generational',
1075
+ backplaneMode: 'stream',
1076
+ }),
1077
+ }),
1078
+ ],
1079
+ })
1080
+ export class AppModule {}
1081
+ ```
1082
+
1083
+ ### Injecting into Services & Controllers
1084
+
1085
+ Use either standard `@Inject(CACHE_MANAGER)` for `@nestjs/cache-manager` compatibility, or `@Inject('TRICACHE_SERVICE')` for direct access to TriCache's three-tier engine:
1086
+
1087
+ ```typescript
1088
+ import { Injectable, Inject } from '@nestjs/common';
1089
+ import { CACHE_MANAGER } from '@nestjs/cache-manager';
1090
+ import type { CacheStore } from '@nestjs/cache-manager';
1091
+ import type { CacheService } from 'tricache';
1092
+
1093
+ @Injectable()
1094
+ export class UsersService {
1095
+ constructor(
1096
+ @Inject(CACHE_MANAGER) private cacheManager: CacheStore,
1097
+ @Inject('TRICACHE_SERVICE') private triCache: CacheService,
1098
+ ) {}
1099
+
1100
+ async getUser(id: string) {
1101
+ // Standard NestJS cache-manager API (millisecond TTL)
1102
+ const cached = await this.cacheManager.get(`user:${id}`);
1103
+ if (cached) return cached;
1104
+
1105
+ // Or use TriCache's native SWR & thundering-herd prevention:
1106
+ return this.triCache.get(`user:${id}`, () => this.fetchFromDb(id), 300, { swr: 60 });
1107
+ }
1108
+ }
1109
+ ```
1110
+
1111
+ ### Declarative Method Decorators (`@Cacheable`, `@CacheEvict`)
1112
+
1113
+ Remove cache boilerplate from your NestJS services using declarative method decorators:
1114
+
1115
+ ```typescript
1116
+ import { Injectable } from '@nestjs/common';
1117
+ import { Cacheable, CacheEvict } from 'tricache/nestjs';
1118
+
1119
+ @Injectable()
1120
+ export class ProductsService {
1121
+ // Automatically caches result in TriCache (L1 -> L1.5 -> L2) with stampede coalescing
1122
+ @Cacheable({
1123
+ key: (id: string) => `product:${id}`,
1124
+ ttl: 300,
1125
+ swr: 60,
1126
+ tags: ['products'],
1127
+ })
1128
+ async findById(id: string) {
1129
+ return this.db.product.findUnique({ where: { id } });
1130
+ }
1131
+
1132
+ // Automatically invalidates tags or keys after successful method execution
1133
+ @CacheEvict({ tags: ['products'] })
1134
+ async updateProduct(id: string, dto: UpdateProductDto) {
1135
+ return this.db.product.update({ where: { id }, data: dto });
1136
+ }
1137
+ }
1138
+ ```
1139
+
1140
+ ---
1141
+
1142
+ ## 🏷️ Generational Tag Invalidation (`tagStrategy: 'generational'`)
1143
+
1144
+ Traditional tag-based caching stores key sets in Redis and performs $O(N)$ key deletions on `invalidateTag()`. For high-cardinality collections, this triggers blocking Redis spikes and cache stampedes.
1145
+
1146
+ With `tagStrategy: 'generational'`:
1147
+ - **$O(1)$ Atomic Tag Invalidation:** `cache.invalidateTag('products')` atomically increments an integer version counter in Redis (`INCR tag_ver:products`) and updates local memory.
1148
+ - **Atomic Multi-Field Hash Schema:** Entries in Redis are stored as a unified Hash `{ d: envelope, t: timestamp, tv: tagVersionsJson }` with an atomic `MULTI/EXEC` transaction.
1149
+ - **Pipelined Batch Invalidation:** `cache.invalidateTags(['t1', 't2'])` pipelines multi-tag version increments in a single network round-trip.
1150
+ - **Zero-Tear Compare-and-Delete:** Stale entries are pruned upon access using an atomic Lua script (`deleteIfSetBefore`) on Redis and L1 RAM, eliminating race conditions where concurrent revalidations write newer data.
1151
+ - **Self-Healing Reconciliation:** In-memory tag versions are verified against Redis when `Date.now() - lastSyncedAt > tagVersionTtlMs` (default: 5 s), guaranteeing bounded staleness even if a backplane broadcast is dropped during a network partition.
1152
+
1153
+ ```typescript
1154
+ const cache = CacheService.create({
1155
+ tagStrategy: 'generational',
1156
+ tagVersionTtlMs: 5_000,
1157
+ });
1158
+
1159
+ // Cache entry with tags
1160
+ await cache.set('item:123', productData, 3600, undefined, { tags: ['catalog', 'electronics'] });
1161
+
1162
+ // Invalidate in O(1) time
1163
+ await cache.invalidateTag('catalog');
1164
+ ```
1165
+
1166
+ ---
1167
+
1168
+ ## 🌊 Redis Streams Backplane (`backplaneMode: 'stream'`)
1169
+
1170
+ Standard Redis Pub/Sub operates on an *at-most-once* delivery model. If an instance experiences a transient network disconnect, container reschedule, or long GC pause, invalidation messages published during the disconnection are lost.
1171
+
1172
+ Setting `backplaneMode: 'stream'` switches the backplane to a durable append-only log in Redis using `XADD` and `XREAD`:
1173
+
1174
+ ```typescript
1175
+ const cache = CacheService.create({
1176
+ backplaneMode: 'stream',
1177
+ backplaneStreamMaxLen: 10_000, // Approximate MAXLEN trimming
1178
+ backplaneStreamBlockMs: 2_000, // XREAD BLOCK timeout
1179
+ });
1180
+ ```
1181
+
1182
+ ### Architecture & Resilience
1183
+ - **Cluster Single-Slot Routing:** Stream keys default to `tricache:stream:{<namespace>}`, ensuring multi-node Redis Clusters route all stream operations to a single slot without cross-slot errors.
1184
+ - **Dedicated Long-Polling Consumer:** Runs on an isolated Redis client connection (`XREAD BLOCK`) so standard cache `GET`/`SET` pipelines are never blocked.
1185
+ - **Zero-Drop Replay on Reconnect:** Tracks `_lastStreamId` to automatically replay all missed invalidations in order after short network drops or GC pauses without flushing L1.
1186
+ - **Trim Gap Fallback:** If an instance was disconnected longer than the stream retention window, it detects the gap, increments `metrics().backplane.streamGaps`, safely flushes L1, and resets to `'$'`.
1187
+ - **Instant Clean Teardown:** `cache.destroy()` immediately disconnects the dedicated client socket to interrupt blocking long-polls without stalling process shutdown.
1188
+
1189
+ ---
1190
+
1191
+ ## 🛡️ Read Safety (`cloneStrategy: 'structuredClone'`)
1192
+
1193
+ By default (`cloneStrategy: 'none'`), TriCache returns raw in-memory JS references from L1 hits for maximum throughput (~350 ns per hit). If application code mutates the returned object, the cached reference is directly modified.
1194
+
1195
+ Setting `cloneStrategy: 'structuredClone'` enables deep clone isolation:
1196
+
1197
+ ```typescript
1198
+ const cache = CacheService.create({
1199
+ cloneStrategy: 'structuredClone',
1200
+ });
1201
+
1202
+ const user = await cache.get('user:1', () => db.fetchUser(1));
1203
+ user.roles.push('admin'); // Mutating caller copy does NOT pollute cached L1 state
1204
+ ```
1205
+
1206
+ Supported types: plain objects, arrays, Dates, Maps, Sets, and TypedArrays. When `frozen: true` is also enabled, L1 entries remain frozen while callers receive fully mutable clones.
767
1207
 
768
1208
  ---
769
1209
 
@@ -816,11 +1256,16 @@ CacheService.create({
816
1256
  { host: 'redis-node-3.example.com', port: 6379 },
817
1257
  ],
818
1258
  redisTls: true,
1259
+ useShardedPubSub: true, // Redis 7+ sharded pub/sub (SPUBLISH / SSUBSCRIBE)
819
1260
  });
820
1261
  ```
821
1262
 
822
1263
  ioredis handles slot routing, moved/ask redirects, and re-queuing commands during slot migrations transparently. You can list any subset of cluster nodes — ioredis discovers the full topology automatically.
823
1264
 
1265
+ #### Sharded Pub/Sub (`useShardedPubSub`)
1266
+
1267
+ When `useShardedPubSub: true` is enabled on Redis Cluster (Redis 7+), invalidation messages are published via `SPUBLISH` and subscribed via `SSUBSCRIBE` bound directly to the `{<namespace>}` slot shard. This eliminates cluster-wide broadcast gossip, drastically reducing cluster bus CPU utilization under heavy invalidation load.
1268
+
824
1269
  ### Redis Sentinel
825
1270
 
826
1271
  ```typescript
@@ -839,7 +1284,20 @@ CacheService.create({
839
1284
 
840
1285
  ioredis monitors the current master via the Sentinel topology and transparently reconnects to a new primary after failover. The backplane subscriber is also constructed in the appropriate cluster/sentinel mode.
841
1286
 
842
- > `redisHost` / `redisPort` are ignored when `redisClusterNodes` or `redisSentinel` is set. All three topology modes support `redisTls`.
1287
+ ### Wire Protocol Compatibility (`redisProtocol: 2 | 3`)
1288
+
1289
+ TriCache uses `ioredis` v6, which connects using **RESP3** (`redisProtocol: 3`) by default for optimized structured parsing and streaming.
1290
+
1291
+ If your infrastructure routes Redis traffic through intermediate proxies that only understand RESP2 (such as **Twemproxy**, **Envoy Redis proxy filter**, or older AWS ElastiCache Serverless proxy configurations that reject the `HELLO 3` handshake), explicitly set `redisProtocol: 2`:
1292
+
1293
+ ```typescript
1294
+ CacheService.create({
1295
+ redisHost: 'envoy-redis-proxy.internal',
1296
+ redisProtocol: 2, // force RESP2 wire protocol
1297
+ });
1298
+ ```
1299
+
1300
+ > `redisHost` / `redisPort` are ignored when `redisClusterNodes` or `redisSentinel` is set. All three topology modes support `redisTls` and `redisProtocol` (RESP2/RESP3).
843
1301
 
844
1302
  ---
845
1303
 
@@ -862,6 +1320,24 @@ The 562-byte WASM binary is inlined as Base64 — zero filesystem access at runt
862
1320
 
863
1321
  ---
864
1322
 
1323
+ ## 🔬 High-Performance Architecture & Memory Hygiene
1324
+
1325
+ TriCache is engineered for low-latency, high-throughput environments where garbage collection (GC) pauses and main-thread blocking must be minimized. The codebase employs several advanced V8 and hardware-aware optimizations:
1326
+
1327
+ ### ⚡ Performance & Memory Hygiene
1328
+ - **Zero-Allocation Hot Paths:** To eliminate object allocation thrashing on hot L1 reads, TriCache reuses a single, pre-allocated static `_hit` object literal in [src/smart-memory-cache.ts](src/smart-memory-cache.ts) to return cache hits synchronously.
1329
+ - **Fast-Path Binary Operations (Uint32Array XOR):** The XOR obfuscation engine in [src/encryption.ts](src/encryption.ts) automatically detects if buffers are 4-byte-aligned. If so, it processes the operation using `Uint32Array` views, allowing the V8 JIT compiler to compile the loop into highly-optimized, 32-bit register-level CPU `XOR` instructions instead of a slow byte-by-byte traversal.
1330
+ - **Pre-allocated Eviction Pools:** During L1 eviction, candidate selection avoids generating temporary object literals. The system samples candidates into a pre-allocated `_evictPool` array and mutates their fields in-place, eliminating GC pressure when the cache is under heavy write load.
1331
+
1332
+ ### 🛡️ Production-First Ergonomics & Resiliency
1333
+ - **Next.js HMR Resiliency:** Normal in-memory caches re-instantiate and wipe their state during Next.js Hot Module Replacement (HMR) reloads. TriCache binds its singleton instance to `globalThis` to preserve the L1 cache across hot-reload cycles in server environments.
1334
+ - **Graceful Degradation & Fallbacks:**
1335
+ - **L2 Circuit Breaker:** Protects your app from cascading failures if Redis gets slow or goes down, automatically failing back to L1/disk and probing Redis health on a cooldown timer.
1336
+ - **Dynamic Bloom Filters:** Uses a WebAssembly Bloom filter for fast miss checks, but automatically falls back to a dynamically-sized, memory-optimized pure JS Bloom filter if the cache size exceeds the WebAssembly filter's hardcoded capacity limit.
1337
+ - **CPU-Efficient Count-Min Sketch:** Keeps access-frequency history across eviction boundaries in a tight `4 rows × 512 counters` `Uint16Array` (4 KB total). This fits entirely within the CPU's L1d cache, ensuring frequency updates are essentially free.
1338
+
1339
+ ---
1340
+
865
1341
  ## 📊 Performance
866
1342
 
867
1343
  Measured on a single Node.js thread (no `await` on synchronous paths):
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { runCli } from '../dist/cli.js';
4
+
5
+ runCli().catch((err) => {
6
+ console.error(err);
7
+ process.exit(1);
8
+ });