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/drizzle/index.cjs
CHANGED
|
@@ -1463,7 +1463,7 @@ var init_smart_memory_cache = __esm({
|
|
|
1463
1463
|
};
|
|
1464
1464
|
return hit;
|
|
1465
1465
|
}
|
|
1466
|
-
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1466
|
+
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions, setAt) {
|
|
1467
1467
|
const packed = this.codec.encode(data);
|
|
1468
1468
|
const size = packed.byteLength;
|
|
1469
1469
|
this.compressions++;
|
|
@@ -1500,7 +1500,7 @@ var init_smart_memory_cache = __esm({
|
|
|
1500
1500
|
priority,
|
|
1501
1501
|
ttlMs,
|
|
1502
1502
|
delta,
|
|
1503
|
-
setAt: now2,
|
|
1503
|
+
setAt: setAt ?? now2,
|
|
1504
1504
|
tagVersions
|
|
1505
1505
|
});
|
|
1506
1506
|
}
|
|
@@ -1528,7 +1528,7 @@ var init_smart_memory_cache = __esm({
|
|
|
1528
1528
|
}
|
|
1529
1529
|
const now = Date.now();
|
|
1530
1530
|
const liveValue = size <= LARGE_VALUE_BYTES ? data : void 0;
|
|
1531
|
-
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 });
|
|
1531
|
+
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 });
|
|
1532
1532
|
if (!existingEntry) this.bloom.add(key);
|
|
1533
1533
|
this.maybeRebuildBloom();
|
|
1534
1534
|
this.totalSize += size;
|
|
@@ -1942,10 +1942,29 @@ var init_smart_memory_cache = __esm({
|
|
|
1942
1942
|
});
|
|
1943
1943
|
|
|
1944
1944
|
// src/compression.ts
|
|
1945
|
+
function initZstd() {
|
|
1946
|
+
if (zstdSimple) return Promise.resolve(zstdSimple);
|
|
1947
|
+
if (!zstdInitPromise) {
|
|
1948
|
+
zstdInitPromise = new Promise((resolve) => {
|
|
1949
|
+
try {
|
|
1950
|
+
import_zstd_codec.ZstdCodec.run((zstd) => {
|
|
1951
|
+
zstdSimple = new zstd.Simple();
|
|
1952
|
+
resolve(zstdSimple);
|
|
1953
|
+
});
|
|
1954
|
+
} catch {
|
|
1955
|
+
resolve(null);
|
|
1956
|
+
}
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
return zstdInitPromise;
|
|
1960
|
+
}
|
|
1945
1961
|
function isCompressed(buf) {
|
|
1946
1962
|
return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
|
|
1947
1963
|
}
|
|
1948
|
-
function compressBuffer(buf, algorithm) {
|
|
1964
|
+
function compressBuffer(buf, algorithm, custom) {
|
|
1965
|
+
if (custom) {
|
|
1966
|
+
return custom.compress(buf);
|
|
1967
|
+
}
|
|
1949
1968
|
if (algorithm === "brotli") {
|
|
1950
1969
|
return import_zlib.default.brotliCompressSync(buf, {
|
|
1951
1970
|
params: {
|
|
@@ -1957,48 +1976,144 @@ function compressBuffer(buf, algorithm) {
|
|
|
1957
1976
|
if (algorithm === "gzip") {
|
|
1958
1977
|
return import_zlib.default.gzipSync(buf, { level: 6 });
|
|
1959
1978
|
}
|
|
1979
|
+
if (algorithm === "lz4") {
|
|
1980
|
+
return Buffer.from(import_lz4js.default.compress(buf));
|
|
1981
|
+
}
|
|
1982
|
+
if (algorithm === "zstd") {
|
|
1983
|
+
if (!zstdSimple) {
|
|
1984
|
+
return import_zlib.default.brotliCompressSync(buf, {
|
|
1985
|
+
params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
return Buffer.from(zstdSimple.compress(buf));
|
|
1989
|
+
}
|
|
1960
1990
|
return buf;
|
|
1961
1991
|
}
|
|
1962
|
-
function decompressBuffer(buf, algorithm = "
|
|
1992
|
+
function decompressBuffer(buf, algorithm = "zstd", custom) {
|
|
1993
|
+
if (custom) {
|
|
1994
|
+
const res = custom.decompress(buf);
|
|
1995
|
+
if (res.length > MAX_DECOMPRESS_BYTES) {
|
|
1996
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
1997
|
+
}
|
|
1998
|
+
return res;
|
|
1999
|
+
}
|
|
2000
|
+
const checkSafety = (decomp) => {
|
|
2001
|
+
if (decomp.length > MAX_DECOMPRESS_BYTES) {
|
|
2002
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2003
|
+
}
|
|
2004
|
+
return decomp;
|
|
2005
|
+
};
|
|
2006
|
+
if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
|
|
2007
|
+
if (zstdSimple) {
|
|
2008
|
+
try {
|
|
2009
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2010
|
+
} catch (err) {
|
|
2011
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
|
|
2016
|
+
try {
|
|
2017
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2018
|
+
} catch (err) {
|
|
2019
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
|
|
2023
|
+
try {
|
|
2024
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2025
|
+
} catch (err) {
|
|
2026
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2027
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
if (algorithm === "none") {
|
|
2032
|
+
return buf;
|
|
2033
|
+
}
|
|
2034
|
+
if (algorithm === "lz4") {
|
|
2035
|
+
try {
|
|
2036
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2037
|
+
} catch (err) {
|
|
2038
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
if (algorithm === "zstd" && zstdSimple) {
|
|
2042
|
+
try {
|
|
2043
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2044
|
+
} catch (err) {
|
|
2045
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
1963
2048
|
const tryBrotli = () => {
|
|
1964
2049
|
try {
|
|
1965
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1966
|
-
} catch {
|
|
2050
|
+
return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2051
|
+
} catch (err) {
|
|
2052
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2053
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2054
|
+
}
|
|
1967
2055
|
return null;
|
|
1968
2056
|
}
|
|
1969
2057
|
};
|
|
1970
2058
|
const tryGzip = () => {
|
|
1971
2059
|
try {
|
|
1972
|
-
return import_zlib.default.gunzipSync(buf);
|
|
1973
|
-
} catch {
|
|
2060
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2061
|
+
} catch (err) {
|
|
2062
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2063
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2064
|
+
}
|
|
1974
2065
|
return null;
|
|
1975
2066
|
}
|
|
1976
2067
|
};
|
|
1977
|
-
const
|
|
2068
|
+
const tryLz4 = () => {
|
|
2069
|
+
try {
|
|
2070
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2071
|
+
} catch (err) {
|
|
2072
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2073
|
+
return null;
|
|
2074
|
+
}
|
|
2075
|
+
};
|
|
2076
|
+
const tryZstd = () => {
|
|
2077
|
+
if (!zstdSimple) return null;
|
|
2078
|
+
try {
|
|
2079
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2080
|
+
} catch (err) {
|
|
2081
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2082
|
+
return null;
|
|
2083
|
+
}
|
|
2084
|
+
};
|
|
2085
|
+
const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
|
|
1978
2086
|
if (result === null) {
|
|
1979
2087
|
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
1980
2088
|
}
|
|
1981
2089
|
return result;
|
|
1982
2090
|
}
|
|
1983
|
-
function compressWithHeader(buf, algorithm) {
|
|
2091
|
+
function compressWithHeader(buf, algorithm, custom) {
|
|
1984
2092
|
if (algorithm === "none") return buf;
|
|
1985
|
-
const compressed = compressBuffer(buf, algorithm);
|
|
2093
|
+
const compressed = compressBuffer(buf, algorithm, custom);
|
|
1986
2094
|
return Buffer.concat([COMPRESSION_MAGIC, compressed]);
|
|
1987
2095
|
}
|
|
1988
|
-
function decompressWithHeader(buf, algorithm = "
|
|
2096
|
+
function decompressWithHeader(buf, algorithm = "zstd", custom) {
|
|
1989
2097
|
if (isCompressed(buf)) {
|
|
1990
|
-
return decompressBuffer(buf.subarray(4), algorithm);
|
|
2098
|
+
return decompressBuffer(buf.subarray(4), algorithm, custom);
|
|
1991
2099
|
}
|
|
1992
2100
|
return buf;
|
|
1993
2101
|
}
|
|
1994
|
-
var import_zlib, PREFIX_COMPRESSED, PREFIX_ENC_COMPRESSED, COMPRESSION_MAGIC;
|
|
2102
|
+
var import_zlib, import_lz4js, import_zstd_codec, PREFIX_COMPRESSED, PREFIX_ENC_COMPRESSED, COMPRESSION_MAGIC, zstdSimple, zstdInitPromise, MAX_DECOMPRESS_BYTES;
|
|
1995
2103
|
var init_compression = __esm({
|
|
1996
2104
|
"src/compression.ts"() {
|
|
1997
2105
|
"use strict";
|
|
1998
2106
|
import_zlib = __toESM(require("zlib"), 1);
|
|
2107
|
+
import_lz4js = __toESM(require("lz4js"), 1);
|
|
2108
|
+
import_zstd_codec = require("zstd-codec");
|
|
1999
2109
|
PREFIX_COMPRESSED = "cmp:v1:";
|
|
2000
2110
|
PREFIX_ENC_COMPRESSED = "ecp:v1:";
|
|
2001
2111
|
COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
|
|
2112
|
+
zstdSimple = null;
|
|
2113
|
+
zstdInitPromise = null;
|
|
2114
|
+
initZstd().catch(() => {
|
|
2115
|
+
});
|
|
2116
|
+
MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
|
|
2002
2117
|
}
|
|
2003
2118
|
});
|
|
2004
2119
|
|
|
@@ -3648,6 +3763,61 @@ var init_ipc_telemetry = __esm({
|
|
|
3648
3763
|
}
|
|
3649
3764
|
});
|
|
3650
3765
|
|
|
3766
|
+
// src/utils/tag-matcher.ts
|
|
3767
|
+
function isWildcardTag(tag) {
|
|
3768
|
+
return tag.includes("*") || tag.includes("?");
|
|
3769
|
+
}
|
|
3770
|
+
function matchesTagPattern(pattern, tag) {
|
|
3771
|
+
if (pattern === "*" || pattern === tag) return true;
|
|
3772
|
+
if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
|
|
3773
|
+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
|
|
3774
|
+
const prefix = pattern.slice(0, -1);
|
|
3775
|
+
return tag.startsWith(prefix);
|
|
3776
|
+
}
|
|
3777
|
+
if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
|
|
3778
|
+
const suffix = pattern.slice(1);
|
|
3779
|
+
return tag.endsWith(suffix);
|
|
3780
|
+
}
|
|
3781
|
+
let re = globRegexCache.get(pattern);
|
|
3782
|
+
if (!re) {
|
|
3783
|
+
if (globRegexCache.size >= 1e3) globRegexCache.clear();
|
|
3784
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
3785
|
+
re = new RegExp(`^${escaped}$`);
|
|
3786
|
+
globRegexCache.set(pattern, re);
|
|
3787
|
+
}
|
|
3788
|
+
return re.test(tag);
|
|
3789
|
+
}
|
|
3790
|
+
function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
3791
|
+
if (candidateTag === parentTag) return true;
|
|
3792
|
+
const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
|
|
3793
|
+
return candidateTag.startsWith(prefix);
|
|
3794
|
+
}
|
|
3795
|
+
function expandHierarchicalTags(tags, delimiter = ":") {
|
|
3796
|
+
if (!tags.length) return [];
|
|
3797
|
+
const result = /* @__PURE__ */ new Set();
|
|
3798
|
+
for (const tag of tags) {
|
|
3799
|
+
if (!tag) continue;
|
|
3800
|
+
const parts = tag.split(delimiter).filter((p) => p.length > 0);
|
|
3801
|
+
if (parts.length <= 1) {
|
|
3802
|
+
result.add(tag);
|
|
3803
|
+
continue;
|
|
3804
|
+
}
|
|
3805
|
+
let accumulated = "";
|
|
3806
|
+
for (let i = 0; i < parts.length; i++) {
|
|
3807
|
+
accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
|
|
3808
|
+
result.add(accumulated);
|
|
3809
|
+
}
|
|
3810
|
+
}
|
|
3811
|
+
return Array.from(result);
|
|
3812
|
+
}
|
|
3813
|
+
var globRegexCache;
|
|
3814
|
+
var init_tag_matcher = __esm({
|
|
3815
|
+
"src/utils/tag-matcher.ts"() {
|
|
3816
|
+
"use strict";
|
|
3817
|
+
globRegexCache = /* @__PURE__ */ new Map();
|
|
3818
|
+
}
|
|
3819
|
+
});
|
|
3820
|
+
|
|
3651
3821
|
// src/cache-service.ts
|
|
3652
3822
|
var cache_service_exports = {};
|
|
3653
3823
|
__export(cache_service_exports, {
|
|
@@ -3656,19 +3826,19 @@ __export(cache_service_exports, {
|
|
|
3656
3826
|
deepMergeOptions: () => deepMergeOptions
|
|
3657
3827
|
});
|
|
3658
3828
|
function getGlobRegex(pattern) {
|
|
3659
|
-
let re =
|
|
3829
|
+
let re = globRegexCache2.get(pattern);
|
|
3660
3830
|
if (re) {
|
|
3661
|
-
|
|
3662
|
-
|
|
3831
|
+
globRegexCache2.delete(pattern);
|
|
3832
|
+
globRegexCache2.set(pattern, re);
|
|
3663
3833
|
return re;
|
|
3664
3834
|
}
|
|
3665
3835
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3666
3836
|
re = new RegExp("^" + escaped + "$");
|
|
3667
|
-
if (
|
|
3668
|
-
const oldestKey =
|
|
3669
|
-
if (oldestKey !== void 0)
|
|
3837
|
+
if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3838
|
+
const oldestKey = globRegexCache2.keys().next().value;
|
|
3839
|
+
if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
|
|
3670
3840
|
}
|
|
3671
|
-
|
|
3841
|
+
globRegexCache2.set(pattern, re);
|
|
3672
3842
|
return re;
|
|
3673
3843
|
}
|
|
3674
3844
|
function deepFreeze(obj) {
|
|
@@ -3711,7 +3881,7 @@ function deepMergeOptions(base, overrides) {
|
|
|
3711
3881
|
}
|
|
3712
3882
|
return output;
|
|
3713
3883
|
}
|
|
3714
|
-
var import_ioredis, import_crypto3, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX,
|
|
3884
|
+
var import_ioredis, import_crypto3, import_os3, import_node_v82, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache2, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, ProcessTerminationBus, CacheService;
|
|
3715
3885
|
var init_cache_service = __esm({
|
|
3716
3886
|
"src/cache-service.ts"() {
|
|
3717
3887
|
"use strict";
|
|
@@ -3732,6 +3902,7 @@ var init_cache_service = __esm({
|
|
|
3732
3902
|
init_auto_pipeliner();
|
|
3733
3903
|
init_ipc_telemetry();
|
|
3734
3904
|
init_compression();
|
|
3905
|
+
init_tag_matcher();
|
|
3735
3906
|
LUA_COMPARE_AND_DELETE = `
|
|
3736
3907
|
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
3737
3908
|
if currentTs and currentTs == ARGV[1] then
|
|
@@ -3749,7 +3920,7 @@ return 0
|
|
|
3749
3920
|
DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3750
3921
|
DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3751
3922
|
GLOB_REGEX_CACHE_MAX = 256;
|
|
3752
|
-
|
|
3923
|
+
globRegexCache2 = /* @__PURE__ */ new Map();
|
|
3753
3924
|
L2CircuitBreaker = class {
|
|
3754
3925
|
constructor(threshold, cooldownMs) {
|
|
3755
3926
|
this.threshold = threshold;
|
|
@@ -3961,6 +4132,7 @@ return 0
|
|
|
3961
4132
|
opts;
|
|
3962
4133
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
3963
4134
|
_namespace;
|
|
4135
|
+
prefixLen;
|
|
3964
4136
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
3965
4137
|
_redisDisabled;
|
|
3966
4138
|
watchdog;
|
|
@@ -3970,6 +4142,8 @@ return 0
|
|
|
3970
4142
|
_l1Counters = /* @__PURE__ */ new Map();
|
|
3971
4143
|
/** tag → Set of namespaced cache keys; maintained in-process for O(1) invalidateTag() */
|
|
3972
4144
|
tagIndex = /* @__PURE__ */ new Map();
|
|
4145
|
+
/** Reverse index of namespaced key → { tags, expiresAt } for bounded cleanup on eviction/delete */
|
|
4146
|
+
keyTags = /* @__PURE__ */ new Map();
|
|
3973
4147
|
/** tag → { version, lastSyncedAt } for generational tag invalidation (bounded to 10,000 entries) */
|
|
3974
4148
|
tagVersions = /* @__PURE__ */ new Map();
|
|
3975
4149
|
/**
|
|
@@ -3977,6 +4151,9 @@ return 0
|
|
|
3977
4151
|
* When an exact-key delete matches a registered pattern, all dependents are cascaded.
|
|
3978
4152
|
*/
|
|
3979
4153
|
dependencyIndex = /* @__PURE__ */ new Map();
|
|
4154
|
+
/** Reverse index of namespaced dependent key → source glob patterns */
|
|
4155
|
+
keyDependencies = /* @__PURE__ */ new Map();
|
|
4156
|
+
_cgroupMemoryLimit;
|
|
3980
4157
|
redis = null;
|
|
3981
4158
|
redisConnecting = null;
|
|
3982
4159
|
cb;
|
|
@@ -4046,6 +4223,84 @@ return 0
|
|
|
4046
4223
|
_getKeyMutationEpoch(namespacedKey) {
|
|
4047
4224
|
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
4048
4225
|
}
|
|
4226
|
+
_removeKeyTags(namespacedKey) {
|
|
4227
|
+
const entry = this.keyTags.get(namespacedKey);
|
|
4228
|
+
if (!entry) return;
|
|
4229
|
+
for (const tag of entry.tags) {
|
|
4230
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
4231
|
+
const members = this.tagIndex.get(tagKey);
|
|
4232
|
+
if (members) {
|
|
4233
|
+
members.delete(namespacedKey);
|
|
4234
|
+
if (members.size === 0) this.tagIndex.delete(tagKey);
|
|
4235
|
+
}
|
|
4236
|
+
}
|
|
4237
|
+
this.keyTags.delete(namespacedKey);
|
|
4238
|
+
}
|
|
4239
|
+
_removeKeyDependencies(namespacedKey) {
|
|
4240
|
+
const patterns = this.keyDependencies.get(namespacedKey);
|
|
4241
|
+
if (patterns) {
|
|
4242
|
+
for (const pat of patterns) {
|
|
4243
|
+
const deps = this.dependencyIndex.get(pat);
|
|
4244
|
+
if (deps) {
|
|
4245
|
+
deps.delete(namespacedKey);
|
|
4246
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
4247
|
+
}
|
|
4248
|
+
}
|
|
4249
|
+
this.keyDependencies.delete(namespacedKey);
|
|
4250
|
+
} else if (this.dependencyIndex.size > 0) {
|
|
4251
|
+
for (const [pat, deps] of this.dependencyIndex) {
|
|
4252
|
+
deps.delete(namespacedKey);
|
|
4253
|
+
if (deps.size === 0) this.dependencyIndex.delete(pat);
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
}
|
|
4257
|
+
_handleL1Eviction(namespacedKey, reason) {
|
|
4258
|
+
const spilledToDisk = !this._diskDisabled && (reason === "capacity" || reason === "category" || reason === "rebalance" || reason === "oom");
|
|
4259
|
+
if (!spilledToDisk) {
|
|
4260
|
+
this._removeKeyTags(namespacedKey);
|
|
4261
|
+
this._removeKeyDependencies(namespacedKey);
|
|
4262
|
+
}
|
|
4263
|
+
}
|
|
4264
|
+
_removePrefixFromIndices(prefix) {
|
|
4265
|
+
for (const k of Array.from(this.keyTags.keys())) {
|
|
4266
|
+
if (k.startsWith(prefix)) this._removeKeyTags(k);
|
|
4267
|
+
}
|
|
4268
|
+
for (const k of Array.from(this.keyDependencies.keys())) {
|
|
4269
|
+
if (k.startsWith(prefix)) this._removeKeyDependencies(k);
|
|
4270
|
+
}
|
|
4271
|
+
for (const k of Array.from(this._l1Counters.keys())) {
|
|
4272
|
+
if (k.startsWith(prefix)) this._l1Counters.delete(k);
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
_sweepExpiredMetadata() {
|
|
4276
|
+
const now = Date.now();
|
|
4277
|
+
for (const [k, c] of this._l1Counters) {
|
|
4278
|
+
if (c.expiresAt <= now) this._l1Counters.delete(k);
|
|
4279
|
+
}
|
|
4280
|
+
for (const [k, meta] of this.keyTags) {
|
|
4281
|
+
if (meta.expiresAt <= now && !this.l1.has(k)) {
|
|
4282
|
+
this._removeKeyTags(k);
|
|
4283
|
+
this._removeKeyDependencies(k);
|
|
4284
|
+
}
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
_runOomCheck() {
|
|
4288
|
+
const heap = import_node_v82.default.getHeapStatistics();
|
|
4289
|
+
const heapUsed = heap.used_heap_size / heap.heap_size_limit;
|
|
4290
|
+
const cgroupUsed = Number.isFinite(this._cgroupMemoryLimit) && this._cgroupMemoryLimit > 0 ? process.memoryUsage().rss / this._cgroupMemoryLimit : 0;
|
|
4291
|
+
const used = Math.max(heapUsed, cgroupUsed);
|
|
4292
|
+
if (used >= this.opts.oomHeapThreshold) {
|
|
4293
|
+
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4294
|
+
this.counters.oomEvictions++;
|
|
4295
|
+
this.counters.oomLastAt = Date.now();
|
|
4296
|
+
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4297
|
+
heapUsedPct: Math.round(heapUsed * 100),
|
|
4298
|
+
cgroupUsedPct: cgroupUsed > 0 ? Math.round(cgroupUsed * 100) : void 0,
|
|
4299
|
+
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4300
|
+
evicted
|
|
4301
|
+
});
|
|
4302
|
+
}
|
|
4303
|
+
}
|
|
4049
4304
|
_ipcServer;
|
|
4050
4305
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
4051
4306
|
_subDisconnectedAt = null;
|
|
@@ -4092,6 +4347,7 @@ return 0
|
|
|
4092
4347
|
constructor(options = {}) {
|
|
4093
4348
|
const logger = options.logger ?? consoleLogger;
|
|
4094
4349
|
this.logger = logger;
|
|
4350
|
+
this._cgroupMemoryLimit = readCgroupMemoryLimit();
|
|
4095
4351
|
const ns = options.namespace?.trim() ?? "";
|
|
4096
4352
|
const encKeyRaw = options.encryptionKey ?? process.env.CACHE_ENCRYPTION_KEY;
|
|
4097
4353
|
this.enc = new CacheEncryption(
|
|
@@ -4169,12 +4425,15 @@ return 0
|
|
|
4169
4425
|
redisSentinel: options.redisSentinel,
|
|
4170
4426
|
redisProtocol: options.redisProtocol,
|
|
4171
4427
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
4172
|
-
compression: options.compression ?? "
|
|
4428
|
+
compression: options.compression ?? "zstd",
|
|
4429
|
+
customCompressor: options.customCompressor,
|
|
4173
4430
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
4174
4431
|
strictSingleton: options.strictSingleton ?? false,
|
|
4175
4432
|
failClosed: options.failClosed ?? false,
|
|
4176
4433
|
tagStrategy: options.tagStrategy ?? "set",
|
|
4177
4434
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
4435
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
4436
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
4178
4437
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
4179
4438
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
4180
4439
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4247,6 +4506,7 @@ return 0
|
|
|
4247
4506
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4248
4507
|
});
|
|
4249
4508
|
this._namespace = ns;
|
|
4509
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4250
4510
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4251
4511
|
this.watchdog = new TierLatencyWatchdog({
|
|
4252
4512
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4271,7 +4531,10 @@ return 0
|
|
|
4271
4531
|
void this.disk.save(key, entry);
|
|
4272
4532
|
});
|
|
4273
4533
|
},
|
|
4274
|
-
onEviction:
|
|
4534
|
+
onEviction: (key, reason) => {
|
|
4535
|
+
this._handleL1Eviction(key, reason);
|
|
4536
|
+
options.onEviction?.(key, reason);
|
|
4537
|
+
},
|
|
4275
4538
|
logger
|
|
4276
4539
|
});
|
|
4277
4540
|
if (!this.snapshotLoaded) {
|
|
@@ -4309,6 +4572,7 @@ return 0
|
|
|
4309
4572
|
}
|
|
4310
4573
|
this.cleanupInterval = setInterval(() => {
|
|
4311
4574
|
const cleaned = this.l1.cleanup();
|
|
4575
|
+
this._sweepExpiredMetadata();
|
|
4312
4576
|
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
4313
4577
|
}, 5 * 60 * 1e3);
|
|
4314
4578
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
@@ -4321,18 +4585,7 @@ return 0
|
|
|
4321
4585
|
}
|
|
4322
4586
|
if (this.opts.oomProtection) {
|
|
4323
4587
|
this.oomInterval = setInterval(() => {
|
|
4324
|
-
|
|
4325
|
-
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
4326
|
-
if (used >= this.opts.oomHeapThreshold) {
|
|
4327
|
-
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
4328
|
-
this.counters.oomEvictions++;
|
|
4329
|
-
this.counters.oomLastAt = Date.now();
|
|
4330
|
-
this.logger.warn("tricache OOM guard: emergency L1 eviction", {
|
|
4331
|
-
heapUsedPct: Math.round(used * 100),
|
|
4332
|
-
threshold: Math.round(this.opts.oomHeapThreshold * 100),
|
|
4333
|
-
evicted
|
|
4334
|
-
});
|
|
4335
|
-
}
|
|
4588
|
+
this._runOomCheck();
|
|
4336
4589
|
}, this.opts.oomCheckIntervalMs);
|
|
4337
4590
|
if (this.oomInterval.unref) this.oomInterval.unref();
|
|
4338
4591
|
}
|
|
@@ -4356,6 +4609,9 @@ return 0
|
|
|
4356
4609
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4357
4610
|
this.initBackplane();
|
|
4358
4611
|
const startupPromises = [];
|
|
4612
|
+
if (this.opts.compression === "zstd") {
|
|
4613
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4614
|
+
}
|
|
4359
4615
|
if (this.opts.remoteSnapshot) {
|
|
4360
4616
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4361
4617
|
}
|
|
@@ -4804,7 +5060,7 @@ return 0
|
|
|
4804
5060
|
else if (f === "src") src = v;
|
|
4805
5061
|
else if (f === "tagVersion") tagVersionRaw = v;
|
|
4806
5062
|
}
|
|
4807
|
-
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
5063
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr" || op === "tag_pattern_incr" || op === "tag_pattern_del";
|
|
4808
5064
|
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
4809
5065
|
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
4810
5066
|
op: String(op).slice(0, 40),
|
|
@@ -4861,6 +5117,50 @@ return 0
|
|
|
4861
5117
|
const tag = key;
|
|
4862
5118
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4863
5119
|
this._setLocalTagVersion(tag, ver, performance.now());
|
|
5120
|
+
} else if (op === "tag_pattern_incr") {
|
|
5121
|
+
const pattern = key;
|
|
5122
|
+
const now = performance.now();
|
|
5123
|
+
for (const [tag, info] of this.tagVersions) {
|
|
5124
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5125
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
5126
|
+
}
|
|
5127
|
+
}
|
|
5128
|
+
this.l1.scan((k, entry) => {
|
|
5129
|
+
if (entry.tagVersions) {
|
|
5130
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
5131
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5132
|
+
this.l1.delete(k);
|
|
5133
|
+
this._bumpKeyMutation(k);
|
|
5134
|
+
break;
|
|
5135
|
+
}
|
|
5136
|
+
}
|
|
5137
|
+
}
|
|
5138
|
+
}, 0);
|
|
5139
|
+
} else if (op === "tag_pattern_del") {
|
|
5140
|
+
const pattern = key;
|
|
5141
|
+
const matchedTagKeys = [];
|
|
5142
|
+
const prefix = this.nk("_tag_:");
|
|
5143
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
5144
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
5145
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5146
|
+
matchedTagKeys.push(tagKey);
|
|
5147
|
+
for (const k of members) {
|
|
5148
|
+
this.l1.delete(k);
|
|
5149
|
+
this._bumpKeyMutation(k);
|
|
5150
|
+
this._pendingDiskDeletes.add(k);
|
|
5151
|
+
setImmediate(() => {
|
|
5152
|
+
try {
|
|
5153
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5154
|
+
} finally {
|
|
5155
|
+
this._pendingDiskDeletes.delete(k);
|
|
5156
|
+
}
|
|
5157
|
+
});
|
|
5158
|
+
}
|
|
5159
|
+
}
|
|
5160
|
+
}
|
|
5161
|
+
for (const tagKey of matchedTagKeys) {
|
|
5162
|
+
this.tagIndex.delete(tagKey);
|
|
5163
|
+
}
|
|
4864
5164
|
}
|
|
4865
5165
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4866
5166
|
}
|
|
@@ -4868,7 +5168,7 @@ return 0
|
|
|
4868
5168
|
_handleBackplaneMessage(message) {
|
|
4869
5169
|
try {
|
|
4870
5170
|
const msg = JSON.parse(message);
|
|
4871
|
-
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") {
|
|
5171
|
+
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") {
|
|
4872
5172
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4873
5173
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4874
5174
|
});
|
|
@@ -5022,6 +5322,72 @@ return 0
|
|
|
5022
5322
|
}
|
|
5023
5323
|
this.tagVersions.set(tag, { version: finalVersion, lastSyncedAt: now });
|
|
5024
5324
|
}
|
|
5325
|
+
async _isGenerationalEntryStale(tagVersions) {
|
|
5326
|
+
if (this.opts.tagStrategy !== "generational" || !tagVersions) return false;
|
|
5327
|
+
const tags = Object.keys(tagVersions);
|
|
5328
|
+
if (tags.length === 0) return false;
|
|
5329
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5330
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5331
|
+
if (currentVers[i] > tagVersions[tags[i]]) return true;
|
|
5332
|
+
}
|
|
5333
|
+
return false;
|
|
5334
|
+
}
|
|
5335
|
+
async _deleteRedisKeys(client, keys) {
|
|
5336
|
+
if (keys.length === 0) return;
|
|
5337
|
+
const CHUNK_SIZE = 1e3;
|
|
5338
|
+
if (client instanceof import_ioredis.Cluster) {
|
|
5339
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
5340
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
5341
|
+
const pl = client.pipeline();
|
|
5342
|
+
for (const k of chunk) pl.del(k);
|
|
5343
|
+
await pl.exec();
|
|
5344
|
+
}
|
|
5345
|
+
return;
|
|
5346
|
+
}
|
|
5347
|
+
for (let i = 0; i < keys.length; i += CHUNK_SIZE) {
|
|
5348
|
+
const chunk = keys.slice(i, i + CHUNK_SIZE);
|
|
5349
|
+
await client.del(...chunk);
|
|
5350
|
+
}
|
|
5351
|
+
}
|
|
5352
|
+
async _parseGenerationalRedisHash(k, hashData) {
|
|
5353
|
+
if (!hashData || !hashData.d) return null;
|
|
5354
|
+
let storedTagVersions = {};
|
|
5355
|
+
if (hashData.tv) {
|
|
5356
|
+
try {
|
|
5357
|
+
storedTagVersions = JSON.parse(hashData.tv);
|
|
5358
|
+
} catch {
|
|
5359
|
+
}
|
|
5360
|
+
}
|
|
5361
|
+
if (await this._isGenerationalEntryStale(storedTagVersions)) {
|
|
5362
|
+
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5363
|
+
this._deleteIfStale(k, setAtMs);
|
|
5364
|
+
return { stale: true };
|
|
5365
|
+
}
|
|
5366
|
+
const value = await this._decryptAndDeserialize(hashData.d);
|
|
5367
|
+
return { value, tagVersions: storedTagVersions, stale: false };
|
|
5368
|
+
}
|
|
5369
|
+
async _readRedisEntry(client, k, allowAutoPipeline = false) {
|
|
5370
|
+
if (this.opts.tagStrategy === "generational" && typeof client.hgetall === "function") {
|
|
5371
|
+
try {
|
|
5372
|
+
const hashData = await client.hgetall(k);
|
|
5373
|
+
if (typeof hashData === "string") {
|
|
5374
|
+
const value2 = await this._decryptAndDeserialize(hashData);
|
|
5375
|
+
return { value: value2, stale: false };
|
|
5376
|
+
}
|
|
5377
|
+
if (hashData && hashData.d) {
|
|
5378
|
+
return await this._parseGenerationalRedisHash(k, hashData);
|
|
5379
|
+
}
|
|
5380
|
+
return null;
|
|
5381
|
+
} catch (err) {
|
|
5382
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
5383
|
+
if (!msg.includes("WRONGTYPE")) throw err;
|
|
5384
|
+
}
|
|
5385
|
+
}
|
|
5386
|
+
const raw = allowAutoPipeline && this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5387
|
+
if (raw == null) return null;
|
|
5388
|
+
const value = await this._decryptAndDeserialize(raw);
|
|
5389
|
+
return { value, stale: false };
|
|
5390
|
+
}
|
|
5025
5391
|
async _getTagVersion(tag) {
|
|
5026
5392
|
const now = performance.now();
|
|
5027
5393
|
const local = this.tagVersions.get(tag);
|
|
@@ -5055,12 +5421,12 @@ return 0
|
|
|
5055
5421
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
5056
5422
|
*/
|
|
5057
5423
|
async _serializeAndEncrypt(serialized) {
|
|
5058
|
-
const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
5059
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5424
|
+
const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
5425
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5060
5426
|
return this._workerPool.encrypt(serialized);
|
|
5061
5427
|
}
|
|
5062
5428
|
if (isCompressed2) {
|
|
5063
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
5429
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
5064
5430
|
if (this.enc.isEnabled) {
|
|
5065
5431
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
5066
5432
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -5075,16 +5441,16 @@ return 0
|
|
|
5075
5441
|
*/
|
|
5076
5442
|
async _decryptAndDeserialize(raw) {
|
|
5077
5443
|
let plain;
|
|
5078
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
5444
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
5079
5445
|
plain = await this._workerPool.decrypt(raw);
|
|
5080
5446
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
5081
5447
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
5082
5448
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
5083
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5449
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
5084
5450
|
plain = decompressed.toString("utf8");
|
|
5085
5451
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
5086
5452
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
5087
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5453
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
5088
5454
|
plain = decompressed.toString("utf8");
|
|
5089
5455
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
5090
5456
|
plain = this.enc.decrypt(raw);
|
|
@@ -5159,8 +5525,8 @@ return 0
|
|
|
5159
5525
|
return client;
|
|
5160
5526
|
}
|
|
5161
5527
|
this.redisConnecting = (async () => {
|
|
5528
|
+
let client = null;
|
|
5162
5529
|
try {
|
|
5163
|
-
let client;
|
|
5164
5530
|
if (this.opts.redisClusterNodes?.length) {
|
|
5165
5531
|
client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
5166
5532
|
redisOptions: {
|
|
@@ -5223,14 +5589,45 @@ return 0
|
|
|
5223
5589
|
});
|
|
5224
5590
|
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
5225
5591
|
}
|
|
5592
|
+
const pendingClient = client;
|
|
5226
5593
|
await new Promise((resolve, reject) => {
|
|
5227
|
-
|
|
5228
|
-
|
|
5594
|
+
let settled = false;
|
|
5595
|
+
const cleanupListeners = () => {
|
|
5596
|
+
pendingClient.removeListener?.("ready", onReady);
|
|
5597
|
+
pendingClient.removeListener?.("error", onError);
|
|
5598
|
+
};
|
|
5599
|
+
const onReady = () => {
|
|
5600
|
+
if (settled) return;
|
|
5601
|
+
settled = true;
|
|
5602
|
+
clearTimeout(timer);
|
|
5603
|
+
cleanupListeners();
|
|
5604
|
+
resolve();
|
|
5605
|
+
};
|
|
5606
|
+
const onError = (e) => {
|
|
5607
|
+
if (settled) return;
|
|
5608
|
+
settled = true;
|
|
5609
|
+
clearTimeout(timer);
|
|
5610
|
+
cleanupListeners();
|
|
5229
5611
|
this._checkAndLogResp3Hint(e);
|
|
5230
5612
|
reject(e);
|
|
5231
|
-
}
|
|
5232
|
-
setTimeout(() =>
|
|
5613
|
+
};
|
|
5614
|
+
const timer = setTimeout(() => {
|
|
5615
|
+
if (settled) return;
|
|
5616
|
+
settled = true;
|
|
5617
|
+
cleanupListeners();
|
|
5618
|
+
reject(new Error("Redis connection timeout"));
|
|
5619
|
+
}, 15e3);
|
|
5620
|
+
if (timer.unref) timer.unref();
|
|
5621
|
+
pendingClient.once("ready", onReady);
|
|
5622
|
+
pendingClient.once("error", onError);
|
|
5233
5623
|
});
|
|
5624
|
+
if (this._destroyed) {
|
|
5625
|
+
try {
|
|
5626
|
+
client.disconnect();
|
|
5627
|
+
} catch {
|
|
5628
|
+
}
|
|
5629
|
+
this._assertActive("getRedis");
|
|
5630
|
+
}
|
|
5234
5631
|
this.cb.onSuccess();
|
|
5235
5632
|
this.redis = client;
|
|
5236
5633
|
this.pipeliner = new AutoPipeliner(client, {
|
|
@@ -5240,6 +5637,10 @@ return 0
|
|
|
5240
5637
|
this.redisConnecting = null;
|
|
5241
5638
|
return client;
|
|
5242
5639
|
} catch (err) {
|
|
5640
|
+
try {
|
|
5641
|
+
client?.disconnect();
|
|
5642
|
+
} catch {
|
|
5643
|
+
}
|
|
5243
5644
|
this.cb.onFailure();
|
|
5244
5645
|
this.redisConnecting = null;
|
|
5245
5646
|
this._checkAndLogResp3Hint(err);
|
|
@@ -5480,20 +5881,10 @@ return 0
|
|
|
5480
5881
|
const optRefreshAhead = opts.refreshAhead;
|
|
5481
5882
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5482
5883
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5483
|
-
const optTags = opts.tags;
|
|
5884
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5484
5885
|
const l1Hit = this.l1.get(k);
|
|
5485
5886
|
if (l1Hit !== null) {
|
|
5486
|
-
|
|
5487
|
-
if (this.opts.tagStrategy === "generational" && l1Hit.tagVersions) {
|
|
5488
|
-
const tags = Object.keys(l1Hit.tagVersions);
|
|
5489
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5490
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5491
|
-
if (currentVers[i] > l1Hit.tagVersions[tags[i]]) {
|
|
5492
|
-
isGenerationalStale = true;
|
|
5493
|
-
break;
|
|
5494
|
-
}
|
|
5495
|
-
}
|
|
5496
|
-
}
|
|
5887
|
+
const isGenerationalStale = await this._isGenerationalEntryStale(l1Hit.tagVersions);
|
|
5497
5888
|
if (isGenerationalStale) {
|
|
5498
5889
|
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
5499
5890
|
} else {
|
|
@@ -5579,17 +5970,7 @@ return 0
|
|
|
5579
5970
|
this.watchdog.recordDisk(diskElapsed);
|
|
5580
5971
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5581
5972
|
if (diskHit !== null) {
|
|
5582
|
-
|
|
5583
|
-
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5584
|
-
const tags = Object.keys(diskHit.tagVersions);
|
|
5585
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5586
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5587
|
-
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5588
|
-
isDiskStale = true;
|
|
5589
|
-
break;
|
|
5590
|
-
}
|
|
5591
|
-
}
|
|
5592
|
-
}
|
|
5973
|
+
const isDiskStale = await this._isGenerationalEntryStale(diskHit.tagVersions);
|
|
5593
5974
|
if (isDiskStale) {
|
|
5594
5975
|
this.disk.delete(k);
|
|
5595
5976
|
} else {
|
|
@@ -5617,57 +5998,27 @@ return 0
|
|
|
5617
5998
|
try {
|
|
5618
5999
|
const client = await this.getRedis();
|
|
5619
6000
|
const redisStart = performance.now();
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
|
|
5623
|
-
|
|
5624
|
-
|
|
5625
|
-
|
|
5626
|
-
|
|
5627
|
-
|
|
5628
|
-
|
|
5629
|
-
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
}
|
|
5634
|
-
const tags = Object.keys(storedTagVersions);
|
|
5635
|
-
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5636
|
-
for (let i = 0; i < tags.length; i++) {
|
|
5637
|
-
if (currentVers[i] > storedTagVersions[tags[i]]) {
|
|
5638
|
-
isStale = true;
|
|
5639
|
-
break;
|
|
5640
|
-
}
|
|
5641
|
-
}
|
|
5642
|
-
if (isStale) {
|
|
5643
|
-
const setAtMs = parseInt(hashData.t, 10) || 0;
|
|
5644
|
-
this._deleteIfStale(k, setAtMs);
|
|
5645
|
-
} else {
|
|
5646
|
-
const parsed = await this._decryptAndDeserialize(hashData.d);
|
|
5647
|
-
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, storedTagVersions);
|
|
5648
|
-
this.counters.l2Hits++;
|
|
5649
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
5650
|
-
this.logger.debug("L2 hit (Redis hash)", { cacheKey });
|
|
5651
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5652
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
5653
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5654
|
-
}
|
|
5655
|
-
}
|
|
5656
|
-
} else {
|
|
5657
|
-
const raw = this.opts.autoPipeline && this.pipeliner ? await this.pipeliner.get(k) : await client.get(k);
|
|
5658
|
-
const redisElapsed = performance.now() - redisStart;
|
|
5659
|
-
this.watchdog.recordRedis(redisElapsed);
|
|
5660
|
-
this.cb.onSuccess();
|
|
5661
|
-
if (raw) {
|
|
5662
|
-
const parsed = await this._decryptAndDeserialize(raw);
|
|
5663
|
-
this.l1.set(k, parsed, ttlMs, priority);
|
|
5664
|
-
this.counters.l2Hits++;
|
|
5665
|
-
this.opts.onHit?.(cacheKey, "l2");
|
|
5666
|
-
this.logger.debug("L2 hit (Redis)", { cacheKey });
|
|
5667
|
-
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
5668
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
5669
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6001
|
+
const redisHit = await this._readRedisEntry(client, k, true);
|
|
6002
|
+
const redisElapsed = performance.now() - redisStart;
|
|
6003
|
+
this.watchdog.recordRedis(redisElapsed);
|
|
6004
|
+
this.cb.onSuccess();
|
|
6005
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
6006
|
+
const parsed = redisHit.value;
|
|
6007
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
6008
|
+
this.logger.debug("Aborting L2 promotion \u2014 key was mutated or deleted during Redis read", { cacheKey });
|
|
6009
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
6010
|
+
const current = this.l1.get(k);
|
|
6011
|
+
const liveVal = current && !current.isStale && current.value !== void 0 ? current.value : parsed;
|
|
6012
|
+
if (this.opts.frozen) deepFreeze(liveVal);
|
|
6013
|
+
return this.opts.cloneStrategy === "structuredClone" && liveVal != null && typeof liveVal === "object" ? structuredClone(liveVal) : liveVal;
|
|
5670
6014
|
}
|
|
6015
|
+
this.l1.set(k, parsed, ttlMs, priority, void 0, void 0, redisHit.tagVersions);
|
|
6016
|
+
this.counters.l2Hits++;
|
|
6017
|
+
this.opts.onHit?.(cacheKey, "l2");
|
|
6018
|
+
this.logger.debug(redisHit.tagVersions ? "L2 hit (Redis hash)" : "L2 hit (Redis)", { cacheKey });
|
|
6019
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "remote").setAttribute("cache.hit_tier", "l2");
|
|
6020
|
+
if (this.opts.frozen) deepFreeze(parsed);
|
|
6021
|
+
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
5671
6022
|
}
|
|
5672
6023
|
} catch (err) {
|
|
5673
6024
|
this.cb.onFailure();
|
|
@@ -5729,20 +6080,20 @@ return 0
|
|
|
5729
6080
|
if (this.opts.frozen) deepFreeze(data);
|
|
5730
6081
|
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5731
6082
|
}
|
|
5732
|
-
|
|
6083
|
+
const writeTs = Date.now();
|
|
6084
|
+
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
5733
6085
|
if (!this._redisDisabled) {
|
|
5734
6086
|
try {
|
|
5735
6087
|
const client = await this.getRedis();
|
|
5736
6088
|
const serialized = JSON.stringify(data);
|
|
5737
6089
|
const toStore = await this._serializeAndEncrypt(serialized);
|
|
5738
6090
|
const ttlSec = Math.ceil(effectiveTtl / 1e3);
|
|
5739
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5740
|
-
const now = Date.now();
|
|
6091
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5741
6092
|
const tx = client.multi();
|
|
5742
6093
|
tx.hset(k, {
|
|
5743
6094
|
d: toStore,
|
|
5744
|
-
t: String(
|
|
5745
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6095
|
+
t: String(writeTs),
|
|
6096
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5746
6097
|
});
|
|
5747
6098
|
tx.expire(k, ttlSec);
|
|
5748
6099
|
await tx.exec();
|
|
@@ -5880,20 +6231,20 @@ return 0
|
|
|
5880
6231
|
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
5881
6232
|
return;
|
|
5882
6233
|
}
|
|
5883
|
-
|
|
6234
|
+
const writeTs = Date.now();
|
|
6235
|
+
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions, writeTs);
|
|
5884
6236
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5885
6237
|
try {
|
|
5886
6238
|
const client = await this.getRedis();
|
|
5887
6239
|
const s = JSON.stringify(data);
|
|
5888
6240
|
const stored = await this._serializeAndEncrypt(s);
|
|
5889
6241
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5890
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5891
|
-
const now = Date.now();
|
|
6242
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5892
6243
|
const tx = client.multi();
|
|
5893
6244
|
tx.hset(cacheKey, {
|
|
5894
6245
|
d: stored,
|
|
5895
|
-
t: String(
|
|
5896
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6246
|
+
t: String(writeTs),
|
|
6247
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5897
6248
|
});
|
|
5898
6249
|
tx.expire(cacheKey, ttlSec);
|
|
5899
6250
|
await tx.exec();
|
|
@@ -5938,27 +6289,35 @@ return 0
|
|
|
5938
6289
|
this._pendingDiskDeletes.delete(k);
|
|
5939
6290
|
this.counters.sets++;
|
|
5940
6291
|
let activeTagVersions;
|
|
5941
|
-
|
|
6292
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
6293
|
+
if (tagsToRegister?.length) {
|
|
5942
6294
|
if (this.opts.tagStrategy === "generational") {
|
|
5943
|
-
const vers = await Promise.all(
|
|
6295
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5944
6296
|
activeTagVersions = {};
|
|
5945
|
-
for (let i = 0; i <
|
|
5946
|
-
activeTagVersions[
|
|
6297
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
6298
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5947
6299
|
}
|
|
5948
6300
|
} else {
|
|
5949
|
-
await this._registerTags(k,
|
|
6301
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5950
6302
|
}
|
|
5951
6303
|
}
|
|
5952
|
-
|
|
5953
|
-
|
|
5954
|
-
|
|
5955
|
-
|
|
5956
|
-
|
|
5957
|
-
|
|
5958
|
-
|
|
5959
|
-
this.
|
|
6304
|
+
const writeTs = Date.now();
|
|
6305
|
+
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions, writeTs);
|
|
6306
|
+
if (opts?.dependsOn !== void 0) {
|
|
6307
|
+
this._removeKeyDependencies(k);
|
|
6308
|
+
if (opts.dependsOn.length > 0) {
|
|
6309
|
+
const nsPatterns = [];
|
|
6310
|
+
for (const pattern of opts.dependsOn) {
|
|
6311
|
+
const nsPattern = this.nk(pattern);
|
|
6312
|
+
nsPatterns.push(nsPattern);
|
|
6313
|
+
let deps = this.dependencyIndex.get(nsPattern);
|
|
6314
|
+
if (!deps) {
|
|
6315
|
+
deps = /* @__PURE__ */ new Set();
|
|
6316
|
+
this.dependencyIndex.set(nsPattern, deps);
|
|
6317
|
+
}
|
|
6318
|
+
deps.add(k);
|
|
5960
6319
|
}
|
|
5961
|
-
|
|
6320
|
+
this.keyDependencies.set(k, nsPatterns);
|
|
5962
6321
|
}
|
|
5963
6322
|
}
|
|
5964
6323
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -5967,13 +6326,12 @@ return 0
|
|
|
5967
6326
|
const s = JSON.stringify(data);
|
|
5968
6327
|
const stored = await this._serializeAndEncrypt(s);
|
|
5969
6328
|
const ttlSec = Math.ceil(ttlMs / 1e3);
|
|
5970
|
-
if (this.opts.tagStrategy === "generational" && activeTagVersions) {
|
|
5971
|
-
const now = Date.now();
|
|
6329
|
+
if (this.opts.tagStrategy === "generational" && (activeTagVersions || !this.opts.autoPipeline && typeof client.hgetall === "function")) {
|
|
5972
6330
|
const tx = client.multi();
|
|
5973
6331
|
tx.hset(k, {
|
|
5974
6332
|
d: stored,
|
|
5975
|
-
t: String(
|
|
5976
|
-
tv: JSON.stringify(activeTagVersions)
|
|
6333
|
+
t: String(writeTs),
|
|
6334
|
+
tv: JSON.stringify(activeTagVersions ?? {})
|
|
5977
6335
|
});
|
|
5978
6336
|
tx.expire(k, ttlSec);
|
|
5979
6337
|
await tx.exec();
|
|
@@ -6008,7 +6366,18 @@ return 0
|
|
|
6008
6366
|
* the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
|
|
6009
6367
|
*/
|
|
6010
6368
|
async _registerTags(k, tags, ttlSeconds) {
|
|
6011
|
-
|
|
6369
|
+
this._removeKeyTags(k);
|
|
6370
|
+
const effectiveTtl = ttlSeconds > 0 ? ttlSeconds : INDEFINITE_TTL_SECONDS;
|
|
6371
|
+
const expiresAt = Date.now() + effectiveTtl * 1e3;
|
|
6372
|
+
if (this.keyTags.size >= 1e5 && !this.keyTags.has(k)) {
|
|
6373
|
+
this._sweepExpiredMetadata();
|
|
6374
|
+
if (this.keyTags.size >= 1e5) {
|
|
6375
|
+
const oldestKey = this.keyTags.keys().next().value;
|
|
6376
|
+
if (oldestKey !== void 0) this._removeKeyTags(oldestKey);
|
|
6377
|
+
}
|
|
6378
|
+
}
|
|
6379
|
+
const uniqueTags = Array.from(new Set(tags));
|
|
6380
|
+
for (const tag of uniqueTags) {
|
|
6012
6381
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6013
6382
|
let members = this.tagIndex.get(tagKey);
|
|
6014
6383
|
if (!members) {
|
|
@@ -6017,14 +6386,15 @@ return 0
|
|
|
6017
6386
|
}
|
|
6018
6387
|
members.add(k);
|
|
6019
6388
|
}
|
|
6389
|
+
this.keyTags.set(k, { tags: uniqueTags, expiresAt });
|
|
6020
6390
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6021
6391
|
try {
|
|
6022
6392
|
const client = await this.getRedis();
|
|
6023
6393
|
const pl = client.pipeline();
|
|
6024
|
-
for (const tag of
|
|
6394
|
+
for (const tag of uniqueTags) {
|
|
6025
6395
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6026
6396
|
pl.sadd(tagKey, k);
|
|
6027
|
-
pl.expire(tagKey,
|
|
6397
|
+
pl.expire(tagKey, effectiveTtl + 3600);
|
|
6028
6398
|
}
|
|
6029
6399
|
await pl.exec();
|
|
6030
6400
|
this.cb.onSuccess();
|
|
@@ -6063,6 +6433,13 @@ return 0
|
|
|
6063
6433
|
}
|
|
6064
6434
|
this._addPatternTombstone(pfx);
|
|
6065
6435
|
this.l1.deletePattern(k);
|
|
6436
|
+
this._removePrefixFromIndices(pfx);
|
|
6437
|
+
for (const ktKey of Array.from(this.keyTags.keys())) {
|
|
6438
|
+
if (this._matchesGlob(ktKey, k)) this._removeKeyTags(ktKey);
|
|
6439
|
+
}
|
|
6440
|
+
for (const kdKey of Array.from(this.keyDependencies.keys())) {
|
|
6441
|
+
if (this._matchesGlob(kdKey, k)) this._removeKeyDependencies(kdKey);
|
|
6442
|
+
}
|
|
6066
6443
|
} else {
|
|
6067
6444
|
this._bumpKeyMutation(k);
|
|
6068
6445
|
this.inflight.delete(k);
|
|
@@ -6075,15 +6452,16 @@ return 0
|
|
|
6075
6452
|
this._pendingDiskDeletes.delete(k);
|
|
6076
6453
|
}
|
|
6077
6454
|
});
|
|
6455
|
+
this._removeKeyTags(k);
|
|
6078
6456
|
this._cascadeDependencies(k);
|
|
6079
|
-
|
|
6457
|
+
this._removeKeyDependencies(k);
|
|
6080
6458
|
}
|
|
6081
6459
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6082
6460
|
try {
|
|
6083
6461
|
const client = await this.getRedis();
|
|
6084
6462
|
if (isPattern) {
|
|
6085
6463
|
const keys = await this._scanKeys(client, k);
|
|
6086
|
-
|
|
6464
|
+
await this._deleteRedisKeys(client, keys);
|
|
6087
6465
|
} else {
|
|
6088
6466
|
if (this.opts.autoPipeline && this.pipeliner) {
|
|
6089
6467
|
await this.pipeliner.del(k);
|
|
@@ -6145,6 +6523,15 @@ return 0
|
|
|
6145
6523
|
entry.value++;
|
|
6146
6524
|
return entry.value;
|
|
6147
6525
|
}
|
|
6526
|
+
if (this._l1Counters.size >= 5e4 && !this._l1Counters.has(k)) {
|
|
6527
|
+
for (const [ck, cv] of this._l1Counters) {
|
|
6528
|
+
if (cv.expiresAt <= now) this._l1Counters.delete(ck);
|
|
6529
|
+
}
|
|
6530
|
+
if (this._l1Counters.size >= 5e4) {
|
|
6531
|
+
const oldest = this._l1Counters.keys().next().value;
|
|
6532
|
+
if (oldest !== void 0) this._l1Counters.delete(oldest);
|
|
6533
|
+
}
|
|
6534
|
+
}
|
|
6148
6535
|
this._l1Counters.set(k, { value: 1, expiresAt: now + ttlMs });
|
|
6149
6536
|
return 1;
|
|
6150
6537
|
}
|
|
@@ -6191,6 +6578,7 @@ return 0
|
|
|
6191
6578
|
}
|
|
6192
6579
|
this._addPatternTombstone(pfx);
|
|
6193
6580
|
this.l1.deletePattern(k);
|
|
6581
|
+
this._removePrefixFromIndices(pfx);
|
|
6194
6582
|
} else {
|
|
6195
6583
|
this._globalEpoch++;
|
|
6196
6584
|
this.inflight.clear();
|
|
@@ -6199,7 +6587,10 @@ return 0
|
|
|
6199
6587
|
if (!this._diskDisabled) this.disk.clear();
|
|
6200
6588
|
this._l1Counters.clear();
|
|
6201
6589
|
this.tagIndex.clear();
|
|
6590
|
+
this.keyTags.clear();
|
|
6202
6591
|
this.tagVersions.clear();
|
|
6592
|
+
this.dependencyIndex.clear();
|
|
6593
|
+
this.keyDependencies.clear();
|
|
6203
6594
|
this._pendingDiskDeletes.clear();
|
|
6204
6595
|
this._keyMutationEpochs.clear();
|
|
6205
6596
|
}
|
|
@@ -6208,7 +6599,7 @@ return 0
|
|
|
6208
6599
|
const client = await this.getRedis();
|
|
6209
6600
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
6210
6601
|
const keys = await this._scanKeys(client, pattern);
|
|
6211
|
-
|
|
6602
|
+
await this._deleteRedisKeys(client, keys);
|
|
6212
6603
|
} catch (err) {
|
|
6213
6604
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6214
6605
|
}
|
|
@@ -6351,6 +6742,10 @@ return 0
|
|
|
6351
6742
|
this._assertActive("touch");
|
|
6352
6743
|
const k = this.nk(cacheKey);
|
|
6353
6744
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
6745
|
+
if (hit) {
|
|
6746
|
+
const kt = this.keyTags.get(k);
|
|
6747
|
+
if (kt) kt.expiresAt = Date.now() + newTtlSeconds * 1e3;
|
|
6748
|
+
}
|
|
6354
6749
|
if (hit && !this._redisDisabled) {
|
|
6355
6750
|
try {
|
|
6356
6751
|
const client = await this.getRedis();
|
|
@@ -6378,6 +6773,10 @@ return 0
|
|
|
6378
6773
|
if (entry.staleAt !== void 0 && entry.staleAt < now) return null;
|
|
6379
6774
|
return entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6380
6775
|
}
|
|
6776
|
+
_prepareReadValue(val) {
|
|
6777
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6778
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6779
|
+
}
|
|
6381
6780
|
/**
|
|
6382
6781
|
* Pure read across cache tiers (L1 RAM → L1.5 Disk → L2 Redis) without invoking a fetcher.
|
|
6383
6782
|
* Returns the cached value if found and valid, or `null` if absent / expired.
|
|
@@ -6391,11 +6790,13 @@ return 0
|
|
|
6391
6790
|
const k = this.nk(cacheKey);
|
|
6392
6791
|
const l1Hit = this.l1.get(k);
|
|
6393
6792
|
if (l1Hit !== null) {
|
|
6394
|
-
this.
|
|
6395
|
-
|
|
6396
|
-
|
|
6397
|
-
|
|
6398
|
-
|
|
6793
|
+
if (await this._isGenerationalEntryStale(l1Hit.tagVersions)) {
|
|
6794
|
+
this._deleteIfStale(k, l1Hit.setAt ?? 0);
|
|
6795
|
+
} else {
|
|
6796
|
+
this.counters.gets++;
|
|
6797
|
+
this.counters.l1Hits++;
|
|
6798
|
+
return this._prepareReadValue(l1Hit.value);
|
|
6799
|
+
}
|
|
6399
6800
|
}
|
|
6400
6801
|
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6401
6802
|
if (this._isTombstonedByPattern(k)) {
|
|
@@ -6410,18 +6811,20 @@ return 0
|
|
|
6410
6811
|
this.watchdog.recordDisk(diskElapsed);
|
|
6411
6812
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6412
6813
|
if (diskHit !== null) {
|
|
6413
|
-
|
|
6414
|
-
|
|
6415
|
-
|
|
6416
|
-
|
|
6417
|
-
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
6421
|
-
this.
|
|
6422
|
-
|
|
6423
|
-
|
|
6424
|
-
|
|
6814
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6815
|
+
this.disk.delete(k);
|
|
6816
|
+
} else {
|
|
6817
|
+
const promoted = this.l1.importEntries(
|
|
6818
|
+
[{ key: k, entry: diskHit }],
|
|
6819
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6820
|
+
);
|
|
6821
|
+
if (promoted > 0) {
|
|
6822
|
+
const l1Check = this.l1.get(k);
|
|
6823
|
+
if (l1Check !== null) {
|
|
6824
|
+
this.counters.gets++;
|
|
6825
|
+
this.counters.diskHits++;
|
|
6826
|
+
return this._prepareReadValue(l1Check.value);
|
|
6827
|
+
}
|
|
6425
6828
|
}
|
|
6426
6829
|
}
|
|
6427
6830
|
}
|
|
@@ -6431,17 +6834,16 @@ return 0
|
|
|
6431
6834
|
try {
|
|
6432
6835
|
const client = await this.getRedis();
|
|
6433
6836
|
const redisStart = performance.now();
|
|
6434
|
-
const
|
|
6837
|
+
const redisHit = await this._readRedisEntry(client, k);
|
|
6435
6838
|
const redisElapsed = performance.now() - redisStart;
|
|
6436
6839
|
this.watchdog.recordRedis(redisElapsed);
|
|
6437
|
-
|
|
6438
|
-
|
|
6439
|
-
|
|
6840
|
+
this.cb.onSuccess();
|
|
6841
|
+
if (redisHit && !redisHit.stale && redisHit.value !== void 0) {
|
|
6842
|
+
const parsed = redisHit.value;
|
|
6843
|
+
this.l1.set(k, parsed, 6e4, inferPriority(cacheKey), void 0, void 0, redisHit.tagVersions);
|
|
6440
6844
|
this.counters.gets++;
|
|
6441
6845
|
this.counters.l2Hits++;
|
|
6442
|
-
this.
|
|
6443
|
-
if (this.opts.frozen) deepFreeze(parsed);
|
|
6444
|
-
return this.opts.cloneStrategy === "structuredClone" && parsed != null && typeof parsed === "object" ? structuredClone(parsed) : parsed;
|
|
6846
|
+
return this._prepareReadValue(parsed);
|
|
6445
6847
|
}
|
|
6446
6848
|
} catch (err) {
|
|
6447
6849
|
this.cb.onFailure();
|
|
@@ -6469,12 +6871,20 @@ return 0
|
|
|
6469
6871
|
const result = Array.from({ length: keys.length });
|
|
6470
6872
|
const missIndexes = [];
|
|
6471
6873
|
const missKeys = [];
|
|
6874
|
+
const now = Date.now();
|
|
6472
6875
|
for (let i = 0; i < keys.length; i++) {
|
|
6473
6876
|
const k = this.nk(keys[i]);
|
|
6474
6877
|
const entry = this.l1.getEntry(k);
|
|
6475
|
-
if (entry && entry.expiresAt >
|
|
6476
|
-
|
|
6477
|
-
|
|
6878
|
+
if (entry && entry.expiresAt > now) {
|
|
6879
|
+
if (await this._isGenerationalEntryStale(entry.tagVersions)) {
|
|
6880
|
+
this._deleteIfStale(k, entry.setAt ?? 0);
|
|
6881
|
+
missIndexes.push(i);
|
|
6882
|
+
missKeys.push(keys[i]);
|
|
6883
|
+
} else {
|
|
6884
|
+
const val = entry.value !== void 0 ? entry.value : this.codec.decode(entry.data);
|
|
6885
|
+
result[i] = this._prepareReadValue(val);
|
|
6886
|
+
this.counters.l1Hits++;
|
|
6887
|
+
}
|
|
6478
6888
|
} else {
|
|
6479
6889
|
missIndexes.push(i);
|
|
6480
6890
|
missKeys.push(keys[i]);
|
|
@@ -6495,23 +6905,57 @@ return 0
|
|
|
6495
6905
|
const client = await this.getRedis();
|
|
6496
6906
|
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
6497
6907
|
const pipeline = client.multi();
|
|
6498
|
-
|
|
6908
|
+
const useHashPipeline = this.opts.tagStrategy === "generational" && typeof pipeline.hgetall === "function";
|
|
6909
|
+
for (const nk of nsKeys) {
|
|
6910
|
+
if (useHashPipeline) {
|
|
6911
|
+
pipeline.hgetall(nk);
|
|
6912
|
+
} else {
|
|
6913
|
+
pipeline.get(nk);
|
|
6914
|
+
}
|
|
6915
|
+
}
|
|
6499
6916
|
const redisStart = performance.now();
|
|
6500
6917
|
const raws = await pipeline.exec();
|
|
6501
6918
|
const redisElapsed = (performance.now() - redisStart) / Math.max(1, missKeys.length);
|
|
6502
6919
|
this.watchdog.recordRedis(redisElapsed);
|
|
6503
6920
|
this.cb.onSuccess();
|
|
6504
6921
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6505
|
-
const
|
|
6922
|
+
const tuple = raws[j];
|
|
6923
|
+
const err = tuple ? tuple[0] : null;
|
|
6924
|
+
const rawVal = tuple ? tuple[1] : null;
|
|
6506
6925
|
const idx = missIndexes[j];
|
|
6507
|
-
|
|
6508
|
-
|
|
6509
|
-
|
|
6926
|
+
const k = nsKeys[j];
|
|
6927
|
+
let parsed;
|
|
6928
|
+
let tagVersions;
|
|
6929
|
+
let hit = false;
|
|
6930
|
+
if (useHashPipeline) {
|
|
6931
|
+
if (err && err.message?.includes("WRONGTYPE")) {
|
|
6932
|
+
const fallbackRaw = await client.get(k);
|
|
6933
|
+
if (fallbackRaw) {
|
|
6934
|
+
parsed = await this._decryptAndDeserialize(fallbackRaw);
|
|
6935
|
+
hit = true;
|
|
6936
|
+
}
|
|
6937
|
+
} else if (!err && typeof rawVal === "string") {
|
|
6938
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6939
|
+
hit = true;
|
|
6940
|
+
} else if (!err && rawVal && typeof rawVal === "object" && rawVal.d) {
|
|
6941
|
+
const hashHit = await this._parseGenerationalRedisHash(k, rawVal);
|
|
6942
|
+
if (hashHit && !hashHit.stale && hashHit.value !== void 0) {
|
|
6943
|
+
parsed = hashHit.value;
|
|
6944
|
+
tagVersions = hashHit.tagVersions;
|
|
6945
|
+
hit = true;
|
|
6946
|
+
}
|
|
6947
|
+
}
|
|
6948
|
+
} else if (!err && rawVal) {
|
|
6949
|
+
parsed = await this._decryptAndDeserialize(rawVal);
|
|
6950
|
+
hit = true;
|
|
6951
|
+
}
|
|
6952
|
+
if (hit && parsed !== void 0) {
|
|
6510
6953
|
const p = priority ?? inferPriority(missKeys[j]);
|
|
6511
|
-
|
|
6954
|
+
const ttlVal = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
|
|
6955
|
+
this.l1.set(k, parsed, this._jitterTtl(ttlVal * 1e3), p, void 0, void 0, tagVersions);
|
|
6512
6956
|
this.counters.l2Hits++;
|
|
6513
6957
|
l2HitCount++;
|
|
6514
|
-
result[idx] = parsed;
|
|
6958
|
+
result[idx] = this._prepareReadValue(parsed);
|
|
6515
6959
|
missIndexes[j] = -1;
|
|
6516
6960
|
missKeys[j] = "";
|
|
6517
6961
|
}
|
|
@@ -6545,6 +6989,10 @@ return 0
|
|
|
6545
6989
|
this.watchdog.recordDisk(diskElapsed);
|
|
6546
6990
|
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6547
6991
|
if (diskHit !== null) {
|
|
6992
|
+
if (await this._isGenerationalEntryStale(diskHit.tagVersions)) {
|
|
6993
|
+
this.disk.delete(k);
|
|
6994
|
+
continue;
|
|
6995
|
+
}
|
|
6548
6996
|
const promoted = this.l1.importEntries(
|
|
6549
6997
|
[{ key: k, entry: diskHit }],
|
|
6550
6998
|
this.opts.forbiddenSnapshotPrefixes
|
|
@@ -6553,7 +7001,7 @@ return 0
|
|
|
6553
7001
|
const l1Check = this.l1.get(k);
|
|
6554
7002
|
if (l1Check !== null) {
|
|
6555
7003
|
this.counters.diskHits++;
|
|
6556
|
-
result[missIndexes[j]] = l1Check.value;
|
|
7004
|
+
result[missIndexes[j]] = this._prepareReadValue(l1Check.value);
|
|
6557
7005
|
missIndexes.splice(j, 1);
|
|
6558
7006
|
missKeys.splice(j, 1);
|
|
6559
7007
|
}
|
|
@@ -6561,16 +7009,23 @@ return 0
|
|
|
6561
7009
|
}
|
|
6562
7010
|
}
|
|
6563
7011
|
}
|
|
6564
|
-
if (missKeys.length > 0) {
|
|
7012
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6565
7013
|
this.counters.fetches++;
|
|
6566
7014
|
const fetched = await fetchFn(missKeys);
|
|
7015
|
+
const isMap = fetched instanceof Map;
|
|
6567
7016
|
const setPromises = [];
|
|
6568
7017
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6569
|
-
const
|
|
7018
|
+
const k = missKeys[j];
|
|
7019
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6570
7020
|
result[missIndexes[j]] = v;
|
|
6571
|
-
if (v !== void 0) {
|
|
6572
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6573
|
-
setPromises.push(this.set(
|
|
7021
|
+
if (v !== void 0 && v !== null) {
|
|
7022
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
7023
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
7024
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
7025
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
7026
|
+
} else if (v === null) {
|
|
7027
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
7028
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6574
7029
|
}
|
|
6575
7030
|
}
|
|
6576
7031
|
if (setPromises.length > 0) {
|
|
@@ -6713,98 +7168,135 @@ return 0
|
|
|
6713
7168
|
}
|
|
6714
7169
|
}
|
|
6715
7170
|
/**
|
|
6716
|
-
*
|
|
6717
|
-
*
|
|
6718
|
-
*
|
|
6719
|
-
* @example
|
|
6720
|
-
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6721
|
-
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7171
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
7172
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
7173
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
6722
7174
|
*/
|
|
6723
|
-
async
|
|
6724
|
-
|
|
6725
|
-
const
|
|
6726
|
-
|
|
6727
|
-
|
|
6728
|
-
|
|
7175
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
7176
|
+
const isPattern = isWildcardTag(tag);
|
|
7177
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7178
|
+
const matched = /* @__PURE__ */ new Set();
|
|
7179
|
+
const tagMatches = (t) => {
|
|
7180
|
+
if (t === tag) return true;
|
|
7181
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
7182
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
7183
|
+
return false;
|
|
7184
|
+
};
|
|
7185
|
+
if (shouldCascade && !isPattern) {
|
|
7186
|
+
matched.add(tag);
|
|
6729
7187
|
}
|
|
6730
|
-
|
|
6731
|
-
|
|
6732
|
-
|
|
6733
|
-
|
|
6734
|
-
|
|
6735
|
-
|
|
6736
|
-
|
|
6737
|
-
|
|
6738
|
-
|
|
6739
|
-
|
|
6740
|
-
|
|
6741
|
-
|
|
6742
|
-
} else {
|
|
6743
|
-
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6744
|
-
newVer = current + 1;
|
|
6745
|
-
}
|
|
6746
|
-
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6747
|
-
if (this.opts.awaitInvalidationBackplane) {
|
|
6748
|
-
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6749
|
-
} else {
|
|
6750
|
-
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
7188
|
+
const tagPrefix = this.nk("_tag_:");
|
|
7189
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
7190
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
7191
|
+
if (tagMatches(t)) matched.add(t);
|
|
7192
|
+
}
|
|
7193
|
+
for (const t of this.tagVersions.keys()) {
|
|
7194
|
+
if (tagMatches(t)) matched.add(t);
|
|
7195
|
+
}
|
|
7196
|
+
this.l1.scan((_k, entry) => {
|
|
7197
|
+
if (entry.tagVersions) {
|
|
7198
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
7199
|
+
if (tagMatches(t)) matched.add(t);
|
|
6751
7200
|
}
|
|
6752
|
-
return;
|
|
6753
7201
|
}
|
|
6754
|
-
|
|
6755
|
-
|
|
6756
|
-
|
|
6757
|
-
this.
|
|
6758
|
-
this.
|
|
6759
|
-
|
|
6760
|
-
|
|
6761
|
-
|
|
6762
|
-
|
|
6763
|
-
|
|
6764
|
-
|
|
7202
|
+
}, 0);
|
|
7203
|
+
if (!this._redisDisabled) {
|
|
7204
|
+
try {
|
|
7205
|
+
const client = await this.getRedis();
|
|
7206
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7207
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
7208
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7209
|
+
const pfx = this.nk("tag_ver:");
|
|
7210
|
+
for (const sk of scannedKeys) {
|
|
7211
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7212
|
+
if (tagMatches(t)) matched.add(t);
|
|
6765
7213
|
}
|
|
6766
|
-
}
|
|
7214
|
+
} else {
|
|
7215
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
7216
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7217
|
+
const pfx = this.nk("_tag_:");
|
|
7218
|
+
for (const sk of scannedKeys) {
|
|
7219
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7220
|
+
if (tagMatches(t)) matched.add(t);
|
|
7221
|
+
}
|
|
7222
|
+
}
|
|
7223
|
+
} catch (err) {
|
|
7224
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
6767
7225
|
}
|
|
6768
|
-
|
|
7226
|
+
}
|
|
7227
|
+
return matched;
|
|
7228
|
+
}
|
|
7229
|
+
async _publishTagInvalidation(op, key, tagVersion) {
|
|
7230
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7231
|
+
await this.publishInvalidation(op, key, tagVersion, false, true);
|
|
7232
|
+
} else {
|
|
7233
|
+
void this.publishInvalidation(op, key, tagVersion, false, true);
|
|
7234
|
+
}
|
|
7235
|
+
}
|
|
7236
|
+
_removeTagMembersLocal(keys) {
|
|
7237
|
+
const keyList = Array.isArray(keys) ? keys : Array.from(keys);
|
|
7238
|
+
for (const k of keyList) {
|
|
7239
|
+
this.l1.delete(k);
|
|
7240
|
+
this._bumpKeyMutation(k);
|
|
7241
|
+
this._removeKeyTags(k);
|
|
7242
|
+
this._removeKeyDependencies(k);
|
|
7243
|
+
this._pendingDiskDeletes.add(k);
|
|
7244
|
+
setImmediate(() => {
|
|
7245
|
+
try {
|
|
7246
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
7247
|
+
} finally {
|
|
7248
|
+
this._pendingDiskDeletes.delete(k);
|
|
7249
|
+
}
|
|
7250
|
+
});
|
|
7251
|
+
}
|
|
7252
|
+
}
|
|
7253
|
+
/**
|
|
7254
|
+
* Executes invalidation for a single already-resolved concrete tag without
|
|
7255
|
+
* wildcard/cascade re-resolution, avoiding mutual recursion with invalidateTags().
|
|
7256
|
+
*/
|
|
7257
|
+
async _invalidateConcreteTag(tag) {
|
|
7258
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7259
|
+
let newVer = 1;
|
|
6769
7260
|
if (!this._redisDisabled) {
|
|
6770
7261
|
try {
|
|
6771
7262
|
const client = await this.getRedis();
|
|
6772
|
-
|
|
6773
|
-
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers])];
|
|
6774
|
-
if (toDelete.length > 0) {
|
|
6775
|
-
await client.del(...toDelete, tagKey);
|
|
6776
|
-
} else {
|
|
6777
|
-
await client.del(tagKey);
|
|
6778
|
-
}
|
|
7263
|
+
newVer = await client.incr(this.nk(`tag_ver:${tag}`));
|
|
6779
7264
|
} catch (err) {
|
|
6780
7265
|
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
7266
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7267
|
+
newVer = current + 1;
|
|
6781
7268
|
}
|
|
7269
|
+
} else {
|
|
7270
|
+
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
7271
|
+
newVer = current + 1;
|
|
7272
|
+
}
|
|
7273
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
7274
|
+
await this._publishTagInvalidation("tag_incr", tag, newVer);
|
|
7275
|
+
return;
|
|
7276
|
+
}
|
|
7277
|
+
const tagKey = this.nk(`_tag_:${tag}`);
|
|
7278
|
+
const members = Array.from(this.tagIndex.get(tagKey) ?? []);
|
|
7279
|
+
this.tagIndex.delete(tagKey);
|
|
7280
|
+
this._removeTagMembersLocal(members);
|
|
7281
|
+
if (!this._redisDisabled) {
|
|
7282
|
+
try {
|
|
7283
|
+
const client = await this.getRedis();
|
|
7284
|
+
const redisMembers = await client.smembers(tagKey);
|
|
7285
|
+
const toDelete = [.../* @__PURE__ */ new Set([...members, ...redisMembers, tagKey])];
|
|
7286
|
+
await this._deleteRedisKeys(client, toDelete);
|
|
7287
|
+
} catch (err) {
|
|
7288
|
+
this.logger.debug("invalidateTag: Redis unavailable", { tag, error: err.message });
|
|
6782
7289
|
}
|
|
6783
|
-
} catch (err) {
|
|
6784
|
-
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6785
|
-
span.recordException?.(err);
|
|
6786
|
-
throw err;
|
|
6787
|
-
} finally {
|
|
6788
|
-
span.end();
|
|
6789
7290
|
}
|
|
6790
7291
|
}
|
|
6791
7292
|
/**
|
|
6792
|
-
*
|
|
6793
|
-
*
|
|
6794
|
-
* reducing latency when invalidating several related tags together.
|
|
6795
|
-
*
|
|
6796
|
-
* Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
|
|
6797
|
-
* synchronously before the Redis round-trip.
|
|
6798
|
-
*
|
|
6799
|
-
* @example
|
|
6800
|
-
* // Instead of three serial round-trips:
|
|
6801
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
7293
|
+
* Executes invalidation for an array of already-resolved concrete tags
|
|
7294
|
+
* without re-entering wildcard/cascade resolution or invalidateTag().
|
|
6802
7295
|
*/
|
|
6803
|
-
async
|
|
6804
|
-
this._assertActive("invalidateTags");
|
|
7296
|
+
async _invalidateConcreteTags(tags) {
|
|
6805
7297
|
if (tags.length === 0) return;
|
|
6806
7298
|
if (tags.length === 1) {
|
|
6807
|
-
await this.
|
|
7299
|
+
await this._invalidateConcreteTag(tags[0]);
|
|
6808
7300
|
return;
|
|
6809
7301
|
}
|
|
6810
7302
|
if (this.opts.tagStrategy === "generational") {
|
|
@@ -6819,11 +7311,7 @@ return 0
|
|
|
6819
7311
|
const [err, newVer] = results[i] ?? [null, null];
|
|
6820
7312
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
6821
7313
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
6822
|
-
|
|
6823
|
-
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6824
|
-
} else {
|
|
6825
|
-
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
6826
|
-
}
|
|
7314
|
+
await this._publishTagInvalidation("tag_incr", tags[i], ver);
|
|
6827
7315
|
}
|
|
6828
7316
|
return;
|
|
6829
7317
|
} catch (err) {
|
|
@@ -6833,11 +7321,7 @@ return 0
|
|
|
6833
7321
|
for (const tag of tags) {
|
|
6834
7322
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
6835
7323
|
this._setLocalTagVersion(tag, ver, now);
|
|
6836
|
-
|
|
6837
|
-
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6838
|
-
} else {
|
|
6839
|
-
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
6840
|
-
}
|
|
7324
|
+
await this._publishTagInvalidation("tag_incr", tag, ver);
|
|
6841
7325
|
}
|
|
6842
7326
|
return;
|
|
6843
7327
|
}
|
|
@@ -6850,18 +7334,7 @@ return 0
|
|
|
6850
7334
|
for (const k of members) allMembers.add(k);
|
|
6851
7335
|
this.tagIndex.delete(tagKey);
|
|
6852
7336
|
}
|
|
6853
|
-
|
|
6854
|
-
this.l1.delete(k);
|
|
6855
|
-
this._bumpKeyMutation(k);
|
|
6856
|
-
this._pendingDiskDeletes.add(k);
|
|
6857
|
-
setImmediate(() => {
|
|
6858
|
-
try {
|
|
6859
|
-
if (!this._diskDisabled) this.disk.delete(k);
|
|
6860
|
-
} finally {
|
|
6861
|
-
this._pendingDiskDeletes.delete(k);
|
|
6862
|
-
}
|
|
6863
|
-
});
|
|
6864
|
-
}
|
|
7337
|
+
this._removeTagMembersLocal(allMembers);
|
|
6865
7338
|
if (!this._redisDisabled) {
|
|
6866
7339
|
try {
|
|
6867
7340
|
const client = await this.getRedis();
|
|
@@ -6877,12 +7350,103 @@ return 0
|
|
|
6877
7350
|
}
|
|
6878
7351
|
}
|
|
6879
7352
|
const keysToRemove = [...toDelete, ...tagKeys];
|
|
6880
|
-
|
|
7353
|
+
await this._deleteRedisKeys(client, keysToRemove);
|
|
6881
7354
|
} catch (err) {
|
|
6882
7355
|
this.logger.debug("invalidateTags: Redis unavailable", { tags, error: err.message });
|
|
6883
7356
|
}
|
|
6884
7357
|
}
|
|
6885
7358
|
}
|
|
7359
|
+
/**
|
|
7360
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
7361
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
7362
|
+
*
|
|
7363
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
7364
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
7365
|
+
*
|
|
7366
|
+
* @example
|
|
7367
|
+
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
7368
|
+
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7369
|
+
*
|
|
7370
|
+
* @example
|
|
7371
|
+
* // Wildcard pattern invalidation
|
|
7372
|
+
* await cache.invalidateTag('org:123:*');
|
|
7373
|
+
*
|
|
7374
|
+
* @example
|
|
7375
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
7376
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
7377
|
+
*/
|
|
7378
|
+
async invalidateTag(tag, opts) {
|
|
7379
|
+
this._assertActive("invalidateTag");
|
|
7380
|
+
const span = this._startSpan("tricache.invalidate_tag");
|
|
7381
|
+
if (this.opts.tracer) {
|
|
7382
|
+
span.setAttribute("cache.tag", tag);
|
|
7383
|
+
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
7384
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
7385
|
+
}
|
|
7386
|
+
try {
|
|
7387
|
+
const isPattern = isWildcardTag(tag);
|
|
7388
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7389
|
+
if (isPattern || shouldCascade) {
|
|
7390
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
7391
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7392
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
7393
|
+
if (matchedTags.size > 0) {
|
|
7394
|
+
await this._invalidateConcreteTags(Array.from(matchedTags));
|
|
7395
|
+
}
|
|
7396
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7397
|
+
await this._publishTagInvalidation(op, broadcastPattern);
|
|
7398
|
+
return;
|
|
7399
|
+
}
|
|
7400
|
+
await this._invalidateConcreteTag(tag);
|
|
7401
|
+
} catch (err) {
|
|
7402
|
+
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
7403
|
+
span.recordException?.(err);
|
|
7404
|
+
throw err;
|
|
7405
|
+
} finally {
|
|
7406
|
+
span.end();
|
|
7407
|
+
}
|
|
7408
|
+
}
|
|
7409
|
+
/**
|
|
7410
|
+
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
7411
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
7412
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
7413
|
+
*
|
|
7414
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
7415
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
7416
|
+
*
|
|
7417
|
+
* @example
|
|
7418
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
7419
|
+
*/
|
|
7420
|
+
async invalidateTags(tags, opts) {
|
|
7421
|
+
this._assertActive("invalidateTags");
|
|
7422
|
+
if (tags.length === 0) return;
|
|
7423
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
7424
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7425
|
+
if (hasWildcards || shouldCascade) {
|
|
7426
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
7427
|
+
const broadcastPatterns = /* @__PURE__ */ new Set();
|
|
7428
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7429
|
+
for (const t of tags) {
|
|
7430
|
+
const tIsPattern = isWildcardTag(t);
|
|
7431
|
+
if (tIsPattern || shouldCascade) {
|
|
7432
|
+
broadcastPatterns.add(tIsPattern ? t : `${t}${delim}*`);
|
|
7433
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
7434
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
7435
|
+
} else {
|
|
7436
|
+
allResolvedTags.add(t);
|
|
7437
|
+
}
|
|
7438
|
+
}
|
|
7439
|
+
if (allResolvedTags.size > 0) {
|
|
7440
|
+
await this._invalidateConcreteTags(Array.from(allResolvedTags));
|
|
7441
|
+
}
|
|
7442
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7443
|
+
for (const pattern of broadcastPatterns) {
|
|
7444
|
+
await this._publishTagInvalidation(op, pattern);
|
|
7445
|
+
}
|
|
7446
|
+
return;
|
|
7447
|
+
}
|
|
7448
|
+
await this._invalidateConcreteTags(Array.from(new Set(tags)));
|
|
7449
|
+
}
|
|
6886
7450
|
/**
|
|
6887
7451
|
* Get the current generational tag version for a tag (synced with Redis when due).
|
|
6888
7452
|
*/
|
|
@@ -7448,6 +8012,13 @@ return 0
|
|
|
7448
8012
|
this._destroyed = true;
|
|
7449
8013
|
this._pendingDiskDeletes.clear();
|
|
7450
8014
|
this._keyMutationEpochs.clear();
|
|
8015
|
+
this.inflight.clear();
|
|
8016
|
+
this.revalidating.clear();
|
|
8017
|
+
this._l1Counters.clear();
|
|
8018
|
+
this.tagIndex.clear();
|
|
8019
|
+
this.keyTags.clear();
|
|
8020
|
+
this.dependencyIndex.clear();
|
|
8021
|
+
this.keyDependencies.clear();
|
|
7451
8022
|
const g = globalThis;
|
|
7452
8023
|
const key = _CacheService.globalKey(this.opts);
|
|
7453
8024
|
if (g[key] === this) {
|