tricache 0.9.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/{cache-service-DVvroyqA.d.ts → cache-service-CREOp7MM.d.ts} +57 -12
- package/dist/{cache-service-KI5ACF3F.js → cache-service-MG7PN6MX.js} +3 -3
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-QNU7B43J.js → chunk-3I5L7K6I.js} +17 -0
- package/dist/{chunk-PL5J3ZNT.js → chunk-JYQFQJNJ.js} +682 -277
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +857 -293
- package/dist/cli.js +4 -4
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +865 -294
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +115 -36
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +88 -37
- package/dist/hono/index.cjs +865 -294
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +1 -1
- package/dist/{hono-VA9A1m0I.d.ts → hono-DSV2ve66.d.ts} +11 -4
- package/dist/http/index.cjs +917 -315
- package/dist/http/index.d.ts +3 -3
- package/dist/http/index.js +60 -29
- package/dist/index.cjs +885 -294
- package/dist/index.d.ts +37 -7
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +856 -292
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +858 -300
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +5 -11
- package/dist/prisma/index.d.ts +2 -2
- package/dist/serialize-worker.cjs +127 -9
- package/dist/serialize-worker.js +8 -4
- package/dist/{types-B_QkVwJ7.d.ts → types-Dyip5wAl.d.ts} +53 -7
- package/package.json +7 -4
- package/src/adapters/node-redis.ts +19 -0
- package/src/cache-service.ts +781 -297
- package/src/cli.ts +1 -1
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +94 -42
- package/src/env.d.ts +13 -0
- package/src/http/express.ts +55 -16
- package/src/http/fastify.ts +3 -7
- package/src/index.ts +9 -1
- package/src/next/cache-handler.ts +1 -4
- package/src/next/isr-handler.ts +1 -4
- package/src/serialize-worker.ts +6 -2
- package/src/smart-memory-cache.ts +3 -2
- package/src/types.ts +45 -5
- package/src/utils/tag-matcher.ts +90 -0
package/dist/index.cjs
CHANGED
|
@@ -66,6 +66,7 @@ __export(index_exports, {
|
|
|
66
66
|
createSigV4SnapshotAdapter: () => createSigV4SnapshotAdapter,
|
|
67
67
|
deepMergeOptions: () => deepMergeOptions,
|
|
68
68
|
defaultCodec: () => defaultCodec,
|
|
69
|
+
expandHierarchicalTags: () => expandHierarchicalTags,
|
|
69
70
|
findActiveSockets: () => findActiveSockets,
|
|
70
71
|
formatBytes: () => formatBytes,
|
|
71
72
|
formatDuration: () => formatDuration,
|
|
@@ -73,6 +74,10 @@ __export(index_exports, {
|
|
|
73
74
|
formatTraceParent: () => formatTraceParent,
|
|
74
75
|
getV8HeapLimit: () => getV8HeapLimit,
|
|
75
76
|
handleDashboardRequest: () => handleDashboardRequest,
|
|
77
|
+
initZstd: () => initZstd,
|
|
78
|
+
isChildTag: () => isChildTag,
|
|
79
|
+
isWildcardTag: () => isWildcardTag,
|
|
80
|
+
matchesTagPattern: () => matchesTagPattern,
|
|
76
81
|
murmur3_32: () => murmur3_32,
|
|
77
82
|
parseTraceParent: () => parseTraceParent,
|
|
78
83
|
readCgroupMemoryLimit: () => readCgroupMemoryLimit,
|
|
@@ -1768,7 +1773,7 @@ var SmartMemoryCache = class {
|
|
|
1768
1773
|
};
|
|
1769
1774
|
return hit;
|
|
1770
1775
|
}
|
|
1771
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1776
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
|
|
1772
1777
|
const packed = this.codec.encode(data);
|
|
1773
1778
|
const size = packed.byteLength;
|
|
1774
1779
|
this.compressions++;
|
|
@@ -1805,7 +1810,7 @@ var SmartMemoryCache = class {
|
|
|
1805
1810
|
priority,
|
|
1806
1811
|
ttlMs,
|
|
1807
1812
|
delta,
|
|
1808
|
-
setAt: now2,
|
|
1813
|
+
setAt: setAt ?? now2,
|
|
1809
1814
|
tagVersions
|
|
1810
1815
|
});
|
|
1811
1816
|
}
|
|
@@ -1833,7 +1838,7 @@ var SmartMemoryCache = class {
|
|
|
1833
1838
|
}
|
|
1834
1839
|
const now = Date.now();
|
|
1835
1840
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1836
|
-
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 });
|
|
1841
|
+
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 });
|
|
1837
1842
|
if (!existingEntry) this.bloom.add(key);
|
|
1838
1843
|
this.maybeRebuildBloom();
|
|
1839
1844
|
this.totalSize += size;
|
|
@@ -2252,13 +2257,38 @@ var import_os2 = __toESM(require("os"), 1);
|
|
|
2252
2257
|
|
|
2253
2258
|
// src/compression.ts
|
|
2254
2259
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
2260
|
+
var import_lz4js = __toESM(require("lz4js"), 1);
|
|
2261
|
+
var import_zstd_codec = require("zstd-codec");
|
|
2255
2262
|
var PREFIX_COMPRESSED = "cmp:v1:";
|
|
2256
2263
|
var PREFIX_ENC_COMPRESSED = "ecp:v1:";
|
|
2257
2264
|
var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
|
|
2265
|
+
var zstdSimple = null;
|
|
2266
|
+
var zstdInitPromise = null;
|
|
2267
|
+
function initZstd() {
|
|
2268
|
+
if (zstdSimple) return Promise.resolve(zstdSimple);
|
|
2269
|
+
if (!zstdInitPromise) {
|
|
2270
|
+
zstdInitPromise = new Promise((resolve) => {
|
|
2271
|
+
try {
|
|
2272
|
+
import_zstd_codec.ZstdCodec.run((zstd) => {
|
|
2273
|
+
zstdSimple = new zstd.Simple();
|
|
2274
|
+
resolve(zstdSimple);
|
|
2275
|
+
});
|
|
2276
|
+
} catch {
|
|
2277
|
+
resolve(null);
|
|
2278
|
+
}
|
|
2279
|
+
});
|
|
2280
|
+
}
|
|
2281
|
+
return zstdInitPromise;
|
|
2282
|
+
}
|
|
2283
|
+
initZstd().catch(() => {
|
|
2284
|
+
});
|
|
2258
2285
|
function isCompressed(buf) {
|
|
2259
2286
|
return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
|
|
2260
2287
|
}
|
|
2261
|
-
function compressBuffer(buf, algorithm) {
|
|
2288
|
+
function compressBuffer(buf, algorithm, custom) {
|
|
2289
|
+
if (custom) {
|
|
2290
|
+
return custom.compress(buf);
|
|
2291
|
+
}
|
|
2262
2292
|
if (algorithm === "brotli") {
|
|
2263
2293
|
return import_zlib.default.brotliCompressSync(buf, {
|
|
2264
2294
|
params: {
|
|
@@ -2270,37 +2300,127 @@ function compressBuffer(buf, algorithm) {
|
|
|
2270
2300
|
if (algorithm === "gzip") {
|
|
2271
2301
|
return import_zlib.default.gzipSync(buf, { level: 6 });
|
|
2272
2302
|
}
|
|
2303
|
+
if (algorithm === "lz4") {
|
|
2304
|
+
return Buffer.from(import_lz4js.default.compress(buf));
|
|
2305
|
+
}
|
|
2306
|
+
if (algorithm === "zstd") {
|
|
2307
|
+
if (!zstdSimple) {
|
|
2308
|
+
return import_zlib.default.brotliCompressSync(buf, {
|
|
2309
|
+
params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
|
|
2310
|
+
});
|
|
2311
|
+
}
|
|
2312
|
+
return Buffer.from(zstdSimple.compress(buf));
|
|
2313
|
+
}
|
|
2273
2314
|
return buf;
|
|
2274
2315
|
}
|
|
2275
|
-
|
|
2316
|
+
var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
|
|
2317
|
+
function decompressBuffer(buf, algorithm = "zstd", custom) {
|
|
2318
|
+
if (custom) {
|
|
2319
|
+
const res = custom.decompress(buf);
|
|
2320
|
+
if (res.length > MAX_DECOMPRESS_BYTES) {
|
|
2321
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2322
|
+
}
|
|
2323
|
+
return res;
|
|
2324
|
+
}
|
|
2325
|
+
const checkSafety = (decomp) => {
|
|
2326
|
+
if (decomp.length > MAX_DECOMPRESS_BYTES) {
|
|
2327
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2328
|
+
}
|
|
2329
|
+
return decomp;
|
|
2330
|
+
};
|
|
2331
|
+
if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
|
|
2332
|
+
if (zstdSimple) {
|
|
2333
|
+
try {
|
|
2334
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2335
|
+
} catch (err) {
|
|
2336
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
|
|
2341
|
+
try {
|
|
2342
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2343
|
+
} catch (err) {
|
|
2344
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
|
|
2348
|
+
try {
|
|
2349
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2350
|
+
} catch (err) {
|
|
2351
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2352
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
if (algorithm === "none") {
|
|
2357
|
+
return buf;
|
|
2358
|
+
}
|
|
2359
|
+
if (algorithm === "lz4") {
|
|
2360
|
+
try {
|
|
2361
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2362
|
+
} catch (err) {
|
|
2363
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
if (algorithm === "zstd" && zstdSimple) {
|
|
2367
|
+
try {
|
|
2368
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2369
|
+
} catch (err) {
|
|
2370
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2276
2373
|
const tryBrotli = () => {
|
|
2277
2374
|
try {
|
|
2278
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
2279
|
-
} catch {
|
|
2375
|
+
return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2376
|
+
} catch (err) {
|
|
2377
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2378
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2379
|
+
}
|
|
2280
2380
|
return null;
|
|
2281
2381
|
}
|
|
2282
2382
|
};
|
|
2283
2383
|
const tryGzip = () => {
|
|
2284
2384
|
try {
|
|
2285
|
-
return import_zlib.default.gunzipSync(buf);
|
|
2286
|
-
} catch {
|
|
2385
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2386
|
+
} catch (err) {
|
|
2387
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2388
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2389
|
+
}
|
|
2390
|
+
return null;
|
|
2391
|
+
}
|
|
2392
|
+
};
|
|
2393
|
+
const tryLz4 = () => {
|
|
2394
|
+
try {
|
|
2395
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2396
|
+
} catch (err) {
|
|
2397
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2398
|
+
return null;
|
|
2399
|
+
}
|
|
2400
|
+
};
|
|
2401
|
+
const tryZstd = () => {
|
|
2402
|
+
if (!zstdSimple) return null;
|
|
2403
|
+
try {
|
|
2404
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2405
|
+
} catch (err) {
|
|
2406
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2287
2407
|
return null;
|
|
2288
2408
|
}
|
|
2289
2409
|
};
|
|
2290
|
-
const result = algorithm === "gzip" ? tryGzip() ??
|
|
2410
|
+
const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
|
|
2291
2411
|
if (result === null) {
|
|
2292
2412
|
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
2293
2413
|
}
|
|
2294
2414
|
return result;
|
|
2295
2415
|
}
|
|
2296
|
-
function compressWithHeader(buf, algorithm) {
|
|
2416
|
+
function compressWithHeader(buf, algorithm, custom) {
|
|
2297
2417
|
if (algorithm === "none") return buf;
|
|
2298
|
-
const compressed = compressBuffer(buf, algorithm);
|
|
2418
|
+
const compressed = compressBuffer(buf, algorithm, custom);
|
|
2299
2419
|
return Buffer.concat([COMPRESSION_MAGIC, compressed]);
|
|
2300
2420
|
}
|
|
2301
|
-
function decompressWithHeader(buf, algorithm = "
|
|
2421
|
+
function decompressWithHeader(buf, algorithm = "zstd", custom) {
|
|
2302
2422
|
if (isCompressed(buf)) {
|
|
2303
|
-
return decompressBuffer(buf.subarray(4), algorithm);
|
|
2423
|
+
return decompressBuffer(buf.subarray(4), algorithm, custom);
|
|
2304
2424
|
}
|
|
2305
2425
|
return buf;
|
|
2306
2426
|
}
|
|
@@ -4130,6 +4250,55 @@ function renderTopDashboard(payload) {
|
|
|
4130
4250
|
return lines.join("\n");
|
|
4131
4251
|
}
|
|
4132
4252
|
|
|
4253
|
+
// src/utils/tag-matcher.ts
|
|
4254
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
4255
|
+
function isWildcardTag(tag) {
|
|
4256
|
+
return tag.includes("*") || tag.includes("?");
|
|
4257
|
+
}
|
|
4258
|
+
function matchesTagPattern(pattern, tag) {
|
|
4259
|
+
if (pattern === "*" || pattern === tag) return true;
|
|
4260
|
+
if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
|
|
4261
|
+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
|
|
4262
|
+
const prefix = pattern.slice(0, -1);
|
|
4263
|
+
return tag.startsWith(prefix);
|
|
4264
|
+
}
|
|
4265
|
+
if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
|
|
4266
|
+
const suffix = pattern.slice(1);
|
|
4267
|
+
return tag.endsWith(suffix);
|
|
4268
|
+
}
|
|
4269
|
+
let re = globRegexCache.get(pattern);
|
|
4270
|
+
if (!re) {
|
|
4271
|
+
if (globRegexCache.size >= 1e3) globRegexCache.clear();
|
|
4272
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
4273
|
+
re = new RegExp(`^${escaped}$`);
|
|
4274
|
+
globRegexCache.set(pattern, re);
|
|
4275
|
+
}
|
|
4276
|
+
return re.test(tag);
|
|
4277
|
+
}
|
|
4278
|
+
function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
4279
|
+
if (candidateTag === parentTag) return true;
|
|
4280
|
+
const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
|
|
4281
|
+
return candidateTag.startsWith(prefix);
|
|
4282
|
+
}
|
|
4283
|
+
function expandHierarchicalTags(tags, delimiter = ":") {
|
|
4284
|
+
if (!tags.length) return [];
|
|
4285
|
+
const result = /* @__PURE__ */ new Set();
|
|
4286
|
+
for (const tag of tags) {
|
|
4287
|
+
if (!tag) continue;
|
|
4288
|
+
const parts = tag.split(delimiter).filter((p) => p.length > 0);
|
|
4289
|
+
if (parts.length <= 1) {
|
|
4290
|
+
result.add(tag);
|
|
4291
|
+
continue;
|
|
4292
|
+
}
|
|
4293
|
+
let accumulated = "";
|
|
4294
|
+
for (let i = 0; i < parts.length; i++) {
|
|
4295
|
+
accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
|
|
4296
|
+
result.add(accumulated);
|
|
4297
|
+
}
|
|
4298
|
+
}
|
|
4299
|
+
return Array.from(result);
|
|
4300
|
+
}
|
|
4301
|
+
|
|
4133
4302
|
// src/cache-service.ts
|
|
4134
4303
|
var LUA_COMPARE_AND_DELETE = `
|
|
4135
4304
|
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
@@ -4148,21 +4317,21 @@ var DEFAULT_CATEGORY_LIMITS = {
|
|
|
4148
4317
|
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
4149
4318
|
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
4150
4319
|
var GLOB_REGEX_CACHE_MAX = 256;
|
|
4151
|
-
var
|
|
4320
|
+
var globRegexCache2 = /* @__PURE__ */ new Map();
|
|
4152
4321
|
function getGlobRegex(pattern) {
|
|
4153
|
-
let re =
|
|
4322
|
+
let re = globRegexCache2.get(pattern);
|
|
4154
4323
|
if (re) {
|
|
4155
|
-
|
|
4156
|
-
|
|
4324
|
+
globRegexCache2.delete(pattern);
|
|
4325
|
+
globRegexCache2.set(pattern, re);
|
|
4157
4326
|
return re;
|
|
4158
4327
|
}
|
|
4159
4328
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
4160
4329
|
re = new RegExp("^" + escaped + "$");
|
|
4161
|
-
if (
|
|
4162
|
-
const oldestKey =
|
|
4163
|
-
if (oldestKey !== void 0)
|
|
4330
|
+
if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
|
|
4331
|
+
const oldestKey = globRegexCache2.keys().next().value;
|
|
4332
|
+
if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
|
|
4164
4333
|
}
|
|
4165
|
-
|
|
4334
|
+
globRegexCache2.set(pattern, re);
|
|
4166
4335
|
return re;
|
|
4167
4336
|
}
|
|
4168
4337
|
var L2CircuitBreaker = class {
|
|
@@ -4416,6 +4585,7 @@ var CacheService = class _CacheService {
|
|
|
4416
4585
|
opts;
|
|
4417
4586
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
4418
4587
|
_namespace;
|
|
4588
|
+
prefixLen;
|
|
4419
4589
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
4420
4590
|
_redisDisabled;
|
|
4421
4591
|
watchdog;
|
|
@@ -4425,6 +4595,8 @@ var CacheService = class _CacheService {
|
|
|
4425
4595
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
4426
4596
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
4427
4597
|
tagIndex = /* @__PURE__ */ new Map();
|
|
4598
|
+
/** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
|
|
4599
|
+
keyTags = /* @__PURE__ */ new Map();
|
|
4428
4600
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
4429
4601
|
tagVersions = /* @__PURE__ */ new Map();
|
|
4430
4602
|
/**
|
|
@@ -4432,6 +4604,9 @@ var CacheService = class _CacheService {
|
|
|
4432
4604
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
4433
4605
|
*/
|
|
4434
4606
|
dependencyIndex = /* @__PURE__ */ new Map();
|
|
4607
|
+
/** Reverse index of namespaced dependent key → source glob patterns */
|
|
4608
|
+
keyDependencies = /* @__PURE__ */ new Map();
|
|
4609
|
+
_cgroupMemoryLimit;
|
|
4435
4610
|
redis = null;
|
|
4436
4611
|
redisConnecting = null;
|
|
4437
4612
|
cb;
|
|
@@ -4501,6 +4676,84 @@ var CacheService = class _CacheService {
|
|
|
4501
4676
|
_getKeyMutationEpoch(namespacedKey) {
|
|
4502
4677
|
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
4503
4678
|
}
|
|
4679
|
+
_removeKeyTags(namespacedKey) {
|
|
4680
|
+
const entry = this.keyTags.get(namespacedKey);
|
|
4681
|
+
if (!entry) return;
|
|
4682
|
+
for (const tag of entry.tags) {
|
|
4683
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4684
|
+
const members = this.tagIndex.get(tagKey);
|
|
4685
|
+
if (members) {
|
|
4686
|
+
members.delete(namespacedKey);
|
|
4687
|
+
if (members.size === 0) this.tagIndex.delete(tagKey);
|
|
4688
|
+
}
|
|
4689
|
+
}
|
|
4690
|
+
this.keyTags.delete(namespacedKey);
|
|
4691
|
+
}
|
|
4692
|
+
_removeKeyDependencies(namespacedKey) {
|
|
4693
|
+
const patterns = this.keyDependencies.get(namespacedKey);
|
|
4694
|
+
if (patterns) {
|
|
4695
|
+
for (const pat of patterns) {
|
|
4696
|
+
const deps = this.dependencyIndex.get(pat);
|
|
4697
|
+
if (deps) {
|
|
4698
|
+
deps.delete(namespacedKey);
|
|
4699
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
4700
|
+
}
|
|
4701
|
+
}
|
|
4702
|
+
this.keyDependencies.delete(namespacedKey);
|
|
4703
|
+
} else if (this.dependencyIndex.size > 0) {
|
|
4704
|
+
for (const [pat, deps] of this.dependencyIndex) {
|
|
4705
|
+
deps.delete(namespacedKey);
|
|
4706
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
4707
|
+
}
|
|
4708
|
+
}
|
|
4709
|
+
}
|
|
4710
|
+
_handleL1Eviction(namespacedKey, reason) {
|
|
4711
|
+
const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
4712
|
+
if (!spilledToDisk) {
|
|
4713
|
+
this._removeKeyTags(namespacedKey);
|
|
4714
|
+
this._removeKeyDependencies(namespacedKey);
|
|
4715
|
+
}
|
|
4716
|
+
}
|
|
4717
|
+
_removePrefixFromIndices(prefix) {
|
|
4718
|
+
for (const k of Array.from(this.keyTags.keys())) {
|
|
4719
|
+
if (k.startsWith(prefix)) this._removeKeyTags(k);
|
|
4720
|
+
}
|
|
4721
|
+
for (const k of Array.from(this.keyDependencies.keys())) {
|
|
4722
|
+
if (k.startsWith(prefix)) this._removeKeyDependencies(k);
|
|
4723
|
+
}
|
|
4724
|
+
for (const k of Array.from(this._l1Counters.keys())) {
|
|
4725
|
+
if (k.startsWith(prefix)) this._l1Counters.delete(k);
|
|
4726
|
+
}
|
|
4727
|
+
}
|
|
4728
|
+
_sweepExpiredMetadata() {
|
|
4729
|
+
const now = Date.now();
|
|
4730
|
+
for (const [k, c] of this._l1Counters) {
|
|
4731
|
+
if (c.expiresAt <= now) this._l1Counters.delete(k);
|
|
4732
|
+
}
|
|
4733
|
+
for (const [k, meta] of this.keyTags) {
|
|
4734
|
+
if (meta.expiresAt <= now && !this.l1.has(k)) {
|
|
4735
|
+
this._removeKeyTags(k);
|
|
4736
|
+
this._removeKeyDependencies(k);
|
|
4737
|
+
}
|
|
4738
|
+
}
|
|
4739
|
+
}
|
|
4740
|
+
_runOomCheck() {
|
|
4741
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
4742
|
+
const heapUsed = heap.used_heap_size / heap.heap_size_limit;
|
|
4743
|
+
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
|
|
4744
|
+
const used = Math.max(heapUsed, cgroupUsed);
|
|
4745
|
+
if (used >= this.opts.oomHeapThreshold) {
|
|
4746
|
+
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4747
|
+
this.counters.oomEvictions++;
|
|
4748
|
+
this.counters.oomLastAt = Date.now();
|
|
4749
|
+
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4750
|
+
heapUsedPct: Math.round(heapUsed * 100),
|
|
4751
|
+
cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
|
|
4752
|
+
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4753
|
+
evicted
|
|
4754
|
+
});
|
|
4755
|
+
}
|
|
4756
|
+
}
|
|
4504
4757
|
_ipcServer;
|
|
4505
4758
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
4506
4759
|
_subDisconnectedAt = null;
|
|
@@ -4547,6 +4800,7 @@ var CacheService = class _CacheService {
|
|
|
4547
4800
|
constructor(options = {}) {
|
|
4548
4801
|
const logger = options.logger ?? consoleLogger;
|
|
4549
4802
|
this.logger = logger;
|
|
4803
|
+
this._cgroupMemoryLimit = readCgroupMemoryLimit();
|
|
4550
4804
|
const ns = options.namespace?.trim() ?? "";
|
|
4551
4805
|
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
4552
4806
|
this.enc = new CacheEncryption(
|
|
@@ -4624,12 +4878,15 @@ var CacheService = class _CacheService {
|
|
|
4624
4878
|
redisSentinel: options.redisSentinel,
|
|
4625
4879
|
redisProtocol: options.redisProtocol,
|
|
4626
4880
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
4627
|
-
compression: options.compression ?? "
|
|
4881
|
+
compression: options.compression ?? "zstd",
|
|
4882
|
+
customCompressor: options.customCompressor,
|
|
4628
4883
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
4629
4884
|
strictSingleton: options.strictSingleton ?? false,
|
|
4630
4885
|
failClosed: options.failClosed ?? false,
|
|
4631
4886
|
tagStrategy: options.tagStrategy ?? "set",
|
|
4632
4887
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
4888
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
4889
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
4633
4890
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
4634
4891
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
4635
4892
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4702,6 +4959,7 @@ var CacheService = class _CacheService {
|
|
|
4702
4959
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4703
4960
|
});
|
|
4704
4961
|
this._namespace = ns;
|
|
4962
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4705
4963
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4706
4964
|
this.watchdog = new TierLatencyWatchdog({
|
|
4707
4965
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4726,7 +4984,10 @@ var CacheService = class _CacheService {
|
|
|
4726
4984
|
void this.disk.save(key, entry);
|
|
4727
4985
|
});
|
|
4728
4986
|
},
|
|
4729
|
-
onEviction:
|
|
4987
|
+
onEviction: (key, reason) => {
|
|
4988
|
+
this._handleL1Eviction(key, reason);
|
|
4989
|
+
options.onEviction?.(key, reason);
|
|
4990
|
+
},
|
|
4730
4991
|
logger
|
|
4731
4992
|
});
|
|
4732
4993
|
if (!this.snapshotLoaded) {
|
|
@@ -4764,6 +5025,7 @@ var CacheService = class _CacheService {
|
|
|
4764
5025
|
}
|
|
4765
5026
|
this.cleanupInterval = setInterval(() => {
|
|
4766
5027
|
const cleaned = this.l1.cleanup();
|
|
5028
|
+
this._sweepExpiredMetadata();
|
|
4767
5029
|
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
4768
5030
|
}, 5 * 60 * 1e3);
|
|
4769
5031
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
@@ -4776,18 +5038,7 @@ var CacheService = class _CacheService {
|
|
|
4776
5038
|
}
|
|
4777
5039
|
if (this.opts.oomProtection) {
|
|
4778
5040
|
this.oomInterval = setInterval(() => {
|
|
4779
|
-
|
|
4780
|
-
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
4781
|
-
if (used >= this.opts.oomHeapThreshold) {
|
|
4782
|
-
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4783
|
-
this.counters.oomEvictions++;
|
|
4784
|
-
this.counters.oomLastAt = Date.now();
|
|
4785
|
-
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4786
|
-
heapUsedPct: Math.round(used * 100),
|
|
4787
|
-
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4788
|
-
evicted
|
|
4789
|
-
});
|
|
4790
|
-
}
|
|
5041
|
+
this._runOomCheck();
|
|
4791
5042
|
}, this.opts.oomCheckIntervalMs);
|
|
4792
5043
|
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
4793
5044
|
}
|
|
@@ -4811,6 +5062,9 @@ var CacheService = class _CacheService {
|
|
|
4811
5062
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4812
5063
|
this.initBackplane();
|
|
4813
5064
|
const startupPromises = [];
|
|
5065
|
+
if (this.opts.compression === "zstd") {
|
|
5066
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
5067
|
+
}
|
|
4814
5068
|
if (this.opts.remoteSnapshot) {
|
|
4815
5069
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4816
5070
|
}
|
|
@@ -5259,7 +5513,7 @@ var CacheService = class _CacheService {
|
|
|
5259
5513
|
else if (f === "src") src = v;
|
|
5260
5514
|
else if (f === "tagVersion") tagVersionRaw = v;
|
|
5261
5515
|
}
|
|
5262
|
-
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
5516
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
|
|
5263
5517
|
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
5264
5518
|
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
5265
5519
|
op: String(op).slice(0, 40),
|
|
@@ -5316,6 +5570,50 @@ var CacheService = class _CacheService {
|
|
|
5316
5570
|
const tag = key;
|
|
5317
5571
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
5318
5572
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
5573
|
+
} else if (op === "tag_pattern_incr") {
|
|
5574
|
+
const pattern = key;
|
|
5575
|
+
const now = performance.now();
|
|
5576
|
+
for (const [tag, info] of this.tagVersions) {
|
|
5577
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5578
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
5579
|
+
}
|
|
5580
|
+
}
|
|
5581
|
+
this.l1.scan((k, entry) => {
|
|
5582
|
+
if (entry.tagVersions) {
|
|
5583
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
5584
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5585
|
+
this.l1.delete(k);
|
|
5586
|
+
this._bumpKeyMutation(k);
|
|
5587
|
+
break;
|
|
5588
|
+
}
|
|
5589
|
+
}
|
|
5590
|
+
}
|
|
5591
|
+
}, 0);
|
|
5592
|
+
} else if (op === "tag_pattern_del") {
|
|
5593
|
+
const pattern = key;
|
|
5594
|
+
const matchedTagKeys = [];
|
|
5595
|
+
const prefix = this.nk("_tag_:");
|
|
5596
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
5597
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
5598
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5599
|
+
matchedTagKeys.push(tagKey);
|
|
5600
|
+
for (const k of members) {
|
|
5601
|
+
this.l1.delete(k);
|
|
5602
|
+
this._bumpKeyMutation(k);
|
|
5603
|
+
this._pendingDiskDeletes.add(k);
|
|
5604
|
+
setImmediate(() => {
|
|
5605
|
+
try {
|
|
5606
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5607
|
+
} finally {
|
|
5608
|
+
this._pendingDiskDeletes.delete(k);
|
|
5609
|
+
}
|
|
5610
|
+
});
|
|
5611
|
+
}
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
for (const tagKey of matchedTagKeys) {
|
|
5615
|
+
this.tagIndex.delete(tagKey);
|
|
5616
|
+
}
|
|
5319
5617
|
}
|
|
5320
5618
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
5321
5619
|
}
|
|
@@ -5323,7 +5621,7 @@ var CacheService = class _CacheService {
|
|
|
5323
5621
|
_handleBackplaneMessage(message) {
|
|
5324
5622
|
try {
|
|
5325
5623
|
const msg = JSON.parse(message);
|
|
5326
|
-
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") {
|
|
5624
|
+
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") {
|
|
5327
5625
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
5328
5626
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
5329
5627
|
});
|
|
@@ -5477,6 +5775,72 @@ var CacheService = class _CacheService {
|
|
|
5477
5775
|
}
|
|
5478
5776
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
5479
5777
|
}
|
|
5778
|
+
async _isGenerationalEntryStale(tagVersions) {
|
|
5779
|
+
if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
|
|
5780
|
+
const tags = Object.keys(tagVersions);
|
|
5781
|
+
if (tags.length === 0) return false;
|
|
5782
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5783
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5784
|
+
if (currentVers[i] > tagVersions[tags[i]]) return true;
|
|
5785
|
+
}
|
|
5786
|
+
return false;
|
|
5787
|
+
}
|
|
5788
|
+
async _deleteRedisKeys(client, keys) {
|
|
5789
|
+
if (keys.length === 0) return;
|
|
5790
|
+
const CHUNK_SIZE = 1e3;
|
|
5791
|
+
if (client instanceof import_ioredis.Cluster) {
|
|
5792
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
5793
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
5794
|
+
const pl = client.pipeline();
|
|
5795
|
+
for (const k of chunk) pl.del(k);
|
|
5796
|
+
await pl.exec();
|
|
5797
|
+
}
|
|
5798
|
+
return;
|
|
5799
|
+
}
|
|
5800
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
5801
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
5802
|
+
await client.del(...chunk);
|
|
5803
|
+
}
|
|
5804
|
+
}
|
|
5805
|
+
async _parseGenerationalRedisHash(k, hashData) {
|
|
5806
|
+
if (!hashData || !hashData.d) return null;
|
|
5807
|
+
let storedTagVersions = {};
|
|
5808
|
+
if (hashData.tv) {
|
|
5809
|
+
try {
|
|
5810
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5811
|
+
} catch {
|
|
5812
|
+
}
|
|
5813
|
+
}
|
|
5814
|
+
if (await this._isGenerationalEntryStale(storedTagVersions)) {
|
|
5815
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5816
|
+
this._deleteIfStale(k, setAtMs);
|
|
5817
|
+
return { stale: true };
|
|
5818
|
+
}
|
|
5819
|
+
const value = await this._decryptAndDeserialize(hashData.d);
|
|
5820
|
+
return { value, tagVersions: storedTagVersions, stale: false };
|
|
5821
|
+
}
|
|
5822
|
+
async _readRedisEntry(client, k, allowAutoPipeline = false) {
|
|
5823
|
+
if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
|
|
5824
|
+
try {
|
|
5825
|
+
const hashData = await client.hgetall(k);
|
|
5826
|
+
if (typeof hashData === "string") {
|
|
5827
|
+
const value2 = await this._decryptAndDeserialize(hashData);
|
|
5828
|
+
return { value: value2, stale: false };
|
|
5829
|
+
}
|
|
5830
|
+
if (hashData && hashData.d) {
|
|
5831
|
+
return await this._parseGenerationalRedisHash(k, hashData);
|
|
5832
|
+
}
|
|
5833
|
+
return null;
|
|
5834
|
+
} catch (err) {
|
|
5835
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
5836
|
+
if (!msg.includes("WRONGTYPE")) throw err;
|
|
5837
|
+
}
|
|
5838
|
+
}
|
|
5839
|
+
const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5840
|
+
if (raw == null) return null;
|
|
5841
|
+
const value = await this._decryptAndDeserialize(raw);
|
|
5842
|
+
return { value, stale: false };
|
|
5843
|
+
}
|
|
5480
5844
|
async _getTagVersion(tag) {
|
|
5481
5845
|
const now = performance.now();
|
|
5482
5846
|
const local = this.tagVersions.get(tag);
|
|
@@ -5510,12 +5874,12 @@ var CacheService = class _CacheService {
|
|
|
5510
5874
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
5511
5875
|
*/
|
|
5512
5876
|
async _serializeAndEncrypt(serialized) {
|
|
5513
|
-
const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
5514
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5877
|
+
const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
5878
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5515
5879
|
return this._workerPool.encrypt(serialized);
|
|
5516
5880
|
}
|
|
5517
5881
|
if (isCompressed2) {
|
|
5518
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
5882
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
5519
5883
|
if (this.enc.isEnabled) {
|
|
5520
5884
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
5521
5885
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -5530,16 +5894,16 @@ var CacheService = class _CacheService {
|
|
|
5530
5894
|
*/
|
|
5531
5895
|
async _decryptAndDeserialize(raw) {
|
|
5532
5896
|
let plain;
|
|
5533
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
5897
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
5534
5898
|
plain = await this._workerPool.decrypt(raw);
|
|
5535
5899
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
5536
5900
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
5537
5901
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
5538
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5902
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
5539
5903
|
plain = decompressed.toString("utf8");
|
|
5540
5904
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
5541
5905
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
5542
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5906
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
5543
5907
|
plain = decompressed.toString("utf8");
|
|
5544
5908
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
5545
5909
|
plain = this.enc.decrypt(raw);
|
|
@@ -5614,8 +5978,8 @@ var CacheService = class _CacheService {
|
|
|
5614
5978
|
return client;
|
|
5615
5979
|
}
|
|
5616
5980
|
this.redisConnecting = (async () => {
|
|
5981
|
+
let client = null;
|
|
5617
5982
|
try {
|
|
5618
|
-
let client;
|
|
5619
5983
|
if (this.opts.redisClusterNodes?.length) {
|
|
5620
5984
|
client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
5621
5985
|
redisOptions: {
|
|
@@ -5678,14 +6042,45 @@ var CacheService = class _CacheService {
|
|
|
5678
6042
|
});
|
|
5679
6043
|
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
5680
6044
|
}
|
|
6045
|
+
const pendingClient = client;
|
|
5681
6046
|
await new Promise((resolve, reject) => {
|
|
5682
|
-
|
|
5683
|
-
|
|
6047
|
+
let settled = false;
|
|
6048
|
+
const cleanupListeners = () => {
|
|
6049
|
+
pendingClient.removeListener?.("ready", onReady);
|
|
6050
|
+
pendingClient.removeListener?.("error", onError);
|
|
6051
|
+
};
|
|
6052
|
+
const onReady = () => {
|
|
6053
|
+
if (settled) return;
|
|
6054
|
+
settled = true;
|
|
6055
|
+
clearTimeout(timer);
|
|
6056
|
+
cleanupListeners();
|
|
6057
|
+
resolve();
|
|
6058
|
+
};
|
|
6059
|
+
const onError = (e) => {
|
|
6060
|
+
if (settled) return;
|
|
6061
|
+
settled = true;
|
|
6062
|
+
clearTimeout(timer);
|
|
6063
|
+
cleanupListeners();
|
|
5684
6064
|
this._checkAndLogResp3Hint(e);
|
|
5685
6065
|
reject(e);
|
|
5686
|
-
}
|
|
5687
|
-
setTimeout(() =>
|
|
6066
|
+
};
|
|
6067
|
+
const timer = setTimeout(() => {
|
|
6068
|
+
if (settled) return;
|
|
6069
|
+
settled = true;
|
|
6070
|
+
cleanupListeners();
|
|
6071
|
+
reject(new Error("Redis connection timeout"));
|
|
6072
|
+
}, 15e3);
|
|
6073
|
+
if (timer.unref) timer.unref();
|
|
6074
|
+
pendingClient.once("ready", onReady);
|
|
6075
|
+
pendingClient.once("error", onError);
|
|
5688
6076
|
});
|
|
6077
|
+
if (this._destroyed) {
|
|
6078
|
+
try {
|
|
6079
|
+
client.disconnect();
|
|
6080
|
+
} catch {
|
|
6081
|
+
}
|
|
6082
|
+
this._assertActive("getRedis");
|
|
6083
|
+
}
|
|
5689
6084
|
this.cb.onSuccess();
|
|
5690
6085
|
this.redis = client;
|
|
5691
6086
|
this.pipeliner = new AutoPipeliner(client, {
|
|
@@ -5695,6 +6090,10 @@ var CacheService = class _CacheService {
|
|
|
5695
6090
|
this.redisConnecting = null;
|
|
5696
6091
|
return client;
|
|
5697
6092
|
} catch (err) {
|
|
6093
|
+
try {
|
|
6094
|
+
client?.disconnect();
|
|
6095
|
+
} catch {
|
|
6096
|
+
}
|
|
5698
6097
|
this.cb.onFailure();
|
|
5699
6098
|
this.redisConnecting = null;
|
|
5700
6099
|
this._checkAndLogResp3Hint(err);
|
|
@@ -5935,20 +6334,10 @@ var CacheService = class _CacheService {
|
|
|
5935
6334
|
const optRefreshAhead = opts.refreshAhead;
|
|
5936
6335
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5937
6336
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5938
|
-
const optTags = opts.tags;
|
|
6337
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5939
6338
|
const l1Hit = this.l1.get(k);
|
|
5940
6339
|
if (l1Hit !== null) {
|
|
5941
|
-
|
|
5942
|
-
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
5943
|
-
const tags = Object.keys(l1Hit.tagVersions);
|
|
5944
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5945
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5946
|
-
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
5947
|
-
isGenerationalStale = true;
|
|
5948
|
-
break;
|
|
5949
|
-
}
|
|
5950
|
-
}
|
|
5951
|
-
}
|
|
6340
|
+
const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
|
|
5952
6341
|
if (isGenerationalStale) {
|
|
5953
6342
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
5954
6343
|
} else {
|
|
@@ -6034,17 +6423,7 @@ var CacheService = class _CacheService {
|
|
|
6034
6423
|
this.watchdog.recordDisk(diskElapsed);
|
|
6035
6424
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6036
6425
|
if (diskHit !== null) {
|
|
6037
|
-
|
|
6038
|
-
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
6039
|
-
const tags = Object.keys(diskHit.tagVersions);
|
|
6040
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
6041
|
-
for (let i = 0; i < tags.length; i++) {
|
|
6042
|
-
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
6043
|
-
isDiskStale = true;
|
|
6044
|
-
break;
|
|
6045
|
-
}
|
|
6046
|
-
}
|
|
6047
|
-
}
|
|
6426
|
+
const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
|
|
6048
6427
|
if (isDiskStale) {
|
|
6049
6428
|
this.disk.delete(k);
|
|
6050
6429
|
} else {
|
|
@@ -6072,57 +6451,27 @@ var CacheService = class _CacheService {
|
|
|
6072
6451
|
try {
|
|
6073
6452
|
const client = await this.getRedis();
|
|
6074
6453
|
const redisStart = performance.now();
|
|
6075
|
-
|
|
6076
|
-
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
6086
|
-
|
|
6087
|
-
|
|
6088
|
-
}
|
|
6089
|
-
const tags = Object.keys(storedTagVersions);
|
|
6090
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
6091
|
-
for (let i = 0; i < tags.length; i++) {
|
|
6092
|
-
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
6093
|
-
isStale = true;
|
|
6094
|
-
break;
|
|
6095
|
-
}
|
|
6096
|
-
}
|
|
6097
|
-
if (isStale) {
|
|
6098
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
6099
|
-
this._deleteIfStale(k, setAtMs);
|
|
6100
|
-
} else {
|
|
6101
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
6102
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
6103
|
-
this.counters.l2Hits++;
|
|
6104
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
6105
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
6106
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
6107
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
6108
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6109
|
-
}
|
|
6110
|
-
}
|
|
6111
|
-
} else {
|
|
6112
|
-
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
6113
|
-
const redisElapsed = performance.now() - redisStart;
|
|
6114
|
-
this.watchdog.recordRedis(redisElapsed);
|
|
6115
|
-
this.cb.onSuccess();
|
|
6116
|
-
if (raw) {
|
|
6117
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
6118
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
6119
|
-
this.counters.l2Hits++;
|
|
6120
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
6121
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
6122
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
6123
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
6124
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6454
|
+
const redisHit = await this._readRedisEntry(client, k, true);
|
|
6455
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6456
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6457
|
+
this.cb.onSuccess();
|
|
6458
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
6459
|
+
const parsed = redisHit.value;
|
|
6460
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
6461
|
+
this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
|
|
6462
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
6463
|
+
const current = this.l1.get(k);
|
|
6464
|
+
const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
|
|
6465
|
+
if (this.opts.frozen) deepFreeze(liveVal);
|
|
6466
|
+
return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
|
|
6125
6467
|
}
|
|
6468
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
|
|
6469
|
+
this.counters.l2Hits++;
|
|
6470
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
6471
|
+
this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
|
|
6472
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
6473
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
6474
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6126
6475
|
}
|
|
6127
6476
|
} catch (err) {
|
|
6128
6477
|
this.cb.onFailure();
|
|
@@ -6184,20 +6533,20 @@ var CacheService = class _CacheService {
|
|
|
6184
6533
|
if (this.opts.frozen) deepFreeze(data);
|
|
6185
6534
|
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
6186
6535
|
}
|
|
6187
|
-
|
|
6536
|
+
const writeTs = Date.now();
|
|
6537
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
6188
6538
|
if (!this._redisDisabled) {
|
|
6189
6539
|
try {
|
|
6190
6540
|
const client = await this.getRedis();
|
|
6191
6541
|
const serialized = JSON.stringify(data);
|
|
6192
6542
|
const toStore = await this._serializeAndEncrypt(serialized);
|
|
6193
6543
|
const ttlSec = Math.ceil(effectiveTtl / 1e3);
|
|
6194
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
6195
|
-
const now = Date.now();
|
|
6544
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
6196
6545
|
const tx = client.multi();
|
|
6197
6546
|
tx.hset(k, {
|
|
6198
6547
|
d: toStore,
|
|
6199
|
-
t: String(
|
|
6200
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6548
|
+
t: String(writeTs),
|
|
6549
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
6201
6550
|
});
|
|
6202
6551
|
tx.expire(k, ttlSec);
|
|
6203
6552
|
await tx.exec();
|
|
@@ -6335,20 +6684,20 @@ var CacheService = class _CacheService {
|
|
|
6335
6684
|
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
6336
6685
|
return;
|
|
6337
6686
|
}
|
|
6338
|
-
|
|
6687
|
+
const writeTs = Date.now();
|
|
6688
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
6339
6689
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6340
6690
|
try {
|
|
6341
6691
|
const client = await this.getRedis();
|
|
6342
6692
|
const s = JSON.stringify(data);
|
|
6343
6693
|
const stored = await this._serializeAndEncrypt(s);
|
|
6344
6694
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
6345
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
6346
|
-
const now = Date.now();
|
|
6695
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
6347
6696
|
const tx = client.multi();
|
|
6348
6697
|
tx.hset(cacheKey, {
|
|
6349
6698
|
d: stored,
|
|
6350
|
-
t: String(
|
|
6351
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6699
|
+
t: String(writeTs),
|
|
6700
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
6352
6701
|
});
|
|
6353
6702
|
tx.expire(cacheKey, ttlSec);
|
|
6354
6703
|
await tx.exec();
|
|
@@ -6393,27 +6742,35 @@ var CacheService = class _CacheService {
|
|
|
6393
6742
|
this._pendingDiskDeletes.delete(k);
|
|
6394
6743
|
this.counters.sets++;
|
|
6395
6744
|
let activeTagVersions;
|
|
6396
|
-
|
|
6745
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
6746
|
+
if (tagsToRegister?.length) {
|
|
6397
6747
|
if (this.opts.tagStrategy === "generational") {
|
|
6398
|
-
const vers = await Promise.all(
|
|
6748
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
6399
6749
|
activeTagVersions = {};
|
|
6400
|
-
for (let i = 0; i <
|
|
6401
|
-
activeTagVersions[
|
|
6750
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
6751
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
6402
6752
|
}
|
|
6403
6753
|
} else {
|
|
6404
|
-
await this._registerTags(k,
|
|
6405
|
-
}
|
|
6406
|
-
}
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6414
|
-
this.
|
|
6754
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
6755
|
+
}
|
|
6756
|
+
}
|
|
6757
|
+
const writeTs = Date.now();
|
|
6758
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
|
|
6759
|
+
if (opts?.dependsOn !== void 0) {
|
|
6760
|
+
this._removeKeyDependencies(k);
|
|
6761
|
+
if (opts.dependsOn.length > 0) {
|
|
6762
|
+
const nsPatterns = [];
|
|
6763
|
+
for (const pattern of opts.dependsOn) {
|
|
6764
|
+
const nsPattern = this.nk(pattern);
|
|
6765
|
+
nsPatterns.push(nsPattern);
|
|
6766
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
6767
|
+
if (!deps) {
|
|
6768
|
+
deps = /* @__PURE__ */ new Set();
|
|
6769
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
6770
|
+
}
|
|
6771
|
+
deps.add(k);
|
|
6415
6772
|
}
|
|
6416
|
-
|
|
6773
|
+
this.keyDependencies.set(k, nsPatterns);
|
|
6417
6774
|
}
|
|
6418
6775
|
}
|
|
6419
6776
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -6422,13 +6779,12 @@ var CacheService = class _CacheService {
|
|
|
6422
6779
|
const s = JSON.stringify(data);
|
|
6423
6780
|
const stored = await this._serializeAndEncrypt(s);
|
|
6424
6781
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
6425
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
6426
|
-
const now = Date.now();
|
|
6782
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
6427
6783
|
const tx = client.multi();
|
|
6428
6784
|
tx.hset(k, {
|
|
6429
6785
|
d: stored,
|
|
6430
|
-
t: String(
|
|
6431
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6786
|
+
t: String(writeTs),
|
|
6787
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
6432
6788
|
});
|
|
6433
6789
|
tx.expire(k, ttlSec);
|
|
6434
6790
|
await tx.exec();
|
|
@@ -6463,7 +6819,18 @@ var CacheService = class _CacheService {
|
|
|
6463
6819
|
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
6464
6820
|
*/
|
|
6465
6821
|
async _registerTags(k, tags, ttlSeconds) {
|
|
6466
|
-
|
|
6822
|
+
this._removeKeyTags(k);
|
|
6823
|
+
const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
|
|
6824
|
+
const expiresAt = Date.now() + effectiveTtl * 1e3;
|
|
6825
|
+
if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
|
|
6826
|
+
this._sweepExpiredMetadata();
|
|
6827
|
+
if (this.keyTags.size >= 1e5) {
|
|
6828
|
+
const oldestKey = this.keyTags.keys().next().value;
|
|
6829
|
+
if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
|
|
6830
|
+
}
|
|
6831
|
+
}
|
|
6832
|
+
const uniqueTags = Array.from(new Set(tags));
|
|
6833
|
+
for (const tag of uniqueTags) {
|
|
6467
6834
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6468
6835
|
let members = this.tagIndex.get(tagKey);
|
|
6469
6836
|
if (!members) {
|
|
@@ -6472,14 +6839,15 @@ var CacheService = class _CacheService {
|
|
|
6472
6839
|
}
|
|
6473
6840
|
members.add(k);
|
|
6474
6841
|
}
|
|
6842
|
+
this.keyTags.set(k, { tags: uniqueTags, expiresAt });
|
|
6475
6843
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6476
6844
|
try {
|
|
6477
6845
|
const client = await this.getRedis();
|
|
6478
6846
|
const pl = client.pipeline();
|
|
6479
|
-
for (const tag of
|
|
6847
|
+
for (const tag of uniqueTags) {
|
|
6480
6848
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6481
6849
|
pl.sadd(tagKey, k);
|
|
6482
|
-
pl.expire(tagKey,
|
|
6850
|
+
pl.expire(tagKey, effectiveTtl + 3600);
|
|
6483
6851
|
}
|
|
6484
6852
|
await pl.exec();
|
|
6485
6853
|
this.cb.onSuccess();
|
|
@@ -6518,6 +6886,13 @@ var CacheService = class _CacheService {
|
|
|
6518
6886
|
}
|
|
6519
6887
|
this._addPatternTombstone(pfx);
|
|
6520
6888
|
this.l1.deletePattern(k);
|
|
6889
|
+
this._removePrefixFromIndices(pfx);
|
|
6890
|
+
for (const ktKey of Array.from(this.keyTags.keys())) {
|
|
6891
|
+
if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
|
|
6892
|
+
}
|
|
6893
|
+
for (const kdKey of Array.from(this.keyDependencies.keys())) {
|
|
6894
|
+
if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
|
|
6895
|
+
}
|
|
6521
6896
|
} else {
|
|
6522
6897
|
this._bumpKeyMutation(k);
|
|
6523
6898
|
this.inflight.delete(k);
|
|
@@ -6530,15 +6905,16 @@ var CacheService = class _CacheService {
|
|
|
6530
6905
|
this._pendingDiskDeletes.delete(k);
|
|
6531
6906
|
}
|
|
6532
6907
|
});
|
|
6908
|
+
this._removeKeyTags(k);
|
|
6533
6909
|
this._cascadeDependencies(k);
|
|
6534
|
-
|
|
6910
|
+
this._removeKeyDependencies(k);
|
|
6535
6911
|
}
|
|
6536
6912
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6537
6913
|
try {
|
|
6538
6914
|
const client = await this.getRedis();
|
|
6539
6915
|
if (isPattern) {
|
|
6540
6916
|
const keys = await this._scanKeys(client, k);
|
|
6541
|
-
|
|
6917
|
+
await this._deleteRedisKeys(client, keys);
|
|
6542
6918
|
} else {
|
|
6543
6919
|
if (this.opts.autoPipeline && this.pipeliner) {
|
|
6544
6920
|
await this.pipeliner.del(k);
|
|
@@ -6600,6 +6976,15 @@ var CacheService = class _CacheService {
|
|
|
6600
6976
|
entry.value++;
|
|
6601
6977
|
return entry.value;
|
|
6602
6978
|
}
|
|
6979
|
+
if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
|
|
6980
|
+
for (const [ck, cv] of this._l1Counters) {
|
|
6981
|
+
if (cv.expiresAt <= now) this._l1Counters.delete(ck);
|
|
6982
|
+
}
|
|
6983
|
+
if (this._l1Counters.size >= 5e4) {
|
|
6984
|
+
const oldest = this._l1Counters.keys().next().value;
|
|
6985
|
+
if (oldest !== void 0) this._l1Counters.delete(oldest);
|
|
6986
|
+
}
|
|
6987
|
+
}
|
|
6603
6988
|
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
6604
6989
|
return 1;
|
|
6605
6990
|
}
|
|
@@ -6646,6 +7031,7 @@ var CacheService = class _CacheService {
|
|
|
6646
7031
|
}
|
|
6647
7032
|
this._addPatternTombstone(pfx);
|
|
6648
7033
|
this.l1.deletePattern(k);
|
|
7034
|
+
this._removePrefixFromIndices(pfx);
|
|
6649
7035
|
} else {
|
|
6650
7036
|
this._globalEpoch++;
|
|
6651
7037
|
this.inflight.clear();
|
|
@@ -6654,7 +7040,10 @@ var CacheService = class _CacheService {
|
|
|
6654
7040
|
if (!this._diskDisabled) this.disk.clear();
|
|
6655
7041
|
this._l1Counters.clear();
|
|
6656
7042
|
this.tagIndex.clear();
|
|
7043
|
+
this.keyTags.clear();
|
|
6657
7044
|
this.tagVersions.clear();
|
|
7045
|
+
this.dependencyIndex.clear();
|
|
7046
|
+
this.keyDependencies.clear();
|
|
6658
7047
|
this._pendingDiskDeletes.clear();
|
|
6659
7048
|
this._keyMutationEpochs.clear();
|
|
6660
7049
|
}
|
|
@@ -6663,7 +7052,7 @@ var CacheService = class _CacheService {
|
|
|
6663
7052
|
const client = await this.getRedis();
|
|
6664
7053
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
6665
7054
|
const keys = await this._scanKeys(client, pattern);
|
|
6666
|
-
|
|
7055
|
+
await this._deleteRedisKeys(client, keys);
|
|
6667
7056
|
} catch (err) {
|
|
6668
7057
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6669
7058
|
}
|
|
@@ -6806,6 +7195,10 @@ var CacheService = class _CacheService {
|
|
|
6806
7195
|
this._assertActive("touch");
|
|
6807
7196
|
const k = this.nk(cacheKey);
|
|
6808
7197
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
7198
|
+
if (hit) {
|
|
7199
|
+
const kt = this.keyTags.get(k);
|
|
7200
|
+
if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
|
|
7201
|
+
}
|
|
6809
7202
|
if (hit && !this._redisDisabled) {
|
|
6810
7203
|
try {
|
|
6811
7204
|
const client = await this.getRedis();
|
|
@@ -6833,6 +7226,10 @@ var CacheService = class _CacheService {
|
|
|
6833
7226
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
6834
7227
|
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6835
7228
|
}
|
|
7229
|
+
_prepareReadValue(val) {
|
|
7230
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
7231
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
7232
|
+
}
|
|
6836
7233
|
/**
|
|
6837
7234
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
6838
7235
|
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
@@ -6846,11 +7243,13 @@ var CacheService = class _CacheService {
|
|
|
6846
7243
|
const k = this.nk(cacheKey);
|
|
6847
7244
|
const l1Hit = this.l1.get(k);
|
|
6848
7245
|
if (l1Hit !== null) {
|
|
6849
|
-
this.
|
|
6850
|
-
|
|
6851
|
-
|
|
6852
|
-
|
|
6853
|
-
|
|
7246
|
+
if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
|
|
7247
|
+
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
7248
|
+
} else {
|
|
7249
|
+
this.counters.gets++;
|
|
7250
|
+
this.counters.l1Hits++;
|
|
7251
|
+
return this._prepareReadValue(l1Hit.value);
|
|
7252
|
+
}
|
|
6854
7253
|
}
|
|
6855
7254
|
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6856
7255
|
if (this._isTombstonedByPattern(k)) {
|
|
@@ -6865,18 +7264,20 @@ var CacheService = class _CacheService {
|
|
|
6865
7264
|
this.watchdog.recordDisk(diskElapsed);
|
|
6866
7265
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6867
7266
|
if (diskHit !== null) {
|
|
6868
|
-
|
|
6869
|
-
|
|
6870
|
-
|
|
6871
|
-
|
|
6872
|
-
|
|
6873
|
-
|
|
6874
|
-
|
|
6875
|
-
|
|
6876
|
-
this.
|
|
6877
|
-
|
|
6878
|
-
|
|
6879
|
-
|
|
7267
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
7268
|
+
this.disk.delete(k);
|
|
7269
|
+
} else {
|
|
7270
|
+
const promoted = this.l1.importEntries(
|
|
7271
|
+
[{ key: k, entry: diskHit }],
|
|
7272
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
7273
|
+
);
|
|
7274
|
+
if (promoted > 0) {
|
|
7275
|
+
const l1Check = this.l1.get(k);
|
|
7276
|
+
if (l1Check !== null) {
|
|
7277
|
+
this.counters.gets++;
|
|
7278
|
+
this.counters.diskHits++;
|
|
7279
|
+
return this._prepareReadValue(l1Check.value);
|
|
7280
|
+
}
|
|
6880
7281
|
}
|
|
6881
7282
|
}
|
|
6882
7283
|
}
|
|
@@ -6886,17 +7287,16 @@ var CacheService = class _CacheService {
|
|
|
6886
7287
|
try {
|
|
6887
7288
|
const client = await this.getRedis();
|
|
6888
7289
|
const redisStart = performance.now();
|
|
6889
|
-
const
|
|
7290
|
+
const redisHit = await this._readRedisEntry(client, k);
|
|
6890
7291
|
const redisElapsed = performance.now() - redisStart;
|
|
6891
7292
|
this.watchdog.recordRedis(redisElapsed);
|
|
6892
|
-
|
|
6893
|
-
|
|
6894
|
-
|
|
7293
|
+
this.cb.onSuccess();
|
|
7294
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
7295
|
+
const parsed = redisHit.value;
|
|
7296
|
+
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
|
|
6895
7297
|
this.counters.gets++;
|
|
6896
7298
|
this.counters.l2Hits++;
|
|
6897
|
-
this.
|
|
6898
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
6899
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
7299
|
+
return this._prepareReadValue(parsed);
|
|
6900
7300
|
}
|
|
6901
7301
|
} catch (err) {
|
|
6902
7302
|
this.cb.onFailure();
|
|
@@ -6924,12 +7324,20 @@ var CacheService = class _CacheService {
|
|
|
6924
7324
|
const result = Array.from({ length: keys.length });
|
|
6925
7325
|
const missIndexes = [];
|
|
6926
7326
|
const missKeys = [];
|
|
7327
|
+
const now = Date.now();
|
|
6927
7328
|
for (let i = 0; i < keys.length; i++) {
|
|
6928
7329
|
const k = this.nk(keys[i]);
|
|
6929
7330
|
const entry = this.l1.getEntry(k);
|
|
6930
|
-
if (entry && entry.expiresAt >
|
|
6931
|
-
|
|
6932
|
-
|
|
7331
|
+
if (entry && entry.expiresAt > now) {
|
|
7332
|
+
if (await this._isGenerationalEntryStale(entry.tagVersions)) {
|
|
7333
|
+
this._deleteIfStale(k, entry.setAt ?? 0);
|
|
7334
|
+
missIndexes.push(i);
|
|
7335
|
+
missKeys.push(keys[i]);
|
|
7336
|
+
} else {
|
|
7337
|
+
const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
7338
|
+
result[i] = this._prepareReadValue(val);
|
|
7339
|
+
this.counters.l1Hits++;
|
|
7340
|
+
}
|
|
6933
7341
|
} else {
|
|
6934
7342
|
missIndexes.push(i);
|
|
6935
7343
|
missKeys.push(keys[i]);
|
|
@@ -6950,23 +7358,57 @@ var CacheService = class _CacheService {
|
|
|
6950
7358
|
const client = await this.getRedis();
|
|
6951
7359
|
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6952
7360
|
const pipeline = client.multi();
|
|
6953
|
-
|
|
7361
|
+
const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
7362
|
+
for (const nk of nsKeys) {
|
|
7363
|
+
if (useHashPipeline) {
|
|
7364
|
+
pipeline.hgetall(nk);
|
|
7365
|
+
} else {
|
|
7366
|
+
pipeline.get(nk);
|
|
7367
|
+
}
|
|
7368
|
+
}
|
|
6954
7369
|
const redisStart = performance.now();
|
|
6955
7370
|
const raws = await pipeline.exec();
|
|
6956
7371
|
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6957
7372
|
this.watchdog.recordRedis(redisElapsed);
|
|
6958
7373
|
this.cb.onSuccess();
|
|
6959
7374
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6960
|
-
const
|
|
7375
|
+
const tuple = raws[j];
|
|
7376
|
+
const err = tuple ? tuple[0] : null;
|
|
7377
|
+
const rawVal = tuple ? tuple[1] : null;
|
|
6961
7378
|
const idx = missIndexes[j];
|
|
6962
|
-
|
|
6963
|
-
|
|
6964
|
-
|
|
7379
|
+
const k = nsKeys[j];
|
|
7380
|
+
let parsed;
|
|
7381
|
+
let tagVersions;
|
|
7382
|
+
let hit = false;
|
|
7383
|
+
if (useHashPipeline) {
|
|
7384
|
+
if (err && err.message?.includes("WRONGTYPE")) {
|
|
7385
|
+
const fallbackRaw = await client.get(k);
|
|
7386
|
+
if (fallbackRaw) {
|
|
7387
|
+
parsed = await this._decryptAndDeserialize(fallbackRaw);
|
|
7388
|
+
hit = true;
|
|
7389
|
+
}
|
|
7390
|
+
} else if (!err && typeof rawVal === "string") {
|
|
7391
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
7392
|
+
hit = true;
|
|
7393
|
+
} else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
|
|
7394
|
+
const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
|
|
7395
|
+
if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
|
|
7396
|
+
parsed = hashHit.value;
|
|
7397
|
+
tagVersions = hashHit.tagVersions;
|
|
7398
|
+
hit = true;
|
|
7399
|
+
}
|
|
7400
|
+
}
|
|
7401
|
+
} else if (!err && rawVal) {
|
|
7402
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
7403
|
+
hit = true;
|
|
7404
|
+
}
|
|
7405
|
+
if (hit && parsed !== void 0) {
|
|
6965
7406
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
6966
|
-
|
|
7407
|
+
const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
7408
|
+
this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
|
|
6967
7409
|
this.counters.l2Hits++;
|
|
6968
7410
|
l2HitCount++;
|
|
6969
|
-
result[idx] = parsed;
|
|
7411
|
+
result[idx] = this._prepareReadValue(parsed);
|
|
6970
7412
|
missIndexes[j] = -1;
|
|
6971
7413
|
missKeys[j] = "";
|
|
6972
7414
|
}
|
|
@@ -7000,6 +7442,10 @@ var CacheService = class _CacheService {
|
|
|
7000
7442
|
this.watchdog.recordDisk(diskElapsed);
|
|
7001
7443
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
7002
7444
|
if (diskHit !== null) {
|
|
7445
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
7446
|
+
this.disk.delete(k);
|
|
7447
|
+
continue;
|
|
7448
|
+
}
|
|
7003
7449
|
const promoted = this.l1.importEntries(
|
|
7004
7450
|
[{ key: k, entry: diskHit }],
|
|
7005
7451
|
this.opts.forbiddenSnapshotPrefixes
|
|
@@ -7008,7 +7454,7 @@ var CacheService = class _CacheService {
|
|
|
7008
7454
|
const l1Check = this.l1.get(k);
|
|
7009
7455
|
if (l1Check !== null) {
|
|
7010
7456
|
this.counters.diskHits++;
|
|
7011
|
-
result[missIndexes[j]] = l1Check.value;
|
|
7457
|
+
result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
|
|
7012
7458
|
missIndexes.splice(j, 1);
|
|
7013
7459
|
missKeys.splice(j, 1);
|
|
7014
7460
|
}
|
|
@@ -7016,16 +7462,23 @@ var CacheService = class _CacheService {
|
|
|
7016
7462
|
}
|
|
7017
7463
|
}
|
|
7018
7464
|
}
|
|
7019
|
-
if (missKeys.length > 0) {
|
|
7465
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
7020
7466
|
this.counters.fetches++;
|
|
7021
7467
|
const fetched = await fetchFn(missKeys);
|
|
7468
|
+
const isMap = fetched instanceof Map;
|
|
7022
7469
|
const setPromises = [];
|
|
7023
7470
|
for (let j = 0; j < missKeys.length; j++) {
|
|
7024
|
-
const
|
|
7471
|
+
const k = missKeys[j];
|
|
7472
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
7025
7473
|
result[missIndexes[j]] = v;
|
|
7026
|
-
if (v !== void 0) {
|
|
7027
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
7028
|
-
setPromises.push(this.set(
|
|
7474
|
+
if (v !== void 0 && v !== null) {
|
|
7475
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
7476
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
7477
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
7478
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
7479
|
+
} else if (v === null) {
|
|
7480
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
7481
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
7029
7482
|
}
|
|
7030
7483
|
}
|
|
7031
7484
|
if (setPromises.length > 0) {
|
|
@@ -7168,98 +7621,135 @@ var CacheService = class _CacheService {
|
|
|
7168
7621
|
}
|
|
7169
7622
|
}
|
|
7170
7623
|
/**
|
|
7171
|
-
*
|
|
7172
|
-
*
|
|
7173
|
-
*
|
|
7174
|
-
* @example
|
|
7175
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
7176
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7624
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
7625
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
7626
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
7177
7627
|
*/
|
|
7178
|
-
async
|
|
7179
|
-
|
|
7180
|
-
const
|
|
7181
|
-
|
|
7182
|
-
|
|
7183
|
-
|
|
7628
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
7629
|
+
const isPattern = isWildcardTag(tag);
|
|
7630
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7631
|
+
const matched = /* @__PURE__ */ new Set();
|
|
7632
|
+
const tagMatches = (t) => {
|
|
7633
|
+
if (t === tag) return true;
|
|
7634
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
7635
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
7636
|
+
return false;
|
|
7637
|
+
};
|
|
7638
|
+
if (shouldCascade && !isPattern) {
|
|
7639
|
+
matched.add(tag);
|
|
7184
7640
|
}
|
|
7185
|
-
|
|
7186
|
-
|
|
7187
|
-
|
|
7188
|
-
|
|
7189
|
-
|
|
7190
|
-
|
|
7191
|
-
|
|
7192
|
-
|
|
7193
|
-
|
|
7194
|
-
|
|
7195
|
-
|
|
7196
|
-
|
|
7197
|
-
} else {
|
|
7198
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7199
|
-
newVer = current + 1;
|
|
7200
|
-
}
|
|
7201
|
-
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
7202
|
-
if (this.opts.awaitInvalidationBackplane) {
|
|
7203
|
-
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
7204
|
-
} else {
|
|
7205
|
-
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
7641
|
+
const tagPrefix = this.nk("_tag_:");
|
|
7642
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
7643
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
7644
|
+
if (tagMatches(t)) matched.add(t);
|
|
7645
|
+
}
|
|
7646
|
+
for (const t of this.tagVersions.keys()) {
|
|
7647
|
+
if (tagMatches(t)) matched.add(t);
|
|
7648
|
+
}
|
|
7649
|
+
this.l1.scan((_k, entry) => {
|
|
7650
|
+
if (entry.tagVersions) {
|
|
7651
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
7652
|
+
if (tagMatches(t)) matched.add(t);
|
|
7206
7653
|
}
|
|
7207
|
-
return;
|
|
7208
7654
|
}
|
|
7209
|
-
|
|
7210
|
-
|
|
7211
|
-
|
|
7212
|
-
this.
|
|
7213
|
-
this.
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
7655
|
+
}, 0);
|
|
7656
|
+
if (!this._redisDisabled) {
|
|
7657
|
+
try {
|
|
7658
|
+
const client = await this.getRedis();
|
|
7659
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7660
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
7661
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7662
|
+
const pfx = this.nk("tag_ver:");
|
|
7663
|
+
for (const sk of scannedKeys) {
|
|
7664
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7665
|
+
if (tagMatches(t)) matched.add(t);
|
|
7220
7666
|
}
|
|
7221
|
-
}
|
|
7667
|
+
} else {
|
|
7668
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
7669
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7670
|
+
const pfx = this.nk("_tag_:");
|
|
7671
|
+
for (const sk of scannedKeys) {
|
|
7672
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7673
|
+
if (tagMatches(t)) matched.add(t);
|
|
7674
|
+
}
|
|
7675
|
+
}
|
|
7676
|
+
} catch (err) {
|
|
7677
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
7222
7678
|
}
|
|
7223
|
-
|
|
7679
|
+
}
|
|
7680
|
+
return matched;
|
|
7681
|
+
}
|
|
7682
|
+
async _publishTagInvalidation(op, key, tagVersion) {
|
|
7683
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7684
|
+
await this.publishInvalidation(op, key, tagVersion, false, true);
|
|
7685
|
+
} else {
|
|
7686
|
+
void this.publishInvalidation(op, key, tagVersion, false, true);
|
|
7687
|
+
}
|
|
7688
|
+
}
|
|
7689
|
+
_removeTagMembersLocal(keys) {
|
|
7690
|
+
const keyList = Array.isArray(keys) ? keys : Array.from(keys);
|
|
7691
|
+
for (const k of keyList) {
|
|
7692
|
+
this.l1.delete(k);
|
|
7693
|
+
this._bumpKeyMutation(k);
|
|
7694
|
+
this._removeKeyTags(k);
|
|
7695
|
+
this._removeKeyDependencies(k);
|
|
7696
|
+
this._pendingDiskDeletes.add(k);
|
|
7697
|
+
setImmediate(() => {
|
|
7698
|
+
try {
|
|
7699
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
7700
|
+
} finally {
|
|
7701
|
+
this._pendingDiskDeletes.delete(k);
|
|
7702
|
+
}
|
|
7703
|
+
});
|
|
7704
|
+
}
|
|
7705
|
+
}
|
|
7706
|
+
/**
|
|
7707
|
+
* Executes invalidation for a single already-resolved concrete tag without
|
|
7708
|
+
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
7709
|
+
*/
|
|
7710
|
+
async _invalidateConcreteTag(tag) {
|
|
7711
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7712
|
+
let newVer = 1;
|
|
7224
7713
|
if (!this._redisDisabled) {
|
|
7225
7714
|
try {
|
|
7226
7715
|
const client = await this.getRedis();
|
|
7227
|
-
|
|
7228
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
7229
|
-
if (toDelete.length > 0) {
|
|
7230
|
-
await client.del(...toDelete, tagKey);
|
|
7231
|
-
} else {
|
|
7232
|
-
await client.del(tagKey);
|
|
7233
|
-
}
|
|
7716
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
7234
7717
|
} catch (err) {
|
|
7235
7718
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
7719
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7720
|
+
newVer = current + 1;
|
|
7236
7721
|
}
|
|
7722
|
+
} else {
|
|
7723
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7724
|
+
newVer = current + 1;
|
|
7725
|
+
}
|
|
7726
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
7727
|
+
await this._publishTagInvalidation("tag_incr", tag, newVer);
|
|
7728
|
+
return;
|
|
7729
|
+
}
|
|
7730
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
7731
|
+
const members = Array.from(this.tagIndex.get(tagKey) ?? []);
|
|
7732
|
+
this.tagIndex.delete(tagKey);
|
|
7733
|
+
this._removeTagMembersLocal(members);
|
|
7734
|
+
if (!this._redisDisabled) {
|
|
7735
|
+
try {
|
|
7736
|
+
const client = await this.getRedis();
|
|
7737
|
+
const redisMembers = await client.smembers(tagKey);
|
|
7738
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
|
|
7739
|
+
await this._deleteRedisKeys(client, toDelete);
|
|
7740
|
+
} catch (err) {
|
|
7741
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
7237
7742
|
}
|
|
7238
|
-
} catch (err) {
|
|
7239
|
-
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
7240
|
-
span.recordException?.(err);
|
|
7241
|
-
throw err;
|
|
7242
|
-
} finally {
|
|
7243
|
-
span.end();
|
|
7244
7743
|
}
|
|
7245
7744
|
}
|
|
7246
7745
|
/**
|
|
7247
|
-
*
|
|
7248
|
-
*
|
|
7249
|
-
* reducing latency when invalidating several related tags together.
|
|
7250
|
-
*
|
|
7251
|
-
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
7252
|
-
* synchronously before the Redis round-trip.
|
|
7253
|
-
*
|
|
7254
|
-
* @example
|
|
7255
|
-
* // Instead of three serial round-trips:
|
|
7256
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
7746
|
+
* Executes invalidation for an array of already-resolved concrete tags
|
|
7747
|
+
* without re-entering wildcard/cascade resolution or invalidateTag().
|
|
7257
7748
|
*/
|
|
7258
|
-
async
|
|
7259
|
-
this._assertActive("invalidateTags");
|
|
7749
|
+
async _invalidateConcreteTags(tags) {
|
|
7260
7750
|
if (tags.length === 0) return;
|
|
7261
7751
|
if (tags.length === 1) {
|
|
7262
|
-
await this.
|
|
7752
|
+
await this._invalidateConcreteTag(tags[0]);
|
|
7263
7753
|
return;
|
|
7264
7754
|
}
|
|
7265
7755
|
if (this.opts.tagStrategy === "generational") {
|
|
@@ -7274,11 +7764,7 @@ var CacheService = class _CacheService {
|
|
|
7274
7764
|
const [err, newVer] = results[i] ?? [null, null];
|
|
7275
7765
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
7276
7766
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
7277
|
-
|
|
7278
|
-
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
7279
|
-
} else {
|
|
7280
|
-
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
7281
|
-
}
|
|
7767
|
+
await this._publishTagInvalidation("tag_incr", tags[i], ver);
|
|
7282
7768
|
}
|
|
7283
7769
|
return;
|
|
7284
7770
|
} catch (err) {
|
|
@@ -7288,11 +7774,7 @@ var CacheService = class _CacheService {
|
|
|
7288
7774
|
for (const tag of tags) {
|
|
7289
7775
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
7290
7776
|
this._setLocalTagVersion(tag, ver, now);
|
|
7291
|
-
|
|
7292
|
-
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
7293
|
-
} else {
|
|
7294
|
-
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
7295
|
-
}
|
|
7777
|
+
await this._publishTagInvalidation("tag_incr", tag, ver);
|
|
7296
7778
|
}
|
|
7297
7779
|
return;
|
|
7298
7780
|
}
|
|
@@ -7305,18 +7787,7 @@ var CacheService = class _CacheService {
|
|
|
7305
7787
|
for (const k of members) allMembers.add(k);
|
|
7306
7788
|
this.tagIndex.delete(tagKey);
|
|
7307
7789
|
}
|
|
7308
|
-
|
|
7309
|
-
this.l1.delete(k);
|
|
7310
|
-
this._bumpKeyMutation(k);
|
|
7311
|
-
this._pendingDiskDeletes.add(k);
|
|
7312
|
-
setImmediate(() => {
|
|
7313
|
-
try {
|
|
7314
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
7315
|
-
} finally {
|
|
7316
|
-
this._pendingDiskDeletes.delete(k);
|
|
7317
|
-
}
|
|
7318
|
-
});
|
|
7319
|
-
}
|
|
7790
|
+
this._removeTagMembersLocal(allMembers);
|
|
7320
7791
|
if (!this._redisDisabled) {
|
|
7321
7792
|
try {
|
|
7322
7793
|
const client = await this.getRedis();
|
|
@@ -7332,12 +7803,103 @@ var CacheService = class _CacheService {
|
|
|
7332
7803
|
}
|
|
7333
7804
|
}
|
|
7334
7805
|
const keysToRemove = [...toDelete, ...tagKeys];
|
|
7335
|
-
|
|
7806
|
+
await this._deleteRedisKeys(client, keysToRemove);
|
|
7336
7807
|
} catch (err) {
|
|
7337
7808
|
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
7338
7809
|
}
|
|
7339
7810
|
}
|
|
7340
7811
|
}
|
|
7812
|
+
/**
|
|
7813
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
7814
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
7815
|
+
*
|
|
7816
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
7817
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
7818
|
+
*
|
|
7819
|
+
* @example
|
|
7820
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
7821
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7822
|
+
*
|
|
7823
|
+
* @example
|
|
7824
|
+
* // Wildcard pattern invalidation
|
|
7825
|
+
* await cache.invalidateTag('org:123:*');
|
|
7826
|
+
*
|
|
7827
|
+
* @example
|
|
7828
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
7829
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
7830
|
+
*/
|
|
7831
|
+
async invalidateTag(tag, opts) {
|
|
7832
|
+
this._assertActive("invalidateTag");
|
|
7833
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
7834
|
+
if (this.opts.tracer) {
|
|
7835
|
+
span.setAttribute("cache.tag", tag);
|
|
7836
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
7837
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
7838
|
+
}
|
|
7839
|
+
try {
|
|
7840
|
+
const isPattern = isWildcardTag(tag);
|
|
7841
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7842
|
+
if (isPattern || shouldCascade) {
|
|
7843
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
7844
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7845
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
7846
|
+
if (matchedTags.size > 0) {
|
|
7847
|
+
await this._invalidateConcreteTags(Array.from(matchedTags));
|
|
7848
|
+
}
|
|
7849
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7850
|
+
await this._publishTagInvalidation(op, broadcastPattern);
|
|
7851
|
+
return;
|
|
7852
|
+
}
|
|
7853
|
+
await this._invalidateConcreteTag(tag);
|
|
7854
|
+
} catch (err) {
|
|
7855
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
7856
|
+
span.recordException?.(err);
|
|
7857
|
+
throw err;
|
|
7858
|
+
} finally {
|
|
7859
|
+
span.end();
|
|
7860
|
+
}
|
|
7861
|
+
}
|
|
7862
|
+
/**
|
|
7863
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
7864
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
7865
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
7866
|
+
*
|
|
7867
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
7868
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
7869
|
+
*
|
|
7870
|
+
* @example
|
|
7871
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
7872
|
+
*/
|
|
7873
|
+
async invalidateTags(tags, opts) {
|
|
7874
|
+
this._assertActive("invalidateTags");
|
|
7875
|
+
if (tags.length === 0) return;
|
|
7876
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
7877
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7878
|
+
if (hasWildcards || shouldCascade) {
|
|
7879
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
7880
|
+
const broadcastPatterns = /* @__PURE__ */ new Set();
|
|
7881
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7882
|
+
for (const t of tags) {
|
|
7883
|
+
const tIsPattern = isWildcardTag(t);
|
|
7884
|
+
if (tIsPattern || shouldCascade) {
|
|
7885
|
+
broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
|
|
7886
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
7887
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
7888
|
+
} else {
|
|
7889
|
+
allResolvedTags.add(t);
|
|
7890
|
+
}
|
|
7891
|
+
}
|
|
7892
|
+
if (allResolvedTags.size > 0) {
|
|
7893
|
+
await this._invalidateConcreteTags(Array.from(allResolvedTags));
|
|
7894
|
+
}
|
|
7895
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7896
|
+
for (const pattern of broadcastPatterns) {
|
|
7897
|
+
await this._publishTagInvalidation(op, pattern);
|
|
7898
|
+
}
|
|
7899
|
+
return;
|
|
7900
|
+
}
|
|
7901
|
+
await this._invalidateConcreteTags(Array.from(new Set(tags)));
|
|
7902
|
+
}
|
|
7341
7903
|
/**
|
|
7342
7904
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
7343
7905
|
*/
|
|
@@ -7903,6 +8465,13 @@ var CacheService = class _CacheService {
|
|
|
7903
8465
|
this._destroyed = true;
|
|
7904
8466
|
this._pendingDiskDeletes.clear();
|
|
7905
8467
|
this._keyMutationEpochs.clear();
|
|
8468
|
+
this.inflight.clear();
|
|
8469
|
+
this.revalidating.clear();
|
|
8470
|
+
this._l1Counters.clear();
|
|
8471
|
+
this.tagIndex.clear();
|
|
8472
|
+
this.keyTags.clear();
|
|
8473
|
+
this.dependencyIndex.clear();
|
|
8474
|
+
this.keyDependencies.clear();
|
|
7906
8475
|
const g = globalThis;
|
|
7907
8476
|
const key = _CacheService.globalKey(this.opts);
|
|
7908
8477
|
if (g[key] === this) {
|
|
@@ -8377,6 +8946,14 @@ var NodeRedisPipelineAdapter = class {
|
|
|
8377
8946
|
}
|
|
8378
8947
|
return this;
|
|
8379
8948
|
}
|
|
8949
|
+
hgetall(key) {
|
|
8950
|
+
if (typeof this.multiInstance.hGetAll === "function") {
|
|
8951
|
+
this.multiInstance.hGetAll(key);
|
|
8952
|
+
} else {
|
|
8953
|
+
this.multiInstance.hgetall(key);
|
|
8954
|
+
}
|
|
8955
|
+
return this;
|
|
8956
|
+
}
|
|
8380
8957
|
async exec() {
|
|
8381
8958
|
const raw = await this.multiInstance.exec();
|
|
8382
8959
|
if (!raw) return null;
|
|
@@ -8518,6 +9095,15 @@ var NodeRedisAdapter = class _NodeRedisAdapter {
|
|
|
8518
9095
|
}
|
|
8519
9096
|
return void 0;
|
|
8520
9097
|
}
|
|
9098
|
+
async hgetall(key) {
|
|
9099
|
+
if (typeof this.client.hGetAll === "function") {
|
|
9100
|
+
return await this.client.hGetAll(key) ?? {};
|
|
9101
|
+
}
|
|
9102
|
+
if (typeof this.client.hgetall === "function") {
|
|
9103
|
+
return await this.client.hgetall(key) ?? {};
|
|
9104
|
+
}
|
|
9105
|
+
return {};
|
|
9106
|
+
}
|
|
8521
9107
|
async publish(channel, message) {
|
|
8522
9108
|
return await this.client.publish(channel, message);
|
|
8523
9109
|
}
|
|
@@ -9821,6 +10407,7 @@ async function startDashboardServer(options) {
|
|
|
9821
10407
|
createSigV4SnapshotAdapter,
|
|
9822
10408
|
deepMergeOptions,
|
|
9823
10409
|
defaultCodec,
|
|
10410
|
+
expandHierarchicalTags,
|
|
9824
10411
|
findActiveSockets,
|
|
9825
10412
|
formatBytes,
|
|
9826
10413
|
formatDuration,
|
|
@@ -9828,6 +10415,10 @@ async function startDashboardServer(options) {
|
|
|
9828
10415
|
formatTraceParent,
|
|
9829
10416
|
getV8HeapLimit,
|
|
9830
10417
|
handleDashboardRequest,
|
|
10418
|
+
initZstd,
|
|
10419
|
+
isChildTag,
|
|
10420
|
+
isWildcardTag,
|
|
10421
|
+
matchesTagPattern,
|
|
9831
10422
|
murmur3_32,
|
|
9832
10423
|
parseTraceParent,
|
|
9833
10424
|
readCgroupMemoryLimit,
|