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
|
@@ -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";
|
|
@@ -1125,7 +1130,7 @@ var SmartMemoryCache = class {
|
|
|
1125
1130
|
};
|
|
1126
1131
|
return hit;
|
|
1127
1132
|
}
|
|
1128
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1133
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
|
|
1129
1134
|
const packed = this.codec.encode(data);
|
|
1130
1135
|
const size = packed.byteLength;
|
|
1131
1136
|
this.compressions++;
|
|
@@ -1162,7 +1167,7 @@ var SmartMemoryCache = class {
|
|
|
1162
1167
|
priority,
|
|
1163
1168
|
ttlMs,
|
|
1164
1169
|
delta,
|
|
1165
|
-
setAt: now2,
|
|
1170
|
+
setAt: setAt ?? now2,
|
|
1166
1171
|
tagVersions
|
|
1167
1172
|
});
|
|
1168
1173
|
}
|
|
@@ -1190,7 +1195,7 @@ var SmartMemoryCache = class {
|
|
|
1190
1195
|
}
|
|
1191
1196
|
const now = Date.now();
|
|
1192
1197
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1193
|
-
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: now, tagVersions });
|
|
1198
|
+
this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
|
|
1194
1199
|
if (!existingEntry) this.bloom.add(key);
|
|
1195
1200
|
this.maybeRebuildBloom();
|
|
1196
1201
|
this.totalSize += size;
|
|
@@ -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;
|
|
@@ -3725,6 +3731,8 @@ var CacheService = class _CacheService {
|
|
|
3725
3731
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
3726
3732
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
3727
3733
|
tagIndex = /* @__PURE__ */ new Map();
|
|
3734
|
+
/** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
|
|
3735
|
+
keyTags = /* @__PURE__ */ new Map();
|
|
3728
3736
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
3729
3737
|
tagVersions = /* @__PURE__ */ new Map();
|
|
3730
3738
|
/**
|
|
@@ -3732,6 +3740,9 @@ var CacheService = class _CacheService {
|
|
|
3732
3740
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
3733
3741
|
*/
|
|
3734
3742
|
dependencyIndex = /* @__PURE__ */ new Map();
|
|
3743
|
+
/** Reverse index of namespaced dependent key → source glob patterns */
|
|
3744
|
+
keyDependencies = /* @__PURE__ */ new Map();
|
|
3745
|
+
_cgroupMemoryLimit;
|
|
3735
3746
|
redis = null;
|
|
3736
3747
|
redisConnecting = null;
|
|
3737
3748
|
cb;
|
|
@@ -3801,6 +3812,84 @@ var CacheService = class _CacheService {
|
|
|
3801
3812
|
_getKeyMutationEpoch(namespacedKey) {
|
|
3802
3813
|
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
3803
3814
|
}
|
|
3815
|
+
_removeKeyTags(namespacedKey) {
|
|
3816
|
+
const entry = this.keyTags.get(namespacedKey);
|
|
3817
|
+
if (!entry) return;
|
|
3818
|
+
for (const tag of entry.tags) {
|
|
3819
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
3820
|
+
const members = this.tagIndex.get(tagKey);
|
|
3821
|
+
if (members) {
|
|
3822
|
+
members.delete(namespacedKey);
|
|
3823
|
+
if (members.size === 0) this.tagIndex.delete(tagKey);
|
|
3824
|
+
}
|
|
3825
|
+
}
|
|
3826
|
+
this.keyTags.delete(namespacedKey);
|
|
3827
|
+
}
|
|
3828
|
+
_removeKeyDependencies(namespacedKey) {
|
|
3829
|
+
const patterns = this.keyDependencies.get(namespacedKey);
|
|
3830
|
+
if (patterns) {
|
|
3831
|
+
for (const pat of patterns) {
|
|
3832
|
+
const deps = this.dependencyIndex.get(pat);
|
|
3833
|
+
if (deps) {
|
|
3834
|
+
deps.delete(namespacedKey);
|
|
3835
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
3836
|
+
}
|
|
3837
|
+
}
|
|
3838
|
+
this.keyDependencies.delete(namespacedKey);
|
|
3839
|
+
} else if (this.dependencyIndex.size > 0) {
|
|
3840
|
+
for (const [pat, deps] of this.dependencyIndex) {
|
|
3841
|
+
deps.delete(namespacedKey);
|
|
3842
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
}
|
|
3846
|
+
_handleL1Eviction(namespacedKey, reason) {
|
|
3847
|
+
const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
3848
|
+
if (!spilledToDisk) {
|
|
3849
|
+
this._removeKeyTags(namespacedKey);
|
|
3850
|
+
this._removeKeyDependencies(namespacedKey);
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
_removePrefixFromIndices(prefix) {
|
|
3854
|
+
for (const k of Array.from(this.keyTags.keys())) {
|
|
3855
|
+
if (k.startsWith(prefix)) this._removeKeyTags(k);
|
|
3856
|
+
}
|
|
3857
|
+
for (const k of Array.from(this.keyDependencies.keys())) {
|
|
3858
|
+
if (k.startsWith(prefix)) this._removeKeyDependencies(k);
|
|
3859
|
+
}
|
|
3860
|
+
for (const k of Array.from(this._l1Counters.keys())) {
|
|
3861
|
+
if (k.startsWith(prefix)) this._l1Counters.delete(k);
|
|
3862
|
+
}
|
|
3863
|
+
}
|
|
3864
|
+
_sweepExpiredMetadata() {
|
|
3865
|
+
const now = Date.now();
|
|
3866
|
+
for (const [k, c] of this._l1Counters) {
|
|
3867
|
+
if (c.expiresAt <= now) this._l1Counters.delete(k);
|
|
3868
|
+
}
|
|
3869
|
+
for (const [k, meta] of this.keyTags) {
|
|
3870
|
+
if (meta.expiresAt <= now && !this.l1.has(k)) {
|
|
3871
|
+
this._removeKeyTags(k);
|
|
3872
|
+
this._removeKeyDependencies(k);
|
|
3873
|
+
}
|
|
3874
|
+
}
|
|
3875
|
+
}
|
|
3876
|
+
_runOomCheck() {
|
|
3877
|
+
const heap = v82.getHeapStatistics();
|
|
3878
|
+
const heapUsed = heap.used_heap_size / heap.heap_size_limit;
|
|
3879
|
+
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
|
|
3880
|
+
const used = Math.max(heapUsed, cgroupUsed);
|
|
3881
|
+
if (used >= this.opts.oomHeapThreshold) {
|
|
3882
|
+
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
3883
|
+
this.counters.oomEvictions++;
|
|
3884
|
+
this.counters.oomLastAt = Date.now();
|
|
3885
|
+
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
3886
|
+
heapUsedPct: Math.round(heapUsed * 100),
|
|
3887
|
+
cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
|
|
3888
|
+
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
3889
|
+
evicted
|
|
3890
|
+
});
|
|
3891
|
+
}
|
|
3892
|
+
}
|
|
3804
3893
|
_ipcServer;
|
|
3805
3894
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
3806
3895
|
_subDisconnectedAt = null;
|
|
@@ -3847,6 +3936,7 @@ var CacheService = class _CacheService {
|
|
|
3847
3936
|
constructor(options = {}) {
|
|
3848
3937
|
const logger = options.logger ?? consoleLogger;
|
|
3849
3938
|
this.logger = logger;
|
|
3939
|
+
this._cgroupMemoryLimit = readCgroupMemoryLimit();
|
|
3850
3940
|
const ns = options.namespace?.trim() ?? "";
|
|
3851
3941
|
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
3852
3942
|
this.enc = new CacheEncryption(
|
|
@@ -3924,12 +4014,15 @@ var CacheService = class _CacheService {
|
|
|
3924
4014
|
redisSentinel: options.redisSentinel,
|
|
3925
4015
|
redisProtocol: options.redisProtocol,
|
|
3926
4016
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
3927
|
-
compression: options.compression ?? "
|
|
4017
|
+
compression: options.compression ?? "zstd",
|
|
4018
|
+
customCompressor: options.customCompressor,
|
|
3928
4019
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
3929
4020
|
strictSingleton: options.strictSingleton ?? false,
|
|
3930
4021
|
failClosed: options.failClosed ?? false,
|
|
3931
4022
|
tagStrategy: options.tagStrategy ?? "set",
|
|
3932
4023
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
4024
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
4025
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
3933
4026
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
3934
4027
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
3935
4028
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4002,6 +4095,7 @@ var CacheService = class _CacheService {
|
|
|
4002
4095
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4003
4096
|
});
|
|
4004
4097
|
this._namespace = ns;
|
|
4098
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4005
4099
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4006
4100
|
this.watchdog = new TierLatencyWatchdog({
|
|
4007
4101
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4026,7 +4120,10 @@ var CacheService = class _CacheService {
|
|
|
4026
4120
|
void this.disk.save(key, entry);
|
|
4027
4121
|
});
|
|
4028
4122
|
},
|
|
4029
|
-
onEviction:
|
|
4123
|
+
onEviction: (key, reason) => {
|
|
4124
|
+
this._handleL1Eviction(key, reason);
|
|
4125
|
+
options.onEviction?.(key, reason);
|
|
4126
|
+
},
|
|
4030
4127
|
logger
|
|
4031
4128
|
});
|
|
4032
4129
|
if (!this.snapshotLoaded) {
|
|
@@ -4064,6 +4161,7 @@ var CacheService = class _CacheService {
|
|
|
4064
4161
|
}
|
|
4065
4162
|
this.cleanupInterval = setInterval(() => {
|
|
4066
4163
|
const cleaned = this.l1.cleanup();
|
|
4164
|
+
this._sweepExpiredMetadata();
|
|
4067
4165
|
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
4068
4166
|
}, 5 * 60 * 1e3);
|
|
4069
4167
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
@@ -4076,18 +4174,7 @@ var CacheService = class _CacheService {
|
|
|
4076
4174
|
}
|
|
4077
4175
|
if (this.opts.oomProtection) {
|
|
4078
4176
|
this.oomInterval = setInterval(() => {
|
|
4079
|
-
|
|
4080
|
-
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
4081
|
-
if (used >= this.opts.oomHeapThreshold) {
|
|
4082
|
-
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4083
|
-
this.counters.oomEvictions++;
|
|
4084
|
-
this.counters.oomLastAt = Date.now();
|
|
4085
|
-
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4086
|
-
heapUsedPct: Math.round(used * 100),
|
|
4087
|
-
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4088
|
-
evicted
|
|
4089
|
-
});
|
|
4090
|
-
}
|
|
4177
|
+
this._runOomCheck();
|
|
4091
4178
|
}, this.opts.oomCheckIntervalMs);
|
|
4092
4179
|
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
4093
4180
|
}
|
|
@@ -4111,6 +4198,9 @@ var CacheService = class _CacheService {
|
|
|
4111
4198
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4112
4199
|
this.initBackplane();
|
|
4113
4200
|
const startupPromises = [];
|
|
4201
|
+
if (this.opts.compression === "zstd") {
|
|
4202
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4203
|
+
}
|
|
4114
4204
|
if (this.opts.remoteSnapshot) {
|
|
4115
4205
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4116
4206
|
}
|
|
@@ -4559,7 +4649,7 @@ var CacheService = class _CacheService {
|
|
|
4559
4649
|
else if (f === "src") src = v;
|
|
4560
4650
|
else if (f === "tagVersion") tagVersionRaw = v;
|
|
4561
4651
|
}
|
|
4562
|
-
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
4652
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
|
|
4563
4653
|
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
4564
4654
|
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
4565
4655
|
op: String(op).slice(0, 40),
|
|
@@ -4616,6 +4706,50 @@ var CacheService = class _CacheService {
|
|
|
4616
4706
|
const tag = key;
|
|
4617
4707
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4618
4708
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
4709
|
+
} else if (op === "tag_pattern_incr") {
|
|
4710
|
+
const pattern = key;
|
|
4711
|
+
const now = performance.now();
|
|
4712
|
+
for (const [tag, info] of this.tagVersions) {
|
|
4713
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4714
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
4715
|
+
}
|
|
4716
|
+
}
|
|
4717
|
+
this.l1.scan((k, entry) => {
|
|
4718
|
+
if (entry.tagVersions) {
|
|
4719
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
4720
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4721
|
+
this.l1.delete(k);
|
|
4722
|
+
this._bumpKeyMutation(k);
|
|
4723
|
+
break;
|
|
4724
|
+
}
|
|
4725
|
+
}
|
|
4726
|
+
}
|
|
4727
|
+
}, 0);
|
|
4728
|
+
} else if (op === "tag_pattern_del") {
|
|
4729
|
+
const pattern = key;
|
|
4730
|
+
const matchedTagKeys = [];
|
|
4731
|
+
const prefix = this.nk("_tag_:");
|
|
4732
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
4733
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
4734
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4735
|
+
matchedTagKeys.push(tagKey);
|
|
4736
|
+
for (const k of members) {
|
|
4737
|
+
this.l1.delete(k);
|
|
4738
|
+
this._bumpKeyMutation(k);
|
|
4739
|
+
this._pendingDiskDeletes.add(k);
|
|
4740
|
+
setImmediate(() => {
|
|
4741
|
+
try {
|
|
4742
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
4743
|
+
} finally {
|
|
4744
|
+
this._pendingDiskDeletes.delete(k);
|
|
4745
|
+
}
|
|
4746
|
+
});
|
|
4747
|
+
}
|
|
4748
|
+
}
|
|
4749
|
+
}
|
|
4750
|
+
for (const tagKey of matchedTagKeys) {
|
|
4751
|
+
this.tagIndex.delete(tagKey);
|
|
4752
|
+
}
|
|
4619
4753
|
}
|
|
4620
4754
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4621
4755
|
}
|
|
@@ -4623,7 +4757,7 @@ var CacheService = class _CacheService {
|
|
|
4623
4757
|
_handleBackplaneMessage(message) {
|
|
4624
4758
|
try {
|
|
4625
4759
|
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") {
|
|
4760
|
+
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
4761
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4628
4762
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4629
4763
|
});
|
|
@@ -4777,6 +4911,72 @@ var CacheService = class _CacheService {
|
|
|
4777
4911
|
}
|
|
4778
4912
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
4779
4913
|
}
|
|
4914
|
+
async _isGenerationalEntryStale(tagVersions) {
|
|
4915
|
+
if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
|
|
4916
|
+
const tags = Object.keys(tagVersions);
|
|
4917
|
+
if (tags.length === 0) return false;
|
|
4918
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
4919
|
+
for (let i = 0; i < tags.length; i++) {
|
|
4920
|
+
if (currentVers[i] > tagVersions[tags[i]]) return true;
|
|
4921
|
+
}
|
|
4922
|
+
return false;
|
|
4923
|
+
}
|
|
4924
|
+
async _deleteRedisKeys(client, keys) {
|
|
4925
|
+
if (keys.length === 0) return;
|
|
4926
|
+
const CHUNK_SIZE = 1e3;
|
|
4927
|
+
if (client instanceof RedisCluster) {
|
|
4928
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
4929
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
4930
|
+
const pl = client.pipeline();
|
|
4931
|
+
for (const k of chunk) pl.del(k);
|
|
4932
|
+
await pl.exec();
|
|
4933
|
+
}
|
|
4934
|
+
return;
|
|
4935
|
+
}
|
|
4936
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
4937
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
4938
|
+
await client.del(...chunk);
|
|
4939
|
+
}
|
|
4940
|
+
}
|
|
4941
|
+
async _parseGenerationalRedisHash(k, hashData) {
|
|
4942
|
+
if (!hashData || !hashData.d) return null;
|
|
4943
|
+
let storedTagVersions = {};
|
|
4944
|
+
if (hashData.tv) {
|
|
4945
|
+
try {
|
|
4946
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
4947
|
+
} catch {
|
|
4948
|
+
}
|
|
4949
|
+
}
|
|
4950
|
+
if (await this._isGenerationalEntryStale(storedTagVersions)) {
|
|
4951
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
4952
|
+
this._deleteIfStale(k, setAtMs);
|
|
4953
|
+
return { stale: true };
|
|
4954
|
+
}
|
|
4955
|
+
const value = await this._decryptAndDeserialize(hashData.d);
|
|
4956
|
+
return { value, tagVersions: storedTagVersions, stale: false };
|
|
4957
|
+
}
|
|
4958
|
+
async _readRedisEntry(client, k, allowAutoPipeline = false) {
|
|
4959
|
+
if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
|
|
4960
|
+
try {
|
|
4961
|
+
const hashData = await client.hgetall(k);
|
|
4962
|
+
if (typeof hashData === "string") {
|
|
4963
|
+
const value2 = await this._decryptAndDeserialize(hashData);
|
|
4964
|
+
return { value: value2, stale: false };
|
|
4965
|
+
}
|
|
4966
|
+
if (hashData && hashData.d) {
|
|
4967
|
+
return await this._parseGenerationalRedisHash(k, hashData);
|
|
4968
|
+
}
|
|
4969
|
+
return null;
|
|
4970
|
+
} catch (err) {
|
|
4971
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4972
|
+
if (!msg.includes("WRONGTYPE")) throw err;
|
|
4973
|
+
}
|
|
4974
|
+
}
|
|
4975
|
+
const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
4976
|
+
if (raw == null) return null;
|
|
4977
|
+
const value = await this._decryptAndDeserialize(raw);
|
|
4978
|
+
return { value, stale: false };
|
|
4979
|
+
}
|
|
4780
4980
|
async _getTagVersion(tag) {
|
|
4781
4981
|
const now = performance.now();
|
|
4782
4982
|
const local = this.tagVersions.get(tag);
|
|
@@ -4810,12 +5010,12 @@ var CacheService = class _CacheService {
|
|
|
4810
5010
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
4811
5011
|
*/
|
|
4812
5012
|
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) {
|
|
5013
|
+
const isCompressed = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
5014
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4815
5015
|
return this._workerPool.encrypt(serialized);
|
|
4816
5016
|
}
|
|
4817
5017
|
if (isCompressed) {
|
|
4818
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
5018
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
4819
5019
|
if (this.enc.isEnabled) {
|
|
4820
5020
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
4821
5021
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -4830,16 +5030,16 @@ var CacheService = class _CacheService {
|
|
|
4830
5030
|
*/
|
|
4831
5031
|
async _decryptAndDeserialize(raw) {
|
|
4832
5032
|
let plain;
|
|
4833
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
5033
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
4834
5034
|
plain = await this._workerPool.decrypt(raw);
|
|
4835
5035
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
4836
5036
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
4837
5037
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
4838
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5038
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4839
5039
|
plain = decompressed.toString("utf8");
|
|
4840
5040
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
4841
5041
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
4842
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5042
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4843
5043
|
plain = decompressed.toString("utf8");
|
|
4844
5044
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
4845
5045
|
plain = this.enc.decrypt(raw);
|
|
@@ -4914,8 +5114,8 @@ var CacheService = class _CacheService {
|
|
|
4914
5114
|
return client;
|
|
4915
5115
|
}
|
|
4916
5116
|
this.redisConnecting = (async () => {
|
|
5117
|
+
let client = null;
|
|
4917
5118
|
try {
|
|
4918
|
-
let client;
|
|
4919
5119
|
if (this.opts.redisClusterNodes?.length) {
|
|
4920
5120
|
client = new RedisCluster(this.opts.redisClusterNodes, {
|
|
4921
5121
|
redisOptions: {
|
|
@@ -4978,14 +5178,45 @@ var CacheService = class _CacheService {
|
|
|
4978
5178
|
});
|
|
4979
5179
|
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
4980
5180
|
}
|
|
5181
|
+
const pendingClient = client;
|
|
4981
5182
|
await new Promise((resolve, reject) => {
|
|
4982
|
-
|
|
4983
|
-
|
|
5183
|
+
let settled = false;
|
|
5184
|
+
const cleanupListeners = () => {
|
|
5185
|
+
pendingClient.removeListener?.("ready", onReady);
|
|
5186
|
+
pendingClient.removeListener?.("error", onError);
|
|
5187
|
+
};
|
|
5188
|
+
const onReady = () => {
|
|
5189
|
+
if (settled) return;
|
|
5190
|
+
settled = true;
|
|
5191
|
+
clearTimeout(timer);
|
|
5192
|
+
cleanupListeners();
|
|
5193
|
+
resolve();
|
|
5194
|
+
};
|
|
5195
|
+
const onError = (e) => {
|
|
5196
|
+
if (settled) return;
|
|
5197
|
+
settled = true;
|
|
5198
|
+
clearTimeout(timer);
|
|
5199
|
+
cleanupListeners();
|
|
4984
5200
|
this._checkAndLogResp3Hint(e);
|
|
4985
5201
|
reject(e);
|
|
4986
|
-
}
|
|
4987
|
-
setTimeout(() =>
|
|
5202
|
+
};
|
|
5203
|
+
const timer = setTimeout(() => {
|
|
5204
|
+
if (settled) return;
|
|
5205
|
+
settled = true;
|
|
5206
|
+
cleanupListeners();
|
|
5207
|
+
reject(new Error("Redis connection timeout"));
|
|
5208
|
+
}, 15e3);
|
|
5209
|
+
if (timer.unref) timer.unref();
|
|
5210
|
+
pendingClient.once("ready", onReady);
|
|
5211
|
+
pendingClient.once("error", onError);
|
|
4988
5212
|
});
|
|
5213
|
+
if (this._destroyed) {
|
|
5214
|
+
try {
|
|
5215
|
+
client.disconnect();
|
|
5216
|
+
} catch {
|
|
5217
|
+
}
|
|
5218
|
+
this._assertActive("getRedis");
|
|
5219
|
+
}
|
|
4989
5220
|
this.cb.onSuccess();
|
|
4990
5221
|
this.redis = client;
|
|
4991
5222
|
this.pipeliner = new AutoPipeliner(client, {
|
|
@@ -4995,6 +5226,10 @@ var CacheService = class _CacheService {
|
|
|
4995
5226
|
this.redisConnecting = null;
|
|
4996
5227
|
return client;
|
|
4997
5228
|
} catch (err) {
|
|
5229
|
+
try {
|
|
5230
|
+
client?.disconnect();
|
|
5231
|
+
} catch {
|
|
5232
|
+
}
|
|
4998
5233
|
this.cb.onFailure();
|
|
4999
5234
|
this.redisConnecting = null;
|
|
5000
5235
|
this._checkAndLogResp3Hint(err);
|
|
@@ -5235,20 +5470,10 @@ var CacheService = class _CacheService {
|
|
|
5235
5470
|
const optRefreshAhead = opts.refreshAhead;
|
|
5236
5471
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5237
5472
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5238
|
-
const optTags = opts.tags;
|
|
5473
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5239
5474
|
const l1Hit = this.l1.get(k);
|
|
5240
5475
|
if (l1Hit !== null) {
|
|
5241
|
-
|
|
5242
|
-
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
5243
|
-
const tags = Object.keys(l1Hit.tagVersions);
|
|
5244
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5245
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5246
|
-
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
5247
|
-
isGenerationalStale = true;
|
|
5248
|
-
break;
|
|
5249
|
-
}
|
|
5250
|
-
}
|
|
5251
|
-
}
|
|
5476
|
+
const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
|
|
5252
5477
|
if (isGenerationalStale) {
|
|
5253
5478
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
5254
5479
|
} else {
|
|
@@ -5334,17 +5559,7 @@ var CacheService = class _CacheService {
|
|
|
5334
5559
|
this.watchdog.recordDisk(diskElapsed);
|
|
5335
5560
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5336
5561
|
if (diskHit !== null) {
|
|
5337
|
-
|
|
5338
|
-
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5339
|
-
const tags = Object.keys(diskHit.tagVersions);
|
|
5340
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5341
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5342
|
-
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5343
|
-
isDiskStale = true;
|
|
5344
|
-
break;
|
|
5345
|
-
}
|
|
5346
|
-
}
|
|
5347
|
-
}
|
|
5562
|
+
const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
|
|
5348
5563
|
if (isDiskStale) {
|
|
5349
5564
|
this.disk.delete(k);
|
|
5350
5565
|
} else {
|
|
@@ -5372,57 +5587,27 @@ var CacheService = class _CacheService {
|
|
|
5372
5587
|
try {
|
|
5373
5588
|
const client = await this.getRedis();
|
|
5374
5589
|
const redisStart = performance.now();
|
|
5375
|
-
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
|
|
5381
|
-
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
}
|
|
5389
|
-
const tags = Object.keys(storedTagVersions);
|
|
5390
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5391
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5392
|
-
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5393
|
-
isStale = true;
|
|
5394
|
-
break;
|
|
5395
|
-
}
|
|
5396
|
-
}
|
|
5397
|
-
if (isStale) {
|
|
5398
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5399
|
-
this._deleteIfStale(k, setAtMs);
|
|
5400
|
-
} else {
|
|
5401
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5402
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5403
|
-
this.counters.l2Hits++;
|
|
5404
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
5405
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5406
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5407
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
5408
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5409
|
-
}
|
|
5410
|
-
}
|
|
5411
|
-
} else {
|
|
5412
|
-
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5413
|
-
const redisElapsed = performance.now() - redisStart;
|
|
5414
|
-
this.watchdog.recordRedis(redisElapsed);
|
|
5415
|
-
this.cb.onSuccess();
|
|
5416
|
-
if (raw) {
|
|
5417
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
5418
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
5419
|
-
this.counters.l2Hits++;
|
|
5420
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
5421
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5422
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5423
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
5424
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5590
|
+
const redisHit = await this._readRedisEntry(client, k, true);
|
|
5591
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5592
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5593
|
+
this.cb.onSuccess();
|
|
5594
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
5595
|
+
const parsed = redisHit.value;
|
|
5596
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5597
|
+
this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
|
|
5598
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5599
|
+
const current = this.l1.get(k);
|
|
5600
|
+
const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
|
|
5601
|
+
if (this.opts.frozen) deepFreeze(liveVal);
|
|
5602
|
+
return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
|
|
5425
5603
|
}
|
|
5604
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
|
|
5605
|
+
this.counters.l2Hits++;
|
|
5606
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5607
|
+
this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
|
|
5608
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5609
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5610
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5426
5611
|
}
|
|
5427
5612
|
} catch (err) {
|
|
5428
5613
|
this.cb.onFailure();
|
|
@@ -5484,20 +5669,20 @@ var CacheService = class _CacheService {
|
|
|
5484
5669
|
if (this.opts.frozen) deepFreeze(data);
|
|
5485
5670
|
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5486
5671
|
}
|
|
5487
|
-
|
|
5672
|
+
const writeTs = Date.now();
|
|
5673
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
5488
5674
|
if (!this._redisDisabled) {
|
|
5489
5675
|
try {
|
|
5490
5676
|
const client = await this.getRedis();
|
|
5491
5677
|
const serialized = JSON.stringify(data);
|
|
5492
5678
|
const toStore = await this._serializeAndEncrypt(serialized);
|
|
5493
5679
|
const ttlSec = Math.ceil(effectiveTtl / 1e3);
|
|
5494
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5495
|
-
const now = Date.now();
|
|
5680
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5496
5681
|
const tx = client.multi();
|
|
5497
5682
|
tx.hset(k, {
|
|
5498
5683
|
d: toStore,
|
|
5499
|
-
t: String(
|
|
5500
|
-
tv: JSON.stringify(activeTagVersions)
|
|
5684
|
+
t: String(writeTs),
|
|
5685
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5501
5686
|
});
|
|
5502
5687
|
tx.expire(k, ttlSec);
|
|
5503
5688
|
await tx.exec();
|
|
@@ -5635,20 +5820,20 @@ var CacheService = class _CacheService {
|
|
|
5635
5820
|
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5636
5821
|
return;
|
|
5637
5822
|
}
|
|
5638
|
-
|
|
5823
|
+
const writeTs = Date.now();
|
|
5824
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
5639
5825
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5640
5826
|
try {
|
|
5641
5827
|
const client = await this.getRedis();
|
|
5642
5828
|
const s = JSON.stringify(data);
|
|
5643
5829
|
const stored = await this._serializeAndEncrypt(s);
|
|
5644
5830
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5645
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5646
|
-
const now = Date.now();
|
|
5831
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5647
5832
|
const tx = client.multi();
|
|
5648
5833
|
tx.hset(cacheKey, {
|
|
5649
5834
|
d: stored,
|
|
5650
|
-
t: String(
|
|
5651
|
-
tv: JSON.stringify(activeTagVersions)
|
|
5835
|
+
t: String(writeTs),
|
|
5836
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5652
5837
|
});
|
|
5653
5838
|
tx.expire(cacheKey, ttlSec);
|
|
5654
5839
|
await tx.exec();
|
|
@@ -5693,27 +5878,35 @@ var CacheService = class _CacheService {
|
|
|
5693
5878
|
this._pendingDiskDeletes.delete(k);
|
|
5694
5879
|
this.counters.sets++;
|
|
5695
5880
|
let activeTagVersions;
|
|
5696
|
-
|
|
5881
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5882
|
+
if (tagsToRegister?.length) {
|
|
5697
5883
|
if (this.opts.tagStrategy === "generational") {
|
|
5698
|
-
const vers = await Promise.all(
|
|
5884
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5699
5885
|
activeTagVersions = {};
|
|
5700
|
-
for (let i = 0; i <
|
|
5701
|
-
activeTagVersions[
|
|
5886
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
5887
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5702
5888
|
}
|
|
5703
5889
|
} else {
|
|
5704
|
-
await this._registerTags(k,
|
|
5890
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5705
5891
|
}
|
|
5706
5892
|
}
|
|
5707
|
-
|
|
5708
|
-
|
|
5709
|
-
|
|
5710
|
-
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
|
|
5714
|
-
this.
|
|
5893
|
+
const writeTs = Date.now();
|
|
5894
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
|
|
5895
|
+
if (opts?.dependsOn !== void 0) {
|
|
5896
|
+
this._removeKeyDependencies(k);
|
|
5897
|
+
if (opts.dependsOn.length > 0) {
|
|
5898
|
+
const nsPatterns = [];
|
|
5899
|
+
for (const pattern of opts.dependsOn) {
|
|
5900
|
+
const nsPattern = this.nk(pattern);
|
|
5901
|
+
nsPatterns.push(nsPattern);
|
|
5902
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
5903
|
+
if (!deps) {
|
|
5904
|
+
deps = /* @__PURE__ */ new Set();
|
|
5905
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
5906
|
+
}
|
|
5907
|
+
deps.add(k);
|
|
5715
5908
|
}
|
|
5716
|
-
|
|
5909
|
+
this.keyDependencies.set(k, nsPatterns);
|
|
5717
5910
|
}
|
|
5718
5911
|
}
|
|
5719
5912
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -5722,13 +5915,12 @@ var CacheService = class _CacheService {
|
|
|
5722
5915
|
const s = JSON.stringify(data);
|
|
5723
5916
|
const stored = await this._serializeAndEncrypt(s);
|
|
5724
5917
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5725
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5726
|
-
const now = Date.now();
|
|
5918
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5727
5919
|
const tx = client.multi();
|
|
5728
5920
|
tx.hset(k, {
|
|
5729
5921
|
d: stored,
|
|
5730
|
-
t: String(
|
|
5731
|
-
tv: JSON.stringify(activeTagVersions)
|
|
5922
|
+
t: String(writeTs),
|
|
5923
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5732
5924
|
});
|
|
5733
5925
|
tx.expire(k, ttlSec);
|
|
5734
5926
|
await tx.exec();
|
|
@@ -5763,7 +5955,18 @@ var CacheService = class _CacheService {
|
|
|
5763
5955
|
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
5764
5956
|
*/
|
|
5765
5957
|
async _registerTags(k, tags, ttlSeconds) {
|
|
5766
|
-
|
|
5958
|
+
this._removeKeyTags(k);
|
|
5959
|
+
const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
|
|
5960
|
+
const expiresAt = Date.now() + effectiveTtl * 1e3;
|
|
5961
|
+
if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
|
|
5962
|
+
this._sweepExpiredMetadata();
|
|
5963
|
+
if (this.keyTags.size >= 1e5) {
|
|
5964
|
+
const oldestKey = this.keyTags.keys().next().value;
|
|
5965
|
+
if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
|
|
5966
|
+
}
|
|
5967
|
+
}
|
|
5968
|
+
const uniqueTags = Array.from(new Set(tags));
|
|
5969
|
+
for (const tag of uniqueTags) {
|
|
5767
5970
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5768
5971
|
let members = this.tagIndex.get(tagKey);
|
|
5769
5972
|
if (!members) {
|
|
@@ -5772,14 +5975,15 @@ var CacheService = class _CacheService {
|
|
|
5772
5975
|
}
|
|
5773
5976
|
members.add(k);
|
|
5774
5977
|
}
|
|
5978
|
+
this.keyTags.set(k, { tags: uniqueTags, expiresAt });
|
|
5775
5979
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5776
5980
|
try {
|
|
5777
5981
|
const client = await this.getRedis();
|
|
5778
5982
|
const pl = client.pipeline();
|
|
5779
|
-
for (const tag of
|
|
5983
|
+
for (const tag of uniqueTags) {
|
|
5780
5984
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5781
5985
|
pl.sadd(tagKey, k);
|
|
5782
|
-
pl.expire(tagKey,
|
|
5986
|
+
pl.expire(tagKey, effectiveTtl + 3600);
|
|
5783
5987
|
}
|
|
5784
5988
|
await pl.exec();
|
|
5785
5989
|
this.cb.onSuccess();
|
|
@@ -5818,6 +6022,13 @@ var CacheService = class _CacheService {
|
|
|
5818
6022
|
}
|
|
5819
6023
|
this._addPatternTombstone(pfx);
|
|
5820
6024
|
this.l1.deletePattern(k);
|
|
6025
|
+
this._removePrefixFromIndices(pfx);
|
|
6026
|
+
for (const ktKey of Array.from(this.keyTags.keys())) {
|
|
6027
|
+
if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
|
|
6028
|
+
}
|
|
6029
|
+
for (const kdKey of Array.from(this.keyDependencies.keys())) {
|
|
6030
|
+
if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
|
|
6031
|
+
}
|
|
5821
6032
|
} else {
|
|
5822
6033
|
this._bumpKeyMutation(k);
|
|
5823
6034
|
this.inflight.delete(k);
|
|
@@ -5830,15 +6041,16 @@ var CacheService = class _CacheService {
|
|
|
5830
6041
|
this._pendingDiskDeletes.delete(k);
|
|
5831
6042
|
}
|
|
5832
6043
|
});
|
|
6044
|
+
this._removeKeyTags(k);
|
|
5833
6045
|
this._cascadeDependencies(k);
|
|
5834
|
-
|
|
6046
|
+
this._removeKeyDependencies(k);
|
|
5835
6047
|
}
|
|
5836
6048
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5837
6049
|
try {
|
|
5838
6050
|
const client = await this.getRedis();
|
|
5839
6051
|
if (isPattern) {
|
|
5840
6052
|
const keys = await this._scanKeys(client, k);
|
|
5841
|
-
|
|
6053
|
+
await this._deleteRedisKeys(client, keys);
|
|
5842
6054
|
} else {
|
|
5843
6055
|
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5844
6056
|
await this.pipeliner.del(k);
|
|
@@ -5900,6 +6112,15 @@ var CacheService = class _CacheService {
|
|
|
5900
6112
|
entry.value++;
|
|
5901
6113
|
return entry.value;
|
|
5902
6114
|
}
|
|
6115
|
+
if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
|
|
6116
|
+
for (const [ck, cv] of this._l1Counters) {
|
|
6117
|
+
if (cv.expiresAt <= now) this._l1Counters.delete(ck);
|
|
6118
|
+
}
|
|
6119
|
+
if (this._l1Counters.size >= 5e4) {
|
|
6120
|
+
const oldest = this._l1Counters.keys().next().value;
|
|
6121
|
+
if (oldest !== void 0) this._l1Counters.delete(oldest);
|
|
6122
|
+
}
|
|
6123
|
+
}
|
|
5903
6124
|
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
5904
6125
|
return 1;
|
|
5905
6126
|
}
|
|
@@ -5946,6 +6167,7 @@ var CacheService = class _CacheService {
|
|
|
5946
6167
|
}
|
|
5947
6168
|
this._addPatternTombstone(pfx);
|
|
5948
6169
|
this.l1.deletePattern(k);
|
|
6170
|
+
this._removePrefixFromIndices(pfx);
|
|
5949
6171
|
} else {
|
|
5950
6172
|
this._globalEpoch++;
|
|
5951
6173
|
this.inflight.clear();
|
|
@@ -5954,7 +6176,10 @@ var CacheService = class _CacheService {
|
|
|
5954
6176
|
if (!this._diskDisabled) this.disk.clear();
|
|
5955
6177
|
this._l1Counters.clear();
|
|
5956
6178
|
this.tagIndex.clear();
|
|
6179
|
+
this.keyTags.clear();
|
|
5957
6180
|
this.tagVersions.clear();
|
|
6181
|
+
this.dependencyIndex.clear();
|
|
6182
|
+
this.keyDependencies.clear();
|
|
5958
6183
|
this._pendingDiskDeletes.clear();
|
|
5959
6184
|
this._keyMutationEpochs.clear();
|
|
5960
6185
|
}
|
|
@@ -5963,7 +6188,7 @@ var CacheService = class _CacheService {
|
|
|
5963
6188
|
const client = await this.getRedis();
|
|
5964
6189
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
5965
6190
|
const keys = await this._scanKeys(client, pattern);
|
|
5966
|
-
|
|
6191
|
+
await this._deleteRedisKeys(client, keys);
|
|
5967
6192
|
} catch (err) {
|
|
5968
6193
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5969
6194
|
}
|
|
@@ -6106,6 +6331,10 @@ var CacheService = class _CacheService {
|
|
|
6106
6331
|
this._assertActive("touch");
|
|
6107
6332
|
const k = this.nk(cacheKey);
|
|
6108
6333
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
6334
|
+
if (hit) {
|
|
6335
|
+
const kt = this.keyTags.get(k);
|
|
6336
|
+
if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
|
|
6337
|
+
}
|
|
6109
6338
|
if (hit && !this._redisDisabled) {
|
|
6110
6339
|
try {
|
|
6111
6340
|
const client = await this.getRedis();
|
|
@@ -6133,6 +6362,10 @@ var CacheService = class _CacheService {
|
|
|
6133
6362
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
6134
6363
|
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6135
6364
|
}
|
|
6365
|
+
_prepareReadValue(val) {
|
|
6366
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6367
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6368
|
+
}
|
|
6136
6369
|
/**
|
|
6137
6370
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
6138
6371
|
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
@@ -6146,11 +6379,13 @@ var CacheService = class _CacheService {
|
|
|
6146
6379
|
const k = this.nk(cacheKey);
|
|
6147
6380
|
const l1Hit = this.l1.get(k);
|
|
6148
6381
|
if (l1Hit !== null) {
|
|
6149
|
-
this.
|
|
6150
|
-
|
|
6151
|
-
|
|
6152
|
-
|
|
6153
|
-
|
|
6382
|
+
if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
|
|
6383
|
+
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
6384
|
+
} else {
|
|
6385
|
+
this.counters.gets++;
|
|
6386
|
+
this.counters.l1Hits++;
|
|
6387
|
+
return this._prepareReadValue(l1Hit.value);
|
|
6388
|
+
}
|
|
6154
6389
|
}
|
|
6155
6390
|
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6156
6391
|
if (this._isTombstonedByPattern(k)) {
|
|
@@ -6165,18 +6400,20 @@ var CacheService = class _CacheService {
|
|
|
6165
6400
|
this.watchdog.recordDisk(diskElapsed);
|
|
6166
6401
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6167
6402
|
if (diskHit !== null) {
|
|
6168
|
-
|
|
6169
|
-
|
|
6170
|
-
|
|
6171
|
-
|
|
6172
|
-
|
|
6173
|
-
|
|
6174
|
-
|
|
6175
|
-
|
|
6176
|
-
this.
|
|
6177
|
-
|
|
6178
|
-
|
|
6179
|
-
|
|
6403
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6404
|
+
this.disk.delete(k);
|
|
6405
|
+
} else {
|
|
6406
|
+
const promoted = this.l1.importEntries(
|
|
6407
|
+
[{ key: k, entry: diskHit }],
|
|
6408
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6409
|
+
);
|
|
6410
|
+
if (promoted > 0) {
|
|
6411
|
+
const l1Check = this.l1.get(k);
|
|
6412
|
+
if (l1Check !== null) {
|
|
6413
|
+
this.counters.gets++;
|
|
6414
|
+
this.counters.diskHits++;
|
|
6415
|
+
return this._prepareReadValue(l1Check.value);
|
|
6416
|
+
}
|
|
6180
6417
|
}
|
|
6181
6418
|
}
|
|
6182
6419
|
}
|
|
@@ -6186,17 +6423,16 @@ var CacheService = class _CacheService {
|
|
|
6186
6423
|
try {
|
|
6187
6424
|
const client = await this.getRedis();
|
|
6188
6425
|
const redisStart = performance.now();
|
|
6189
|
-
const
|
|
6426
|
+
const redisHit = await this._readRedisEntry(client, k);
|
|
6190
6427
|
const redisElapsed = performance.now() - redisStart;
|
|
6191
6428
|
this.watchdog.recordRedis(redisElapsed);
|
|
6192
|
-
|
|
6193
|
-
|
|
6194
|
-
|
|
6429
|
+
this.cb.onSuccess();
|
|
6430
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
6431
|
+
const parsed = redisHit.value;
|
|
6432
|
+
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
|
|
6195
6433
|
this.counters.gets++;
|
|
6196
6434
|
this.counters.l2Hits++;
|
|
6197
|
-
this.
|
|
6198
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
6199
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6435
|
+
return this._prepareReadValue(parsed);
|
|
6200
6436
|
}
|
|
6201
6437
|
} catch (err) {
|
|
6202
6438
|
this.cb.onFailure();
|
|
@@ -6224,12 +6460,20 @@ var CacheService = class _CacheService {
|
|
|
6224
6460
|
const result = Array.from({ length: keys.length });
|
|
6225
6461
|
const missIndexes = [];
|
|
6226
6462
|
const missKeys = [];
|
|
6463
|
+
const now = Date.now();
|
|
6227
6464
|
for (let i = 0; i < keys.length; i++) {
|
|
6228
6465
|
const k = this.nk(keys[i]);
|
|
6229
6466
|
const entry = this.l1.getEntry(k);
|
|
6230
|
-
if (entry && entry.expiresAt >
|
|
6231
|
-
|
|
6232
|
-
|
|
6467
|
+
if (entry && entry.expiresAt > now) {
|
|
6468
|
+
if (await this._isGenerationalEntryStale(entry.tagVersions)) {
|
|
6469
|
+
this._deleteIfStale(k, entry.setAt ?? 0);
|
|
6470
|
+
missIndexes.push(i);
|
|
6471
|
+
missKeys.push(keys[i]);
|
|
6472
|
+
} else {
|
|
6473
|
+
const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6474
|
+
result[i] = this._prepareReadValue(val);
|
|
6475
|
+
this.counters.l1Hits++;
|
|
6476
|
+
}
|
|
6233
6477
|
} else {
|
|
6234
6478
|
missIndexes.push(i);
|
|
6235
6479
|
missKeys.push(keys[i]);
|
|
@@ -6250,23 +6494,57 @@ var CacheService = class _CacheService {
|
|
|
6250
6494
|
const client = await this.getRedis();
|
|
6251
6495
|
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6252
6496
|
const pipeline = client.multi();
|
|
6253
|
-
|
|
6497
|
+
const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
6498
|
+
for (const nk of nsKeys) {
|
|
6499
|
+
if (useHashPipeline) {
|
|
6500
|
+
pipeline.hgetall(nk);
|
|
6501
|
+
} else {
|
|
6502
|
+
pipeline.get(nk);
|
|
6503
|
+
}
|
|
6504
|
+
}
|
|
6254
6505
|
const redisStart = performance.now();
|
|
6255
6506
|
const raws = await pipeline.exec();
|
|
6256
6507
|
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6257
6508
|
this.watchdog.recordRedis(redisElapsed);
|
|
6258
6509
|
this.cb.onSuccess();
|
|
6259
6510
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6260
|
-
const
|
|
6511
|
+
const tuple = raws[j];
|
|
6512
|
+
const err = tuple ? tuple[0] : null;
|
|
6513
|
+
const rawVal = tuple ? tuple[1] : null;
|
|
6261
6514
|
const idx = missIndexes[j];
|
|
6262
|
-
|
|
6263
|
-
|
|
6264
|
-
|
|
6515
|
+
const k = nsKeys[j];
|
|
6516
|
+
let parsed;
|
|
6517
|
+
let tagVersions;
|
|
6518
|
+
let hit = false;
|
|
6519
|
+
if (useHashPipeline) {
|
|
6520
|
+
if (err && err.message?.includes("WRONGTYPE")) {
|
|
6521
|
+
const fallbackRaw = await client.get(k);
|
|
6522
|
+
if (fallbackRaw) {
|
|
6523
|
+
parsed = await this._decryptAndDeserialize(fallbackRaw);
|
|
6524
|
+
hit = true;
|
|
6525
|
+
}
|
|
6526
|
+
} else if (!err && typeof rawVal === "string") {
|
|
6527
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6528
|
+
hit = true;
|
|
6529
|
+
} else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
|
|
6530
|
+
const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
|
|
6531
|
+
if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
|
|
6532
|
+
parsed = hashHit.value;
|
|
6533
|
+
tagVersions = hashHit.tagVersions;
|
|
6534
|
+
hit = true;
|
|
6535
|
+
}
|
|
6536
|
+
}
|
|
6537
|
+
} else if (!err && rawVal) {
|
|
6538
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6539
|
+
hit = true;
|
|
6540
|
+
}
|
|
6541
|
+
if (hit && parsed !== void 0) {
|
|
6265
6542
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
6266
|
-
|
|
6543
|
+
const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6544
|
+
this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
|
|
6267
6545
|
this.counters.l2Hits++;
|
|
6268
6546
|
l2HitCount++;
|
|
6269
|
-
result[idx] = parsed;
|
|
6547
|
+
result[idx] = this._prepareReadValue(parsed);
|
|
6270
6548
|
missIndexes[j] = -1;
|
|
6271
6549
|
missKeys[j] = "";
|
|
6272
6550
|
}
|
|
@@ -6300,6 +6578,10 @@ var CacheService = class _CacheService {
|
|
|
6300
6578
|
this.watchdog.recordDisk(diskElapsed);
|
|
6301
6579
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6302
6580
|
if (diskHit !== null) {
|
|
6581
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6582
|
+
this.disk.delete(k);
|
|
6583
|
+
continue;
|
|
6584
|
+
}
|
|
6303
6585
|
const promoted = this.l1.importEntries(
|
|
6304
6586
|
[{ key: k, entry: diskHit }],
|
|
6305
6587
|
this.opts.forbiddenSnapshotPrefixes
|
|
@@ -6308,7 +6590,7 @@ var CacheService = class _CacheService {
|
|
|
6308
6590
|
const l1Check = this.l1.get(k);
|
|
6309
6591
|
if (l1Check !== null) {
|
|
6310
6592
|
this.counters.diskHits++;
|
|
6311
|
-
result[missIndexes[j]] = l1Check.value;
|
|
6593
|
+
result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
|
|
6312
6594
|
missIndexes.splice(j, 1);
|
|
6313
6595
|
missKeys.splice(j, 1);
|
|
6314
6596
|
}
|
|
@@ -6316,16 +6598,23 @@ var CacheService = class _CacheService {
|
|
|
6316
6598
|
}
|
|
6317
6599
|
}
|
|
6318
6600
|
}
|
|
6319
|
-
if (missKeys.length > 0) {
|
|
6601
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6320
6602
|
this.counters.fetches++;
|
|
6321
6603
|
const fetched = await fetchFn(missKeys);
|
|
6604
|
+
const isMap = fetched instanceof Map;
|
|
6322
6605
|
const setPromises = [];
|
|
6323
6606
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6324
|
-
const
|
|
6607
|
+
const k = missKeys[j];
|
|
6608
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6325
6609
|
result[missIndexes[j]] = v;
|
|
6326
|
-
if (v !== void 0) {
|
|
6327
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6328
|
-
setPromises.push(this.set(
|
|
6610
|
+
if (v !== void 0 && v !== null) {
|
|
6611
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6612
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
6613
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
6614
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
6615
|
+
} else if (v === null) {
|
|
6616
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6617
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6329
6618
|
}
|
|
6330
6619
|
}
|
|
6331
6620
|
if (setPromises.length > 0) {
|
|
@@ -6468,98 +6757,135 @@ var CacheService = class _CacheService {
|
|
|
6468
6757
|
}
|
|
6469
6758
|
}
|
|
6470
6759
|
/**
|
|
6471
|
-
*
|
|
6472
|
-
*
|
|
6473
|
-
*
|
|
6474
|
-
* @example
|
|
6475
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6476
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
6760
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
6761
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
6762
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
6477
6763
|
*/
|
|
6478
|
-
async
|
|
6479
|
-
|
|
6480
|
-
const
|
|
6481
|
-
|
|
6482
|
-
|
|
6483
|
-
|
|
6764
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
6765
|
+
const isPattern = isWildcardTag(tag);
|
|
6766
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6767
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6768
|
+
const tagMatches = (t) => {
|
|
6769
|
+
if (t === tag) return true;
|
|
6770
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
6771
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
6772
|
+
return false;
|
|
6773
|
+
};
|
|
6774
|
+
if (shouldCascade && !isPattern) {
|
|
6775
|
+
matched.add(tag);
|
|
6484
6776
|
}
|
|
6485
|
-
|
|
6486
|
-
|
|
6487
|
-
|
|
6488
|
-
|
|
6489
|
-
|
|
6490
|
-
|
|
6491
|
-
|
|
6492
|
-
|
|
6493
|
-
|
|
6494
|
-
|
|
6495
|
-
|
|
6496
|
-
|
|
6497
|
-
} else {
|
|
6498
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6499
|
-
newVer = current + 1;
|
|
6500
|
-
}
|
|
6501
|
-
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6502
|
-
if (this.opts.awaitInvalidationBackplane) {
|
|
6503
|
-
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6504
|
-
} else {
|
|
6505
|
-
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6777
|
+
const tagPrefix = this.nk("_tag_:");
|
|
6778
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
6779
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
6780
|
+
if (tagMatches(t)) matched.add(t);
|
|
6781
|
+
}
|
|
6782
|
+
for (const t of this.tagVersions.keys()) {
|
|
6783
|
+
if (tagMatches(t)) matched.add(t);
|
|
6784
|
+
}
|
|
6785
|
+
this.l1.scan((_k, entry) => {
|
|
6786
|
+
if (entry.tagVersions) {
|
|
6787
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
6788
|
+
if (tagMatches(t)) matched.add(t);
|
|
6506
6789
|
}
|
|
6507
|
-
return;
|
|
6508
6790
|
}
|
|
6509
|
-
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
this.
|
|
6513
|
-
this.
|
|
6514
|
-
|
|
6515
|
-
|
|
6516
|
-
|
|
6517
|
-
|
|
6518
|
-
|
|
6519
|
-
|
|
6791
|
+
}, 0);
|
|
6792
|
+
if (!this._redisDisabled) {
|
|
6793
|
+
try {
|
|
6794
|
+
const client = await this.getRedis();
|
|
6795
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6796
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
6797
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6798
|
+
const pfx = this.nk("tag_ver:");
|
|
6799
|
+
for (const sk of scannedKeys) {
|
|
6800
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6801
|
+
if (tagMatches(t)) matched.add(t);
|
|
6520
6802
|
}
|
|
6521
|
-
}
|
|
6803
|
+
} else {
|
|
6804
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
6805
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6806
|
+
const pfx = this.nk("_tag_:");
|
|
6807
|
+
for (const sk of scannedKeys) {
|
|
6808
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6809
|
+
if (tagMatches(t)) matched.add(t);
|
|
6810
|
+
}
|
|
6811
|
+
}
|
|
6812
|
+
} catch (err) {
|
|
6813
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
6522
6814
|
}
|
|
6523
|
-
|
|
6815
|
+
}
|
|
6816
|
+
return matched;
|
|
6817
|
+
}
|
|
6818
|
+
async _publishTagInvalidation(op, key, tagVersion) {
|
|
6819
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6820
|
+
await this.publishInvalidation(op, key, tagVersion, false, true);
|
|
6821
|
+
} else {
|
|
6822
|
+
void this.publishInvalidation(op, key, tagVersion, false, true);
|
|
6823
|
+
}
|
|
6824
|
+
}
|
|
6825
|
+
_removeTagMembersLocal(keys) {
|
|
6826
|
+
const keyList = Array.isArray(keys) ? keys : Array.from(keys);
|
|
6827
|
+
for (const k of keyList) {
|
|
6828
|
+
this.l1.delete(k);
|
|
6829
|
+
this._bumpKeyMutation(k);
|
|
6830
|
+
this._removeKeyTags(k);
|
|
6831
|
+
this._removeKeyDependencies(k);
|
|
6832
|
+
this._pendingDiskDeletes.add(k);
|
|
6833
|
+
setImmediate(() => {
|
|
6834
|
+
try {
|
|
6835
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6836
|
+
} finally {
|
|
6837
|
+
this._pendingDiskDeletes.delete(k);
|
|
6838
|
+
}
|
|
6839
|
+
});
|
|
6840
|
+
}
|
|
6841
|
+
}
|
|
6842
|
+
/**
|
|
6843
|
+
* Executes invalidation for a single already-resolved concrete tag without
|
|
6844
|
+
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
6845
|
+
*/
|
|
6846
|
+
async _invalidateConcreteTag(tag) {
|
|
6847
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6848
|
+
let newVer = 1;
|
|
6524
6849
|
if (!this._redisDisabled) {
|
|
6525
6850
|
try {
|
|
6526
6851
|
const client = await this.getRedis();
|
|
6527
|
-
|
|
6528
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6529
|
-
if (toDelete.length > 0) {
|
|
6530
|
-
await client.del(...toDelete, tagKey);
|
|
6531
|
-
} else {
|
|
6532
|
-
await client.del(tagKey);
|
|
6533
|
-
}
|
|
6852
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6534
6853
|
} catch (err) {
|
|
6535
6854
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6855
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6856
|
+
newVer = current + 1;
|
|
6536
6857
|
}
|
|
6858
|
+
} else {
|
|
6859
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6860
|
+
newVer = current + 1;
|
|
6861
|
+
}
|
|
6862
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6863
|
+
await this._publishTagInvalidation("tag_incr", tag, newVer);
|
|
6864
|
+
return;
|
|
6865
|
+
}
|
|
6866
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6867
|
+
const members = Array.from(this.tagIndex.get(tagKey) ?? []);
|
|
6868
|
+
this.tagIndex.delete(tagKey);
|
|
6869
|
+
this._removeTagMembersLocal(members);
|
|
6870
|
+
if (!this._redisDisabled) {
|
|
6871
|
+
try {
|
|
6872
|
+
const client = await this.getRedis();
|
|
6873
|
+
const redisMembers = await client.smembers(tagKey);
|
|
6874
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
|
|
6875
|
+
await this._deleteRedisKeys(client, toDelete);
|
|
6876
|
+
} catch (err) {
|
|
6877
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6537
6878
|
}
|
|
6538
|
-
} catch (err) {
|
|
6539
|
-
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6540
|
-
span.recordException?.(err);
|
|
6541
|
-
throw err;
|
|
6542
|
-
} finally {
|
|
6543
|
-
span.end();
|
|
6544
6879
|
}
|
|
6545
6880
|
}
|
|
6546
6881
|
/**
|
|
6547
|
-
*
|
|
6548
|
-
*
|
|
6549
|
-
* reducing latency when invalidating several related tags together.
|
|
6550
|
-
*
|
|
6551
|
-
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
6552
|
-
* synchronously before the Redis round-trip.
|
|
6553
|
-
*
|
|
6554
|
-
* @example
|
|
6555
|
-
* // Instead of three serial round-trips:
|
|
6556
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
6882
|
+
* Executes invalidation for an array of already-resolved concrete tags
|
|
6883
|
+
* without re-entering wildcard/cascade resolution or invalidateTag().
|
|
6557
6884
|
*/
|
|
6558
|
-
async
|
|
6559
|
-
this._assertActive("invalidateTags");
|
|
6885
|
+
async _invalidateConcreteTags(tags) {
|
|
6560
6886
|
if (tags.length === 0) return;
|
|
6561
6887
|
if (tags.length === 1) {
|
|
6562
|
-
await this.
|
|
6888
|
+
await this._invalidateConcreteTag(tags[0]);
|
|
6563
6889
|
return;
|
|
6564
6890
|
}
|
|
6565
6891
|
if (this.opts.tagStrategy === "generational") {
|
|
@@ -6574,11 +6900,7 @@ var CacheService = class _CacheService {
|
|
|
6574
6900
|
const [err, newVer] = results[i] ?? [null, null];
|
|
6575
6901
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
6576
6902
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
6577
|
-
|
|
6578
|
-
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6579
|
-
} else {
|
|
6580
|
-
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6581
|
-
}
|
|
6903
|
+
await this._publishTagInvalidation("tag_incr", tags[i], ver);
|
|
6582
6904
|
}
|
|
6583
6905
|
return;
|
|
6584
6906
|
} catch (err) {
|
|
@@ -6588,11 +6910,7 @@ var CacheService = class _CacheService {
|
|
|
6588
6910
|
for (const tag of tags) {
|
|
6589
6911
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
6590
6912
|
this._setLocalTagVersion(tag, ver, now);
|
|
6591
|
-
|
|
6592
|
-
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6593
|
-
} else {
|
|
6594
|
-
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6595
|
-
}
|
|
6913
|
+
await this._publishTagInvalidation("tag_incr", tag, ver);
|
|
6596
6914
|
}
|
|
6597
6915
|
return;
|
|
6598
6916
|
}
|
|
@@ -6605,18 +6923,7 @@ var CacheService = class _CacheService {
|
|
|
6605
6923
|
for (const k of members) allMembers.add(k);
|
|
6606
6924
|
this.tagIndex.delete(tagKey);
|
|
6607
6925
|
}
|
|
6608
|
-
|
|
6609
|
-
this.l1.delete(k);
|
|
6610
|
-
this._bumpKeyMutation(k);
|
|
6611
|
-
this._pendingDiskDeletes.add(k);
|
|
6612
|
-
setImmediate(() => {
|
|
6613
|
-
try {
|
|
6614
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
6615
|
-
} finally {
|
|
6616
|
-
this._pendingDiskDeletes.delete(k);
|
|
6617
|
-
}
|
|
6618
|
-
});
|
|
6619
|
-
}
|
|
6926
|
+
this._removeTagMembersLocal(allMembers);
|
|
6620
6927
|
if (!this._redisDisabled) {
|
|
6621
6928
|
try {
|
|
6622
6929
|
const client = await this.getRedis();
|
|
@@ -6632,12 +6939,103 @@ var CacheService = class _CacheService {
|
|
|
6632
6939
|
}
|
|
6633
6940
|
}
|
|
6634
6941
|
const keysToRemove = [...toDelete, ...tagKeys];
|
|
6635
|
-
|
|
6942
|
+
await this._deleteRedisKeys(client, keysToRemove);
|
|
6636
6943
|
} catch (err) {
|
|
6637
6944
|
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
6638
6945
|
}
|
|
6639
6946
|
}
|
|
6640
6947
|
}
|
|
6948
|
+
/**
|
|
6949
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
6950
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
6951
|
+
*
|
|
6952
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
6953
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
6954
|
+
*
|
|
6955
|
+
* @example
|
|
6956
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6957
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
6958
|
+
*
|
|
6959
|
+
* @example
|
|
6960
|
+
* // Wildcard pattern invalidation
|
|
6961
|
+
* await cache.invalidateTag('org:123:*');
|
|
6962
|
+
*
|
|
6963
|
+
* @example
|
|
6964
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
6965
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
6966
|
+
*/
|
|
6967
|
+
async invalidateTag(tag, opts) {
|
|
6968
|
+
this._assertActive("invalidateTag");
|
|
6969
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
6970
|
+
if (this.opts.tracer) {
|
|
6971
|
+
span.setAttribute("cache.tag", tag);
|
|
6972
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6973
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
6974
|
+
}
|
|
6975
|
+
try {
|
|
6976
|
+
const isPattern = isWildcardTag(tag);
|
|
6977
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
6978
|
+
if (isPattern || shouldCascade) {
|
|
6979
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
6980
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6981
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
6982
|
+
if (matchedTags.size > 0) {
|
|
6983
|
+
await this._invalidateConcreteTags(Array.from(matchedTags));
|
|
6984
|
+
}
|
|
6985
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
6986
|
+
await this._publishTagInvalidation(op, broadcastPattern);
|
|
6987
|
+
return;
|
|
6988
|
+
}
|
|
6989
|
+
await this._invalidateConcreteTag(tag);
|
|
6990
|
+
} catch (err) {
|
|
6991
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6992
|
+
span.recordException?.(err);
|
|
6993
|
+
throw err;
|
|
6994
|
+
} finally {
|
|
6995
|
+
span.end();
|
|
6996
|
+
}
|
|
6997
|
+
}
|
|
6998
|
+
/**
|
|
6999
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
7000
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
7001
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
7002
|
+
*
|
|
7003
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
7004
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
7005
|
+
*
|
|
7006
|
+
* @example
|
|
7007
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
7008
|
+
*/
|
|
7009
|
+
async invalidateTags(tags, opts) {
|
|
7010
|
+
this._assertActive("invalidateTags");
|
|
7011
|
+
if (tags.length === 0) return;
|
|
7012
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
7013
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7014
|
+
if (hasWildcards || shouldCascade) {
|
|
7015
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
7016
|
+
const broadcastPatterns = /* @__PURE__ */ new Set();
|
|
7017
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7018
|
+
for (const t of tags) {
|
|
7019
|
+
const tIsPattern = isWildcardTag(t);
|
|
7020
|
+
if (tIsPattern || shouldCascade) {
|
|
7021
|
+
broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
|
|
7022
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
7023
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
7024
|
+
} else {
|
|
7025
|
+
allResolvedTags.add(t);
|
|
7026
|
+
}
|
|
7027
|
+
}
|
|
7028
|
+
if (allResolvedTags.size > 0) {
|
|
7029
|
+
await this._invalidateConcreteTags(Array.from(allResolvedTags));
|
|
7030
|
+
}
|
|
7031
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7032
|
+
for (const pattern of broadcastPatterns) {
|
|
7033
|
+
await this._publishTagInvalidation(op, pattern);
|
|
7034
|
+
}
|
|
7035
|
+
return;
|
|
7036
|
+
}
|
|
7037
|
+
await this._invalidateConcreteTags(Array.from(new Set(tags)));
|
|
7038
|
+
}
|
|
6641
7039
|
/**
|
|
6642
7040
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
6643
7041
|
*/
|
|
@@ -7203,6 +7601,13 @@ var CacheService = class _CacheService {
|
|
|
7203
7601
|
this._destroyed = true;
|
|
7204
7602
|
this._pendingDiskDeletes.clear();
|
|
7205
7603
|
this._keyMutationEpochs.clear();
|
|
7604
|
+
this.inflight.clear();
|
|
7605
|
+
this.revalidating.clear();
|
|
7606
|
+
this._l1Counters.clear();
|
|
7607
|
+
this.tagIndex.clear();
|
|
7608
|
+
this.keyTags.clear();
|
|
7609
|
+
this.dependencyIndex.clear();
|
|
7610
|
+
this.keyDependencies.clear();
|
|
7206
7611
|
const g = globalThis;
|
|
7207
7612
|
const key = _CacheService.globalKey(this.opts);
|
|
7208
7613
|
if (g[key] === this) {
|