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/next/index.cjs
CHANGED
|
@@ -1430,7 +1430,7 @@ var SmartMemoryCache = class {
|
|
|
1430
1430
|
};
|
|
1431
1431
|
return hit;
|
|
1432
1432
|
}
|
|
1433
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1433
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
|
|
1434
1434
|
const packed = this.codec.encode(data);
|
|
1435
1435
|
const size = packed.byteLength;
|
|
1436
1436
|
this.compressions++;
|
|
@@ -1467,7 +1467,7 @@ var SmartMemoryCache = class {
|
|
|
1467
1467
|
priority,
|
|
1468
1468
|
ttlMs,
|
|
1469
1469
|
delta,
|
|
1470
|
-
setAt: now2,
|
|
1470
|
+
setAt: setAt ?? now2,
|
|
1471
1471
|
tagVersions
|
|
1472
1472
|
});
|
|
1473
1473
|
}
|
|
@@ -1495,7 +1495,7 @@ var SmartMemoryCache = class {
|
|
|
1495
1495
|
}
|
|
1496
1496
|
const now = Date.now();
|
|
1497
1497
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1498
|
-
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 });
|
|
1498
|
+
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 });
|
|
1499
1499
|
if (!existingEntry) this.bloom.add(key);
|
|
1500
1500
|
this.maybeRebuildBloom();
|
|
1501
1501
|
this.totalSize += size;
|
|
@@ -1914,13 +1914,38 @@ var import_os2 = __toESM(require("os"), 1);
|
|
|
1914
1914
|
|
|
1915
1915
|
// src/compression.ts
|
|
1916
1916
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
1917
|
+
var import_lz4js = __toESM(require("lz4js"), 1);
|
|
1918
|
+
var import_zstd_codec = require("zstd-codec");
|
|
1917
1919
|
var PREFIX_COMPRESSED = "cmp:v1:";
|
|
1918
1920
|
var PREFIX_ENC_COMPRESSED = "ecp:v1:";
|
|
1919
1921
|
var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
|
|
1922
|
+
var zstdSimple = null;
|
|
1923
|
+
var zstdInitPromise = null;
|
|
1924
|
+
function initZstd() {
|
|
1925
|
+
if (zstdSimple) return Promise.resolve(zstdSimple);
|
|
1926
|
+
if (!zstdInitPromise) {
|
|
1927
|
+
zstdInitPromise = new Promise((resolve) => {
|
|
1928
|
+
try {
|
|
1929
|
+
import_zstd_codec.ZstdCodec.run((zstd) => {
|
|
1930
|
+
zstdSimple = new zstd.Simple();
|
|
1931
|
+
resolve(zstdSimple);
|
|
1932
|
+
});
|
|
1933
|
+
} catch {
|
|
1934
|
+
resolve(null);
|
|
1935
|
+
}
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
return zstdInitPromise;
|
|
1939
|
+
}
|
|
1940
|
+
initZstd().catch(() => {
|
|
1941
|
+
});
|
|
1920
1942
|
function isCompressed(buf) {
|
|
1921
1943
|
return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
|
|
1922
1944
|
}
|
|
1923
|
-
function compressBuffer(buf, algorithm) {
|
|
1945
|
+
function compressBuffer(buf, algorithm, custom) {
|
|
1946
|
+
if (custom) {
|
|
1947
|
+
return custom.compress(buf);
|
|
1948
|
+
}
|
|
1924
1949
|
if (algorithm === "brotli") {
|
|
1925
1950
|
return import_zlib.default.brotliCompressSync(buf, {
|
|
1926
1951
|
params: {
|
|
@@ -1932,37 +1957,127 @@ function compressBuffer(buf, algorithm) {
|
|
|
1932
1957
|
if (algorithm === "gzip") {
|
|
1933
1958
|
return import_zlib.default.gzipSync(buf, { level: 6 });
|
|
1934
1959
|
}
|
|
1960
|
+
if (algorithm === "lz4") {
|
|
1961
|
+
return Buffer.from(import_lz4js.default.compress(buf));
|
|
1962
|
+
}
|
|
1963
|
+
if (algorithm === "zstd") {
|
|
1964
|
+
if (!zstdSimple) {
|
|
1965
|
+
return import_zlib.default.brotliCompressSync(buf, {
|
|
1966
|
+
params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
return Buffer.from(zstdSimple.compress(buf));
|
|
1970
|
+
}
|
|
1935
1971
|
return buf;
|
|
1936
1972
|
}
|
|
1937
|
-
|
|
1973
|
+
var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
|
|
1974
|
+
function decompressBuffer(buf, algorithm = "zstd", custom) {
|
|
1975
|
+
if (custom) {
|
|
1976
|
+
const res = custom.decompress(buf);
|
|
1977
|
+
if (res.length > MAX_DECOMPRESS_BYTES) {
|
|
1978
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
1979
|
+
}
|
|
1980
|
+
return res;
|
|
1981
|
+
}
|
|
1982
|
+
const checkSafety = (decomp) => {
|
|
1983
|
+
if (decomp.length > MAX_DECOMPRESS_BYTES) {
|
|
1984
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
1985
|
+
}
|
|
1986
|
+
return decomp;
|
|
1987
|
+
};
|
|
1988
|
+
if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
|
|
1989
|
+
if (zstdSimple) {
|
|
1990
|
+
try {
|
|
1991
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
1992
|
+
} catch (err) {
|
|
1993
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
|
|
1998
|
+
try {
|
|
1999
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2000
|
+
} catch (err) {
|
|
2001
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
|
|
2005
|
+
try {
|
|
2006
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2007
|
+
} catch (err) {
|
|
2008
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2009
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
if (algorithm === "none") {
|
|
2014
|
+
return buf;
|
|
2015
|
+
}
|
|
2016
|
+
if (algorithm === "lz4") {
|
|
2017
|
+
try {
|
|
2018
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2019
|
+
} catch (err) {
|
|
2020
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
if (algorithm === "zstd" && zstdSimple) {
|
|
2024
|
+
try {
|
|
2025
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2026
|
+
} catch (err) {
|
|
2027
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
1938
2030
|
const tryBrotli = () => {
|
|
1939
2031
|
try {
|
|
1940
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1941
|
-
} catch {
|
|
2032
|
+
return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2033
|
+
} catch (err) {
|
|
2034
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2035
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2036
|
+
}
|
|
1942
2037
|
return null;
|
|
1943
2038
|
}
|
|
1944
2039
|
};
|
|
1945
2040
|
const tryGzip = () => {
|
|
1946
2041
|
try {
|
|
1947
|
-
return import_zlib.default.gunzipSync(buf);
|
|
1948
|
-
} catch {
|
|
2042
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2043
|
+
} catch (err) {
|
|
2044
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2045
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2046
|
+
}
|
|
2047
|
+
return null;
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
const tryLz4 = () => {
|
|
2051
|
+
try {
|
|
2052
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2053
|
+
} catch (err) {
|
|
2054
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2055
|
+
return null;
|
|
2056
|
+
}
|
|
2057
|
+
};
|
|
2058
|
+
const tryZstd = () => {
|
|
2059
|
+
if (!zstdSimple) return null;
|
|
2060
|
+
try {
|
|
2061
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2062
|
+
} catch (err) {
|
|
2063
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
1949
2064
|
return null;
|
|
1950
2065
|
}
|
|
1951
2066
|
};
|
|
1952
|
-
const result = algorithm === "gzip" ? tryGzip() ??
|
|
2067
|
+
const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
|
|
1953
2068
|
if (result === null) {
|
|
1954
2069
|
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
1955
2070
|
}
|
|
1956
2071
|
return result;
|
|
1957
2072
|
}
|
|
1958
|
-
function compressWithHeader(buf, algorithm) {
|
|
2073
|
+
function compressWithHeader(buf, algorithm, custom) {
|
|
1959
2074
|
if (algorithm === "none") return buf;
|
|
1960
|
-
const compressed = compressBuffer(buf, algorithm);
|
|
2075
|
+
const compressed = compressBuffer(buf, algorithm, custom);
|
|
1961
2076
|
return Buffer.concat([COMPRESSION_MAGIC, compressed]);
|
|
1962
2077
|
}
|
|
1963
|
-
function decompressWithHeader(buf, algorithm = "
|
|
2078
|
+
function decompressWithHeader(buf, algorithm = "zstd", custom) {
|
|
1964
2079
|
if (isCompressed(buf)) {
|
|
1965
|
-
return decompressBuffer(buf.subarray(4), algorithm);
|
|
2080
|
+
return decompressBuffer(buf.subarray(4), algorithm, custom);
|
|
1966
2081
|
}
|
|
1967
2082
|
return buf;
|
|
1968
2083
|
}
|
|
@@ -3577,6 +3692,55 @@ var IpcTelemetryServer = class {
|
|
|
3577
3692
|
}
|
|
3578
3693
|
};
|
|
3579
3694
|
|
|
3695
|
+
// src/utils/tag-matcher.ts
|
|
3696
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
3697
|
+
function isWildcardTag(tag) {
|
|
3698
|
+
return tag.includes("*") || tag.includes("?");
|
|
3699
|
+
}
|
|
3700
|
+
function matchesTagPattern(pattern, tag) {
|
|
3701
|
+
if (pattern === "*" || pattern === tag) return true;
|
|
3702
|
+
if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
|
|
3703
|
+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
|
|
3704
|
+
const prefix = pattern.slice(0, -1);
|
|
3705
|
+
return tag.startsWith(prefix);
|
|
3706
|
+
}
|
|
3707
|
+
if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
|
|
3708
|
+
const suffix = pattern.slice(1);
|
|
3709
|
+
return tag.endsWith(suffix);
|
|
3710
|
+
}
|
|
3711
|
+
let re = globRegexCache.get(pattern);
|
|
3712
|
+
if (!re) {
|
|
3713
|
+
if (globRegexCache.size >= 1e3) globRegexCache.clear();
|
|
3714
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
3715
|
+
re = new RegExp(`^${escaped}$`);
|
|
3716
|
+
globRegexCache.set(pattern, re);
|
|
3717
|
+
}
|
|
3718
|
+
return re.test(tag);
|
|
3719
|
+
}
|
|
3720
|
+
function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
3721
|
+
if (candidateTag === parentTag) return true;
|
|
3722
|
+
const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
|
|
3723
|
+
return candidateTag.startsWith(prefix);
|
|
3724
|
+
}
|
|
3725
|
+
function expandHierarchicalTags(tags, delimiter = ":") {
|
|
3726
|
+
if (!tags.length) return [];
|
|
3727
|
+
const result = /* @__PURE__ */ new Set();
|
|
3728
|
+
for (const tag of tags) {
|
|
3729
|
+
if (!tag) continue;
|
|
3730
|
+
const parts = tag.split(delimiter).filter((p) => p.length > 0);
|
|
3731
|
+
if (parts.length <= 1) {
|
|
3732
|
+
result.add(tag);
|
|
3733
|
+
continue;
|
|
3734
|
+
}
|
|
3735
|
+
let accumulated = "";
|
|
3736
|
+
for (let i = 0; i < parts.length; i++) {
|
|
3737
|
+
accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
|
|
3738
|
+
result.add(accumulated);
|
|
3739
|
+
}
|
|
3740
|
+
}
|
|
3741
|
+
return Array.from(result);
|
|
3742
|
+
}
|
|
3743
|
+
|
|
3580
3744
|
// src/cache-service.ts
|
|
3581
3745
|
var LUA_COMPARE_AND_DELETE = `
|
|
3582
3746
|
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
@@ -3595,21 +3759,21 @@ var DEFAULT_CATEGORY_LIMITS = {
|
|
|
3595
3759
|
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3596
3760
|
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3597
3761
|
var GLOB_REGEX_CACHE_MAX = 256;
|
|
3598
|
-
var
|
|
3762
|
+
var globRegexCache2 = /* @__PURE__ */ new Map();
|
|
3599
3763
|
function getGlobRegex(pattern) {
|
|
3600
|
-
let re =
|
|
3764
|
+
let re = globRegexCache2.get(pattern);
|
|
3601
3765
|
if (re) {
|
|
3602
|
-
|
|
3603
|
-
|
|
3766
|
+
globRegexCache2.delete(pattern);
|
|
3767
|
+
globRegexCache2.set(pattern, re);
|
|
3604
3768
|
return re;
|
|
3605
3769
|
}
|
|
3606
3770
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3607
3771
|
re = new RegExp("^" + escaped + "$");
|
|
3608
|
-
if (
|
|
3609
|
-
const oldestKey =
|
|
3610
|
-
if (oldestKey !== void 0)
|
|
3772
|
+
if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3773
|
+
const oldestKey = globRegexCache2.keys().next().value;
|
|
3774
|
+
if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
|
|
3611
3775
|
}
|
|
3612
|
-
|
|
3776
|
+
globRegexCache2.set(pattern, re);
|
|
3613
3777
|
return re;
|
|
3614
3778
|
}
|
|
3615
3779
|
var L2CircuitBreaker = class {
|
|
@@ -3863,6 +4027,7 @@ var CacheService = class _CacheService {
|
|
|
3863
4027
|
opts;
|
|
3864
4028
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
3865
4029
|
_namespace;
|
|
4030
|
+
prefixLen;
|
|
3866
4031
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
3867
4032
|
_redisDisabled;
|
|
3868
4033
|
watchdog;
|
|
@@ -3872,6 +4037,8 @@ var CacheService = class _CacheService {
|
|
|
3872
4037
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
3873
4038
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
3874
4039
|
tagIndex = /* @__PURE__ */ new Map();
|
|
4040
|
+
/** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
|
|
4041
|
+
keyTags = /* @__PURE__ */ new Map();
|
|
3875
4042
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
3876
4043
|
tagVersions = /* @__PURE__ */ new Map();
|
|
3877
4044
|
/**
|
|
@@ -3879,6 +4046,9 @@ var CacheService = class _CacheService {
|
|
|
3879
4046
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
3880
4047
|
*/
|
|
3881
4048
|
dependencyIndex = /* @__PURE__ */ new Map();
|
|
4049
|
+
/** Reverse index of namespaced dependent key → source glob patterns */
|
|
4050
|
+
keyDependencies = /* @__PURE__ */ new Map();
|
|
4051
|
+
_cgroupMemoryLimit;
|
|
3882
4052
|
redis = null;
|
|
3883
4053
|
redisConnecting = null;
|
|
3884
4054
|
cb;
|
|
@@ -3948,6 +4118,84 @@ var CacheService = class _CacheService {
|
|
|
3948
4118
|
_getKeyMutationEpoch(namespacedKey) {
|
|
3949
4119
|
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
3950
4120
|
}
|
|
4121
|
+
_removeKeyTags(namespacedKey) {
|
|
4122
|
+
const entry = this.keyTags.get(namespacedKey);
|
|
4123
|
+
if (!entry) return;
|
|
4124
|
+
for (const tag of entry.tags) {
|
|
4125
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4126
|
+
const members = this.tagIndex.get(tagKey);
|
|
4127
|
+
if (members) {
|
|
4128
|
+
members.delete(namespacedKey);
|
|
4129
|
+
if (members.size === 0) this.tagIndex.delete(tagKey);
|
|
4130
|
+
}
|
|
4131
|
+
}
|
|
4132
|
+
this.keyTags.delete(namespacedKey);
|
|
4133
|
+
}
|
|
4134
|
+
_removeKeyDependencies(namespacedKey) {
|
|
4135
|
+
const patterns = this.keyDependencies.get(namespacedKey);
|
|
4136
|
+
if (patterns) {
|
|
4137
|
+
for (const pat of patterns) {
|
|
4138
|
+
const deps = this.dependencyIndex.get(pat);
|
|
4139
|
+
if (deps) {
|
|
4140
|
+
deps.delete(namespacedKey);
|
|
4141
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
this.keyDependencies.delete(namespacedKey);
|
|
4145
|
+
} else if (this.dependencyIndex.size > 0) {
|
|
4146
|
+
for (const [pat, deps] of this.dependencyIndex) {
|
|
4147
|
+
deps.delete(namespacedKey);
|
|
4148
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
4149
|
+
}
|
|
4150
|
+
}
|
|
4151
|
+
}
|
|
4152
|
+
_handleL1Eviction(namespacedKey, reason) {
|
|
4153
|
+
const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
4154
|
+
if (!spilledToDisk) {
|
|
4155
|
+
this._removeKeyTags(namespacedKey);
|
|
4156
|
+
this._removeKeyDependencies(namespacedKey);
|
|
4157
|
+
}
|
|
4158
|
+
}
|
|
4159
|
+
_removePrefixFromIndices(prefix) {
|
|
4160
|
+
for (const k of Array.from(this.keyTags.keys())) {
|
|
4161
|
+
if (k.startsWith(prefix)) this._removeKeyTags(k);
|
|
4162
|
+
}
|
|
4163
|
+
for (const k of Array.from(this.keyDependencies.keys())) {
|
|
4164
|
+
if (k.startsWith(prefix)) this._removeKeyDependencies(k);
|
|
4165
|
+
}
|
|
4166
|
+
for (const k of Array.from(this._l1Counters.keys())) {
|
|
4167
|
+
if (k.startsWith(prefix)) this._l1Counters.delete(k);
|
|
4168
|
+
}
|
|
4169
|
+
}
|
|
4170
|
+
_sweepExpiredMetadata() {
|
|
4171
|
+
const now = Date.now();
|
|
4172
|
+
for (const [k, c] of this._l1Counters) {
|
|
4173
|
+
if (c.expiresAt <= now) this._l1Counters.delete(k);
|
|
4174
|
+
}
|
|
4175
|
+
for (const [k, meta] of this.keyTags) {
|
|
4176
|
+
if (meta.expiresAt <= now && !this.l1.has(k)) {
|
|
4177
|
+
this._removeKeyTags(k);
|
|
4178
|
+
this._removeKeyDependencies(k);
|
|
4179
|
+
}
|
|
4180
|
+
}
|
|
4181
|
+
}
|
|
4182
|
+
_runOomCheck() {
|
|
4183
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
4184
|
+
const heapUsed = heap.used_heap_size / heap.heap_size_limit;
|
|
4185
|
+
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
|
|
4186
|
+
const used = Math.max(heapUsed, cgroupUsed);
|
|
4187
|
+
if (used >= this.opts.oomHeapThreshold) {
|
|
4188
|
+
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4189
|
+
this.counters.oomEvictions++;
|
|
4190
|
+
this.counters.oomLastAt = Date.now();
|
|
4191
|
+
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4192
|
+
heapUsedPct: Math.round(heapUsed * 100),
|
|
4193
|
+
cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
|
|
4194
|
+
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4195
|
+
evicted
|
|
4196
|
+
});
|
|
4197
|
+
}
|
|
4198
|
+
}
|
|
3951
4199
|
_ipcServer;
|
|
3952
4200
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
3953
4201
|
_subDisconnectedAt = null;
|
|
@@ -3994,6 +4242,7 @@ var CacheService = class _CacheService {
|
|
|
3994
4242
|
constructor(options = {}) {
|
|
3995
4243
|
const logger = options.logger ?? consoleLogger;
|
|
3996
4244
|
this.logger = logger;
|
|
4245
|
+
this._cgroupMemoryLimit = readCgroupMemoryLimit();
|
|
3997
4246
|
const ns = options.namespace?.trim() ?? "";
|
|
3998
4247
|
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
3999
4248
|
this.enc = new CacheEncryption(
|
|
@@ -4071,12 +4320,15 @@ var CacheService = class _CacheService {
|
|
|
4071
4320
|
redisSentinel: options.redisSentinel,
|
|
4072
4321
|
redisProtocol: options.redisProtocol,
|
|
4073
4322
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
4074
|
-
compression: options.compression ?? "
|
|
4323
|
+
compression: options.compression ?? "zstd",
|
|
4324
|
+
customCompressor: options.customCompressor,
|
|
4075
4325
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
4076
4326
|
strictSingleton: options.strictSingleton ?? false,
|
|
4077
4327
|
failClosed: options.failClosed ?? false,
|
|
4078
4328
|
tagStrategy: options.tagStrategy ?? "set",
|
|
4079
4329
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
4330
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
4331
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
4080
4332
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
4081
4333
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
4082
4334
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4149,6 +4401,7 @@ var CacheService = class _CacheService {
|
|
|
4149
4401
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4150
4402
|
});
|
|
4151
4403
|
this._namespace = ns;
|
|
4404
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4152
4405
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4153
4406
|
this.watchdog = new TierLatencyWatchdog({
|
|
4154
4407
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4173,7 +4426,10 @@ var CacheService = class _CacheService {
|
|
|
4173
4426
|
void this.disk.save(key, entry);
|
|
4174
4427
|
});
|
|
4175
4428
|
},
|
|
4176
|
-
onEviction:
|
|
4429
|
+
onEviction: (key, reason) => {
|
|
4430
|
+
this._handleL1Eviction(key, reason);
|
|
4431
|
+
options.onEviction?.(key, reason);
|
|
4432
|
+
},
|
|
4177
4433
|
logger
|
|
4178
4434
|
});
|
|
4179
4435
|
if (!this.snapshotLoaded) {
|
|
@@ -4211,6 +4467,7 @@ var CacheService = class _CacheService {
|
|
|
4211
4467
|
}
|
|
4212
4468
|
this.cleanupInterval = setInterval(() => {
|
|
4213
4469
|
const cleaned = this.l1.cleanup();
|
|
4470
|
+
this._sweepExpiredMetadata();
|
|
4214
4471
|
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
4215
4472
|
}, 5 * 60 * 1e3);
|
|
4216
4473
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
@@ -4223,18 +4480,7 @@ var CacheService = class _CacheService {
|
|
|
4223
4480
|
}
|
|
4224
4481
|
if (this.opts.oomProtection) {
|
|
4225
4482
|
this.oomInterval = setInterval(() => {
|
|
4226
|
-
|
|
4227
|
-
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
4228
|
-
if (used >= this.opts.oomHeapThreshold) {
|
|
4229
|
-
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4230
|
-
this.counters.oomEvictions++;
|
|
4231
|
-
this.counters.oomLastAt = Date.now();
|
|
4232
|
-
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4233
|
-
heapUsedPct: Math.round(used * 100),
|
|
4234
|
-
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4235
|
-
evicted
|
|
4236
|
-
});
|
|
4237
|
-
}
|
|
4483
|
+
this._runOomCheck();
|
|
4238
4484
|
}, this.opts.oomCheckIntervalMs);
|
|
4239
4485
|
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
4240
4486
|
}
|
|
@@ -4258,6 +4504,9 @@ var CacheService = class _CacheService {
|
|
|
4258
4504
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4259
4505
|
this.initBackplane();
|
|
4260
4506
|
const startupPromises = [];
|
|
4507
|
+
if (this.opts.compression === "zstd") {
|
|
4508
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4509
|
+
}
|
|
4261
4510
|
if (this.opts.remoteSnapshot) {
|
|
4262
4511
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4263
4512
|
}
|
|
@@ -4706,7 +4955,7 @@ var CacheService = class _CacheService {
|
|
|
4706
4955
|
else if (f === "src") src = v;
|
|
4707
4956
|
else if (f === "tagVersion") tagVersionRaw = v;
|
|
4708
4957
|
}
|
|
4709
|
-
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
4958
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
|
|
4710
4959
|
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
4711
4960
|
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
4712
4961
|
op: String(op).slice(0, 40),
|
|
@@ -4763,6 +5012,50 @@ var CacheService = class _CacheService {
|
|
|
4763
5012
|
const tag = key;
|
|
4764
5013
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4765
5014
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
5015
|
+
} else if (op === "tag_pattern_incr") {
|
|
5016
|
+
const pattern = key;
|
|
5017
|
+
const now = performance.now();
|
|
5018
|
+
for (const [tag, info] of this.tagVersions) {
|
|
5019
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5020
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
5021
|
+
}
|
|
5022
|
+
}
|
|
5023
|
+
this.l1.scan((k, entry) => {
|
|
5024
|
+
if (entry.tagVersions) {
|
|
5025
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
5026
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5027
|
+
this.l1.delete(k);
|
|
5028
|
+
this._bumpKeyMutation(k);
|
|
5029
|
+
break;
|
|
5030
|
+
}
|
|
5031
|
+
}
|
|
5032
|
+
}
|
|
5033
|
+
}, 0);
|
|
5034
|
+
} else if (op === "tag_pattern_del") {
|
|
5035
|
+
const pattern = key;
|
|
5036
|
+
const matchedTagKeys = [];
|
|
5037
|
+
const prefix = this.nk("_tag_:");
|
|
5038
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
5039
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
5040
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5041
|
+
matchedTagKeys.push(tagKey);
|
|
5042
|
+
for (const k of members) {
|
|
5043
|
+
this.l1.delete(k);
|
|
5044
|
+
this._bumpKeyMutation(k);
|
|
5045
|
+
this._pendingDiskDeletes.add(k);
|
|
5046
|
+
setImmediate(() => {
|
|
5047
|
+
try {
|
|
5048
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5049
|
+
} finally {
|
|
5050
|
+
this._pendingDiskDeletes.delete(k);
|
|
5051
|
+
}
|
|
5052
|
+
});
|
|
5053
|
+
}
|
|
5054
|
+
}
|
|
5055
|
+
}
|
|
5056
|
+
for (const tagKey of matchedTagKeys) {
|
|
5057
|
+
this.tagIndex.delete(tagKey);
|
|
5058
|
+
}
|
|
4766
5059
|
}
|
|
4767
5060
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4768
5061
|
}
|
|
@@ -4770,7 +5063,7 @@ var CacheService = class _CacheService {
|
|
|
4770
5063
|
_handleBackplaneMessage(message) {
|
|
4771
5064
|
try {
|
|
4772
5065
|
const msg = JSON.parse(message);
|
|
4773
|
-
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") {
|
|
5066
|
+
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") {
|
|
4774
5067
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4775
5068
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4776
5069
|
});
|
|
@@ -4924,6 +5217,72 @@ var CacheService = class _CacheService {
|
|
|
4924
5217
|
}
|
|
4925
5218
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
4926
5219
|
}
|
|
5220
|
+
async _isGenerationalEntryStale(tagVersions) {
|
|
5221
|
+
if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
|
|
5222
|
+
const tags = Object.keys(tagVersions);
|
|
5223
|
+
if (tags.length === 0) return false;
|
|
5224
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5225
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5226
|
+
if (currentVers[i] > tagVersions[tags[i]]) return true;
|
|
5227
|
+
}
|
|
5228
|
+
return false;
|
|
5229
|
+
}
|
|
5230
|
+
async _deleteRedisKeys(client, keys) {
|
|
5231
|
+
if (keys.length === 0) return;
|
|
5232
|
+
const CHUNK_SIZE = 1e3;
|
|
5233
|
+
if (client instanceof import_ioredis.Cluster) {
|
|
5234
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
5235
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
5236
|
+
const pl = client.pipeline();
|
|
5237
|
+
for (const k of chunk) pl.del(k);
|
|
5238
|
+
await pl.exec();
|
|
5239
|
+
}
|
|
5240
|
+
return;
|
|
5241
|
+
}
|
|
5242
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
5243
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
5244
|
+
await client.del(...chunk);
|
|
5245
|
+
}
|
|
5246
|
+
}
|
|
5247
|
+
async _parseGenerationalRedisHash(k, hashData) {
|
|
5248
|
+
if (!hashData || !hashData.d) return null;
|
|
5249
|
+
let storedTagVersions = {};
|
|
5250
|
+
if (hashData.tv) {
|
|
5251
|
+
try {
|
|
5252
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5253
|
+
} catch {
|
|
5254
|
+
}
|
|
5255
|
+
}
|
|
5256
|
+
if (await this._isGenerationalEntryStale(storedTagVersions)) {
|
|
5257
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5258
|
+
this._deleteIfStale(k, setAtMs);
|
|
5259
|
+
return { stale: true };
|
|
5260
|
+
}
|
|
5261
|
+
const value = await this._decryptAndDeserialize(hashData.d);
|
|
5262
|
+
return { value, tagVersions: storedTagVersions, stale: false };
|
|
5263
|
+
}
|
|
5264
|
+
async _readRedisEntry(client, k, allowAutoPipeline = false) {
|
|
5265
|
+
if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
|
|
5266
|
+
try {
|
|
5267
|
+
const hashData = await client.hgetall(k);
|
|
5268
|
+
if (typeof hashData === "string") {
|
|
5269
|
+
const value2 = await this._decryptAndDeserialize(hashData);
|
|
5270
|
+
return { value: value2, stale: false };
|
|
5271
|
+
}
|
|
5272
|
+
if (hashData && hashData.d) {
|
|
5273
|
+
return await this._parseGenerationalRedisHash(k, hashData);
|
|
5274
|
+
}
|
|
5275
|
+
return null;
|
|
5276
|
+
} catch (err) {
|
|
5277
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
5278
|
+
if (!msg.includes("WRONGTYPE")) throw err;
|
|
5279
|
+
}
|
|
5280
|
+
}
|
|
5281
|
+
const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5282
|
+
if (raw == null) return null;
|
|
5283
|
+
const value = await this._decryptAndDeserialize(raw);
|
|
5284
|
+
return { value, stale: false };
|
|
5285
|
+
}
|
|
4927
5286
|
async _getTagVersion(tag) {
|
|
4928
5287
|
const now = performance.now();
|
|
4929
5288
|
const local = this.tagVersions.get(tag);
|
|
@@ -4957,12 +5316,12 @@ var CacheService = class _CacheService {
|
|
|
4957
5316
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
4958
5317
|
*/
|
|
4959
5318
|
async _serializeAndEncrypt(serialized) {
|
|
4960
|
-
const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
4961
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5319
|
+
const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
5320
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4962
5321
|
return this._workerPool.encrypt(serialized);
|
|
4963
5322
|
}
|
|
4964
5323
|
if (isCompressed2) {
|
|
4965
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
5324
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
4966
5325
|
if (this.enc.isEnabled) {
|
|
4967
5326
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
4968
5327
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -4977,16 +5336,16 @@ var CacheService = class _CacheService {
|
|
|
4977
5336
|
*/
|
|
4978
5337
|
async _decryptAndDeserialize(raw) {
|
|
4979
5338
|
let plain;
|
|
4980
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
5339
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
4981
5340
|
plain = await this._workerPool.decrypt(raw);
|
|
4982
5341
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
4983
5342
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
4984
5343
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
4985
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5344
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4986
5345
|
plain = decompressed.toString("utf8");
|
|
4987
5346
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
4988
5347
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
4989
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5348
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4990
5349
|
plain = decompressed.toString("utf8");
|
|
4991
5350
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
4992
5351
|
plain = this.enc.decrypt(raw);
|
|
@@ -5061,8 +5420,8 @@ var CacheService = class _CacheService {
|
|
|
5061
5420
|
return client;
|
|
5062
5421
|
}
|
|
5063
5422
|
this.redisConnecting = (async () => {
|
|
5423
|
+
let client = null;
|
|
5064
5424
|
try {
|
|
5065
|
-
let client;
|
|
5066
5425
|
if (this.opts.redisClusterNodes?.length) {
|
|
5067
5426
|
client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
5068
5427
|
redisOptions: {
|
|
@@ -5125,14 +5484,45 @@ var CacheService = class _CacheService {
|
|
|
5125
5484
|
});
|
|
5126
5485
|
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
5127
5486
|
}
|
|
5487
|
+
const pendingClient = client;
|
|
5128
5488
|
await new Promise((resolve, reject) => {
|
|
5129
|
-
|
|
5130
|
-
|
|
5489
|
+
let settled = false;
|
|
5490
|
+
const cleanupListeners = () => {
|
|
5491
|
+
pendingClient.removeListener?.("ready", onReady);
|
|
5492
|
+
pendingClient.removeListener?.("error", onError);
|
|
5493
|
+
};
|
|
5494
|
+
const onReady = () => {
|
|
5495
|
+
if (settled) return;
|
|
5496
|
+
settled = true;
|
|
5497
|
+
clearTimeout(timer);
|
|
5498
|
+
cleanupListeners();
|
|
5499
|
+
resolve();
|
|
5500
|
+
};
|
|
5501
|
+
const onError = (e) => {
|
|
5502
|
+
if (settled) return;
|
|
5503
|
+
settled = true;
|
|
5504
|
+
clearTimeout(timer);
|
|
5505
|
+
cleanupListeners();
|
|
5131
5506
|
this._checkAndLogResp3Hint(e);
|
|
5132
5507
|
reject(e);
|
|
5133
|
-
}
|
|
5134
|
-
setTimeout(() =>
|
|
5508
|
+
};
|
|
5509
|
+
const timer = setTimeout(() => {
|
|
5510
|
+
if (settled) return;
|
|
5511
|
+
settled = true;
|
|
5512
|
+
cleanupListeners();
|
|
5513
|
+
reject(new Error("Redis connection timeout"));
|
|
5514
|
+
}, 15e3);
|
|
5515
|
+
if (timer.unref) timer.unref();
|
|
5516
|
+
pendingClient.once("ready", onReady);
|
|
5517
|
+
pendingClient.once("error", onError);
|
|
5135
5518
|
});
|
|
5519
|
+
if (this._destroyed) {
|
|
5520
|
+
try {
|
|
5521
|
+
client.disconnect();
|
|
5522
|
+
} catch {
|
|
5523
|
+
}
|
|
5524
|
+
this._assertActive("getRedis");
|
|
5525
|
+
}
|
|
5136
5526
|
this.cb.onSuccess();
|
|
5137
5527
|
this.redis = client;
|
|
5138
5528
|
this.pipeliner = new AutoPipeliner(client, {
|
|
@@ -5142,6 +5532,10 @@ var CacheService = class _CacheService {
|
|
|
5142
5532
|
this.redisConnecting = null;
|
|
5143
5533
|
return client;
|
|
5144
5534
|
} catch (err) {
|
|
5535
|
+
try {
|
|
5536
|
+
client?.disconnect();
|
|
5537
|
+
} catch {
|
|
5538
|
+
}
|
|
5145
5539
|
this.cb.onFailure();
|
|
5146
5540
|
this.redisConnecting = null;
|
|
5147
5541
|
this._checkAndLogResp3Hint(err);
|
|
@@ -5382,20 +5776,10 @@ var CacheService = class _CacheService {
|
|
|
5382
5776
|
const optRefreshAhead = opts.refreshAhead;
|
|
5383
5777
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5384
5778
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5385
|
-
const optTags = opts.tags;
|
|
5779
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5386
5780
|
const l1Hit = this.l1.get(k);
|
|
5387
5781
|
if (l1Hit !== null) {
|
|
5388
|
-
|
|
5389
|
-
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
5390
|
-
const tags = Object.keys(l1Hit.tagVersions);
|
|
5391
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5392
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5393
|
-
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
5394
|
-
isGenerationalStale = true;
|
|
5395
|
-
break;
|
|
5396
|
-
}
|
|
5397
|
-
}
|
|
5398
|
-
}
|
|
5782
|
+
const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
|
|
5399
5783
|
if (isGenerationalStale) {
|
|
5400
5784
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
5401
5785
|
} else {
|
|
@@ -5481,17 +5865,7 @@ var CacheService = class _CacheService {
|
|
|
5481
5865
|
this.watchdog.recordDisk(diskElapsed);
|
|
5482
5866
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5483
5867
|
if (diskHit !== null) {
|
|
5484
|
-
|
|
5485
|
-
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5486
|
-
const tags = Object.keys(diskHit.tagVersions);
|
|
5487
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5488
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5489
|
-
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5490
|
-
isDiskStale = true;
|
|
5491
|
-
break;
|
|
5492
|
-
}
|
|
5493
|
-
}
|
|
5494
|
-
}
|
|
5868
|
+
const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
|
|
5495
5869
|
if (isDiskStale) {
|
|
5496
5870
|
this.disk.delete(k);
|
|
5497
5871
|
} else {
|
|
@@ -5519,57 +5893,27 @@ var CacheService = class _CacheService {
|
|
|
5519
5893
|
try {
|
|
5520
5894
|
const client = await this.getRedis();
|
|
5521
5895
|
const redisStart = performance.now();
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
|
|
5528
|
-
|
|
5529
|
-
|
|
5530
|
-
|
|
5531
|
-
|
|
5532
|
-
|
|
5533
|
-
|
|
5534
|
-
|
|
5535
|
-
}
|
|
5536
|
-
const tags = Object.keys(storedTagVersions);
|
|
5537
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5538
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5539
|
-
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5540
|
-
isStale = true;
|
|
5541
|
-
break;
|
|
5542
|
-
}
|
|
5543
|
-
}
|
|
5544
|
-
if (isStale) {
|
|
5545
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5546
|
-
this._deleteIfStale(k, setAtMs);
|
|
5547
|
-
} else {
|
|
5548
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5549
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5550
|
-
this.counters.l2Hits++;
|
|
5551
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
5552
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5553
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5554
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
5555
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5556
|
-
}
|
|
5557
|
-
}
|
|
5558
|
-
} else {
|
|
5559
|
-
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5560
|
-
const redisElapsed = performance.now() - redisStart;
|
|
5561
|
-
this.watchdog.recordRedis(redisElapsed);
|
|
5562
|
-
this.cb.onSuccess();
|
|
5563
|
-
if (raw) {
|
|
5564
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
5565
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
5566
|
-
this.counters.l2Hits++;
|
|
5567
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
5568
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5569
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5570
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
5571
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5896
|
+
const redisHit = await this._readRedisEntry(client, k, true);
|
|
5897
|
+
const redisElapsed = performance.now() - redisStart;
|
|
5898
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
5899
|
+
this.cb.onSuccess();
|
|
5900
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
5901
|
+
const parsed = redisHit.value;
|
|
5902
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5903
|
+
this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
|
|
5904
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5905
|
+
const current = this.l1.get(k);
|
|
5906
|
+
const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
|
|
5907
|
+
if (this.opts.frozen) deepFreeze(liveVal);
|
|
5908
|
+
return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
|
|
5572
5909
|
}
|
|
5910
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
|
|
5911
|
+
this.counters.l2Hits++;
|
|
5912
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
5913
|
+
this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
|
|
5914
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5915
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
5916
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5573
5917
|
}
|
|
5574
5918
|
} catch (err) {
|
|
5575
5919
|
this.cb.onFailure();
|
|
@@ -5631,20 +5975,20 @@ var CacheService = class _CacheService {
|
|
|
5631
5975
|
if (this.opts.frozen) deepFreeze(data);
|
|
5632
5976
|
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5633
5977
|
}
|
|
5634
|
-
|
|
5978
|
+
const writeTs = Date.now();
|
|
5979
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
5635
5980
|
if (!this._redisDisabled) {
|
|
5636
5981
|
try {
|
|
5637
5982
|
const client = await this.getRedis();
|
|
5638
5983
|
const serialized = JSON.stringify(data);
|
|
5639
5984
|
const toStore = await this._serializeAndEncrypt(serialized);
|
|
5640
5985
|
const ttlSec = Math.ceil(effectiveTtl / 1e3);
|
|
5641
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5642
|
-
const now = Date.now();
|
|
5986
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5643
5987
|
const tx = client.multi();
|
|
5644
5988
|
tx.hset(k, {
|
|
5645
5989
|
d: toStore,
|
|
5646
|
-
t: String(
|
|
5647
|
-
tv: JSON.stringify(activeTagVersions)
|
|
5990
|
+
t: String(writeTs),
|
|
5991
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5648
5992
|
});
|
|
5649
5993
|
tx.expire(k, ttlSec);
|
|
5650
5994
|
await tx.exec();
|
|
@@ -5782,20 +6126,20 @@ var CacheService = class _CacheService {
|
|
|
5782
6126
|
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5783
6127
|
return;
|
|
5784
6128
|
}
|
|
5785
|
-
|
|
6129
|
+
const writeTs = Date.now();
|
|
6130
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
5786
6131
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5787
6132
|
try {
|
|
5788
6133
|
const client = await this.getRedis();
|
|
5789
6134
|
const s = JSON.stringify(data);
|
|
5790
6135
|
const stored = await this._serializeAndEncrypt(s);
|
|
5791
6136
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5792
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5793
|
-
const now = Date.now();
|
|
6137
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5794
6138
|
const tx = client.multi();
|
|
5795
6139
|
tx.hset(cacheKey, {
|
|
5796
6140
|
d: stored,
|
|
5797
|
-
t: String(
|
|
5798
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6141
|
+
t: String(writeTs),
|
|
6142
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5799
6143
|
});
|
|
5800
6144
|
tx.expire(cacheKey, ttlSec);
|
|
5801
6145
|
await tx.exec();
|
|
@@ -5840,27 +6184,35 @@ var CacheService = class _CacheService {
|
|
|
5840
6184
|
this._pendingDiskDeletes.delete(k);
|
|
5841
6185
|
this.counters.sets++;
|
|
5842
6186
|
let activeTagVersions;
|
|
5843
|
-
|
|
6187
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
6188
|
+
if (tagsToRegister?.length) {
|
|
5844
6189
|
if (this.opts.tagStrategy === "generational") {
|
|
5845
|
-
const vers = await Promise.all(
|
|
6190
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5846
6191
|
activeTagVersions = {};
|
|
5847
|
-
for (let i = 0; i <
|
|
5848
|
-
activeTagVersions[
|
|
6192
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
6193
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5849
6194
|
}
|
|
5850
6195
|
} else {
|
|
5851
|
-
await this._registerTags(k,
|
|
6196
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5852
6197
|
}
|
|
5853
6198
|
}
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
this.
|
|
6199
|
+
const writeTs = Date.now();
|
|
6200
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
|
|
6201
|
+
if (opts?.dependsOn !== void 0) {
|
|
6202
|
+
this._removeKeyDependencies(k);
|
|
6203
|
+
if (opts.dependsOn.length > 0) {
|
|
6204
|
+
const nsPatterns = [];
|
|
6205
|
+
for (const pattern of opts.dependsOn) {
|
|
6206
|
+
const nsPattern = this.nk(pattern);
|
|
6207
|
+
nsPatterns.push(nsPattern);
|
|
6208
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
6209
|
+
if (!deps) {
|
|
6210
|
+
deps = /* @__PURE__ */ new Set();
|
|
6211
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
6212
|
+
}
|
|
6213
|
+
deps.add(k);
|
|
5862
6214
|
}
|
|
5863
|
-
|
|
6215
|
+
this.keyDependencies.set(k, nsPatterns);
|
|
5864
6216
|
}
|
|
5865
6217
|
}
|
|
5866
6218
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -5869,13 +6221,12 @@ var CacheService = class _CacheService {
|
|
|
5869
6221
|
const s = JSON.stringify(data);
|
|
5870
6222
|
const stored = await this._serializeAndEncrypt(s);
|
|
5871
6223
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5872
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5873
|
-
const now = Date.now();
|
|
6224
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5874
6225
|
const tx = client.multi();
|
|
5875
6226
|
tx.hset(k, {
|
|
5876
6227
|
d: stored,
|
|
5877
|
-
t: String(
|
|
5878
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6228
|
+
t: String(writeTs),
|
|
6229
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5879
6230
|
});
|
|
5880
6231
|
tx.expire(k, ttlSec);
|
|
5881
6232
|
await tx.exec();
|
|
@@ -5910,7 +6261,18 @@ var CacheService = class _CacheService {
|
|
|
5910
6261
|
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
5911
6262
|
*/
|
|
5912
6263
|
async _registerTags(k, tags, ttlSeconds) {
|
|
5913
|
-
|
|
6264
|
+
this._removeKeyTags(k);
|
|
6265
|
+
const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
|
|
6266
|
+
const expiresAt = Date.now() + effectiveTtl * 1e3;
|
|
6267
|
+
if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
|
|
6268
|
+
this._sweepExpiredMetadata();
|
|
6269
|
+
if (this.keyTags.size >= 1e5) {
|
|
6270
|
+
const oldestKey = this.keyTags.keys().next().value;
|
|
6271
|
+
if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
|
|
6272
|
+
}
|
|
6273
|
+
}
|
|
6274
|
+
const uniqueTags = Array.from(new Set(tags));
|
|
6275
|
+
for (const tag of uniqueTags) {
|
|
5914
6276
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5915
6277
|
let members = this.tagIndex.get(tagKey);
|
|
5916
6278
|
if (!members) {
|
|
@@ -5919,14 +6281,15 @@ var CacheService = class _CacheService {
|
|
|
5919
6281
|
}
|
|
5920
6282
|
members.add(k);
|
|
5921
6283
|
}
|
|
6284
|
+
this.keyTags.set(k, { tags: uniqueTags, expiresAt });
|
|
5922
6285
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5923
6286
|
try {
|
|
5924
6287
|
const client = await this.getRedis();
|
|
5925
6288
|
const pl = client.pipeline();
|
|
5926
|
-
for (const tag of
|
|
6289
|
+
for (const tag of uniqueTags) {
|
|
5927
6290
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
5928
6291
|
pl.sadd(tagKey, k);
|
|
5929
|
-
pl.expire(tagKey,
|
|
6292
|
+
pl.expire(tagKey, effectiveTtl + 3600);
|
|
5930
6293
|
}
|
|
5931
6294
|
await pl.exec();
|
|
5932
6295
|
this.cb.onSuccess();
|
|
@@ -5965,6 +6328,13 @@ var CacheService = class _CacheService {
|
|
|
5965
6328
|
}
|
|
5966
6329
|
this._addPatternTombstone(pfx);
|
|
5967
6330
|
this.l1.deletePattern(k);
|
|
6331
|
+
this._removePrefixFromIndices(pfx);
|
|
6332
|
+
for (const ktKey of Array.from(this.keyTags.keys())) {
|
|
6333
|
+
if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
|
|
6334
|
+
}
|
|
6335
|
+
for (const kdKey of Array.from(this.keyDependencies.keys())) {
|
|
6336
|
+
if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
|
|
6337
|
+
}
|
|
5968
6338
|
} else {
|
|
5969
6339
|
this._bumpKeyMutation(k);
|
|
5970
6340
|
this.inflight.delete(k);
|
|
@@ -5977,15 +6347,16 @@ var CacheService = class _CacheService {
|
|
|
5977
6347
|
this._pendingDiskDeletes.delete(k);
|
|
5978
6348
|
}
|
|
5979
6349
|
});
|
|
6350
|
+
this._removeKeyTags(k);
|
|
5980
6351
|
this._cascadeDependencies(k);
|
|
5981
|
-
|
|
6352
|
+
this._removeKeyDependencies(k);
|
|
5982
6353
|
}
|
|
5983
6354
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5984
6355
|
try {
|
|
5985
6356
|
const client = await this.getRedis();
|
|
5986
6357
|
if (isPattern) {
|
|
5987
6358
|
const keys = await this._scanKeys(client, k);
|
|
5988
|
-
|
|
6359
|
+
await this._deleteRedisKeys(client, keys);
|
|
5989
6360
|
} else {
|
|
5990
6361
|
if (this.opts.autoPipeline && this.pipeliner) {
|
|
5991
6362
|
await this.pipeliner.del(k);
|
|
@@ -6047,6 +6418,15 @@ var CacheService = class _CacheService {
|
|
|
6047
6418
|
entry.value++;
|
|
6048
6419
|
return entry.value;
|
|
6049
6420
|
}
|
|
6421
|
+
if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
|
|
6422
|
+
for (const [ck, cv] of this._l1Counters) {
|
|
6423
|
+
if (cv.expiresAt <= now) this._l1Counters.delete(ck);
|
|
6424
|
+
}
|
|
6425
|
+
if (this._l1Counters.size >= 5e4) {
|
|
6426
|
+
const oldest = this._l1Counters.keys().next().value;
|
|
6427
|
+
if (oldest !== void 0) this._l1Counters.delete(oldest);
|
|
6428
|
+
}
|
|
6429
|
+
}
|
|
6050
6430
|
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
6051
6431
|
return 1;
|
|
6052
6432
|
}
|
|
@@ -6093,6 +6473,7 @@ var CacheService = class _CacheService {
|
|
|
6093
6473
|
}
|
|
6094
6474
|
this._addPatternTombstone(pfx);
|
|
6095
6475
|
this.l1.deletePattern(k);
|
|
6476
|
+
this._removePrefixFromIndices(pfx);
|
|
6096
6477
|
} else {
|
|
6097
6478
|
this._globalEpoch++;
|
|
6098
6479
|
this.inflight.clear();
|
|
@@ -6101,7 +6482,10 @@ var CacheService = class _CacheService {
|
|
|
6101
6482
|
if (!this._diskDisabled) this.disk.clear();
|
|
6102
6483
|
this._l1Counters.clear();
|
|
6103
6484
|
this.tagIndex.clear();
|
|
6485
|
+
this.keyTags.clear();
|
|
6104
6486
|
this.tagVersions.clear();
|
|
6487
|
+
this.dependencyIndex.clear();
|
|
6488
|
+
this.keyDependencies.clear();
|
|
6105
6489
|
this._pendingDiskDeletes.clear();
|
|
6106
6490
|
this._keyMutationEpochs.clear();
|
|
6107
6491
|
}
|
|
@@ -6110,7 +6494,7 @@ var CacheService = class _CacheService {
|
|
|
6110
6494
|
const client = await this.getRedis();
|
|
6111
6495
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
6112
6496
|
const keys = await this._scanKeys(client, pattern);
|
|
6113
|
-
|
|
6497
|
+
await this._deleteRedisKeys(client, keys);
|
|
6114
6498
|
} catch (err) {
|
|
6115
6499
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6116
6500
|
}
|
|
@@ -6253,6 +6637,10 @@ var CacheService = class _CacheService {
|
|
|
6253
6637
|
this._assertActive("touch");
|
|
6254
6638
|
const k = this.nk(cacheKey);
|
|
6255
6639
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
6640
|
+
if (hit) {
|
|
6641
|
+
const kt = this.keyTags.get(k);
|
|
6642
|
+
if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
|
|
6643
|
+
}
|
|
6256
6644
|
if (hit && !this._redisDisabled) {
|
|
6257
6645
|
try {
|
|
6258
6646
|
const client = await this.getRedis();
|
|
@@ -6280,6 +6668,10 @@ var CacheService = class _CacheService {
|
|
|
6280
6668
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
6281
6669
|
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6282
6670
|
}
|
|
6671
|
+
_prepareReadValue(val) {
|
|
6672
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6673
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6674
|
+
}
|
|
6283
6675
|
/**
|
|
6284
6676
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
6285
6677
|
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
@@ -6293,11 +6685,13 @@ var CacheService = class _CacheService {
|
|
|
6293
6685
|
const k = this.nk(cacheKey);
|
|
6294
6686
|
const l1Hit = this.l1.get(k);
|
|
6295
6687
|
if (l1Hit !== null) {
|
|
6296
|
-
this.
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6688
|
+
if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
|
|
6689
|
+
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
6690
|
+
} else {
|
|
6691
|
+
this.counters.gets++;
|
|
6692
|
+
this.counters.l1Hits++;
|
|
6693
|
+
return this._prepareReadValue(l1Hit.value);
|
|
6694
|
+
}
|
|
6301
6695
|
}
|
|
6302
6696
|
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6303
6697
|
if (this._isTombstonedByPattern(k)) {
|
|
@@ -6312,18 +6706,20 @@ var CacheService = class _CacheService {
|
|
|
6312
6706
|
this.watchdog.recordDisk(diskElapsed);
|
|
6313
6707
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6314
6708
|
if (diskHit !== null) {
|
|
6315
|
-
|
|
6316
|
-
|
|
6317
|
-
|
|
6318
|
-
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6323
|
-
this.
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6709
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6710
|
+
this.disk.delete(k);
|
|
6711
|
+
} else {
|
|
6712
|
+
const promoted = this.l1.importEntries(
|
|
6713
|
+
[{ key: k, entry: diskHit }],
|
|
6714
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6715
|
+
);
|
|
6716
|
+
if (promoted > 0) {
|
|
6717
|
+
const l1Check = this.l1.get(k);
|
|
6718
|
+
if (l1Check !== null) {
|
|
6719
|
+
this.counters.gets++;
|
|
6720
|
+
this.counters.diskHits++;
|
|
6721
|
+
return this._prepareReadValue(l1Check.value);
|
|
6722
|
+
}
|
|
6327
6723
|
}
|
|
6328
6724
|
}
|
|
6329
6725
|
}
|
|
@@ -6333,17 +6729,16 @@ var CacheService = class _CacheService {
|
|
|
6333
6729
|
try {
|
|
6334
6730
|
const client = await this.getRedis();
|
|
6335
6731
|
const redisStart = performance.now();
|
|
6336
|
-
const
|
|
6732
|
+
const redisHit = await this._readRedisEntry(client, k);
|
|
6337
6733
|
const redisElapsed = performance.now() - redisStart;
|
|
6338
6734
|
this.watchdog.recordRedis(redisElapsed);
|
|
6339
|
-
|
|
6340
|
-
|
|
6341
|
-
|
|
6735
|
+
this.cb.onSuccess();
|
|
6736
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
6737
|
+
const parsed = redisHit.value;
|
|
6738
|
+
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
|
|
6342
6739
|
this.counters.gets++;
|
|
6343
6740
|
this.counters.l2Hits++;
|
|
6344
|
-
this.
|
|
6345
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
6346
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6741
|
+
return this._prepareReadValue(parsed);
|
|
6347
6742
|
}
|
|
6348
6743
|
} catch (err) {
|
|
6349
6744
|
this.cb.onFailure();
|
|
@@ -6371,12 +6766,20 @@ var CacheService = class _CacheService {
|
|
|
6371
6766
|
const result = Array.from({ length: keys.length });
|
|
6372
6767
|
const missIndexes = [];
|
|
6373
6768
|
const missKeys = [];
|
|
6769
|
+
const now = Date.now();
|
|
6374
6770
|
for (let i = 0; i < keys.length; i++) {
|
|
6375
6771
|
const k = this.nk(keys[i]);
|
|
6376
6772
|
const entry = this.l1.getEntry(k);
|
|
6377
|
-
if (entry && entry.expiresAt >
|
|
6378
|
-
|
|
6379
|
-
|
|
6773
|
+
if (entry && entry.expiresAt > now) {
|
|
6774
|
+
if (await this._isGenerationalEntryStale(entry.tagVersions)) {
|
|
6775
|
+
this._deleteIfStale(k, entry.setAt ?? 0);
|
|
6776
|
+
missIndexes.push(i);
|
|
6777
|
+
missKeys.push(keys[i]);
|
|
6778
|
+
} else {
|
|
6779
|
+
const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6780
|
+
result[i] = this._prepareReadValue(val);
|
|
6781
|
+
this.counters.l1Hits++;
|
|
6782
|
+
}
|
|
6380
6783
|
} else {
|
|
6381
6784
|
missIndexes.push(i);
|
|
6382
6785
|
missKeys.push(keys[i]);
|
|
@@ -6397,23 +6800,57 @@ var CacheService = class _CacheService {
|
|
|
6397
6800
|
const client = await this.getRedis();
|
|
6398
6801
|
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6399
6802
|
const pipeline = client.multi();
|
|
6400
|
-
|
|
6803
|
+
const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
6804
|
+
for (const nk of nsKeys) {
|
|
6805
|
+
if (useHashPipeline) {
|
|
6806
|
+
pipeline.hgetall(nk);
|
|
6807
|
+
} else {
|
|
6808
|
+
pipeline.get(nk);
|
|
6809
|
+
}
|
|
6810
|
+
}
|
|
6401
6811
|
const redisStart = performance.now();
|
|
6402
6812
|
const raws = await pipeline.exec();
|
|
6403
6813
|
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6404
6814
|
this.watchdog.recordRedis(redisElapsed);
|
|
6405
6815
|
this.cb.onSuccess();
|
|
6406
6816
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6407
|
-
const
|
|
6817
|
+
const tuple = raws[j];
|
|
6818
|
+
const err = tuple ? tuple[0] : null;
|
|
6819
|
+
const rawVal = tuple ? tuple[1] : null;
|
|
6408
6820
|
const idx = missIndexes[j];
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6821
|
+
const k = nsKeys[j];
|
|
6822
|
+
let parsed;
|
|
6823
|
+
let tagVersions;
|
|
6824
|
+
let hit = false;
|
|
6825
|
+
if (useHashPipeline) {
|
|
6826
|
+
if (err && err.message?.includes("WRONGTYPE")) {
|
|
6827
|
+
const fallbackRaw = await client.get(k);
|
|
6828
|
+
if (fallbackRaw) {
|
|
6829
|
+
parsed = await this._decryptAndDeserialize(fallbackRaw);
|
|
6830
|
+
hit = true;
|
|
6831
|
+
}
|
|
6832
|
+
} else if (!err && typeof rawVal === "string") {
|
|
6833
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6834
|
+
hit = true;
|
|
6835
|
+
} else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
|
|
6836
|
+
const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
|
|
6837
|
+
if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
|
|
6838
|
+
parsed = hashHit.value;
|
|
6839
|
+
tagVersions = hashHit.tagVersions;
|
|
6840
|
+
hit = true;
|
|
6841
|
+
}
|
|
6842
|
+
}
|
|
6843
|
+
} else if (!err && rawVal) {
|
|
6844
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6845
|
+
hit = true;
|
|
6846
|
+
}
|
|
6847
|
+
if (hit && parsed !== void 0) {
|
|
6412
6848
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
6413
|
-
|
|
6849
|
+
const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6850
|
+
this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
|
|
6414
6851
|
this.counters.l2Hits++;
|
|
6415
6852
|
l2HitCount++;
|
|
6416
|
-
result[idx] = parsed;
|
|
6853
|
+
result[idx] = this._prepareReadValue(parsed);
|
|
6417
6854
|
missIndexes[j] = -1;
|
|
6418
6855
|
missKeys[j] = "";
|
|
6419
6856
|
}
|
|
@@ -6447,6 +6884,10 @@ var CacheService = class _CacheService {
|
|
|
6447
6884
|
this.watchdog.recordDisk(diskElapsed);
|
|
6448
6885
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6449
6886
|
if (diskHit !== null) {
|
|
6887
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6888
|
+
this.disk.delete(k);
|
|
6889
|
+
continue;
|
|
6890
|
+
}
|
|
6450
6891
|
const promoted = this.l1.importEntries(
|
|
6451
6892
|
[{ key: k, entry: diskHit }],
|
|
6452
6893
|
this.opts.forbiddenSnapshotPrefixes
|
|
@@ -6455,7 +6896,7 @@ var CacheService = class _CacheService {
|
|
|
6455
6896
|
const l1Check = this.l1.get(k);
|
|
6456
6897
|
if (l1Check !== null) {
|
|
6457
6898
|
this.counters.diskHits++;
|
|
6458
|
-
result[missIndexes[j]] = l1Check.value;
|
|
6899
|
+
result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
|
|
6459
6900
|
missIndexes.splice(j, 1);
|
|
6460
6901
|
missKeys.splice(j, 1);
|
|
6461
6902
|
}
|
|
@@ -6463,16 +6904,23 @@ var CacheService = class _CacheService {
|
|
|
6463
6904
|
}
|
|
6464
6905
|
}
|
|
6465
6906
|
}
|
|
6466
|
-
if (missKeys.length > 0) {
|
|
6907
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6467
6908
|
this.counters.fetches++;
|
|
6468
6909
|
const fetched = await fetchFn(missKeys);
|
|
6910
|
+
const isMap = fetched instanceof Map;
|
|
6469
6911
|
const setPromises = [];
|
|
6470
6912
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6471
|
-
const
|
|
6913
|
+
const k = missKeys[j];
|
|
6914
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6472
6915
|
result[missIndexes[j]] = v;
|
|
6473
|
-
if (v !== void 0) {
|
|
6474
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6475
|
-
setPromises.push(this.set(
|
|
6916
|
+
if (v !== void 0 && v !== null) {
|
|
6917
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6918
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
6919
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
6920
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
6921
|
+
} else if (v === null) {
|
|
6922
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6923
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6476
6924
|
}
|
|
6477
6925
|
}
|
|
6478
6926
|
if (setPromises.length > 0) {
|
|
@@ -6615,98 +7063,135 @@ var CacheService = class _CacheService {
|
|
|
6615
7063
|
}
|
|
6616
7064
|
}
|
|
6617
7065
|
/**
|
|
6618
|
-
*
|
|
6619
|
-
*
|
|
6620
|
-
*
|
|
6621
|
-
* @example
|
|
6622
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6623
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7066
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
7067
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
7068
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
6624
7069
|
*/
|
|
6625
|
-
async
|
|
6626
|
-
|
|
6627
|
-
const
|
|
6628
|
-
|
|
6629
|
-
|
|
6630
|
-
|
|
7070
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
7071
|
+
const isPattern = isWildcardTag(tag);
|
|
7072
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7073
|
+
const matched = /* @__PURE__ */ new Set();
|
|
7074
|
+
const tagMatches = (t) => {
|
|
7075
|
+
if (t === tag) return true;
|
|
7076
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
7077
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
7078
|
+
return false;
|
|
7079
|
+
};
|
|
7080
|
+
if (shouldCascade && !isPattern) {
|
|
7081
|
+
matched.add(tag);
|
|
6631
7082
|
}
|
|
6632
|
-
|
|
6633
|
-
|
|
6634
|
-
|
|
6635
|
-
|
|
6636
|
-
|
|
6637
|
-
|
|
6638
|
-
|
|
6639
|
-
|
|
6640
|
-
|
|
6641
|
-
|
|
6642
|
-
|
|
6643
|
-
|
|
6644
|
-
} else {
|
|
6645
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6646
|
-
newVer = current + 1;
|
|
6647
|
-
}
|
|
6648
|
-
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6649
|
-
if (this.opts.awaitInvalidationBackplane) {
|
|
6650
|
-
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6651
|
-
} else {
|
|
6652
|
-
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
7083
|
+
const tagPrefix = this.nk("_tag_:");
|
|
7084
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
7085
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
7086
|
+
if (tagMatches(t)) matched.add(t);
|
|
7087
|
+
}
|
|
7088
|
+
for (const t of this.tagVersions.keys()) {
|
|
7089
|
+
if (tagMatches(t)) matched.add(t);
|
|
7090
|
+
}
|
|
7091
|
+
this.l1.scan((_k, entry) => {
|
|
7092
|
+
if (entry.tagVersions) {
|
|
7093
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
7094
|
+
if (tagMatches(t)) matched.add(t);
|
|
6653
7095
|
}
|
|
6654
|
-
return;
|
|
6655
7096
|
}
|
|
6656
|
-
|
|
6657
|
-
|
|
6658
|
-
|
|
6659
|
-
this.
|
|
6660
|
-
this.
|
|
6661
|
-
|
|
6662
|
-
|
|
6663
|
-
|
|
6664
|
-
|
|
6665
|
-
|
|
6666
|
-
|
|
7097
|
+
}, 0);
|
|
7098
|
+
if (!this._redisDisabled) {
|
|
7099
|
+
try {
|
|
7100
|
+
const client = await this.getRedis();
|
|
7101
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7102
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
7103
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7104
|
+
const pfx = this.nk("tag_ver:");
|
|
7105
|
+
for (const sk of scannedKeys) {
|
|
7106
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7107
|
+
if (tagMatches(t)) matched.add(t);
|
|
6667
7108
|
}
|
|
6668
|
-
}
|
|
7109
|
+
} else {
|
|
7110
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
7111
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7112
|
+
const pfx = this.nk("_tag_:");
|
|
7113
|
+
for (const sk of scannedKeys) {
|
|
7114
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7115
|
+
if (tagMatches(t)) matched.add(t);
|
|
7116
|
+
}
|
|
7117
|
+
}
|
|
7118
|
+
} catch (err) {
|
|
7119
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
6669
7120
|
}
|
|
6670
|
-
|
|
7121
|
+
}
|
|
7122
|
+
return matched;
|
|
7123
|
+
}
|
|
7124
|
+
async _publishTagInvalidation(op, key, tagVersion) {
|
|
7125
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7126
|
+
await this.publishInvalidation(op, key, tagVersion, false, true);
|
|
7127
|
+
} else {
|
|
7128
|
+
void this.publishInvalidation(op, key, tagVersion, false, true);
|
|
7129
|
+
}
|
|
7130
|
+
}
|
|
7131
|
+
_removeTagMembersLocal(keys) {
|
|
7132
|
+
const keyList = Array.isArray(keys) ? keys : Array.from(keys);
|
|
7133
|
+
for (const k of keyList) {
|
|
7134
|
+
this.l1.delete(k);
|
|
7135
|
+
this._bumpKeyMutation(k);
|
|
7136
|
+
this._removeKeyTags(k);
|
|
7137
|
+
this._removeKeyDependencies(k);
|
|
7138
|
+
this._pendingDiskDeletes.add(k);
|
|
7139
|
+
setImmediate(() => {
|
|
7140
|
+
try {
|
|
7141
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
7142
|
+
} finally {
|
|
7143
|
+
this._pendingDiskDeletes.delete(k);
|
|
7144
|
+
}
|
|
7145
|
+
});
|
|
7146
|
+
}
|
|
7147
|
+
}
|
|
7148
|
+
/**
|
|
7149
|
+
* Executes invalidation for a single already-resolved concrete tag without
|
|
7150
|
+
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
7151
|
+
*/
|
|
7152
|
+
async _invalidateConcreteTag(tag) {
|
|
7153
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7154
|
+
let newVer = 1;
|
|
6671
7155
|
if (!this._redisDisabled) {
|
|
6672
7156
|
try {
|
|
6673
7157
|
const client = await this.getRedis();
|
|
6674
|
-
|
|
6675
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6676
|
-
if (toDelete.length > 0) {
|
|
6677
|
-
await client.del(...toDelete, tagKey);
|
|
6678
|
-
} else {
|
|
6679
|
-
await client.del(tagKey);
|
|
6680
|
-
}
|
|
7158
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6681
7159
|
} catch (err) {
|
|
6682
7160
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
7161
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7162
|
+
newVer = current + 1;
|
|
6683
7163
|
}
|
|
7164
|
+
} else {
|
|
7165
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7166
|
+
newVer = current + 1;
|
|
7167
|
+
}
|
|
7168
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
7169
|
+
await this._publishTagInvalidation("tag_incr", tag, newVer);
|
|
7170
|
+
return;
|
|
7171
|
+
}
|
|
7172
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
7173
|
+
const members = Array.from(this.tagIndex.get(tagKey) ?? []);
|
|
7174
|
+
this.tagIndex.delete(tagKey);
|
|
7175
|
+
this._removeTagMembersLocal(members);
|
|
7176
|
+
if (!this._redisDisabled) {
|
|
7177
|
+
try {
|
|
7178
|
+
const client = await this.getRedis();
|
|
7179
|
+
const redisMembers = await client.smembers(tagKey);
|
|
7180
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
|
|
7181
|
+
await this._deleteRedisKeys(client, toDelete);
|
|
7182
|
+
} catch (err) {
|
|
7183
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6684
7184
|
}
|
|
6685
|
-
} catch (err) {
|
|
6686
|
-
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6687
|
-
span.recordException?.(err);
|
|
6688
|
-
throw err;
|
|
6689
|
-
} finally {
|
|
6690
|
-
span.end();
|
|
6691
7185
|
}
|
|
6692
7186
|
}
|
|
6693
7187
|
/**
|
|
6694
|
-
*
|
|
6695
|
-
*
|
|
6696
|
-
* reducing latency when invalidating several related tags together.
|
|
6697
|
-
*
|
|
6698
|
-
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
6699
|
-
* synchronously before the Redis round-trip.
|
|
6700
|
-
*
|
|
6701
|
-
* @example
|
|
6702
|
-
* // Instead of three serial round-trips:
|
|
6703
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
7188
|
+
* Executes invalidation for an array of already-resolved concrete tags
|
|
7189
|
+
* without re-entering wildcard/cascade resolution or invalidateTag().
|
|
6704
7190
|
*/
|
|
6705
|
-
async
|
|
6706
|
-
this._assertActive("invalidateTags");
|
|
7191
|
+
async _invalidateConcreteTags(tags) {
|
|
6707
7192
|
if (tags.length === 0) return;
|
|
6708
7193
|
if (tags.length === 1) {
|
|
6709
|
-
await this.
|
|
7194
|
+
await this._invalidateConcreteTag(tags[0]);
|
|
6710
7195
|
return;
|
|
6711
7196
|
}
|
|
6712
7197
|
if (this.opts.tagStrategy === "generational") {
|
|
@@ -6721,11 +7206,7 @@ var CacheService = class _CacheService {
|
|
|
6721
7206
|
const [err, newVer] = results[i] ?? [null, null];
|
|
6722
7207
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
6723
7208
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
6724
|
-
|
|
6725
|
-
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6726
|
-
} else {
|
|
6727
|
-
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6728
|
-
}
|
|
7209
|
+
await this._publishTagInvalidation("tag_incr", tags[i], ver);
|
|
6729
7210
|
}
|
|
6730
7211
|
return;
|
|
6731
7212
|
} catch (err) {
|
|
@@ -6735,11 +7216,7 @@ var CacheService = class _CacheService {
|
|
|
6735
7216
|
for (const tag of tags) {
|
|
6736
7217
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
6737
7218
|
this._setLocalTagVersion(tag, ver, now);
|
|
6738
|
-
|
|
6739
|
-
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6740
|
-
} else {
|
|
6741
|
-
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6742
|
-
}
|
|
7219
|
+
await this._publishTagInvalidation("tag_incr", tag, ver);
|
|
6743
7220
|
}
|
|
6744
7221
|
return;
|
|
6745
7222
|
}
|
|
@@ -6752,18 +7229,7 @@ var CacheService = class _CacheService {
|
|
|
6752
7229
|
for (const k of members) allMembers.add(k);
|
|
6753
7230
|
this.tagIndex.delete(tagKey);
|
|
6754
7231
|
}
|
|
6755
|
-
|
|
6756
|
-
this.l1.delete(k);
|
|
6757
|
-
this._bumpKeyMutation(k);
|
|
6758
|
-
this._pendingDiskDeletes.add(k);
|
|
6759
|
-
setImmediate(() => {
|
|
6760
|
-
try {
|
|
6761
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
6762
|
-
} finally {
|
|
6763
|
-
this._pendingDiskDeletes.delete(k);
|
|
6764
|
-
}
|
|
6765
|
-
});
|
|
6766
|
-
}
|
|
7232
|
+
this._removeTagMembersLocal(allMembers);
|
|
6767
7233
|
if (!this._redisDisabled) {
|
|
6768
7234
|
try {
|
|
6769
7235
|
const client = await this.getRedis();
|
|
@@ -6779,12 +7245,103 @@ var CacheService = class _CacheService {
|
|
|
6779
7245
|
}
|
|
6780
7246
|
}
|
|
6781
7247
|
const keysToRemove = [...toDelete, ...tagKeys];
|
|
6782
|
-
|
|
7248
|
+
await this._deleteRedisKeys(client, keysToRemove);
|
|
6783
7249
|
} catch (err) {
|
|
6784
7250
|
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
6785
7251
|
}
|
|
6786
7252
|
}
|
|
6787
7253
|
}
|
|
7254
|
+
/**
|
|
7255
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
7256
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
7257
|
+
*
|
|
7258
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
7259
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
7260
|
+
*
|
|
7261
|
+
* @example
|
|
7262
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
7263
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7264
|
+
*
|
|
7265
|
+
* @example
|
|
7266
|
+
* // Wildcard pattern invalidation
|
|
7267
|
+
* await cache.invalidateTag('org:123:*');
|
|
7268
|
+
*
|
|
7269
|
+
* @example
|
|
7270
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
7271
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
7272
|
+
*/
|
|
7273
|
+
async invalidateTag(tag, opts) {
|
|
7274
|
+
this._assertActive("invalidateTag");
|
|
7275
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
7276
|
+
if (this.opts.tracer) {
|
|
7277
|
+
span.setAttribute("cache.tag", tag);
|
|
7278
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
7279
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
7280
|
+
}
|
|
7281
|
+
try {
|
|
7282
|
+
const isPattern = isWildcardTag(tag);
|
|
7283
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7284
|
+
if (isPattern || shouldCascade) {
|
|
7285
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
7286
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7287
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
7288
|
+
if (matchedTags.size > 0) {
|
|
7289
|
+
await this._invalidateConcreteTags(Array.from(matchedTags));
|
|
7290
|
+
}
|
|
7291
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7292
|
+
await this._publishTagInvalidation(op, broadcastPattern);
|
|
7293
|
+
return;
|
|
7294
|
+
}
|
|
7295
|
+
await this._invalidateConcreteTag(tag);
|
|
7296
|
+
} catch (err) {
|
|
7297
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
7298
|
+
span.recordException?.(err);
|
|
7299
|
+
throw err;
|
|
7300
|
+
} finally {
|
|
7301
|
+
span.end();
|
|
7302
|
+
}
|
|
7303
|
+
}
|
|
7304
|
+
/**
|
|
7305
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
7306
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
7307
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
7308
|
+
*
|
|
7309
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
7310
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
7311
|
+
*
|
|
7312
|
+
* @example
|
|
7313
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
7314
|
+
*/
|
|
7315
|
+
async invalidateTags(tags, opts) {
|
|
7316
|
+
this._assertActive("invalidateTags");
|
|
7317
|
+
if (tags.length === 0) return;
|
|
7318
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
7319
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7320
|
+
if (hasWildcards || shouldCascade) {
|
|
7321
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
7322
|
+
const broadcastPatterns = /* @__PURE__ */ new Set();
|
|
7323
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7324
|
+
for (const t of tags) {
|
|
7325
|
+
const tIsPattern = isWildcardTag(t);
|
|
7326
|
+
if (tIsPattern || shouldCascade) {
|
|
7327
|
+
broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
|
|
7328
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
7329
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
7330
|
+
} else {
|
|
7331
|
+
allResolvedTags.add(t);
|
|
7332
|
+
}
|
|
7333
|
+
}
|
|
7334
|
+
if (allResolvedTags.size > 0) {
|
|
7335
|
+
await this._invalidateConcreteTags(Array.from(allResolvedTags));
|
|
7336
|
+
}
|
|
7337
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7338
|
+
for (const pattern of broadcastPatterns) {
|
|
7339
|
+
await this._publishTagInvalidation(op, pattern);
|
|
7340
|
+
}
|
|
7341
|
+
return;
|
|
7342
|
+
}
|
|
7343
|
+
await this._invalidateConcreteTags(Array.from(new Set(tags)));
|
|
7344
|
+
}
|
|
6788
7345
|
/**
|
|
6789
7346
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
6790
7347
|
*/
|
|
@@ -7350,6 +7907,13 @@ var CacheService = class _CacheService {
|
|
|
7350
7907
|
this._destroyed = true;
|
|
7351
7908
|
this._pendingDiskDeletes.clear();
|
|
7352
7909
|
this._keyMutationEpochs.clear();
|
|
7910
|
+
this.inflight.clear();
|
|
7911
|
+
this.revalidating.clear();
|
|
7912
|
+
this._l1Counters.clear();
|
|
7913
|
+
this.tagIndex.clear();
|
|
7914
|
+
this.keyTags.clear();
|
|
7915
|
+
this.dependencyIndex.clear();
|
|
7916
|
+
this.keyDependencies.clear();
|
|
7353
7917
|
const g = globalThis;
|
|
7354
7918
|
const key = _CacheService.globalKey(this.opts);
|
|
7355
7919
|
if (g[key] === this) {
|
|
@@ -7485,10 +8049,7 @@ var TriCacheHandler = class {
|
|
|
7485
8049
|
* and returns a fresh unlocked ReadableStream if the stored value was a stream.
|
|
7486
8050
|
*/
|
|
7487
8051
|
async get(cacheKey, ctx) {
|
|
7488
|
-
const stored = await this.cache.
|
|
7489
|
-
cacheKey,
|
|
7490
|
-
async () => null
|
|
7491
|
-
);
|
|
8052
|
+
const stored = await this.cache.peek(cacheKey);
|
|
7492
8053
|
if (!stored || stored.data == null) {
|
|
7493
8054
|
return void 0;
|
|
7494
8055
|
}
|
|
@@ -7641,10 +8202,7 @@ var TriCacheISRHandler = class {
|
|
|
7641
8202
|
if (this.requestCache.has(key)) {
|
|
7642
8203
|
return this.requestCache.get(key) ?? null;
|
|
7643
8204
|
}
|
|
7644
|
-
const stored = await this.cache.
|
|
7645
|
-
key,
|
|
7646
|
-
async () => null
|
|
7647
|
-
);
|
|
8205
|
+
const stored = await this.cache.peek(key);
|
|
7648
8206
|
if (stored) {
|
|
7649
8207
|
this.requestCache.set(key, stored);
|
|
7650
8208
|
return stored;
|