tricache 0.8.0 → 1.0.0
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 +10 -4
- package/dashboards/prometheus-scrape.yml +18 -0
- package/dist/{cache-service-5MZXFIGK.js → cache-service-26GCO3UU.js} +3 -3
- package/dist/{cache-service-CyLdpo77.d.ts → cache-service-pJ-nFcVj.d.ts} +44 -12
- package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
- package/dist/{chunk-6PQ5MOWR.js → chunk-7SZSQS55.js} +571 -115
- package/dist/chunk-BQRURGGD.js +60 -0
- package/dist/chunk-IITRFWHY.js +196 -0
- package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
- package/dist/cli.cjs +767 -133
- package/dist/cli.js +24 -6
- package/dist/dashboard/index.d.ts +2 -2
- package/dist/drizzle/index.cjs +734 -132
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +163 -46
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +42 -14
- package/dist/hono/index.cjs +8093 -0
- package/dist/hono/index.d.ts +91 -0
- package/dist/hono/index.js +185 -0
- package/dist/{hono-DQRS1Xd7.d.ts → hono-DuNvciyq.d.ts} +6 -5
- package/dist/http/index.cjs +833 -170
- package/dist/http/index.d.ts +6 -30
- package/dist/http/index.js +9 -59
- package/dist/index.cjs +755 -130
- package/dist/index.d.ts +35 -6
- package/dist/index.js +16 -6
- package/dist/nestjs/index.cjs +725 -130
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +4 -4
- package/dist/next/index.cjs +725 -130
- package/dist/next/index.d.ts +2 -2
- package/dist/next/index.js +3 -3
- 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-B6krw64X.d.ts → types-5HXqBfAf.d.ts} +74 -7
- package/dist/utils-CEsU_Z0s.d.ts +27 -0
- package/package.json +22 -9
- package/src/cache-service.ts +540 -68
- package/src/cli.ts +21 -4
- package/src/compression.ts +193 -15
- package/src/cross-region.ts +1 -1
- package/src/edge/cache.ts +38 -11
- package/src/edge/hono.ts +123 -42
- package/src/env.d.ts +13 -0
- package/src/hono/index.ts +316 -0
- package/src/http/index.ts +5 -0
- package/src/index.ts +9 -1
- package/src/ipc-telemetry.ts +29 -1
- package/src/serialize-worker.ts +6 -2
- package/src/types.ts +68 -5
- package/src/utils/tag-matcher.ts +90 -0
- package/dist/chunk-ZTSWCFYO.js +0 -135
- /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
package/dist/nestjs/index.cjs
CHANGED
|
@@ -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
|
+
}
|
|
1950
2048
|
return null;
|
|
1951
2049
|
}
|
|
1952
2050
|
};
|
|
1953
|
-
const
|
|
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;
|
|
2065
|
+
return null;
|
|
2066
|
+
}
|
|
2067
|
+
};
|
|
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;
|
|
@@ -3903,6 +4068,52 @@ var CacheService = class _CacheService {
|
|
|
3903
4068
|
streamClient = null;
|
|
3904
4069
|
_lastStreamId = "$";
|
|
3905
4070
|
_destroyed = false;
|
|
4071
|
+
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
4072
|
+
_globalEpoch = 0;
|
|
4073
|
+
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
4074
|
+
/**
|
|
4075
|
+
* Pattern tombstones for disk tier.
|
|
4076
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
4077
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
4078
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
4079
|
+
*/
|
|
4080
|
+
_patternTombstones = [];
|
|
4081
|
+
_addPatternTombstone(prefix) {
|
|
4082
|
+
const now = Date.now();
|
|
4083
|
+
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
4084
|
+
this._patternTombstones.shift();
|
|
4085
|
+
}
|
|
4086
|
+
if (this._patternTombstones.length >= 2e3) {
|
|
4087
|
+
this._patternTombstones.shift();
|
|
4088
|
+
}
|
|
4089
|
+
this._patternTombstones.push({ prefix, createdAt: now });
|
|
4090
|
+
}
|
|
4091
|
+
_isTombstonedByPattern(namespacedKey) {
|
|
4092
|
+
if (this._patternTombstones.length === 0) return false;
|
|
4093
|
+
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
4094
|
+
if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
|
|
4095
|
+
return true;
|
|
4096
|
+
}
|
|
4097
|
+
}
|
|
4098
|
+
return false;
|
|
4099
|
+
}
|
|
4100
|
+
_assertActive(operation) {
|
|
4101
|
+
if (this._destroyed) {
|
|
4102
|
+
throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
|
|
4103
|
+
}
|
|
4104
|
+
}
|
|
4105
|
+
_bumpKeyMutation(namespacedKey) {
|
|
4106
|
+
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
4107
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
4108
|
+
if (this._keyMutationEpochs.size > 5e4) {
|
|
4109
|
+
const oldest = this._keyMutationEpochs.keys().next().value;
|
|
4110
|
+
if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
|
|
4111
|
+
}
|
|
4112
|
+
return next;
|
|
4113
|
+
}
|
|
4114
|
+
_getKeyMutationEpoch(namespacedKey) {
|
|
4115
|
+
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
4116
|
+
}
|
|
3906
4117
|
_ipcServer;
|
|
3907
4118
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
3908
4119
|
_subDisconnectedAt = null;
|
|
@@ -3991,6 +4202,8 @@ var CacheService = class _CacheService {
|
|
|
3991
4202
|
),
|
|
3992
4203
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
3993
4204
|
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
4205
|
+
awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
|
|
4206
|
+
lockFailClosed: options.lockFailClosed ?? false,
|
|
3994
4207
|
oomProtection: options.oomProtection ?? true,
|
|
3995
4208
|
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
3996
4209
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
@@ -4024,12 +4237,15 @@ var CacheService = class _CacheService {
|
|
|
4024
4237
|
redisSentinel: options.redisSentinel,
|
|
4025
4238
|
redisProtocol: options.redisProtocol,
|
|
4026
4239
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
4027
|
-
compression: options.compression ?? "
|
|
4240
|
+
compression: options.compression ?? "zstd",
|
|
4241
|
+
customCompressor: options.customCompressor,
|
|
4028
4242
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
4029
4243
|
strictSingleton: options.strictSingleton ?? false,
|
|
4030
4244
|
failClosed: options.failClosed ?? false,
|
|
4031
4245
|
tagStrategy: options.tagStrategy ?? "set",
|
|
4032
4246
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
4247
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
4248
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
4033
4249
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
4034
4250
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
4035
4251
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4102,6 +4318,7 @@ var CacheService = class _CacheService {
|
|
|
4102
4318
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4103
4319
|
});
|
|
4104
4320
|
this._namespace = ns;
|
|
4321
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4105
4322
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4106
4323
|
this.watchdog = new TierLatencyWatchdog({
|
|
4107
4324
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4211,6 +4428,9 @@ var CacheService = class _CacheService {
|
|
|
4211
4428
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4212
4429
|
this.initBackplane();
|
|
4213
4430
|
const startupPromises = [];
|
|
4431
|
+
if (this.opts.compression === "zstd") {
|
|
4432
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4433
|
+
}
|
|
4214
4434
|
if (this.opts.remoteSnapshot) {
|
|
4215
4435
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4216
4436
|
}
|
|
@@ -4356,7 +4576,9 @@ var CacheService = class _CacheService {
|
|
|
4356
4576
|
"adaptiveTtl",
|
|
4357
4577
|
"l2WriteMode",
|
|
4358
4578
|
"instanceName",
|
|
4359
|
-
"invalidationBackplane"
|
|
4579
|
+
"invalidationBackplane",
|
|
4580
|
+
"awaitInvalidationBackplane",
|
|
4581
|
+
"lockFailClosed"
|
|
4360
4582
|
];
|
|
4361
4583
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
4362
4584
|
static optionsDiff(a, b) {
|
|
@@ -4397,6 +4619,8 @@ var CacheService = class _CacheService {
|
|
|
4397
4619
|
frozen: o.frozen,
|
|
4398
4620
|
adaptiveTtl: o.adaptiveTtl,
|
|
4399
4621
|
invalidationBackplane: o.invalidationBackplane,
|
|
4622
|
+
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4623
|
+
lockFailClosed: o.lockFailClosed,
|
|
4400
4624
|
strictSingleton: o.strictSingleton,
|
|
4401
4625
|
remoteSnapshot: o.remoteSnapshot,
|
|
4402
4626
|
crossRegion: o.crossRegion
|
|
@@ -4682,16 +4906,80 @@ var CacheService = class _CacheService {
|
|
|
4682
4906
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
4683
4907
|
if (op === "del") {
|
|
4684
4908
|
this.l1.delete(key);
|
|
4909
|
+
this._bumpKeyMutation(key);
|
|
4910
|
+
this.inflight.delete(key);
|
|
4911
|
+
this._pendingDiskDeletes.add(key);
|
|
4685
4912
|
setImmediate(() => {
|
|
4686
|
-
|
|
4913
|
+
try {
|
|
4914
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
4915
|
+
} finally {
|
|
4916
|
+
this._pendingDiskDeletes.delete(key);
|
|
4917
|
+
}
|
|
4687
4918
|
});
|
|
4688
4919
|
this._cascadeDependencies(key);
|
|
4689
4920
|
} else if (op === "del-glob") {
|
|
4690
4921
|
this.l1.deletePattern(key);
|
|
4922
|
+
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
4923
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
4924
|
+
if (liveKey.startsWith(pfx)) {
|
|
4925
|
+
this._bumpKeyMutation(liveKey);
|
|
4926
|
+
}
|
|
4927
|
+
}
|
|
4928
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
4929
|
+
if (inflightKey.startsWith(pfx)) {
|
|
4930
|
+
this._bumpKeyMutation(inflightKey);
|
|
4931
|
+
this.inflight.delete(inflightKey);
|
|
4932
|
+
}
|
|
4933
|
+
}
|
|
4934
|
+
this._addPatternTombstone(pfx);
|
|
4691
4935
|
} else if (op === "tag_incr") {
|
|
4692
4936
|
const tag = key;
|
|
4693
4937
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4694
|
-
this._setLocalTagVersion(tag, ver,
|
|
4938
|
+
this._setLocalTagVersion(tag, ver, performance.now());
|
|
4939
|
+
} else if (op === "tag_pattern_incr") {
|
|
4940
|
+
const pattern = key;
|
|
4941
|
+
const now = performance.now();
|
|
4942
|
+
for (const [tag, info] of this.tagVersions) {
|
|
4943
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4944
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
4945
|
+
}
|
|
4946
|
+
}
|
|
4947
|
+
this.l1.scan((k, entry) => {
|
|
4948
|
+
if (entry.tagVersions) {
|
|
4949
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
4950
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4951
|
+
this.l1.delete(k);
|
|
4952
|
+
this._bumpKeyMutation(k);
|
|
4953
|
+
break;
|
|
4954
|
+
}
|
|
4955
|
+
}
|
|
4956
|
+
}
|
|
4957
|
+
}, 0);
|
|
4958
|
+
} else if (op === "tag_pattern_del") {
|
|
4959
|
+
const pattern = key;
|
|
4960
|
+
const matchedTagKeys = [];
|
|
4961
|
+
const prefix = this.nk("_tag_:");
|
|
4962
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
4963
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
4964
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
4965
|
+
matchedTagKeys.push(tagKey);
|
|
4966
|
+
for (const k of members) {
|
|
4967
|
+
this.l1.delete(k);
|
|
4968
|
+
this._bumpKeyMutation(k);
|
|
4969
|
+
this._pendingDiskDeletes.add(k);
|
|
4970
|
+
setImmediate(() => {
|
|
4971
|
+
try {
|
|
4972
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
4973
|
+
} finally {
|
|
4974
|
+
this._pendingDiskDeletes.delete(k);
|
|
4975
|
+
}
|
|
4976
|
+
});
|
|
4977
|
+
}
|
|
4978
|
+
}
|
|
4979
|
+
}
|
|
4980
|
+
for (const tagKey of matchedTagKeys) {
|
|
4981
|
+
this.tagIndex.delete(tagKey);
|
|
4982
|
+
}
|
|
4695
4983
|
}
|
|
4696
4984
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4697
4985
|
}
|
|
@@ -4699,7 +4987,7 @@ var CacheService = class _CacheService {
|
|
|
4699
4987
|
_handleBackplaneMessage(message) {
|
|
4700
4988
|
try {
|
|
4701
4989
|
const msg = JSON.parse(message);
|
|
4702
|
-
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") {
|
|
4990
|
+
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") {
|
|
4703
4991
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4704
4992
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4705
4993
|
});
|
|
@@ -4719,7 +5007,11 @@ var CacheService = class _CacheService {
|
|
|
4719
5007
|
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4720
5008
|
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4721
5009
|
if (shouldBroadcast) {
|
|
4722
|
-
|
|
5010
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5011
|
+
await this._broadcastCrossRegion(op, key, tagVersion);
|
|
5012
|
+
} else {
|
|
5013
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
5014
|
+
}
|
|
4723
5015
|
}
|
|
4724
5016
|
}
|
|
4725
5017
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
@@ -4760,7 +5052,11 @@ var CacheService = class _CacheService {
|
|
|
4760
5052
|
);
|
|
4761
5053
|
}
|
|
4762
5054
|
this.counters.invSent++;
|
|
4763
|
-
} catch {
|
|
5055
|
+
} catch (err) {
|
|
5056
|
+
this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
|
|
5057
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5058
|
+
throw err;
|
|
5059
|
+
}
|
|
4764
5060
|
}
|
|
4765
5061
|
}
|
|
4766
5062
|
_markCrossRegionEventSeen(id) {
|
|
@@ -4878,12 +5174,12 @@ var CacheService = class _CacheService {
|
|
|
4878
5174
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
4879
5175
|
*/
|
|
4880
5176
|
async _serializeAndEncrypt(serialized) {
|
|
4881
|
-
const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
4882
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5177
|
+
const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
5178
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
4883
5179
|
return this._workerPool.encrypt(serialized);
|
|
4884
5180
|
}
|
|
4885
5181
|
if (isCompressed2) {
|
|
4886
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
5182
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
4887
5183
|
if (this.enc.isEnabled) {
|
|
4888
5184
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
4889
5185
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -4898,16 +5194,16 @@ var CacheService = class _CacheService {
|
|
|
4898
5194
|
*/
|
|
4899
5195
|
async _decryptAndDeserialize(raw) {
|
|
4900
5196
|
let plain;
|
|
4901
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
5197
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
4902
5198
|
plain = await this._workerPool.decrypt(raw);
|
|
4903
5199
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
4904
5200
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
4905
5201
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
4906
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5202
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4907
5203
|
plain = decompressed.toString("utf8");
|
|
4908
5204
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
4909
5205
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
4910
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5206
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
4911
5207
|
plain = decompressed.toString("utf8");
|
|
4912
5208
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
4913
5209
|
plain = this.enc.decrypt(raw);
|
|
@@ -4964,6 +5260,7 @@ var CacheService = class _CacheService {
|
|
|
4964
5260
|
}
|
|
4965
5261
|
}
|
|
4966
5262
|
async getRedis() {
|
|
5263
|
+
this._assertActive("getRedis");
|
|
4967
5264
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
4968
5265
|
if (this.redis) return this.redis;
|
|
4969
5266
|
if (this.redisConnecting) return this.redisConnecting;
|
|
@@ -5292,6 +5589,7 @@ var CacheService = class _CacheService {
|
|
|
5292
5589
|
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
5293
5590
|
*/
|
|
5294
5591
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
5592
|
+
this._assertActive("get");
|
|
5295
5593
|
const span = this._startSpan("tricache.get");
|
|
5296
5594
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5297
5595
|
const k = this.nk(cacheKey);
|
|
@@ -5301,7 +5599,7 @@ var CacheService = class _CacheService {
|
|
|
5301
5599
|
const optRefreshAhead = opts.refreshAhead;
|
|
5302
5600
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5303
5601
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5304
|
-
const optTags = opts.tags;
|
|
5602
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5305
5603
|
const l1Hit = this.l1.get(k);
|
|
5306
5604
|
if (l1Hit !== null) {
|
|
5307
5605
|
let isGenerationalStale = false;
|
|
@@ -5323,7 +5621,14 @@ var CacheService = class _CacheService {
|
|
|
5323
5621
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
5324
5622
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
5325
5623
|
this.revalidating.add(k);
|
|
5326
|
-
void this._revalidate(
|
|
5624
|
+
void this._revalidate(
|
|
5625
|
+
k,
|
|
5626
|
+
fetchFn,
|
|
5627
|
+
ttlSeconds * 1e3,
|
|
5628
|
+
swrGraceMs2,
|
|
5629
|
+
priority2,
|
|
5630
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5631
|
+
);
|
|
5327
5632
|
this.counters.swrRevalidations++;
|
|
5328
5633
|
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
5329
5634
|
} else {
|
|
@@ -5342,7 +5647,14 @@ var CacheService = class _CacheService {
|
|
|
5342
5647
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
5343
5648
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
5344
5649
|
this.revalidating.add(k);
|
|
5345
|
-
void this._revalidate(
|
|
5650
|
+
void this._revalidate(
|
|
5651
|
+
k,
|
|
5652
|
+
fetchFn,
|
|
5653
|
+
entryTtl,
|
|
5654
|
+
optSwr * 1e3,
|
|
5655
|
+
priority2,
|
|
5656
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5657
|
+
);
|
|
5346
5658
|
this.counters.swrRevalidations++;
|
|
5347
5659
|
this.logger.debug(
|
|
5348
5660
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -5368,44 +5680,52 @@ var CacheService = class _CacheService {
|
|
|
5368
5680
|
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5369
5681
|
return existing;
|
|
5370
5682
|
}
|
|
5683
|
+
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5371
5684
|
const executionPromise = (async () => {
|
|
5372
5685
|
try {
|
|
5373
|
-
if (!this._diskDisabled) {
|
|
5374
|
-
|
|
5375
|
-
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
|
|
5379
|
-
|
|
5380
|
-
this.watchdog.
|
|
5381
|
-
if (
|
|
5382
|
-
|
|
5383
|
-
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
|
|
5388
|
-
|
|
5389
|
-
|
|
5686
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
5687
|
+
if (this._isTombstonedByPattern(k)) {
|
|
5688
|
+
try {
|
|
5689
|
+
this.disk.delete(k);
|
|
5690
|
+
} catch {
|
|
5691
|
+
}
|
|
5692
|
+
} else {
|
|
5693
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5694
|
+
if (isDiskAllowed) {
|
|
5695
|
+
const diskStart = performance.now();
|
|
5696
|
+
const diskHit = this.disk.load(k);
|
|
5697
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5698
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5699
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5700
|
+
if (diskHit !== null) {
|
|
5701
|
+
let isDiskStale = false;
|
|
5702
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5703
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5704
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5705
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5706
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5707
|
+
isDiskStale = true;
|
|
5708
|
+
break;
|
|
5709
|
+
}
|
|
5390
5710
|
}
|
|
5391
5711
|
}
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
|
|
5401
|
-
|
|
5402
|
-
|
|
5403
|
-
|
|
5404
|
-
|
|
5405
|
-
|
|
5406
|
-
|
|
5407
|
-
|
|
5408
|
-
|
|
5712
|
+
if (isDiskStale) {
|
|
5713
|
+
this.disk.delete(k);
|
|
5714
|
+
} else {
|
|
5715
|
+
const promoted = this.l1.importEntries(
|
|
5716
|
+
[{ key: k, entry: diskHit }],
|
|
5717
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5718
|
+
);
|
|
5719
|
+
if (promoted > 0) {
|
|
5720
|
+
const l1Check = this.l1.get(k);
|
|
5721
|
+
if (l1Check !== null) {
|
|
5722
|
+
this.counters.diskHits++;
|
|
5723
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5724
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5725
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5726
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5727
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5728
|
+
}
|
|
5409
5729
|
}
|
|
5410
5730
|
}
|
|
5411
5731
|
}
|
|
@@ -5516,6 +5836,18 @@ var CacheService = class _CacheService {
|
|
|
5516
5836
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
5517
5837
|
}
|
|
5518
5838
|
}
|
|
5839
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
5840
|
+
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5841
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
5842
|
+
const current = this.l1.get(k);
|
|
5843
|
+
if (current && !current.isStale && current.value !== void 0) {
|
|
5844
|
+
const freshVal = current.value;
|
|
5845
|
+
if (this.opts.frozen) deepFreeze(freshVal);
|
|
5846
|
+
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
5847
|
+
}
|
|
5848
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
5849
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
5850
|
+
}
|
|
5519
5851
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
5520
5852
|
if (!this._redisDisabled) {
|
|
5521
5853
|
try {
|
|
@@ -5632,22 +5964,40 @@ var CacheService = class _CacheService {
|
|
|
5632
5964
|
const ttl = options?.ttl ?? 300;
|
|
5633
5965
|
return this.get(cacheKey, fetchFn, ttl, options);
|
|
5634
5966
|
}
|
|
5635
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
5967
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
5968
|
+
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
5636
5969
|
try {
|
|
5637
5970
|
const fetchStart = Date.now();
|
|
5638
5971
|
const data = await fetchFn();
|
|
5639
5972
|
const delta = Date.now() - fetchStart;
|
|
5640
5973
|
const staleAt = Date.now() + ttlMs;
|
|
5974
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5975
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
5976
|
+
return;
|
|
5977
|
+
}
|
|
5641
5978
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
5642
5979
|
let activeTagVersions;
|
|
5643
5980
|
const l1Existing = this.l1.get(cacheKey);
|
|
5644
|
-
|
|
5645
|
-
|
|
5981
|
+
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
5982
|
+
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
5983
|
+
const tags = Object.keys(tagVersionsSource);
|
|
5646
5984
|
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5647
5985
|
activeTagVersions = {};
|
|
5648
5986
|
for (let i = 0; i < tags.length; i++) {
|
|
5649
5987
|
activeTagVersions[tags[i]] = vers[i];
|
|
5650
5988
|
}
|
|
5989
|
+
if (knownTagVersions) {
|
|
5990
|
+
for (const t of tags) {
|
|
5991
|
+
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
5992
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
5993
|
+
return;
|
|
5994
|
+
}
|
|
5995
|
+
}
|
|
5996
|
+
}
|
|
5997
|
+
}
|
|
5998
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
5999
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
6000
|
+
return;
|
|
5651
6001
|
}
|
|
5652
6002
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
5653
6003
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -5691,6 +6041,7 @@ var CacheService = class _CacheService {
|
|
|
5691
6041
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
5692
6042
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
5693
6043
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
6044
|
+
this._assertActive("set");
|
|
5694
6045
|
const span = this._startSpan("tricache.set");
|
|
5695
6046
|
if (this.opts.tracer) {
|
|
5696
6047
|
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
@@ -5701,17 +6052,21 @@ var CacheService = class _CacheService {
|
|
|
5701
6052
|
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5702
6053
|
const p = priority ?? inferPriority(cacheKey);
|
|
5703
6054
|
const k = this.nk(cacheKey);
|
|
6055
|
+
this._bumpKeyMutation(k);
|
|
6056
|
+
this.inflight.delete(k);
|
|
6057
|
+
this._pendingDiskDeletes.delete(k);
|
|
5704
6058
|
this.counters.sets++;
|
|
5705
6059
|
let activeTagVersions;
|
|
5706
|
-
|
|
6060
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
6061
|
+
if (tagsToRegister?.length) {
|
|
5707
6062
|
if (this.opts.tagStrategy === "generational") {
|
|
5708
|
-
const vers = await Promise.all(
|
|
6063
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5709
6064
|
activeTagVersions = {};
|
|
5710
|
-
for (let i = 0; i <
|
|
5711
|
-
activeTagVersions[
|
|
6065
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
6066
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5712
6067
|
}
|
|
5713
6068
|
} else {
|
|
5714
|
-
await this._registerTags(k,
|
|
6069
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5715
6070
|
}
|
|
5716
6071
|
}
|
|
5717
6072
|
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
@@ -5755,7 +6110,11 @@ var CacheService = class _CacheService {
|
|
|
5755
6110
|
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
5756
6111
|
}
|
|
5757
6112
|
}
|
|
5758
|
-
|
|
6113
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6114
|
+
await this.publishInvalidation("del", k);
|
|
6115
|
+
} else {
|
|
6116
|
+
void this.publishInvalidation("del", k);
|
|
6117
|
+
}
|
|
5759
6118
|
} catch (err) {
|
|
5760
6119
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5761
6120
|
span.recordException?.(err);
|
|
@@ -5802,6 +6161,7 @@ var CacheService = class _CacheService {
|
|
|
5802
6161
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
5803
6162
|
*/
|
|
5804
6163
|
async delete(cacheKey) {
|
|
6164
|
+
this._assertActive("delete");
|
|
5805
6165
|
const span = this._startSpan("tricache.delete");
|
|
5806
6166
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5807
6167
|
try {
|
|
@@ -5809,11 +6169,31 @@ var CacheService = class _CacheService {
|
|
|
5809
6169
|
const k = this.nk(cacheKey);
|
|
5810
6170
|
this.counters.deletes++;
|
|
5811
6171
|
if (isPattern) {
|
|
6172
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6173
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6174
|
+
if (liveKey.startsWith(pfx)) {
|
|
6175
|
+
this._bumpKeyMutation(liveKey);
|
|
6176
|
+
}
|
|
6177
|
+
}
|
|
6178
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6179
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6180
|
+
this._bumpKeyMutation(inflightKey);
|
|
6181
|
+
this.inflight.delete(inflightKey);
|
|
6182
|
+
}
|
|
6183
|
+
}
|
|
6184
|
+
this._addPatternTombstone(pfx);
|
|
5812
6185
|
this.l1.deletePattern(k);
|
|
5813
6186
|
} else {
|
|
6187
|
+
this._bumpKeyMutation(k);
|
|
6188
|
+
this.inflight.delete(k);
|
|
5814
6189
|
this.l1.delete(k);
|
|
6190
|
+
this._pendingDiskDeletes.add(k);
|
|
5815
6191
|
setImmediate(() => {
|
|
5816
|
-
|
|
6192
|
+
try {
|
|
6193
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6194
|
+
} finally {
|
|
6195
|
+
this._pendingDiskDeletes.delete(k);
|
|
6196
|
+
}
|
|
5817
6197
|
});
|
|
5818
6198
|
this._cascadeDependencies(k);
|
|
5819
6199
|
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
@@ -5837,7 +6217,11 @@ var CacheService = class _CacheService {
|
|
|
5837
6217
|
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
5838
6218
|
}
|
|
5839
6219
|
}
|
|
5840
|
-
|
|
6220
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6221
|
+
await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6222
|
+
} else {
|
|
6223
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6224
|
+
}
|
|
5841
6225
|
} catch (err) {
|
|
5842
6226
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5843
6227
|
span.recordException?.(err);
|
|
@@ -5864,6 +6248,7 @@ var CacheService = class _CacheService {
|
|
|
5864
6248
|
* fleet-wide.
|
|
5865
6249
|
*/
|
|
5866
6250
|
async increment(cacheKey, ttlSeconds) {
|
|
6251
|
+
this._assertActive("increment");
|
|
5867
6252
|
const k = this.nk(cacheKey);
|
|
5868
6253
|
if (this._redisDisabled) {
|
|
5869
6254
|
if (!this._incrementFallbackWarned) {
|
|
@@ -5905,19 +6290,38 @@ var CacheService = class _CacheService {
|
|
|
5905
6290
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
5906
6291
|
*/
|
|
5907
6292
|
async clear(prefix) {
|
|
6293
|
+
this._assertActive("clear");
|
|
5908
6294
|
const span = this._startSpan("tricache.clear");
|
|
5909
6295
|
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
5910
6296
|
try {
|
|
5911
6297
|
this.counters.deletes++;
|
|
5912
6298
|
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
5913
6299
|
if (k) {
|
|
6300
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6301
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6302
|
+
if (liveKey.startsWith(pfx)) {
|
|
6303
|
+
this._bumpKeyMutation(liveKey);
|
|
6304
|
+
}
|
|
6305
|
+
}
|
|
6306
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6307
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6308
|
+
this._bumpKeyMutation(inflightKey);
|
|
6309
|
+
this.inflight.delete(inflightKey);
|
|
6310
|
+
}
|
|
6311
|
+
}
|
|
6312
|
+
this._addPatternTombstone(pfx);
|
|
5914
6313
|
this.l1.deletePattern(k);
|
|
5915
6314
|
} else {
|
|
6315
|
+
this._globalEpoch++;
|
|
6316
|
+
this.inflight.clear();
|
|
6317
|
+
this._patternTombstones.length = 0;
|
|
5916
6318
|
this.l1.clear();
|
|
5917
6319
|
if (!this._diskDisabled) this.disk.clear();
|
|
5918
6320
|
this._l1Counters.clear();
|
|
5919
6321
|
this.tagIndex.clear();
|
|
5920
6322
|
this.tagVersions.clear();
|
|
6323
|
+
this._pendingDiskDeletes.clear();
|
|
6324
|
+
this._keyMutationEpochs.clear();
|
|
5921
6325
|
}
|
|
5922
6326
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
5923
6327
|
try {
|
|
@@ -5929,13 +6333,23 @@ var CacheService = class _CacheService {
|
|
|
5929
6333
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
5930
6334
|
}
|
|
5931
6335
|
}
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
|
|
5936
|
-
|
|
5937
|
-
|
|
5938
|
-
|
|
6336
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6337
|
+
await this.publishInvalidation(
|
|
6338
|
+
"del-glob",
|
|
6339
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6340
|
+
void 0,
|
|
6341
|
+
false,
|
|
6342
|
+
true
|
|
6343
|
+
);
|
|
6344
|
+
} else {
|
|
6345
|
+
void this.publishInvalidation(
|
|
6346
|
+
"del-glob",
|
|
6347
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6348
|
+
void 0,
|
|
6349
|
+
false,
|
|
6350
|
+
true
|
|
6351
|
+
);
|
|
6352
|
+
}
|
|
5939
6353
|
} catch (err) {
|
|
5940
6354
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5941
6355
|
span.recordException?.(err);
|
|
@@ -5950,6 +6364,7 @@ var CacheService = class _CacheService {
|
|
|
5950
6364
|
* Returns the number of entries evicted.
|
|
5951
6365
|
*/
|
|
5952
6366
|
rebalance() {
|
|
6367
|
+
this._assertActive("rebalance");
|
|
5953
6368
|
return this.l1.rebalance();
|
|
5954
6369
|
}
|
|
5955
6370
|
/**
|
|
@@ -5958,6 +6373,7 @@ var CacheService = class _CacheService {
|
|
|
5958
6373
|
* Only reflects L1 state — does not query Redis or disk.
|
|
5959
6374
|
*/
|
|
5960
6375
|
ttl(cacheKey) {
|
|
6376
|
+
this._assertActive("ttl");
|
|
5961
6377
|
return this.l1.ttl(this.nk(cacheKey));
|
|
5962
6378
|
}
|
|
5963
6379
|
/**
|
|
@@ -5965,6 +6381,7 @@ var CacheService = class _CacheService {
|
|
|
5965
6381
|
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
5966
6382
|
*/
|
|
5967
6383
|
has(cacheKey) {
|
|
6384
|
+
this._assertActive("has");
|
|
5968
6385
|
return this.l1.has(this.nk(cacheKey));
|
|
5969
6386
|
}
|
|
5970
6387
|
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
@@ -5975,6 +6392,7 @@ var CacheService = class _CacheService {
|
|
|
5975
6392
|
* for (const key of cache.keys()) console.log(key);
|
|
5976
6393
|
*/
|
|
5977
6394
|
*keys() {
|
|
6395
|
+
this._assertActive("keys");
|
|
5978
6396
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
5979
6397
|
for (const key of this.l1.liveKeys()) {
|
|
5980
6398
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -5989,6 +6407,7 @@ var CacheService = class _CacheService {
|
|
|
5989
6407
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
5990
6408
|
*/
|
|
5991
6409
|
*values() {
|
|
6410
|
+
this._assertActive("values");
|
|
5992
6411
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
5993
6412
|
if (!prefix) {
|
|
5994
6413
|
yield* this.l1.liveValues();
|
|
@@ -6007,6 +6426,7 @@ var CacheService = class _CacheService {
|
|
|
6007
6426
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
6008
6427
|
*/
|
|
6009
6428
|
*entries() {
|
|
6429
|
+
this._assertActive("entries");
|
|
6010
6430
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
6011
6431
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
6012
6432
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -6034,6 +6454,7 @@ var CacheService = class _CacheService {
|
|
|
6034
6454
|
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
6035
6455
|
*/
|
|
6036
6456
|
scan(fn) {
|
|
6457
|
+
this._assertActive("scan");
|
|
6037
6458
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
6038
6459
|
this.l1.scan((key, entry, pfx) => {
|
|
6039
6460
|
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
@@ -6047,6 +6468,7 @@ var CacheService = class _CacheService {
|
|
|
6047
6468
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
6048
6469
|
*/
|
|
6049
6470
|
async touch(cacheKey, newTtlSeconds) {
|
|
6471
|
+
this._assertActive("touch");
|
|
6050
6472
|
const k = this.nk(cacheKey);
|
|
6051
6473
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
6052
6474
|
if (hit && !this._redisDisabled) {
|
|
@@ -6067,6 +6489,7 @@ var CacheService = class _CacheService {
|
|
|
6067
6489
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
6068
6490
|
*/
|
|
6069
6491
|
getIfFresh(cacheKey) {
|
|
6492
|
+
this._assertActive("getIfFresh");
|
|
6070
6493
|
const k = this.nk(cacheKey);
|
|
6071
6494
|
const entry = this.l1.getEntry(k);
|
|
6072
6495
|
if (!entry) return null;
|
|
@@ -6084,6 +6507,7 @@ var CacheService = class _CacheService {
|
|
|
6084
6507
|
* const val = await cache.peek<User>('user:123');
|
|
6085
6508
|
*/
|
|
6086
6509
|
async peek(cacheKey) {
|
|
6510
|
+
this._assertActive("peek");
|
|
6087
6511
|
const k = this.nk(cacheKey);
|
|
6088
6512
|
const l1Hit = this.l1.get(k);
|
|
6089
6513
|
if (l1Hit !== null) {
|
|
@@ -6093,25 +6517,32 @@ var CacheService = class _CacheService {
|
|
|
6093
6517
|
if (this.opts.frozen) deepFreeze(val);
|
|
6094
6518
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6095
6519
|
}
|
|
6096
|
-
if (!this._diskDisabled && this.
|
|
6097
|
-
|
|
6098
|
-
|
|
6099
|
-
|
|
6100
|
-
|
|
6101
|
-
|
|
6102
|
-
if (
|
|
6103
|
-
const
|
|
6104
|
-
|
|
6105
|
-
|
|
6106
|
-
);
|
|
6107
|
-
|
|
6108
|
-
|
|
6109
|
-
|
|
6110
|
-
|
|
6111
|
-
this.
|
|
6112
|
-
|
|
6113
|
-
|
|
6114
|
-
|
|
6520
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6521
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6522
|
+
try {
|
|
6523
|
+
this.disk.delete(k);
|
|
6524
|
+
} catch {
|
|
6525
|
+
}
|
|
6526
|
+
} else if (this.watchdog.isDiskAllowed()) {
|
|
6527
|
+
const diskStart = performance.now();
|
|
6528
|
+
const diskHit = this.disk.load(k);
|
|
6529
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6530
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6531
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6532
|
+
if (diskHit !== null) {
|
|
6533
|
+
const promoted = this.l1.importEntries(
|
|
6534
|
+
[{ key: k, entry: diskHit }],
|
|
6535
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6536
|
+
);
|
|
6537
|
+
if (promoted > 0) {
|
|
6538
|
+
const l1Check = this.l1.get(k);
|
|
6539
|
+
if (l1Check !== null) {
|
|
6540
|
+
this.counters.gets++;
|
|
6541
|
+
this.counters.diskHits++;
|
|
6542
|
+
const val = l1Check.value;
|
|
6543
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6544
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6545
|
+
}
|
|
6115
6546
|
}
|
|
6116
6547
|
}
|
|
6117
6548
|
}
|
|
@@ -6149,6 +6580,7 @@ var CacheService = class _CacheService {
|
|
|
6149
6580
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
6150
6581
|
*/
|
|
6151
6582
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
6583
|
+
this._assertActive("mget");
|
|
6152
6584
|
const span = this._startSpan("tricache.mget");
|
|
6153
6585
|
if (this.opts.tracer) {
|
|
6154
6586
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6217,8 +6649,16 @@ var CacheService = class _CacheService {
|
|
|
6217
6649
|
}
|
|
6218
6650
|
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6219
6651
|
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6220
|
-
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6221
6652
|
const k = this.nk(missKeys[j]);
|
|
6653
|
+
if (this._pendingDiskDeletes.has(k)) continue;
|
|
6654
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6655
|
+
try {
|
|
6656
|
+
this.disk.delete(k);
|
|
6657
|
+
} catch {
|
|
6658
|
+
}
|
|
6659
|
+
continue;
|
|
6660
|
+
}
|
|
6661
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6222
6662
|
const diskStart = performance.now();
|
|
6223
6663
|
const diskHit = this.disk.load(k);
|
|
6224
6664
|
const diskElapsed = performance.now() - diskStart;
|
|
@@ -6241,16 +6681,23 @@ var CacheService = class _CacheService {
|
|
|
6241
6681
|
}
|
|
6242
6682
|
}
|
|
6243
6683
|
}
|
|
6244
|
-
if (missKeys.length > 0) {
|
|
6684
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6245
6685
|
this.counters.fetches++;
|
|
6246
6686
|
const fetched = await fetchFn(missKeys);
|
|
6687
|
+
const isMap = fetched instanceof Map;
|
|
6247
6688
|
const setPromises = [];
|
|
6248
6689
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6249
|
-
const
|
|
6690
|
+
const k = missKeys[j];
|
|
6691
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6250
6692
|
result[missIndexes[j]] = v;
|
|
6251
|
-
if (v !== void 0) {
|
|
6252
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6253
|
-
setPromises.push(this.set(
|
|
6693
|
+
if (v !== void 0 && v !== null) {
|
|
6694
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6695
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
6696
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
6697
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
6698
|
+
} else if (v === null) {
|
|
6699
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6700
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6254
6701
|
}
|
|
6255
6702
|
}
|
|
6256
6703
|
if (setPromises.length > 0) {
|
|
@@ -6298,6 +6745,7 @@ var CacheService = class _CacheService {
|
|
|
6298
6745
|
* });
|
|
6299
6746
|
*/
|
|
6300
6747
|
async mset(entries) {
|
|
6748
|
+
this._assertActive("mset");
|
|
6301
6749
|
const span = this._startSpan("tricache.mset");
|
|
6302
6750
|
const keys = Object.keys(entries);
|
|
6303
6751
|
if (this.opts.tracer) {
|
|
@@ -6325,6 +6773,7 @@ var CacheService = class _CacheService {
|
|
|
6325
6773
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
6326
6774
|
*/
|
|
6327
6775
|
async mdel(keys) {
|
|
6776
|
+
this._assertActive("mdel");
|
|
6328
6777
|
const span = this._startSpan("tricache.mdel");
|
|
6329
6778
|
if (this.opts.tracer) {
|
|
6330
6779
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6352,6 +6801,7 @@ var CacheService = class _CacheService {
|
|
|
6352
6801
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
6353
6802
|
*/
|
|
6354
6803
|
async warmFromL2(pattern, opts) {
|
|
6804
|
+
this._assertActive("warmFromL2");
|
|
6355
6805
|
if (this._redisDisabled) return 0;
|
|
6356
6806
|
try {
|
|
6357
6807
|
const client = await this.getRedis();
|
|
@@ -6390,20 +6840,109 @@ var CacheService = class _CacheService {
|
|
|
6390
6840
|
}
|
|
6391
6841
|
}
|
|
6392
6842
|
/**
|
|
6393
|
-
*
|
|
6394
|
-
*
|
|
6843
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
6844
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
6845
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
6846
|
+
*/
|
|
6847
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
6848
|
+
const isPattern = isWildcardTag(tag);
|
|
6849
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6850
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6851
|
+
const tagMatches = (t) => {
|
|
6852
|
+
if (t === tag) return true;
|
|
6853
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
6854
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
6855
|
+
return false;
|
|
6856
|
+
};
|
|
6857
|
+
if (shouldCascade && !isPattern) {
|
|
6858
|
+
matched.add(tag);
|
|
6859
|
+
}
|
|
6860
|
+
const tagPrefix = this.nk("_tag_:");
|
|
6861
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
6862
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
6863
|
+
if (tagMatches(t)) matched.add(t);
|
|
6864
|
+
}
|
|
6865
|
+
for (const t of this.tagVersions.keys()) {
|
|
6866
|
+
if (tagMatches(t)) matched.add(t);
|
|
6867
|
+
}
|
|
6868
|
+
this.l1.scan((_k, entry) => {
|
|
6869
|
+
if (entry.tagVersions) {
|
|
6870
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
6871
|
+
if (tagMatches(t)) matched.add(t);
|
|
6872
|
+
}
|
|
6873
|
+
}
|
|
6874
|
+
}, 0);
|
|
6875
|
+
if (!this._redisDisabled) {
|
|
6876
|
+
try {
|
|
6877
|
+
const client = await this.getRedis();
|
|
6878
|
+
if (this.opts.tagStrategy === "generational") {
|
|
6879
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
6880
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6881
|
+
const pfx = this.nk("tag_ver:");
|
|
6882
|
+
for (const sk of scannedKeys) {
|
|
6883
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6884
|
+
if (tagMatches(t)) matched.add(t);
|
|
6885
|
+
}
|
|
6886
|
+
} else {
|
|
6887
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
6888
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
6889
|
+
const pfx = this.nk("_tag_:");
|
|
6890
|
+
for (const sk of scannedKeys) {
|
|
6891
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
6892
|
+
if (tagMatches(t)) matched.add(t);
|
|
6893
|
+
}
|
|
6894
|
+
}
|
|
6895
|
+
} catch (err) {
|
|
6896
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
6897
|
+
}
|
|
6898
|
+
}
|
|
6899
|
+
return matched;
|
|
6900
|
+
}
|
|
6901
|
+
/**
|
|
6902
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
6903
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
6904
|
+
*
|
|
6905
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
6906
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
6395
6907
|
*
|
|
6396
6908
|
* @example
|
|
6397
6909
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6398
6910
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
6911
|
+
*
|
|
6912
|
+
* @example
|
|
6913
|
+
* // Wildcard pattern invalidation
|
|
6914
|
+
* await cache.invalidateTag('org:123:*');
|
|
6915
|
+
*
|
|
6916
|
+
* @example
|
|
6917
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
6918
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
6399
6919
|
*/
|
|
6400
|
-
async invalidateTag(tag) {
|
|
6920
|
+
async invalidateTag(tag, opts) {
|
|
6921
|
+
this._assertActive("invalidateTag");
|
|
6401
6922
|
const span = this._startSpan("tricache.invalidate_tag");
|
|
6402
6923
|
if (this.opts.tracer) {
|
|
6403
6924
|
span.setAttribute("cache.tag", tag);
|
|
6404
6925
|
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
6926
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
6405
6927
|
}
|
|
6406
6928
|
try {
|
|
6929
|
+
const isPattern = isWildcardTag(tag);
|
|
6930
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
6931
|
+
if (isPattern || shouldCascade) {
|
|
6932
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
6933
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
6934
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
6935
|
+
if (matchedTags.size > 0) {
|
|
6936
|
+
await this.invalidateTags(Array.from(matchedTags));
|
|
6937
|
+
}
|
|
6938
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
6939
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6940
|
+
await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
6941
|
+
} else {
|
|
6942
|
+
void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
6943
|
+
}
|
|
6944
|
+
return;
|
|
6945
|
+
}
|
|
6407
6946
|
if (this.opts.tagStrategy === "generational") {
|
|
6408
6947
|
let newVer = 1;
|
|
6409
6948
|
if (!this._redisDisabled) {
|
|
@@ -6419,15 +6958,27 @@ var CacheService = class _CacheService {
|
|
|
6419
6958
|
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6420
6959
|
newVer = current + 1;
|
|
6421
6960
|
}
|
|
6422
|
-
this._setLocalTagVersion(tag, newVer,
|
|
6423
|
-
|
|
6961
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
6962
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6963
|
+
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6964
|
+
} else {
|
|
6965
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
6966
|
+
}
|
|
6424
6967
|
return;
|
|
6425
6968
|
}
|
|
6426
6969
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6427
6970
|
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6428
6971
|
for (const k of members) {
|
|
6429
6972
|
this.l1.delete(k);
|
|
6430
|
-
|
|
6973
|
+
this._bumpKeyMutation(k);
|
|
6974
|
+
this._pendingDiskDeletes.add(k);
|
|
6975
|
+
setImmediate(() => {
|
|
6976
|
+
try {
|
|
6977
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6978
|
+
} finally {
|
|
6979
|
+
this._pendingDiskDeletes.delete(k);
|
|
6980
|
+
}
|
|
6981
|
+
});
|
|
6431
6982
|
}
|
|
6432
6983
|
this.tagIndex.delete(tagKey);
|
|
6433
6984
|
if (!this._redisDisabled) {
|
|
@@ -6454,24 +7005,39 @@ var CacheService = class _CacheService {
|
|
|
6454
7005
|
}
|
|
6455
7006
|
/**
|
|
6456
7007
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
6457
|
-
*
|
|
6458
|
-
*
|
|
7008
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
7009
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
6459
7010
|
*
|
|
6460
|
-
*
|
|
6461
|
-
*
|
|
7011
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
7012
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
6462
7013
|
*
|
|
6463
7014
|
* @example
|
|
6464
|
-
*
|
|
6465
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
7015
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
6466
7016
|
*/
|
|
6467
|
-
async invalidateTags(tags) {
|
|
7017
|
+
async invalidateTags(tags, opts) {
|
|
7018
|
+
this._assertActive("invalidateTags");
|
|
6468
7019
|
if (tags.length === 0) return;
|
|
7020
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
7021
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7022
|
+
if (hasWildcards || shouldCascade) {
|
|
7023
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
7024
|
+
for (const t of tags) {
|
|
7025
|
+
if (isWildcardTag(t) || shouldCascade) {
|
|
7026
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
7027
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
7028
|
+
} else {
|
|
7029
|
+
allResolvedTags.add(t);
|
|
7030
|
+
}
|
|
7031
|
+
}
|
|
7032
|
+
if (allResolvedTags.size === 0) return;
|
|
7033
|
+
tags = Array.from(allResolvedTags);
|
|
7034
|
+
}
|
|
6469
7035
|
if (tags.length === 1) {
|
|
6470
|
-
await this.invalidateTag(tags[0]);
|
|
7036
|
+
await this.invalidateTag(tags[0], opts);
|
|
6471
7037
|
return;
|
|
6472
7038
|
}
|
|
6473
7039
|
if (this.opts.tagStrategy === "generational") {
|
|
6474
|
-
const now =
|
|
7040
|
+
const now = performance.now();
|
|
6475
7041
|
if (!this._redisDisabled) {
|
|
6476
7042
|
try {
|
|
6477
7043
|
const client = await this.getRedis();
|
|
@@ -6482,7 +7048,11 @@ var CacheService = class _CacheService {
|
|
|
6482
7048
|
const [err, newVer] = results[i] ?? [null, null];
|
|
6483
7049
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
6484
7050
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
6485
|
-
|
|
7051
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7052
|
+
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
7053
|
+
} else {
|
|
7054
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
7055
|
+
}
|
|
6486
7056
|
}
|
|
6487
7057
|
return;
|
|
6488
7058
|
} catch (err) {
|
|
@@ -6492,7 +7062,11 @@ var CacheService = class _CacheService {
|
|
|
6492
7062
|
for (const tag of tags) {
|
|
6493
7063
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
6494
7064
|
this._setLocalTagVersion(tag, ver, now);
|
|
6495
|
-
|
|
7065
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7066
|
+
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
7067
|
+
} else {
|
|
7068
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
7069
|
+
}
|
|
6496
7070
|
}
|
|
6497
7071
|
return;
|
|
6498
7072
|
}
|
|
@@ -6507,7 +7081,15 @@ var CacheService = class _CacheService {
|
|
|
6507
7081
|
}
|
|
6508
7082
|
for (const k of allMembers) {
|
|
6509
7083
|
this.l1.delete(k);
|
|
6510
|
-
this.
|
|
7084
|
+
this._bumpKeyMutation(k);
|
|
7085
|
+
this._pendingDiskDeletes.add(k);
|
|
7086
|
+
setImmediate(() => {
|
|
7087
|
+
try {
|
|
7088
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
7089
|
+
} finally {
|
|
7090
|
+
this._pendingDiskDeletes.delete(k);
|
|
7091
|
+
}
|
|
7092
|
+
});
|
|
6511
7093
|
}
|
|
6512
7094
|
if (!this._redisDisabled) {
|
|
6513
7095
|
try {
|
|
@@ -6544,6 +7126,7 @@ var CacheService = class _CacheService {
|
|
|
6544
7126
|
* `l2` is `null` when Redis is disabled.
|
|
6545
7127
|
*/
|
|
6546
7128
|
async ping() {
|
|
7129
|
+
this._assertActive("ping");
|
|
6547
7130
|
const t0 = Date.now();
|
|
6548
7131
|
this.l1.has("__ping__");
|
|
6549
7132
|
const l1 = Date.now() - t0;
|
|
@@ -6623,6 +7206,7 @@ var CacheService = class _CacheService {
|
|
|
6623
7206
|
* Returns the number of keys written.
|
|
6624
7207
|
*/
|
|
6625
7208
|
async drainToL2() {
|
|
7209
|
+
this._assertActive("drainToL2");
|
|
6626
7210
|
if (this._redisDisabled) return 0;
|
|
6627
7211
|
try {
|
|
6628
7212
|
const client = await this.getRedis();
|
|
@@ -6666,6 +7250,7 @@ var CacheService = class _CacheService {
|
|
|
6666
7250
|
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
6667
7251
|
*/
|
|
6668
7252
|
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
7253
|
+
this._assertActive("setIfAbsent");
|
|
6669
7254
|
const k = this.nk(cacheKey);
|
|
6670
7255
|
if (this.l1.has(k)) return false;
|
|
6671
7256
|
if (!this._redisDisabled) {
|
|
@@ -6684,6 +7269,8 @@ var CacheService = class _CacheService {
|
|
|
6684
7269
|
}
|
|
6685
7270
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
6686
7271
|
const p = priority ?? inferPriority(cacheKey);
|
|
7272
|
+
this._bumpKeyMutation(k);
|
|
7273
|
+
this._pendingDiskDeletes.delete(k);
|
|
6687
7274
|
this.l1.set(k, value, ttlMs, p);
|
|
6688
7275
|
this.counters.sets++;
|
|
6689
7276
|
return true;
|
|
@@ -6702,6 +7289,7 @@ var CacheService = class _CacheService {
|
|
|
6702
7289
|
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
6703
7290
|
*/
|
|
6704
7291
|
async lock(resourceKey, fn, options) {
|
|
7292
|
+
this._assertActive("lock");
|
|
6705
7293
|
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
6706
7294
|
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
6707
7295
|
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
@@ -6728,6 +7316,10 @@ var CacheService = class _CacheService {
|
|
|
6728
7316
|
}
|
|
6729
7317
|
} catch (err) {
|
|
6730
7318
|
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
7319
|
+
const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
|
|
7320
|
+
if (failClosed) {
|
|
7321
|
+
throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
|
|
7322
|
+
}
|
|
6731
7323
|
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
6732
7324
|
resourceKey,
|
|
6733
7325
|
error: err.message
|
|
@@ -7073,6 +7665,7 @@ var CacheService = class _CacheService {
|
|
|
7073
7665
|
* the previous key for seamless fallback decryption of existing cache entries.
|
|
7074
7666
|
*/
|
|
7075
7667
|
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
7668
|
+
this._assertActive("rotateEncryptionKey");
|
|
7076
7669
|
this.enc.rotateKey(newKeyBase64, newMode);
|
|
7077
7670
|
if (this._workerPool) {
|
|
7078
7671
|
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
@@ -7082,6 +7675,8 @@ var CacheService = class _CacheService {
|
|
|
7082
7675
|
/** Close Redis connections and stop all background timers. */
|
|
7083
7676
|
async destroy() {
|
|
7084
7677
|
this._destroyed = true;
|
|
7678
|
+
this._pendingDiskDeletes.clear();
|
|
7679
|
+
this._keyMutationEpochs.clear();
|
|
7085
7680
|
const g = globalThis;
|
|
7086
7681
|
const key = _CacheService.globalKey(this.opts);
|
|
7087
7682
|
if (g[key] === this) {
|