tricache 0.9.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/{cache-service-DVvroyqA.d.ts → cache-service-CREOp7MM.d.ts} +57 -12
- package/dist/{cache-service-KI5ACF3F.js → cache-service-MG7PN6MX.js} +3 -3
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-QNU7B43J.js → chunk-3I5L7K6I.js} +17 -0
- package/dist/{chunk-PL5J3ZNT.js → chunk-JYQFQJNJ.js} +682 -277
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +857 -293
- package/dist/cli.js +4 -4
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +865 -294
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +115 -36
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +88 -37
- package/dist/hono/index.cjs +865 -294
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +1 -1
- package/dist/{hono-VA9A1m0I.d.ts → hono-DSV2ve66.d.ts} +11 -4
- package/dist/http/index.cjs +917 -315
- package/dist/http/index.d.ts +3 -3
- package/dist/http/index.js +60 -29
- package/dist/index.cjs +885 -294
- package/dist/index.d.ts +37 -7
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +856 -292
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +858 -300
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +5 -11
- package/dist/prisma/index.d.ts +2 -2
- package/dist/serialize-worker.cjs +127 -9
- package/dist/serialize-worker.js +8 -4
- package/dist/{types-B_QkVwJ7.d.ts → types-Dyip5wAl.d.ts} +53 -7
- package/package.json +7 -4
- package/src/adapters/node-redis.ts +19 -0
- package/src/cache-service.ts +781 -297
- package/src/cli.ts +1 -1
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +94 -42
- package/src/env.d.ts +13 -0
- package/src/http/express.ts +55 -16
- package/src/http/fastify.ts +3 -7
- package/src/index.ts +9 -1
- package/src/next/cache-handler.ts +1 -4
- package/src/next/isr-handler.ts +1 -4
- package/src/serialize-worker.ts +6 -2
- package/src/smart-memory-cache.ts +3 -2
- package/src/types.ts +45 -5
- package/src/utils/tag-matcher.ts +90 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://kareem411.github.io/TriCache/)
|
|
5
5
|
[](https://www.npmjs.com/package/tricache)
|
|
6
6
|
[](https://www.npmjs.com/package/tricache)
|
|
7
|
-
[](tests)
|
|
8
8
|
[](src)
|
|
9
9
|
[](LICENSE)
|
|
10
10
|
[](https://nodejs.org)
|
|
@@ -73,10 +73,12 @@ await cache.invalidateTag('users');
|
|
|
73
73
|
```
|
|
74
74
|
|
|
75
75
|
* **Window TinyLFU (W-TinyLFU)**: ~1% Window LRU absorbs recency bursts; 4-row Count-Min Sketch rejects table scans. [[Internals $\rightarrow$](https://kareem411.github.io/TriCache/architecture-internals)]
|
|
76
|
+
* **WebAssembly Zstandard Compression**: Out-of-the-box `zstd` WASM engine compresses payloads $>1$ KB by ~95% with automatic Brotli fallback and optional LZ4.
|
|
76
77
|
* **Off-Heap `/dev/shm` RAM Spill**: Targets Linux POSIX shared memory tmpfs ($\ge 256\text{MB}$ total, $\ge 128\text{MB}$ free), burning 0 cloud IOPS. [[SRE Guide $\rightarrow$](https://kareem411.github.io/TriCache/kubernetes-production-guide)]
|
|
77
78
|
* **Dynamic Latency Watchdog**: Graduated shedding (0% $\rightarrow$ 25% $\rightarrow$ 75% $\rightarrow$ 100%) with asymmetric Redis hysteresis (15ms cutoff, 10ms recovery floor).
|
|
78
79
|
* **Ephemeral Quotas & K8s Eviction Defense**: Chunked watermark pruning (80% $\rightarrow$ 60% in 500-entry batches) and proactive $<10\%$ space spill pauses.
|
|
79
|
-
* **
|
|
80
|
+
* **Wildcard & Hierarchical Tag Invalidation**: Glob matching (`user:*`) and parent-child tree cascading (`{ cascade: true }`) over $O(1)$ generational version counters.
|
|
81
|
+
* **Differential Multi-Tier Waterfall Batching**: Cascading `cache.mget` resolves L1 $\rightarrow$ L2 $\rightarrow$ Disk $\rightarrow$ DB miss fetch with zero $N+1$ queries.
|
|
80
82
|
* **Zero-Dependency Cloud Hydration (SigV4)**: Hydrates cold pods from S3/R2 in milliseconds via native Web Crypto. [[Cloud Guide $\rightarrow$](https://kareem411.github.io/TriCache/cold-start-cloud-hydration)]
|
|
81
83
|
|
|
82
84
|
---
|
|
@@ -88,8 +90,10 @@ await cache.invalidateTag('users');
|
|
|
88
90
|
| **Storage Hierarchy** | In-Memory only | Single Remote (Redis) | Memory + Redis | **Three-Tier (RAM $\rightarrow$ `/dev/shm` $\rightarrow$ Redis)** |
|
|
89
91
|
| **Warm Hit Latency** | ~300 ns | 1,200,000 ns (1.2 ms) | ~400 ns | **356 ns (2.81M ops/sec)** |
|
|
90
92
|
| **Thundering-Herd Defense**| ❌ No | ❌ External plugin | ❌ No | **✅ Native Singleflight Coalescing** |
|
|
91
|
-
| **Tag Invalidation** | ❌ None | $O(N)$ blocking scan | $O(N)$ Redis Set | **✅ $O(1)$ Generational
|
|
93
|
+
| **Tag Invalidation** | ❌ None | $O(N)$ blocking scan | $O(N)$ Redis Set | **✅ $O(1)$ Generational + Wildcards & Cascades** |
|
|
92
94
|
| **Cluster Sync Backplane**| ❌ None | At-most-once Pub/Sub | Pub/Sub | **✅ Durable Redis Streams (`XADD`/`XREAD`)** |
|
|
95
|
+
| **Compression** | ❌ None | ❌ Manual | ❌ None | **✅ WebAssembly Zstandard (Default) & LZ4** |
|
|
96
|
+
| **Waterfall Batching (`mget`)**| ❌ None | ❌ Manual loops | ❌ None | **✅ Multi-Tier Cascading ($0$ $N+1$ Queries)** |
|
|
93
97
|
| **Container Memory Safety**| Unbounded GC | N/A (Remote only) | Heap-bound | **✅ Off-heap tmpfs + 80% OOM Guard** |
|
|
94
98
|
| **Encryption at Rest** | ❌ None | ❌ None | ❌ None | **✅ AES-256-GCM / Web Crypto AEAD** |
|
|
95
99
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CacheOptions,
|
|
1
|
+
import { C as CacheOptions, b as CacheMetrics, c as CacheHealthStatus, d as CachePresetType, e as CrossRegionInvalidationEvent, f as CachePriority, W as WrapOptions, a as InvalidateTagOptions, g as CachePingResult, D as DiskBackpressureStats, L as LockOptions, E as EncryptionMode, h as WTinyLfuStats } from './types-Dyip5wAl.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* TierLatencyWatchdog — Graduated, self-healing tier latency watchdog.
|
|
@@ -227,6 +227,7 @@ declare class CacheService {
|
|
|
227
227
|
private readonly opts;
|
|
228
228
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
229
229
|
private readonly _namespace;
|
|
230
|
+
private readonly prefixLen;
|
|
230
231
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
231
232
|
private readonly _redisDisabled;
|
|
232
233
|
private readonly watchdog;
|
|
@@ -236,6 +237,8 @@ declare class CacheService {
|
|
|
236
237
|
private readonly _l1Counters;
|
|
237
238
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
238
239
|
private readonly tagIndex;
|
|
240
|
+
/** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
|
|
241
|
+
private readonly keyTags;
|
|
239
242
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
240
243
|
private readonly tagVersions;
|
|
241
244
|
/**
|
|
@@ -243,6 +246,9 @@ declare class CacheService {
|
|
|
243
246
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
244
247
|
*/
|
|
245
248
|
private readonly dependencyIndex;
|
|
249
|
+
/** Reverse index of namespaced dependent key → source glob patterns */
|
|
250
|
+
private readonly keyDependencies;
|
|
251
|
+
private readonly _cgroupMemoryLimit;
|
|
246
252
|
private redis;
|
|
247
253
|
private redisConnecting;
|
|
248
254
|
private readonly cb;
|
|
@@ -281,6 +287,12 @@ declare class CacheService {
|
|
|
281
287
|
private _assertActive;
|
|
282
288
|
private _bumpKeyMutation;
|
|
283
289
|
private _getKeyMutationEpoch;
|
|
290
|
+
private _removeKeyTags;
|
|
291
|
+
private _removeKeyDependencies;
|
|
292
|
+
private _handleL1Eviction;
|
|
293
|
+
private _removePrefixFromIndices;
|
|
294
|
+
private _sweepExpiredMetadata;
|
|
295
|
+
private _runOomCheck;
|
|
284
296
|
private _ipcServer?;
|
|
285
297
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
286
298
|
private _subDisconnectedAt;
|
|
@@ -389,6 +401,10 @@ declare class CacheService {
|
|
|
389
401
|
*/
|
|
390
402
|
receiveCrossRegionInvalidation(event: CrossRegionInvalidationEvent): Promise<boolean>;
|
|
391
403
|
private _setLocalTagVersion;
|
|
404
|
+
private _isGenerationalEntryStale;
|
|
405
|
+
private _deleteRedisKeys;
|
|
406
|
+
private _parseGenerationalRedisHash;
|
|
407
|
+
private _readRedisEntry;
|
|
392
408
|
private _getTagVersion;
|
|
393
409
|
private _deleteIfStale;
|
|
394
410
|
/**
|
|
@@ -620,6 +636,7 @@ declare class CacheService {
|
|
|
620
636
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
621
637
|
*/
|
|
622
638
|
getIfFresh<T = unknown>(cacheKey: string): T | null;
|
|
639
|
+
private _prepareReadValue;
|
|
623
640
|
/**
|
|
624
641
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
625
642
|
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
@@ -638,7 +655,7 @@ declare class CacheService {
|
|
|
638
655
|
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
639
656
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
640
657
|
*/
|
|
641
|
-
mget<T>(keys: string[], fetchFn
|
|
658
|
+
mget<T>(keys: string[], fetchFn?: (missKeys: string[]) => Promise<Record<string, T> | Map<string, T>>, ttl?: number | ((key: string) => number), priority?: CachePriority): Promise<(T | undefined)[]>;
|
|
642
659
|
/**
|
|
643
660
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
644
661
|
* startup warming configured via `warmKeys` has completed.
|
|
@@ -692,27 +709,55 @@ declare class CacheService {
|
|
|
692
709
|
priority?: CachePriority;
|
|
693
710
|
}): Promise<number>;
|
|
694
711
|
/**
|
|
695
|
-
*
|
|
696
|
-
*
|
|
712
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
713
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
714
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
715
|
+
*/
|
|
716
|
+
private _resolveMatchingTags;
|
|
717
|
+
private _publishTagInvalidation;
|
|
718
|
+
private _removeTagMembersLocal;
|
|
719
|
+
/**
|
|
720
|
+
* Executes invalidation for a single already-resolved concrete tag without
|
|
721
|
+
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
722
|
+
*/
|
|
723
|
+
private _invalidateConcreteTag;
|
|
724
|
+
/**
|
|
725
|
+
* Executes invalidation for an array of already-resolved concrete tags
|
|
726
|
+
* without re-entering wildcard/cascade resolution or invalidateTag().
|
|
727
|
+
*/
|
|
728
|
+
private _invalidateConcreteTags;
|
|
729
|
+
/**
|
|
730
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
731
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
732
|
+
*
|
|
733
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
734
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
697
735
|
*
|
|
698
736
|
* @example
|
|
699
737
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
700
738
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
739
|
+
*
|
|
740
|
+
* @example
|
|
741
|
+
* // Wildcard pattern invalidation
|
|
742
|
+
* await cache.invalidateTag('org:123:*');
|
|
743
|
+
*
|
|
744
|
+
* @example
|
|
745
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
746
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
701
747
|
*/
|
|
702
|
-
invalidateTag(tag: string): Promise<void>;
|
|
748
|
+
invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
|
|
703
749
|
/**
|
|
704
750
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
705
|
-
*
|
|
706
|
-
*
|
|
751
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
752
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
707
753
|
*
|
|
708
|
-
*
|
|
709
|
-
*
|
|
754
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
755
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
710
756
|
*
|
|
711
757
|
* @example
|
|
712
|
-
*
|
|
713
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
758
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
714
759
|
*/
|
|
715
|
-
invalidateTags(tags: string[]): Promise<void>;
|
|
760
|
+
invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void>;
|
|
716
761
|
/**
|
|
717
762
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
718
763
|
*/
|
|
@@ -2,9 +2,9 @@ import {
|
|
|
2
2
|
CacheService,
|
|
3
3
|
ProcessTerminationBus,
|
|
4
4
|
deepMergeOptions
|
|
5
|
-
} from "./chunk-
|
|
6
|
-
import "./chunk-
|
|
7
|
-
import "./chunk-
|
|
5
|
+
} from "./chunk-JYQFQJNJ.js";
|
|
6
|
+
import "./chunk-UBWLPKTI.js";
|
|
7
|
+
import "./chunk-2AJKEQMZ.js";
|
|
8
8
|
export {
|
|
9
9
|
CacheService,
|
|
10
10
|
ProcessTerminationBus,
|
|
@@ -99,10 +99,63 @@ var WasmBloomFilter = class {
|
|
|
99
99
|
}
|
|
100
100
|
};
|
|
101
101
|
|
|
102
|
+
// src/utils/tag-matcher.ts
|
|
103
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
104
|
+
function isWildcardTag(tag) {
|
|
105
|
+
return tag.includes("*") || tag.includes("?");
|
|
106
|
+
}
|
|
107
|
+
function matchesTagPattern(pattern, tag) {
|
|
108
|
+
if (pattern === "*" || pattern === tag) return true;
|
|
109
|
+
if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
|
|
110
|
+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
|
|
111
|
+
const prefix = pattern.slice(0, -1);
|
|
112
|
+
return tag.startsWith(prefix);
|
|
113
|
+
}
|
|
114
|
+
if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
|
|
115
|
+
const suffix = pattern.slice(1);
|
|
116
|
+
return tag.endsWith(suffix);
|
|
117
|
+
}
|
|
118
|
+
let re = globRegexCache.get(pattern);
|
|
119
|
+
if (!re) {
|
|
120
|
+
if (globRegexCache.size >= 1e3) globRegexCache.clear();
|
|
121
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
122
|
+
re = new RegExp(`^${escaped}$`);
|
|
123
|
+
globRegexCache.set(pattern, re);
|
|
124
|
+
}
|
|
125
|
+
return re.test(tag);
|
|
126
|
+
}
|
|
127
|
+
function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
128
|
+
if (candidateTag === parentTag) return true;
|
|
129
|
+
const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
|
|
130
|
+
return candidateTag.startsWith(prefix);
|
|
131
|
+
}
|
|
132
|
+
function expandHierarchicalTags(tags, delimiter = ":") {
|
|
133
|
+
if (!tags.length) return [];
|
|
134
|
+
const result = /* @__PURE__ */ new Set();
|
|
135
|
+
for (const tag of tags) {
|
|
136
|
+
if (!tag) continue;
|
|
137
|
+
const parts = tag.split(delimiter).filter((p) => p.length > 0);
|
|
138
|
+
if (parts.length <= 1) {
|
|
139
|
+
result.add(tag);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
let accumulated = "";
|
|
143
|
+
for (let i = 0; i < parts.length; i++) {
|
|
144
|
+
accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
|
|
145
|
+
result.add(accumulated);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return Array.from(result);
|
|
149
|
+
}
|
|
150
|
+
|
|
102
151
|
export {
|
|
103
152
|
uint8ArrayToBase64,
|
|
104
153
|
base64ToUint8Array,
|
|
105
154
|
utf8ToUint8Array,
|
|
106
155
|
uint8ArrayToUtf8,
|
|
107
|
-
WasmBloomFilter
|
|
156
|
+
WasmBloomFilter,
|
|
157
|
+
isWildcardTag,
|
|
158
|
+
matchesTagPattern,
|
|
159
|
+
isChildTag,
|
|
160
|
+
expandHierarchicalTags
|
|
108
161
|
};
|
|
@@ -407,6 +407,14 @@ var NodeRedisPipelineAdapter = class {
|
|
|
407
407
|
}
|
|
408
408
|
return this;
|
|
409
409
|
}
|
|
410
|
+
hgetall(key) {
|
|
411
|
+
if (typeof this.multiInstance.hGetAll === "function") {
|
|
412
|
+
this.multiInstance.hGetAll(key);
|
|
413
|
+
} else {
|
|
414
|
+
this.multiInstance.hgetall(key);
|
|
415
|
+
}
|
|
416
|
+
return this;
|
|
417
|
+
}
|
|
410
418
|
async exec() {
|
|
411
419
|
const raw = await this.multiInstance.exec();
|
|
412
420
|
if (!raw) return null;
|
|
@@ -548,6 +556,15 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
|
|
|
548
556
|
}
|
|
549
557
|
return void 0;
|
|
550
558
|
}
|
|
559
|
+
async hgetall(key) {
|
|
560
|
+
if (typeof this.client.hGetAll === "function") {
|
|
561
|
+
return await this.client.hGetAll(key) ?? {};
|
|
562
|
+
}
|
|
563
|
+
if (typeof this.client.hgetall === "function") {
|
|
564
|
+
return await this.client.hgetall(key) ?? {};
|
|
565
|
+
}
|
|
566
|
+
return {};
|
|
567
|
+
}
|
|
551
568
|
async publish(channel, message) {
|
|
552
569
|
return await this.client.publish(channel, message);
|
|
553
570
|
}
|