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