tricache 0.9.0 → 1.0.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.
- package/README.md +7 -3
- package/dist/{cache-service-KI5ACF3F.js → cache-service-26GCO3UU.js} +3 -3
- package/dist/{cache-service-DVvroyqA.d.ts → cache-service-pJ-nFcVj.d.ts} +29 -12
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-PL5J3ZNT.js → chunk-7SZSQS55.js} +201 -34
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +376 -50
- package/dist/cli.js +4 -4
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +384 -51
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +64 -8
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +37 -9
- package/dist/hono/index.cjs +384 -51
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +1 -1
- package/dist/{hono-VA9A1m0I.d.ts → hono-DuNvciyq.d.ts} +4 -4
- package/dist/http/index.cjs +384 -51
- package/dist/http/index.d.ts +3 -3
- package/dist/http/index.js +8 -8
- package/dist/index.cjs +385 -49
- package/dist/index.d.ts +35 -6
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +375 -49
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +375 -49
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +3 -3
- 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-5HXqBfAf.d.ts} +51 -7
- package/package.json +7 -4
- package/src/cache-service.ts +238 -33
- package/src/cli.ts +1 -1
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +38 -11
- package/src/env.d.ts +13 -0
- package/src/index.ts +9 -1
- package/src/serialize-worker.ts +6 -2
- package/src/types.ts +43 -5
- package/src/utils/tag-matcher.ts +90 -0
- /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -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
|
|
|
@@ -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-7SZSQS55.js";
|
|
6
|
+
import "./chunk-UBWLPKTI.js";
|
|
7
|
+
import "./chunk-2AJKEQMZ.js";
|
|
8
8
|
export {
|
|
9
9
|
CacheService,
|
|
10
10
|
ProcessTerminationBus,
|
|
@@ -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-5HXqBfAf.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;
|
|
@@ -638,7 +639,7 @@ declare class CacheService {
|
|
|
638
639
|
* @param ttl - TTL in seconds for newly fetched values. Accepts a per-key function
|
|
639
640
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
640
641
|
*/
|
|
641
|
-
mget<T>(keys: string[], fetchFn
|
|
642
|
+
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
643
|
/**
|
|
643
644
|
* Returns a Promise that resolves once the cache is fully initialised and any
|
|
644
645
|
* startup warming configured via `warmKeys` has completed.
|
|
@@ -692,27 +693,43 @@ declare class CacheService {
|
|
|
692
693
|
priority?: CachePriority;
|
|
693
694
|
}): Promise<number>;
|
|
694
695
|
/**
|
|
695
|
-
*
|
|
696
|
-
*
|
|
696
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
697
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
698
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
699
|
+
*/
|
|
700
|
+
private _resolveMatchingTags;
|
|
701
|
+
/**
|
|
702
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
703
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
704
|
+
*
|
|
705
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
706
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
697
707
|
*
|
|
698
708
|
* @example
|
|
699
709
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
700
710
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
711
|
+
*
|
|
712
|
+
* @example
|
|
713
|
+
* // Wildcard pattern invalidation
|
|
714
|
+
* await cache.invalidateTag('org:123:*');
|
|
715
|
+
*
|
|
716
|
+
* @example
|
|
717
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
718
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
701
719
|
*/
|
|
702
|
-
invalidateTag(tag: string): Promise<void>;
|
|
720
|
+
invalidateTag(tag: string, opts?: InvalidateTagOptions): Promise<void>;
|
|
703
721
|
/**
|
|
704
722
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
705
|
-
*
|
|
706
|
-
*
|
|
723
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
724
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
707
725
|
*
|
|
708
|
-
*
|
|
709
|
-
*
|
|
726
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
727
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
710
728
|
*
|
|
711
729
|
* @example
|
|
712
|
-
*
|
|
713
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
730
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
714
731
|
*/
|
|
715
|
-
invalidateTags(tags: string[]): Promise<void>;
|
|
732
|
+
invalidateTags(tags: string[], opts?: InvalidateTagOptions): Promise<void>;
|
|
716
733
|
/**
|
|
717
734
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
718
735
|
*/
|
|
@@ -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
|
};
|
|
@@ -7,11 +7,16 @@ import {
|
|
|
7
7
|
compressWithHeader,
|
|
8
8
|
consoleLogger,
|
|
9
9
|
decompressBuffer,
|
|
10
|
-
decompressWithHeader
|
|
11
|
-
|
|
10
|
+
decompressWithHeader,
|
|
11
|
+
initZstd
|
|
12
|
+
} from "./chunk-UBWLPKTI.js";
|
|
12
13
|
import {
|
|
13
|
-
WasmBloomFilter
|
|
14
|
-
|
|
14
|
+
WasmBloomFilter,
|
|
15
|
+
expandHierarchicalTags,
|
|
16
|
+
isChildTag,
|
|
17
|
+
isWildcardTag,
|
|
18
|
+
matchesTagPattern
|
|
19
|
+
} from "./chunk-2AJKEQMZ.js";
|
|
15
20
|
|
|
16
21
|
// src/cache-service.ts
|
|
17
22
|
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
@@ -3716,6 +3721,7 @@ var CacheService = class _CacheService {
|
|
|
3716
3721
|
opts;
|
|
3717
3722
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
3718
3723
|
_namespace;
|
|
3724
|
+
prefixLen;
|
|
3719
3725
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
3720
3726
|
_redisDisabled;
|
|
3721
3727
|
watchdog;
|
|
@@ -3924,12 +3930,15 @@ var CacheService = class _CacheService {
|
|
|
3924
3930
|
redisSentinel: options.redisSentinel,
|
|
3925
3931
|
redisProtocol: options.redisProtocol,
|
|
3926
3932
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
3927
|
-
compression: options.compression ?? "
|
|
3933
|
+
compression: options.compression ?? "zstd",
|
|
3934
|
+
customCompressor: options.customCompressor,
|
|
3928
3935
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
3929
3936
|
strictSingleton: options.strictSingleton ?? false,
|
|
3930
3937
|
failClosed: options.failClosed ?? false,
|
|
3931
3938
|
tagStrategy: options.tagStrategy ?? "set",
|
|
3932
3939
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
3940
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
3941
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
3933
3942
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
3934
3943
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
3935
3944
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4002,6 +4011,7 @@ var CacheService = class _CacheService {
|
|
|
4002
4011
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4003
4012
|
});
|
|
4004
4013
|
this._namespace = ns;
|
|
4014
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4005
4015
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4006
4016
|
this.watchdog = new TierLatencyWatchdog({
|
|
4007
4017
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4111,6 +4121,9 @@ var CacheService = class _CacheService {
|
|
|
4111
4121
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4112
4122
|
this.initBackplane();
|
|
4113
4123
|
const startupPromises = [];
|
|
4124
|
+
if (this.opts.compression === "zstd") {
|
|
4125
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4126
|
+
}
|
|
4114
4127
|
if (this.opts.remoteSnapshot) {
|
|
4115
4128
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4116
4129
|
}
|
|
@@ -4616,6 +4629,50 @@ var CacheService = class _CacheService {
|
|
|
4616
4629
|
const tag = key;
|
|
4617
4630
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4618
4631
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
4632
|
+
} else if (op === "tag_pattern_incr") {
|
|
4633
|
+
const pattern = key;
|
|
4634
|
+
const now = performance.now();
|
|
4635
|
+
for (const [tag, info] of this.tagVersions) {
|
|
4636
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4637
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
4638
|
+
}
|
|
4639
|
+
}
|
|
4640
|
+
this.l1.scan((k, entry) => {
|
|
4641
|
+
if (entry.tagVersions) {
|
|
4642
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
4643
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4644
|
+
this.l1.delete(k);
|
|
4645
|
+
this._bumpKeyMutation(k);
|
|
4646
|
+
break;
|
|
4647
|
+
}
|
|
4648
|
+
}
|
|
4649
|
+
}
|
|
4650
|
+
}, 0);
|
|
4651
|
+
} else if (op === "tag_pattern_del") {
|
|
4652
|
+
const pattern = key;
|
|
4653
|
+
const matchedTagKeys = [];
|
|
4654
|
+
const prefix = this.nk("_tag_:");
|
|
4655
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
4656
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
4657
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4658
|
+
matchedTagKeys.push(tagKey);
|
|
4659
|
+
for (const k of members) {
|
|
4660
|
+
this.l1.delete(k);
|
|
4661
|
+
this._bumpKeyMutation(k);
|
|
4662
|
+
this._pendingDiskDeletes.add(k);
|
|
4663
|
+
setImmediate(() => {
|
|
4664
|
+
try {
|
|
4665
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
4666
|
+
} finally {
|
|
4667
|
+
this._pendingDiskDeletes.delete(k);
|
|
4668
|
+
}
|
|
4669
|
+
});
|
|
4670
|
+
}
|
|
4671
|
+
}
|
|
4672
|
+
}
|
|
4673
|
+
for (const tagKey of matchedTagKeys) {
|
|
4674
|
+
this.tagIndex.delete(tagKey);
|
|
4675
|
+
}
|
|
4619
4676
|
}
|
|
4620
4677
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4621
4678
|
}
|
|
@@ -4623,7 +4680,7 @@ var CacheService = class _CacheService {
|
|
|
4623
4680
|
_handleBackplaneMessage(message) {
|
|
4624
4681
|
try {
|
|
4625
4682
|
const msg = JSON.parse(message);
|
|
4626
|
-
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
|
|
4683
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr" && msg.op !== "tag_pattern_incr" && msg.op !== "tag_pattern_del") {
|
|
4627
4684
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4628
4685
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4629
4686
|
});
|
|
@@ -4810,12 +4867,12 @@ var CacheService = class _CacheService {
|
|
|
4810
4867
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
4811
4868
|
*/
|
|
4812
4869
|
async _serializeAndEncrypt(serialized) {
|
|
4813
|
-
const isCompressed = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
4814
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4870
|
+
const isCompressed = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
4871
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4815
4872
|
return this._workerPool.encrypt(serialized);
|
|
4816
4873
|
}
|
|
4817
4874
|
if (isCompressed) {
|
|
4818
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
4875
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
4819
4876
|
if (this.enc.isEnabled) {
|
|
4820
4877
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
4821
4878
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -4830,16 +4887,16 @@ var CacheService = class _CacheService {
|
|
|
4830
4887
|
*/
|
|
4831
4888
|
async _decryptAndDeserialize(raw) {
|
|
4832
4889
|
let plain;
|
|
4833
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
4890
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
4834
4891
|
plain = await this._workerPool.decrypt(raw);
|
|
4835
4892
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
4836
4893
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
4837
4894
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
4838
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
4895
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4839
4896
|
plain = decompressed.toString("utf8");
|
|
4840
4897
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
4841
4898
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
4842
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
4899
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4843
4900
|
plain = decompressed.toString("utf8");
|
|
4844
4901
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
4845
4902
|
plain = this.enc.decrypt(raw);
|
|
@@ -5235,7 +5292,7 @@ var CacheService = class _CacheService {
|
|
|
5235
5292
|
const optRefreshAhead = opts.refreshAhead;
|
|
5236
5293
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5237
5294
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5238
|
-
const optTags = opts.tags;
|
|
5295
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5239
5296
|
const l1Hit = this.l1.get(k);
|
|
5240
5297
|
if (l1Hit !== null) {
|
|
5241
5298
|
let isGenerationalStale = false;
|
|
@@ -5693,15 +5750,16 @@ var CacheService = class _CacheService {
|
|
|
5693
5750
|
this._pendingDiskDeletes.delete(k);
|
|
5694
5751
|
this.counters.sets++;
|
|
5695
5752
|
let activeTagVersions;
|
|
5696
|
-
|
|
5753
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5754
|
+
if (tagsToRegister?.length) {
|
|
5697
5755
|
if (this.opts.tagStrategy === "generational") {
|
|
5698
|
-
const vers = await Promise.all(
|
|
5756
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5699
5757
|
activeTagVersions = {};
|
|
5700
|
-
for (let i = 0; i <
|
|
5701
|
-
activeTagVersions[
|
|
5758
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
5759
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5702
5760
|
}
|
|
5703
5761
|
} else {
|
|
5704
|
-
await this._registerTags(k,
|
|
5762
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5705
5763
|
}
|
|
5706
5764
|
}
|
|
5707
5765
|
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
@@ -6316,16 +6374,23 @@ var CacheService = class _CacheService {
|
|
|
6316
6374
|
}
|
|
6317
6375
|
}
|
|
6318
6376
|
}
|
|
6319
|
-
if (missKeys.length > 0) {
|
|
6377
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6320
6378
|
this.counters.fetches++;
|
|
6321
6379
|
const fetched = await fetchFn(missKeys);
|
|
6380
|
+
const isMap = fetched instanceof Map;
|
|
6322
6381
|
const setPromises = [];
|
|
6323
6382
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6324
|
-
const
|
|
6383
|
+
const k = missKeys[j];
|
|
6384
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6325
6385
|
result[missIndexes[j]] = v;
|
|
6326
|
-
if (v !== void 0) {
|
|
6327
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6328
|
-
setPromises.push(this.set(
|
|
6386
|
+
if (v !== void 0 && v !== null) {
|
|
6387
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6388
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
6389
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
6390
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
6391
|
+
} else if (v === null) {
|
|
6392
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6393
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6329
6394
|
}
|
|
6330
6395
|
}
|
|
6331
6396
|
if (setPromises.length > 0) {
|
|
@@ -6468,21 +6533,109 @@ var CacheService = class _CacheService {
|
|
|
6468
6533
|
}
|
|
6469
6534
|
}
|
|
6470
6535
|
/**
|
|
6471
|
-
*
|
|
6472
|
-
*
|
|
6536
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
6537
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
6538
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
6539
|
+
*/
|
|
6540
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
6541
|
+
const isPattern = isWildcardTag(tag);
|
|
6542
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6543
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6544
|
+
const tagMatches = (t) => {
|
|
6545
|
+
if (t === tag) return true;
|
|
6546
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
6547
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
6548
|
+
return false;
|
|
6549
|
+
};
|
|
6550
|
+
if (shouldCascade && !isPattern) {
|
|
6551
|
+
matched.add(tag);
|
|
6552
|
+
}
|
|
6553
|
+
const tagPrefix = this.nk("_tag_:");
|
|
6554
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
6555
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
6556
|
+
if (tagMatches(t)) matched.add(t);
|
|
6557
|
+
}
|
|
6558
|
+
for (const t of this.tagVersions.keys()) {
|
|
6559
|
+
if (tagMatches(t)) matched.add(t);
|
|
6560
|
+
}
|
|
6561
|
+
this.l1.scan((_k, entry) => {
|
|
6562
|
+
if (entry.tagVersions) {
|
|
6563
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
6564
|
+
if (tagMatches(t)) matched.add(t);
|
|
6565
|
+
}
|
|
6566
|
+
}
|
|
6567
|
+
}, 0);
|
|
6568
|
+
if (!this._redisDisabled) {
|
|
6569
|
+
try {
|
|
6570
|
+
const client = await this.getRedis();
|
|
6571
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6572
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
6573
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6574
|
+
const pfx = this.nk("tag_ver:");
|
|
6575
|
+
for (const sk of scannedKeys) {
|
|
6576
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6577
|
+
if (tagMatches(t)) matched.add(t);
|
|
6578
|
+
}
|
|
6579
|
+
} else {
|
|
6580
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
6581
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6582
|
+
const pfx = this.nk("_tag_:");
|
|
6583
|
+
for (const sk of scannedKeys) {
|
|
6584
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6585
|
+
if (tagMatches(t)) matched.add(t);
|
|
6586
|
+
}
|
|
6587
|
+
}
|
|
6588
|
+
} catch (err) {
|
|
6589
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
6590
|
+
}
|
|
6591
|
+
}
|
|
6592
|
+
return matched;
|
|
6593
|
+
}
|
|
6594
|
+
/**
|
|
6595
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
6596
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
6597
|
+
*
|
|
6598
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
6599
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
6473
6600
|
*
|
|
6474
6601
|
* @example
|
|
6475
6602
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6476
6603
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
6604
|
+
*
|
|
6605
|
+
* @example
|
|
6606
|
+
* // Wildcard pattern invalidation
|
|
6607
|
+
* await cache.invalidateTag('org:123:*');
|
|
6608
|
+
*
|
|
6609
|
+
* @example
|
|
6610
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
6611
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
6477
6612
|
*/
|
|
6478
|
-
async invalidateTag(tag) {
|
|
6613
|
+
async invalidateTag(tag, opts) {
|
|
6479
6614
|
this._assertActive("invalidateTag");
|
|
6480
6615
|
const span = this._startSpan("tricache.invalidate_tag");
|
|
6481
6616
|
if (this.opts.tracer) {
|
|
6482
6617
|
span.setAttribute("cache.tag", tag);
|
|
6483
6618
|
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6619
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
6484
6620
|
}
|
|
6485
6621
|
try {
|
|
6622
|
+
const isPattern = isWildcardTag(tag);
|
|
6623
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
6624
|
+
if (isPattern || shouldCascade) {
|
|
6625
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
6626
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6627
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
6628
|
+
if (matchedTags.size > 0) {
|
|
6629
|
+
await this.invalidateTags(Array.from(matchedTags));
|
|
6630
|
+
}
|
|
6631
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
6632
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6633
|
+
await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
6634
|
+
} else {
|
|
6635
|
+
void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
6636
|
+
}
|
|
6637
|
+
return;
|
|
6638
|
+
}
|
|
6486
6639
|
if (this.opts.tagStrategy === "generational") {
|
|
6487
6640
|
let newVer = 1;
|
|
6488
6641
|
if (!this._redisDisabled) {
|
|
@@ -6545,21 +6698,35 @@ var CacheService = class _CacheService {
|
|
|
6545
6698
|
}
|
|
6546
6699
|
/**
|
|
6547
6700
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
6548
|
-
*
|
|
6549
|
-
*
|
|
6701
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
6702
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
6550
6703
|
*
|
|
6551
|
-
*
|
|
6552
|
-
*
|
|
6704
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
6705
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
6553
6706
|
*
|
|
6554
6707
|
* @example
|
|
6555
|
-
*
|
|
6556
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
6708
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
6557
6709
|
*/
|
|
6558
|
-
async invalidateTags(tags) {
|
|
6710
|
+
async invalidateTags(tags, opts) {
|
|
6559
6711
|
this._assertActive("invalidateTags");
|
|
6560
6712
|
if (tags.length === 0) return;
|
|
6713
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
6714
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
6715
|
+
if (hasWildcards || shouldCascade) {
|
|
6716
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
6717
|
+
for (const t of tags) {
|
|
6718
|
+
if (isWildcardTag(t) || shouldCascade) {
|
|
6719
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
6720
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
6721
|
+
} else {
|
|
6722
|
+
allResolvedTags.add(t);
|
|
6723
|
+
}
|
|
6724
|
+
}
|
|
6725
|
+
if (allResolvedTags.size === 0) return;
|
|
6726
|
+
tags = Array.from(allResolvedTags);
|
|
6727
|
+
}
|
|
6561
6728
|
if (tags.length === 1) {
|
|
6562
|
-
await this.invalidateTag(tags[0]);
|
|
6729
|
+
await this.invalidateTag(tags[0], opts);
|
|
6563
6730
|
return;
|
|
6564
6731
|
}
|
|
6565
6732
|
if (this.opts.tagStrategy === "generational") {
|