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/cli.cjs
CHANGED
|
@@ -33,6 +33,7 @@ __export(cli_exports, {
|
|
|
33
33
|
runCli: () => runCli
|
|
34
34
|
});
|
|
35
35
|
module.exports = __toCommonJS(cli_exports);
|
|
36
|
+
var import_node_fs3 = require("fs");
|
|
36
37
|
var import_node_util = require("util");
|
|
37
38
|
|
|
38
39
|
// src/cache-service.ts
|
|
@@ -1910,13 +1911,38 @@ var import_os2 = __toESM(require("os"), 1);
|
|
|
1910
1911
|
|
|
1911
1912
|
// src/compression.ts
|
|
1912
1913
|
var import_zlib = __toESM(require("zlib"), 1);
|
|
1914
|
+
var import_lz4js = __toESM(require("lz4js"), 1);
|
|
1915
|
+
var import_zstd_codec = require("zstd-codec");
|
|
1913
1916
|
var PREFIX_COMPRESSED = "cmp:v1:";
|
|
1914
1917
|
var PREFIX_ENC_COMPRESSED = "ecp:v1:";
|
|
1915
1918
|
var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
|
|
1919
|
+
var zstdSimple = null;
|
|
1920
|
+
var zstdInitPromise = null;
|
|
1921
|
+
function initZstd() {
|
|
1922
|
+
if (zstdSimple) return Promise.resolve(zstdSimple);
|
|
1923
|
+
if (!zstdInitPromise) {
|
|
1924
|
+
zstdInitPromise = new Promise((resolve) => {
|
|
1925
|
+
try {
|
|
1926
|
+
import_zstd_codec.ZstdCodec.run((zstd) => {
|
|
1927
|
+
zstdSimple = new zstd.Simple();
|
|
1928
|
+
resolve(zstdSimple);
|
|
1929
|
+
});
|
|
1930
|
+
} catch {
|
|
1931
|
+
resolve(null);
|
|
1932
|
+
}
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
return zstdInitPromise;
|
|
1936
|
+
}
|
|
1937
|
+
initZstd().catch(() => {
|
|
1938
|
+
});
|
|
1916
1939
|
function isCompressed(buf) {
|
|
1917
1940
|
return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
|
|
1918
1941
|
}
|
|
1919
|
-
function compressBuffer(buf, algorithm) {
|
|
1942
|
+
function compressBuffer(buf, algorithm, custom) {
|
|
1943
|
+
if (custom) {
|
|
1944
|
+
return custom.compress(buf);
|
|
1945
|
+
}
|
|
1920
1946
|
if (algorithm === "brotli") {
|
|
1921
1947
|
return import_zlib.default.brotliCompressSync(buf, {
|
|
1922
1948
|
params: {
|
|
@@ -1928,37 +1954,127 @@ function compressBuffer(buf, algorithm) {
|
|
|
1928
1954
|
if (algorithm === "gzip") {
|
|
1929
1955
|
return import_zlib.default.gzipSync(buf, { level: 6 });
|
|
1930
1956
|
}
|
|
1957
|
+
if (algorithm === "lz4") {
|
|
1958
|
+
return Buffer.from(import_lz4js.default.compress(buf));
|
|
1959
|
+
}
|
|
1960
|
+
if (algorithm === "zstd") {
|
|
1961
|
+
if (!zstdSimple) {
|
|
1962
|
+
return import_zlib.default.brotliCompressSync(buf, {
|
|
1963
|
+
params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
return Buffer.from(zstdSimple.compress(buf));
|
|
1967
|
+
}
|
|
1931
1968
|
return buf;
|
|
1932
1969
|
}
|
|
1933
|
-
|
|
1970
|
+
var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
|
|
1971
|
+
function decompressBuffer(buf, algorithm = "zstd", custom) {
|
|
1972
|
+
if (custom) {
|
|
1973
|
+
const res = custom.decompress(buf);
|
|
1974
|
+
if (res.length > MAX_DECOMPRESS_BYTES) {
|
|
1975
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
1976
|
+
}
|
|
1977
|
+
return res;
|
|
1978
|
+
}
|
|
1979
|
+
const checkSafety = (decomp) => {
|
|
1980
|
+
if (decomp.length > MAX_DECOMPRESS_BYTES) {
|
|
1981
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
1982
|
+
}
|
|
1983
|
+
return decomp;
|
|
1984
|
+
};
|
|
1985
|
+
if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
|
|
1986
|
+
if (zstdSimple) {
|
|
1987
|
+
try {
|
|
1988
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
1989
|
+
} catch (err) {
|
|
1990
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
|
|
1995
|
+
try {
|
|
1996
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
1997
|
+
} catch (err) {
|
|
1998
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
|
|
2002
|
+
try {
|
|
2003
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2004
|
+
} catch (err) {
|
|
2005
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2006
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
if (algorithm === "none") {
|
|
2011
|
+
return buf;
|
|
2012
|
+
}
|
|
2013
|
+
if (algorithm === "lz4") {
|
|
2014
|
+
try {
|
|
2015
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2016
|
+
} catch (err) {
|
|
2017
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
if (algorithm === "zstd" && zstdSimple) {
|
|
2021
|
+
try {
|
|
2022
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2023
|
+
} catch (err) {
|
|
2024
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
1934
2027
|
const tryBrotli = () => {
|
|
1935
2028
|
try {
|
|
1936
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1937
|
-
} catch {
|
|
2029
|
+
return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2030
|
+
} catch (err) {
|
|
2031
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2032
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2033
|
+
}
|
|
1938
2034
|
return null;
|
|
1939
2035
|
}
|
|
1940
2036
|
};
|
|
1941
2037
|
const tryGzip = () => {
|
|
1942
2038
|
try {
|
|
1943
|
-
return import_zlib.default.gunzipSync(buf);
|
|
1944
|
-
} catch {
|
|
2039
|
+
return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
|
|
2040
|
+
} catch (err) {
|
|
2041
|
+
if (err?.code === "ERR_BUFFER_TOO_LARGE") {
|
|
2042
|
+
throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
|
|
2043
|
+
}
|
|
2044
|
+
return null;
|
|
2045
|
+
}
|
|
2046
|
+
};
|
|
2047
|
+
const tryLz4 = () => {
|
|
2048
|
+
try {
|
|
2049
|
+
return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
|
|
2050
|
+
} catch (err) {
|
|
2051
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
2052
|
+
return null;
|
|
2053
|
+
}
|
|
2054
|
+
};
|
|
2055
|
+
const tryZstd = () => {
|
|
2056
|
+
if (!zstdSimple) return null;
|
|
2057
|
+
try {
|
|
2058
|
+
return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
|
|
2059
|
+
} catch (err) {
|
|
2060
|
+
if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
|
|
1945
2061
|
return null;
|
|
1946
2062
|
}
|
|
1947
2063
|
};
|
|
1948
|
-
const result = algorithm === "gzip" ? tryGzip() ??
|
|
2064
|
+
const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
|
|
1949
2065
|
if (result === null) {
|
|
1950
2066
|
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
1951
2067
|
}
|
|
1952
2068
|
return result;
|
|
1953
2069
|
}
|
|
1954
|
-
function compressWithHeader(buf, algorithm) {
|
|
2070
|
+
function compressWithHeader(buf, algorithm, custom) {
|
|
1955
2071
|
if (algorithm === "none") return buf;
|
|
1956
|
-
const compressed = compressBuffer(buf, algorithm);
|
|
2072
|
+
const compressed = compressBuffer(buf, algorithm, custom);
|
|
1957
2073
|
return Buffer.concat([COMPRESSION_MAGIC, compressed]);
|
|
1958
2074
|
}
|
|
1959
|
-
function decompressWithHeader(buf, algorithm = "
|
|
2075
|
+
function decompressWithHeader(buf, algorithm = "zstd", custom) {
|
|
1960
2076
|
if (isCompressed(buf)) {
|
|
1961
|
-
return decompressBuffer(buf.subarray(4), algorithm);
|
|
2077
|
+
return decompressBuffer(buf.subarray(4), algorithm, custom);
|
|
1962
2078
|
}
|
|
1963
2079
|
return buf;
|
|
1964
2080
|
}
|
|
@@ -3664,6 +3780,26 @@ async function findActiveSockets() {
|
|
|
3664
3780
|
active.push(currentPipe);
|
|
3665
3781
|
} catch {
|
|
3666
3782
|
}
|
|
3783
|
+
try {
|
|
3784
|
+
const { execFileSync } = await import("child_process");
|
|
3785
|
+
const stdout = execFileSync(
|
|
3786
|
+
"powershell.exe",
|
|
3787
|
+
["-NoProfile", "-NonInteractive", "-Command", '[System.IO.Directory]::GetFiles("\\\\.\\pipe\\") | Where-Object { $_ -like "*tricache-*" }'],
|
|
3788
|
+
{ timeout: 1500, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
|
|
3789
|
+
);
|
|
3790
|
+
const candidates = stdout.split(/\r?\n/).map((name) => name.trim()).filter((name) => name.length > 0 && !active.includes(name));
|
|
3791
|
+
await Promise.all(
|
|
3792
|
+
candidates.map(async (pipePath) => {
|
|
3793
|
+
const testClient = new IpcTelemetryClient(pipePath);
|
|
3794
|
+
try {
|
|
3795
|
+
await testClient.ping(100);
|
|
3796
|
+
active.push(pipePath);
|
|
3797
|
+
} catch {
|
|
3798
|
+
}
|
|
3799
|
+
})
|
|
3800
|
+
);
|
|
3801
|
+
} catch {
|
|
3802
|
+
}
|
|
3667
3803
|
return active;
|
|
3668
3804
|
}
|
|
3669
3805
|
const dir = process.env.TMPDIR || "/tmp";
|
|
@@ -3768,6 +3904,55 @@ function renderTopDashboard(payload) {
|
|
|
3768
3904
|
return lines.join("\n");
|
|
3769
3905
|
}
|
|
3770
3906
|
|
|
3907
|
+
// src/utils/tag-matcher.ts
|
|
3908
|
+
var globRegexCache = /* @__PURE__ */ new Map();
|
|
3909
|
+
function isWildcardTag(tag) {
|
|
3910
|
+
return tag.includes("*") || tag.includes("?");
|
|
3911
|
+
}
|
|
3912
|
+
function matchesTagPattern(pattern, tag) {
|
|
3913
|
+
if (pattern === "*" || pattern === tag) return true;
|
|
3914
|
+
if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
|
|
3915
|
+
if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
|
|
3916
|
+
const prefix = pattern.slice(0, -1);
|
|
3917
|
+
return tag.startsWith(prefix);
|
|
3918
|
+
}
|
|
3919
|
+
if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
|
|
3920
|
+
const suffix = pattern.slice(1);
|
|
3921
|
+
return tag.endsWith(suffix);
|
|
3922
|
+
}
|
|
3923
|
+
let re = globRegexCache.get(pattern);
|
|
3924
|
+
if (!re) {
|
|
3925
|
+
if (globRegexCache.size >= 1e3) globRegexCache.clear();
|
|
3926
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
3927
|
+
re = new RegExp(`^${escaped}$`);
|
|
3928
|
+
globRegexCache.set(pattern, re);
|
|
3929
|
+
}
|
|
3930
|
+
return re.test(tag);
|
|
3931
|
+
}
|
|
3932
|
+
function isChildTag(parentTag, candidateTag, delimiter = ":") {
|
|
3933
|
+
if (candidateTag === parentTag) return true;
|
|
3934
|
+
const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
|
|
3935
|
+
return candidateTag.startsWith(prefix);
|
|
3936
|
+
}
|
|
3937
|
+
function expandHierarchicalTags(tags, delimiter = ":") {
|
|
3938
|
+
if (!tags.length) return [];
|
|
3939
|
+
const result = /* @__PURE__ */ new Set();
|
|
3940
|
+
for (const tag of tags) {
|
|
3941
|
+
if (!tag) continue;
|
|
3942
|
+
const parts = tag.split(delimiter).filter((p) => p.length > 0);
|
|
3943
|
+
if (parts.length <= 1) {
|
|
3944
|
+
result.add(tag);
|
|
3945
|
+
continue;
|
|
3946
|
+
}
|
|
3947
|
+
let accumulated = "";
|
|
3948
|
+
for (let i = 0; i < parts.length; i++) {
|
|
3949
|
+
accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
|
|
3950
|
+
result.add(accumulated);
|
|
3951
|
+
}
|
|
3952
|
+
}
|
|
3953
|
+
return Array.from(result);
|
|
3954
|
+
}
|
|
3955
|
+
|
|
3771
3956
|
// src/cache-service.ts
|
|
3772
3957
|
var LUA_COMPARE_AND_DELETE = `
|
|
3773
3958
|
local currentTs = redis.call('HGET', KEYS[1], 't')
|
|
@@ -3786,21 +3971,21 @@ var DEFAULT_CATEGORY_LIMITS = {
|
|
|
3786
3971
|
var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
|
|
3787
3972
|
var DEFAULT_COUNTER_TTL_SECONDS = 60;
|
|
3788
3973
|
var GLOB_REGEX_CACHE_MAX = 256;
|
|
3789
|
-
var
|
|
3974
|
+
var globRegexCache2 = /* @__PURE__ */ new Map();
|
|
3790
3975
|
function getGlobRegex(pattern) {
|
|
3791
|
-
let re =
|
|
3976
|
+
let re = globRegexCache2.get(pattern);
|
|
3792
3977
|
if (re) {
|
|
3793
|
-
|
|
3794
|
-
|
|
3978
|
+
globRegexCache2.delete(pattern);
|
|
3979
|
+
globRegexCache2.set(pattern, re);
|
|
3795
3980
|
return re;
|
|
3796
3981
|
}
|
|
3797
3982
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
|
|
3798
3983
|
re = new RegExp("^" + escaped + "$");
|
|
3799
|
-
if (
|
|
3800
|
-
const oldestKey =
|
|
3801
|
-
if (oldestKey !== void 0)
|
|
3984
|
+
if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
|
|
3985
|
+
const oldestKey = globRegexCache2.keys().next().value;
|
|
3986
|
+
if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
|
|
3802
3987
|
}
|
|
3803
|
-
|
|
3988
|
+
globRegexCache2.set(pattern, re);
|
|
3804
3989
|
return re;
|
|
3805
3990
|
}
|
|
3806
3991
|
var L2CircuitBreaker = class {
|
|
@@ -4054,6 +4239,7 @@ var CacheService = class _CacheService {
|
|
|
4054
4239
|
opts;
|
|
4055
4240
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
4056
4241
|
_namespace;
|
|
4242
|
+
prefixLen;
|
|
4057
4243
|
/** Pre-computed once — disableRedis and redisHost never change after construction. */
|
|
4058
4244
|
_redisDisabled;
|
|
4059
4245
|
watchdog;
|
|
@@ -4093,6 +4279,52 @@ var CacheService = class _CacheService {
|
|
|
4093
4279
|
streamClient = null;
|
|
4094
4280
|
_lastStreamId = "$";
|
|
4095
4281
|
_destroyed = false;
|
|
4282
|
+
_pendingDiskDeletes = /* @__PURE__ */ new Set();
|
|
4283
|
+
_globalEpoch = 0;
|
|
4284
|
+
_keyMutationEpochs = /* @__PURE__ */ new Map();
|
|
4285
|
+
/**
|
|
4286
|
+
* Pattern tombstones for disk tier.
|
|
4287
|
+
* Files in the disk tier are keyed by SHA-256 of namespacedKey.
|
|
4288
|
+
* Wildcard pattern deletes cannot scan the filesystem synchronously, so we maintain
|
|
4289
|
+
* pattern tombstones in memory to intercept subsequent disk reads and evict matching files.
|
|
4290
|
+
*/
|
|
4291
|
+
_patternTombstones = [];
|
|
4292
|
+
_addPatternTombstone(prefix) {
|
|
4293
|
+
const now = Date.now();
|
|
4294
|
+
while (this._patternTombstones.length > 0 && now - this._patternTombstones[0].createdAt > 36e5) {
|
|
4295
|
+
this._patternTombstones.shift();
|
|
4296
|
+
}
|
|
4297
|
+
if (this._patternTombstones.length >= 2e3) {
|
|
4298
|
+
this._patternTombstones.shift();
|
|
4299
|
+
}
|
|
4300
|
+
this._patternTombstones.push({ prefix, createdAt: now });
|
|
4301
|
+
}
|
|
4302
|
+
_isTombstonedByPattern(namespacedKey) {
|
|
4303
|
+
if (this._patternTombstones.length === 0) return false;
|
|
4304
|
+
for (let i = this._patternTombstones.length - 1; i >= 0; i--) {
|
|
4305
|
+
if (namespacedKey.startsWith(this._patternTombstones[i].prefix)) {
|
|
4306
|
+
return true;
|
|
4307
|
+
}
|
|
4308
|
+
}
|
|
4309
|
+
return false;
|
|
4310
|
+
}
|
|
4311
|
+
_assertActive(operation) {
|
|
4312
|
+
if (this._destroyed) {
|
|
4313
|
+
throw new Error(`TriCacheError: Cannot perform '${operation}' on a destroyed CacheService instance (namespace: '${this._namespace || "(default)"}').`);
|
|
4314
|
+
}
|
|
4315
|
+
}
|
|
4316
|
+
_bumpKeyMutation(namespacedKey) {
|
|
4317
|
+
const next = (this._keyMutationEpochs.get(namespacedKey) ?? 0) + 1;
|
|
4318
|
+
this._keyMutationEpochs.set(namespacedKey, next);
|
|
4319
|
+
if (this._keyMutationEpochs.size > 5e4) {
|
|
4320
|
+
const oldest = this._keyMutationEpochs.keys().next().value;
|
|
4321
|
+
if (oldest !== void 0) this._keyMutationEpochs.delete(oldest);
|
|
4322
|
+
}
|
|
4323
|
+
return next;
|
|
4324
|
+
}
|
|
4325
|
+
_getKeyMutationEpoch(namespacedKey) {
|
|
4326
|
+
return this._globalEpoch + (this._keyMutationEpochs.get(namespacedKey) ?? 0);
|
|
4327
|
+
}
|
|
4096
4328
|
_ipcServer;
|
|
4097
4329
|
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
4098
4330
|
_subDisconnectedAt = null;
|
|
@@ -4181,6 +4413,8 @@ var CacheService = class _CacheService {
|
|
|
4181
4413
|
),
|
|
4182
4414
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
4183
4415
|
invalidationBackplane: options.invalidationBackplane ?? true,
|
|
4416
|
+
awaitInvalidationBackplane: options.awaitInvalidationBackplane ?? false,
|
|
4417
|
+
lockFailClosed: options.lockFailClosed ?? false,
|
|
4184
4418
|
oomProtection: options.oomProtection ?? true,
|
|
4185
4419
|
oomHeapThreshold: options.oomHeapThreshold ?? 0.85,
|
|
4186
4420
|
oomCheckIntervalMs: options.oomCheckIntervalMs ?? 1e4,
|
|
@@ -4214,12 +4448,15 @@ var CacheService = class _CacheService {
|
|
|
4214
4448
|
redisSentinel: options.redisSentinel,
|
|
4215
4449
|
redisProtocol: options.redisProtocol,
|
|
4216
4450
|
useShardedPubSub: options.useShardedPubSub ?? false,
|
|
4217
|
-
compression: options.compression ?? "
|
|
4451
|
+
compression: options.compression ?? "zstd",
|
|
4452
|
+
customCompressor: options.customCompressor,
|
|
4218
4453
|
compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
|
|
4219
4454
|
strictSingleton: options.strictSingleton ?? false,
|
|
4220
4455
|
failClosed: options.failClosed ?? false,
|
|
4221
4456
|
tagStrategy: options.tagStrategy ?? "set",
|
|
4222
4457
|
tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
|
|
4458
|
+
hierarchicalTags: options.hierarchicalTags ?? false,
|
|
4459
|
+
tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
|
|
4223
4460
|
cloneStrategy: options.cloneStrategy ?? "none",
|
|
4224
4461
|
backplaneMode: options.backplaneMode ?? "pubsub",
|
|
4225
4462
|
backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
|
|
@@ -4292,6 +4529,7 @@ var CacheService = class _CacheService {
|
|
|
4292
4529
|
diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
|
|
4293
4530
|
});
|
|
4294
4531
|
this._namespace = ns;
|
|
4532
|
+
this.prefixLen = ns ? ns.length + 1 : 0;
|
|
4295
4533
|
this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
4296
4534
|
this.watchdog = new TierLatencyWatchdog({
|
|
4297
4535
|
enabled: options.diskLatencyWatchdog ?? true,
|
|
@@ -4401,6 +4639,9 @@ var CacheService = class _CacheService {
|
|
|
4401
4639
|
this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
|
|
4402
4640
|
this.initBackplane();
|
|
4403
4641
|
const startupPromises = [];
|
|
4642
|
+
if (this.opts.compression === "zstd") {
|
|
4643
|
+
startupPromises.push(initZstd().then(() => void 0));
|
|
4644
|
+
}
|
|
4404
4645
|
if (this.opts.remoteSnapshot) {
|
|
4405
4646
|
startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
|
|
4406
4647
|
}
|
|
@@ -4546,7 +4787,9 @@ var CacheService = class _CacheService {
|
|
|
4546
4787
|
"adaptiveTtl",
|
|
4547
4788
|
"l2WriteMode",
|
|
4548
4789
|
"instanceName",
|
|
4549
|
-
"invalidationBackplane"
|
|
4790
|
+
"invalidationBackplane",
|
|
4791
|
+
"awaitInvalidationBackplane",
|
|
4792
|
+
"lockFailClosed"
|
|
4550
4793
|
];
|
|
4551
4794
|
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
4552
4795
|
static optionsDiff(a, b) {
|
|
@@ -4587,6 +4830,8 @@ var CacheService = class _CacheService {
|
|
|
4587
4830
|
frozen: o.frozen,
|
|
4588
4831
|
adaptiveTtl: o.adaptiveTtl,
|
|
4589
4832
|
invalidationBackplane: o.invalidationBackplane,
|
|
4833
|
+
awaitInvalidationBackplane: o.awaitInvalidationBackplane,
|
|
4834
|
+
lockFailClosed: o.lockFailClosed,
|
|
4590
4835
|
strictSingleton: o.strictSingleton,
|
|
4591
4836
|
remoteSnapshot: o.remoteSnapshot,
|
|
4592
4837
|
crossRegion: o.crossRegion
|
|
@@ -4872,16 +5117,80 @@ var CacheService = class _CacheService {
|
|
|
4872
5117
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
4873
5118
|
if (op === "del") {
|
|
4874
5119
|
this.l1.delete(key);
|
|
5120
|
+
this._bumpKeyMutation(key);
|
|
5121
|
+
this.inflight.delete(key);
|
|
5122
|
+
this._pendingDiskDeletes.add(key);
|
|
4875
5123
|
setImmediate(() => {
|
|
4876
|
-
|
|
5124
|
+
try {
|
|
5125
|
+
if (!this._diskDisabled) this.disk.delete(key);
|
|
5126
|
+
} finally {
|
|
5127
|
+
this._pendingDiskDeletes.delete(key);
|
|
5128
|
+
}
|
|
4877
5129
|
});
|
|
4878
5130
|
this._cascadeDependencies(key);
|
|
4879
5131
|
} else if (op === "del-glob") {
|
|
4880
5132
|
this.l1.deletePattern(key);
|
|
5133
|
+
const pfx = key.endsWith("*") ? key.slice(0, -1) : key;
|
|
5134
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
5135
|
+
if (liveKey.startsWith(pfx)) {
|
|
5136
|
+
this._bumpKeyMutation(liveKey);
|
|
5137
|
+
}
|
|
5138
|
+
}
|
|
5139
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
5140
|
+
if (inflightKey.startsWith(pfx)) {
|
|
5141
|
+
this._bumpKeyMutation(inflightKey);
|
|
5142
|
+
this.inflight.delete(inflightKey);
|
|
5143
|
+
}
|
|
5144
|
+
}
|
|
5145
|
+
this._addPatternTombstone(pfx);
|
|
4881
5146
|
} else if (op === "tag_incr") {
|
|
4882
5147
|
const tag = key;
|
|
4883
5148
|
const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
4884
|
-
this._setLocalTagVersion(tag, ver,
|
|
5149
|
+
this._setLocalTagVersion(tag, ver, performance.now());
|
|
5150
|
+
} else if (op === "tag_pattern_incr") {
|
|
5151
|
+
const pattern = key;
|
|
5152
|
+
const now = performance.now();
|
|
5153
|
+
for (const [tag, info] of this.tagVersions) {
|
|
5154
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5155
|
+
this._setLocalTagVersion(tag, info.version + 1, now);
|
|
5156
|
+
}
|
|
5157
|
+
}
|
|
5158
|
+
this.l1.scan((k, entry) => {
|
|
5159
|
+
if (entry.tagVersions) {
|
|
5160
|
+
for (const tag of Object.keys(entry.tagVersions)) {
|
|
5161
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5162
|
+
this.l1.delete(k);
|
|
5163
|
+
this._bumpKeyMutation(k);
|
|
5164
|
+
break;
|
|
5165
|
+
}
|
|
5166
|
+
}
|
|
5167
|
+
}
|
|
5168
|
+
}, 0);
|
|
5169
|
+
} else if (op === "tag_pattern_del") {
|
|
5170
|
+
const pattern = key;
|
|
5171
|
+
const matchedTagKeys = [];
|
|
5172
|
+
const prefix = this.nk("_tag_:");
|
|
5173
|
+
for (const [tagKey, members] of this.tagIndex) {
|
|
5174
|
+
const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
|
|
5175
|
+
if (matchesTagPattern(pattern, tag)) {
|
|
5176
|
+
matchedTagKeys.push(tagKey);
|
|
5177
|
+
for (const k of members) {
|
|
5178
|
+
this.l1.delete(k);
|
|
5179
|
+
this._bumpKeyMutation(k);
|
|
5180
|
+
this._pendingDiskDeletes.add(k);
|
|
5181
|
+
setImmediate(() => {
|
|
5182
|
+
try {
|
|
5183
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
5184
|
+
} finally {
|
|
5185
|
+
this._pendingDiskDeletes.delete(k);
|
|
5186
|
+
}
|
|
5187
|
+
});
|
|
5188
|
+
}
|
|
5189
|
+
}
|
|
5190
|
+
}
|
|
5191
|
+
for (const tagKey of matchedTagKeys) {
|
|
5192
|
+
this.tagIndex.delete(tagKey);
|
|
5193
|
+
}
|
|
4885
5194
|
}
|
|
4886
5195
|
this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
|
|
4887
5196
|
}
|
|
@@ -4889,7 +5198,7 @@ var CacheService = class _CacheService {
|
|
|
4889
5198
|
_handleBackplaneMessage(message) {
|
|
4890
5199
|
try {
|
|
4891
5200
|
const msg = JSON.parse(message);
|
|
4892
|
-
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") {
|
|
5201
|
+
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") {
|
|
4893
5202
|
this.logger.warn("Backplane: rejected invalid pubsub message format", {
|
|
4894
5203
|
raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
|
|
4895
5204
|
});
|
|
@@ -4909,7 +5218,11 @@ var CacheService = class _CacheService {
|
|
|
4909
5218
|
if (!isCrossRegionRelay && this.opts.crossRegion) {
|
|
4910
5219
|
const shouldBroadcast = isExplicitInvalidation || Boolean(this.opts.crossRegion.broadcastOnSet);
|
|
4911
5220
|
if (shouldBroadcast) {
|
|
4912
|
-
|
|
5221
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5222
|
+
await this._broadcastCrossRegion(op, key, tagVersion);
|
|
5223
|
+
} else {
|
|
5224
|
+
void this._broadcastCrossRegion(op, key, tagVersion);
|
|
5225
|
+
}
|
|
4913
5226
|
}
|
|
4914
5227
|
}
|
|
4915
5228
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
@@ -4950,7 +5263,11 @@ var CacheService = class _CacheService {
|
|
|
4950
5263
|
);
|
|
4951
5264
|
}
|
|
4952
5265
|
this.counters.invSent++;
|
|
4953
|
-
} catch {
|
|
5266
|
+
} catch (err) {
|
|
5267
|
+
this.logger.warn("Backplane invalidation publish failed", { op, key, error: err.message });
|
|
5268
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
5269
|
+
throw err;
|
|
5270
|
+
}
|
|
4954
5271
|
}
|
|
4955
5272
|
}
|
|
4956
5273
|
_markCrossRegionEventSeen(id) {
|
|
@@ -5068,12 +5385,12 @@ var CacheService = class _CacheService {
|
|
|
5068
5385
|
* Offloads to worker thread if pool is active and payload exceeds threshold.
|
|
5069
5386
|
*/
|
|
5070
5387
|
async _serializeAndEncrypt(serialized) {
|
|
5071
|
-
const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
|
|
5072
|
-
if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5388
|
+
const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
|
|
5389
|
+
if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
|
|
5073
5390
|
return this._workerPool.encrypt(serialized);
|
|
5074
5391
|
}
|
|
5075
5392
|
if (isCompressed2) {
|
|
5076
|
-
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
|
|
5393
|
+
const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
|
|
5077
5394
|
if (this.enc.isEnabled) {
|
|
5078
5395
|
const encrypted = this.enc.encryptBuffer(compressed);
|
|
5079
5396
|
return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
|
|
@@ -5088,16 +5405,16 @@ var CacheService = class _CacheService {
|
|
|
5088
5405
|
*/
|
|
5089
5406
|
async _decryptAndDeserialize(raw) {
|
|
5090
5407
|
let plain;
|
|
5091
|
-
if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
|
|
5408
|
+
if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
|
|
5092
5409
|
plain = await this._workerPool.decrypt(raw);
|
|
5093
5410
|
} else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
|
|
5094
5411
|
const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
|
|
5095
5412
|
const decBuf = this.enc.decryptBuffer(encBuf);
|
|
5096
|
-
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5413
|
+
const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
5097
5414
|
plain = decompressed.toString("utf8");
|
|
5098
5415
|
} else if (raw.startsWith(PREFIX_COMPRESSED)) {
|
|
5099
5416
|
const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
|
|
5100
|
-
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
|
|
5417
|
+
const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
|
|
5101
5418
|
plain = decompressed.toString("utf8");
|
|
5102
5419
|
} else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
|
|
5103
5420
|
plain = this.enc.decrypt(raw);
|
|
@@ -5154,6 +5471,7 @@ var CacheService = class _CacheService {
|
|
|
5154
5471
|
}
|
|
5155
5472
|
}
|
|
5156
5473
|
async getRedis() {
|
|
5474
|
+
this._assertActive("getRedis");
|
|
5157
5475
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
5158
5476
|
if (this.redis) return this.redis;
|
|
5159
5477
|
if (this.redisConnecting) return this.redisConnecting;
|
|
@@ -5482,6 +5800,7 @@ var CacheService = class _CacheService {
|
|
|
5482
5800
|
* Caches negative lookups to avoid repeated DB hits for missing keys.
|
|
5483
5801
|
*/
|
|
5484
5802
|
async get(cacheKey, fetchFn, ttlSeconds = 300, opts = {}) {
|
|
5803
|
+
this._assertActive("get");
|
|
5485
5804
|
const span = this._startSpan("tricache.get");
|
|
5486
5805
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5487
5806
|
const k = this.nk(cacheKey);
|
|
@@ -5491,7 +5810,7 @@ var CacheService = class _CacheService {
|
|
|
5491
5810
|
const optRefreshAhead = opts.refreshAhead;
|
|
5492
5811
|
const optXfetchBeta = opts.xfetchBeta;
|
|
5493
5812
|
const optNotFoundTtl = opts.notFoundTtl;
|
|
5494
|
-
const optTags = opts.tags;
|
|
5813
|
+
const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
5495
5814
|
const l1Hit = this.l1.get(k);
|
|
5496
5815
|
if (l1Hit !== null) {
|
|
5497
5816
|
let isGenerationalStale = false;
|
|
@@ -5513,7 +5832,14 @@ var CacheService = class _CacheService {
|
|
|
5513
5832
|
if (swrGraceMs2 > 0 && !this.revalidating.has(k)) {
|
|
5514
5833
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
5515
5834
|
this.revalidating.add(k);
|
|
5516
|
-
void this._revalidate(
|
|
5835
|
+
void this._revalidate(
|
|
5836
|
+
k,
|
|
5837
|
+
fetchFn,
|
|
5838
|
+
ttlSeconds * 1e3,
|
|
5839
|
+
swrGraceMs2,
|
|
5840
|
+
priority2,
|
|
5841
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5842
|
+
);
|
|
5517
5843
|
this.counters.swrRevalidations++;
|
|
5518
5844
|
this.logger.debug("SWR: serving stale, revalidating", { cacheKey });
|
|
5519
5845
|
} else {
|
|
@@ -5532,7 +5858,14 @@ var CacheService = class _CacheService {
|
|
|
5532
5858
|
if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
|
|
5533
5859
|
const priority2 = optPriority ?? inferPriority(cacheKey);
|
|
5534
5860
|
this.revalidating.add(k);
|
|
5535
|
-
void this._revalidate(
|
|
5861
|
+
void this._revalidate(
|
|
5862
|
+
k,
|
|
5863
|
+
fetchFn,
|
|
5864
|
+
entryTtl,
|
|
5865
|
+
optSwr * 1e3,
|
|
5866
|
+
priority2,
|
|
5867
|
+
l1Hit.tagVersions ?? (optTags ? Object.fromEntries(optTags.map((t) => [t, 0])) : void 0)
|
|
5868
|
+
);
|
|
5536
5869
|
this.counters.swrRevalidations++;
|
|
5537
5870
|
this.logger.debug(
|
|
5538
5871
|
shouldXFetch ? "XFetch: proactive background recompute" : "Refresh-ahead: proactive background recompute",
|
|
@@ -5558,44 +5891,52 @@ var CacheService = class _CacheService {
|
|
|
5558
5891
|
span.setAttribute("cache.hit", true).setAttribute("cache.stampede_coalesced", true).end();
|
|
5559
5892
|
return existing;
|
|
5560
5893
|
}
|
|
5894
|
+
const mutationEpochAtStart = this._getKeyMutationEpoch(k);
|
|
5561
5895
|
const executionPromise = (async () => {
|
|
5562
5896
|
try {
|
|
5563
|
-
if (!this._diskDisabled) {
|
|
5564
|
-
|
|
5565
|
-
|
|
5566
|
-
|
|
5567
|
-
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
this.watchdog.
|
|
5571
|
-
if (
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5897
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
5898
|
+
if (this._isTombstonedByPattern(k)) {
|
|
5899
|
+
try {
|
|
5900
|
+
this.disk.delete(k);
|
|
5901
|
+
} catch {
|
|
5902
|
+
}
|
|
5903
|
+
} else {
|
|
5904
|
+
const isDiskAllowed = this.watchdog.isDiskAllowed();
|
|
5905
|
+
if (isDiskAllowed) {
|
|
5906
|
+
const diskStart = performance.now();
|
|
5907
|
+
const diskHit = this.disk.load(k);
|
|
5908
|
+
const diskElapsed = performance.now() - diskStart;
|
|
5909
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
5910
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
5911
|
+
if (diskHit !== null) {
|
|
5912
|
+
let isDiskStale = false;
|
|
5913
|
+
if (this.opts.tagStrategy === "generational" && diskHit.tagVersions) {
|
|
5914
|
+
const tags = Object.keys(diskHit.tagVersions);
|
|
5915
|
+
const currentVers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5916
|
+
for (let i = 0; i < tags.length; i++) {
|
|
5917
|
+
if (currentVers[i] > diskHit.tagVersions[tags[i]]) {
|
|
5918
|
+
isDiskStale = true;
|
|
5919
|
+
break;
|
|
5920
|
+
}
|
|
5580
5921
|
}
|
|
5581
5922
|
}
|
|
5582
|
-
|
|
5583
|
-
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
5590
|
-
|
|
5591
|
-
|
|
5592
|
-
|
|
5593
|
-
|
|
5594
|
-
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5923
|
+
if (isDiskStale) {
|
|
5924
|
+
this.disk.delete(k);
|
|
5925
|
+
} else {
|
|
5926
|
+
const promoted = this.l1.importEntries(
|
|
5927
|
+
[{ key: k, entry: diskHit }],
|
|
5928
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
5929
|
+
);
|
|
5930
|
+
if (promoted > 0) {
|
|
5931
|
+
const l1Check = this.l1.get(k);
|
|
5932
|
+
if (l1Check !== null) {
|
|
5933
|
+
this.counters.diskHits++;
|
|
5934
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
5935
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
5936
|
+
span.setAttribute("cache.hit", true).setAttribute("cache.item.tier", "disk").setAttribute("cache.hit_tier", "disk");
|
|
5937
|
+
if (this.opts.frozen) deepFreeze(l1Check.value);
|
|
5938
|
+
return this.opts.cloneStrategy === "structuredClone" && l1Check.value != null && typeof l1Check.value === "object" ? structuredClone(l1Check.value) : l1Check.value;
|
|
5939
|
+
}
|
|
5599
5940
|
}
|
|
5600
5941
|
}
|
|
5601
5942
|
}
|
|
@@ -5706,6 +6047,18 @@ var CacheService = class _CacheService {
|
|
|
5706
6047
|
await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1e3));
|
|
5707
6048
|
}
|
|
5708
6049
|
}
|
|
6050
|
+
if (this._getKeyMutationEpoch(k) !== mutationEpochAtStart) {
|
|
6051
|
+
this.logger.debug("Aborting in-flight cache commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
6052
|
+
span.setAttribute("cache.aborted_mutation_race", true);
|
|
6053
|
+
const current = this.l1.get(k);
|
|
6054
|
+
if (current && !current.isStale && current.value !== void 0) {
|
|
6055
|
+
const freshVal = current.value;
|
|
6056
|
+
if (this.opts.frozen) deepFreeze(freshVal);
|
|
6057
|
+
return this.opts.cloneStrategy === "structuredClone" && freshVal != null && typeof freshVal === "object" ? structuredClone(freshVal) : freshVal;
|
|
6058
|
+
}
|
|
6059
|
+
if (this.opts.frozen) deepFreeze(data);
|
|
6060
|
+
return this.opts.cloneStrategy === "structuredClone" && data != null && typeof data === "object" ? structuredClone(data) : data;
|
|
6061
|
+
}
|
|
5709
6062
|
this.l1.set(k, data, storeTtl, priority, staleAt, delta, activeTagVersions);
|
|
5710
6063
|
if (!this._redisDisabled) {
|
|
5711
6064
|
try {
|
|
@@ -5822,22 +6175,40 @@ var CacheService = class _CacheService {
|
|
|
5822
6175
|
const ttl = options?.ttl ?? 300;
|
|
5823
6176
|
return this.get(cacheKey, fetchFn, ttl, options);
|
|
5824
6177
|
}
|
|
5825
|
-
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority) {
|
|
6178
|
+
async _revalidate(cacheKey, fetchFn, ttlMs, swrGraceMs, priority, knownTagVersions) {
|
|
6179
|
+
const startEpoch = this._getKeyMutationEpoch(cacheKey);
|
|
5826
6180
|
try {
|
|
5827
6181
|
const fetchStart = Date.now();
|
|
5828
6182
|
const data = await fetchFn();
|
|
5829
6183
|
const delta = Date.now() - fetchStart;
|
|
5830
6184
|
const staleAt = Date.now() + ttlMs;
|
|
6185
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
6186
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during fetch", { cacheKey });
|
|
6187
|
+
return;
|
|
6188
|
+
}
|
|
5831
6189
|
if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
|
|
5832
6190
|
let activeTagVersions;
|
|
5833
6191
|
const l1Existing = this.l1.get(cacheKey);
|
|
5834
|
-
|
|
5835
|
-
|
|
6192
|
+
const tagVersionsSource = l1Existing?.tagVersions ?? knownTagVersions;
|
|
6193
|
+
if (this.opts.tagStrategy === "generational" && tagVersionsSource) {
|
|
6194
|
+
const tags = Object.keys(tagVersionsSource);
|
|
5836
6195
|
const vers = await Promise.all(tags.map((tag) => this._getTagVersion(tag)));
|
|
5837
6196
|
activeTagVersions = {};
|
|
5838
6197
|
for (let i = 0; i < tags.length; i++) {
|
|
5839
6198
|
activeTagVersions[tags[i]] = vers[i];
|
|
5840
6199
|
}
|
|
6200
|
+
if (knownTagVersions) {
|
|
6201
|
+
for (const t of tags) {
|
|
6202
|
+
if (knownTagVersions[t] !== void 0 && activeTagVersions[t] !== knownTagVersions[t]) {
|
|
6203
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 tag version bumped during revalidation", { cacheKey, tag: t });
|
|
6204
|
+
return;
|
|
6205
|
+
}
|
|
6206
|
+
}
|
|
6207
|
+
}
|
|
6208
|
+
}
|
|
6209
|
+
if (this._getKeyMutationEpoch(cacheKey) !== startEpoch) {
|
|
6210
|
+
this.logger.debug("SWR: aborting revalidation commit \u2014 key was mutated or deleted during tag resolution", { cacheKey });
|
|
6211
|
+
return;
|
|
5841
6212
|
}
|
|
5842
6213
|
this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta, activeTagVersions);
|
|
5843
6214
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
@@ -5881,6 +6252,7 @@ var CacheService = class _CacheService {
|
|
|
5881
6252
|
// ── Explicit set / delete ─────────────────────────────────────────────────
|
|
5882
6253
|
/** Explicitly write a value into L1 (+ L2 in production). */
|
|
5883
6254
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
6255
|
+
this._assertActive("set");
|
|
5884
6256
|
const span = this._startSpan("tricache.set");
|
|
5885
6257
|
if (this.opts.tracer) {
|
|
5886
6258
|
span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
@@ -5891,17 +6263,21 @@ var CacheService = class _CacheService {
|
|
|
5891
6263
|
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
5892
6264
|
const p = priority ?? inferPriority(cacheKey);
|
|
5893
6265
|
const k = this.nk(cacheKey);
|
|
6266
|
+
this._bumpKeyMutation(k);
|
|
6267
|
+
this.inflight.delete(k);
|
|
6268
|
+
this._pendingDiskDeletes.delete(k);
|
|
5894
6269
|
this.counters.sets++;
|
|
5895
6270
|
let activeTagVersions;
|
|
5896
|
-
|
|
6271
|
+
const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
|
|
6272
|
+
if (tagsToRegister?.length) {
|
|
5897
6273
|
if (this.opts.tagStrategy === "generational") {
|
|
5898
|
-
const vers = await Promise.all(
|
|
6274
|
+
const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
|
|
5899
6275
|
activeTagVersions = {};
|
|
5900
|
-
for (let i = 0; i <
|
|
5901
|
-
activeTagVersions[
|
|
6276
|
+
for (let i = 0; i < tagsToRegister.length; i++) {
|
|
6277
|
+
activeTagVersions[tagsToRegister[i]] = vers[i];
|
|
5902
6278
|
}
|
|
5903
6279
|
} else {
|
|
5904
|
-
await this._registerTags(k,
|
|
6280
|
+
await this._registerTags(k, tagsToRegister, ttlSeconds);
|
|
5905
6281
|
}
|
|
5906
6282
|
}
|
|
5907
6283
|
this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
|
|
@@ -5945,7 +6321,11 @@ var CacheService = class _CacheService {
|
|
|
5945
6321
|
this.logger.debug("set: Redis unavailable", { cacheKey, error: err.message });
|
|
5946
6322
|
}
|
|
5947
6323
|
}
|
|
5948
|
-
|
|
6324
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6325
|
+
await this.publishInvalidation("del", k);
|
|
6326
|
+
} else {
|
|
6327
|
+
void this.publishInvalidation("del", k);
|
|
6328
|
+
}
|
|
5949
6329
|
} catch (err) {
|
|
5950
6330
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
5951
6331
|
span.recordException?.(err);
|
|
@@ -5992,6 +6372,7 @@ var CacheService = class _CacheService {
|
|
|
5992
6372
|
* await cache.delete('user:abc:*'); // all keys for user abc
|
|
5993
6373
|
*/
|
|
5994
6374
|
async delete(cacheKey) {
|
|
6375
|
+
this._assertActive("delete");
|
|
5995
6376
|
const span = this._startSpan("tricache.delete");
|
|
5996
6377
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
5997
6378
|
try {
|
|
@@ -5999,11 +6380,31 @@ var CacheService = class _CacheService {
|
|
|
5999
6380
|
const k = this.nk(cacheKey);
|
|
6000
6381
|
this.counters.deletes++;
|
|
6001
6382
|
if (isPattern) {
|
|
6383
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6384
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6385
|
+
if (liveKey.startsWith(pfx)) {
|
|
6386
|
+
this._bumpKeyMutation(liveKey);
|
|
6387
|
+
}
|
|
6388
|
+
}
|
|
6389
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6390
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6391
|
+
this._bumpKeyMutation(inflightKey);
|
|
6392
|
+
this.inflight.delete(inflightKey);
|
|
6393
|
+
}
|
|
6394
|
+
}
|
|
6395
|
+
this._addPatternTombstone(pfx);
|
|
6002
6396
|
this.l1.deletePattern(k);
|
|
6003
6397
|
} else {
|
|
6398
|
+
this._bumpKeyMutation(k);
|
|
6399
|
+
this.inflight.delete(k);
|
|
6004
6400
|
this.l1.delete(k);
|
|
6401
|
+
this._pendingDiskDeletes.add(k);
|
|
6005
6402
|
setImmediate(() => {
|
|
6006
|
-
|
|
6403
|
+
try {
|
|
6404
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
6405
|
+
} finally {
|
|
6406
|
+
this._pendingDiskDeletes.delete(k);
|
|
6407
|
+
}
|
|
6007
6408
|
});
|
|
6008
6409
|
this._cascadeDependencies(k);
|
|
6009
6410
|
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
@@ -6027,7 +6428,11 @@ var CacheService = class _CacheService {
|
|
|
6027
6428
|
this.logger.debug("delete: Redis unavailable", { cacheKey, error: err.message });
|
|
6028
6429
|
}
|
|
6029
6430
|
}
|
|
6030
|
-
|
|
6431
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6432
|
+
await this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6433
|
+
} else {
|
|
6434
|
+
void this.publishInvalidation(isPattern ? "del-glob" : "del", k, void 0, false, true);
|
|
6435
|
+
}
|
|
6031
6436
|
} catch (err) {
|
|
6032
6437
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6033
6438
|
span.recordException?.(err);
|
|
@@ -6054,6 +6459,7 @@ var CacheService = class _CacheService {
|
|
|
6054
6459
|
* fleet-wide.
|
|
6055
6460
|
*/
|
|
6056
6461
|
async increment(cacheKey, ttlSeconds) {
|
|
6462
|
+
this._assertActive("increment");
|
|
6057
6463
|
const k = this.nk(cacheKey);
|
|
6058
6464
|
if (this._redisDisabled) {
|
|
6059
6465
|
if (!this._incrementFallbackWarned) {
|
|
@@ -6095,19 +6501,38 @@ var CacheService = class _CacheService {
|
|
|
6095
6501
|
* await cache.clear('user:abc'); // flush all keys for one user
|
|
6096
6502
|
*/
|
|
6097
6503
|
async clear(prefix) {
|
|
6504
|
+
this._assertActive("clear");
|
|
6098
6505
|
const span = this._startSpan("tricache.clear");
|
|
6099
6506
|
if (this.opts.tracer) span.setAttribute("cache.prefix", prefix || "*");
|
|
6100
6507
|
try {
|
|
6101
6508
|
this.counters.deletes++;
|
|
6102
6509
|
const k = prefix ? this.nk(prefix.includes("*") ? prefix : `${prefix}*`) : void 0;
|
|
6103
6510
|
if (k) {
|
|
6511
|
+
const pfx = k.endsWith("*") ? k.slice(0, -1) : k;
|
|
6512
|
+
for (const liveKey of this.l1.liveKeys()) {
|
|
6513
|
+
if (liveKey.startsWith(pfx)) {
|
|
6514
|
+
this._bumpKeyMutation(liveKey);
|
|
6515
|
+
}
|
|
6516
|
+
}
|
|
6517
|
+
for (const inflightKey of Array.from(this.inflight.keys())) {
|
|
6518
|
+
if (inflightKey.startsWith(pfx)) {
|
|
6519
|
+
this._bumpKeyMutation(inflightKey);
|
|
6520
|
+
this.inflight.delete(inflightKey);
|
|
6521
|
+
}
|
|
6522
|
+
}
|
|
6523
|
+
this._addPatternTombstone(pfx);
|
|
6104
6524
|
this.l1.deletePattern(k);
|
|
6105
6525
|
} else {
|
|
6526
|
+
this._globalEpoch++;
|
|
6527
|
+
this.inflight.clear();
|
|
6528
|
+
this._patternTombstones.length = 0;
|
|
6106
6529
|
this.l1.clear();
|
|
6107
6530
|
if (!this._diskDisabled) this.disk.clear();
|
|
6108
6531
|
this._l1Counters.clear();
|
|
6109
6532
|
this.tagIndex.clear();
|
|
6110
6533
|
this.tagVersions.clear();
|
|
6534
|
+
this._pendingDiskDeletes.clear();
|
|
6535
|
+
this._keyMutationEpochs.clear();
|
|
6111
6536
|
}
|
|
6112
6537
|
if (!this._redisDisabled && this.opts.l2WriteMode === "read-write") {
|
|
6113
6538
|
try {
|
|
@@ -6119,13 +6544,23 @@ var CacheService = class _CacheService {
|
|
|
6119
6544
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
6120
6545
|
}
|
|
6121
6546
|
}
|
|
6122
|
-
|
|
6123
|
-
|
|
6124
|
-
|
|
6125
|
-
|
|
6126
|
-
|
|
6127
|
-
|
|
6128
|
-
|
|
6547
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
6548
|
+
await this.publishInvalidation(
|
|
6549
|
+
"del-glob",
|
|
6550
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6551
|
+
void 0,
|
|
6552
|
+
false,
|
|
6553
|
+
true
|
|
6554
|
+
);
|
|
6555
|
+
} else {
|
|
6556
|
+
void this.publishInvalidation(
|
|
6557
|
+
"del-glob",
|
|
6558
|
+
k ?? (this._namespace ? `${this._namespace}:*` : "*"),
|
|
6559
|
+
void 0,
|
|
6560
|
+
false,
|
|
6561
|
+
true
|
|
6562
|
+
);
|
|
6563
|
+
}
|
|
6129
6564
|
} catch (err) {
|
|
6130
6565
|
span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });
|
|
6131
6566
|
span.recordException?.(err);
|
|
@@ -6140,6 +6575,7 @@ var CacheService = class _CacheService {
|
|
|
6140
6575
|
* Returns the number of entries evicted.
|
|
6141
6576
|
*/
|
|
6142
6577
|
rebalance() {
|
|
6578
|
+
this._assertActive("rebalance");
|
|
6143
6579
|
return this.l1.rebalance();
|
|
6144
6580
|
}
|
|
6145
6581
|
/**
|
|
@@ -6148,6 +6584,7 @@ var CacheService = class _CacheService {
|
|
|
6148
6584
|
* Only reflects L1 state — does not query Redis or disk.
|
|
6149
6585
|
*/
|
|
6150
6586
|
ttl(cacheKey) {
|
|
6587
|
+
this._assertActive("ttl");
|
|
6151
6588
|
return this.l1.ttl(this.nk(cacheKey));
|
|
6152
6589
|
}
|
|
6153
6590
|
/**
|
|
@@ -6155,6 +6592,7 @@ var CacheService = class _CacheService {
|
|
|
6155
6592
|
* Bloom-filter fast path — no fetch, no disk or Redis round-trip.
|
|
6156
6593
|
*/
|
|
6157
6594
|
has(cacheKey) {
|
|
6595
|
+
this._assertActive("has");
|
|
6158
6596
|
return this.l1.has(this.nk(cacheKey));
|
|
6159
6597
|
}
|
|
6160
6598
|
// ── Iteration ─────────────────────────────────────────────────────────────
|
|
@@ -6165,6 +6603,7 @@ var CacheService = class _CacheService {
|
|
|
6165
6603
|
* for (const key of cache.keys()) console.log(key);
|
|
6166
6604
|
*/
|
|
6167
6605
|
*keys() {
|
|
6606
|
+
this._assertActive("keys");
|
|
6168
6607
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
6169
6608
|
for (const key of this.l1.liveKeys()) {
|
|
6170
6609
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -6179,6 +6618,7 @@ var CacheService = class _CacheService {
|
|
|
6179
6618
|
* for (const val of cache.values<User>()) console.log(val.id);
|
|
6180
6619
|
*/
|
|
6181
6620
|
*values() {
|
|
6621
|
+
this._assertActive("values");
|
|
6182
6622
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
6183
6623
|
if (!prefix) {
|
|
6184
6624
|
yield* this.l1.liveValues();
|
|
@@ -6197,6 +6637,7 @@ var CacheService = class _CacheService {
|
|
|
6197
6637
|
* for (const [key, val] of cache.entries<User>()) console.log(key, val.id);
|
|
6198
6638
|
*/
|
|
6199
6639
|
*entries() {
|
|
6640
|
+
this._assertActive("entries");
|
|
6200
6641
|
const prefix = this._namespace ? this._namespace + ":" : "";
|
|
6201
6642
|
for (const [key, entry] of this.l1.liveEntries()) {
|
|
6202
6643
|
if (prefix && !key.startsWith(prefix)) continue;
|
|
@@ -6224,6 +6665,7 @@ var CacheService = class _CacheService {
|
|
|
6224
6665
|
* `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
|
|
6225
6666
|
*/
|
|
6226
6667
|
scan(fn) {
|
|
6668
|
+
this._assertActive("scan");
|
|
6227
6669
|
const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
|
|
6228
6670
|
this.l1.scan((key, entry, pfx) => {
|
|
6229
6671
|
const value = entry.value !== void 0 ? entry.value : entry.data;
|
|
@@ -6237,6 +6679,7 @@ var CacheService = class _CacheService {
|
|
|
6237
6679
|
* @param newTtlSeconds - The new TTL from now, in seconds.
|
|
6238
6680
|
*/
|
|
6239
6681
|
async touch(cacheKey, newTtlSeconds) {
|
|
6682
|
+
this._assertActive("touch");
|
|
6240
6683
|
const k = this.nk(cacheKey);
|
|
6241
6684
|
const hit = this.l1.touch(k, newTtlSeconds * 1e3);
|
|
6242
6685
|
if (hit && !this._redisDisabled) {
|
|
@@ -6257,6 +6700,7 @@ var CacheService = class _CacheService {
|
|
|
6257
6700
|
* if (fresh !== null) return fresh; // serve from L1, no network hop
|
|
6258
6701
|
*/
|
|
6259
6702
|
getIfFresh(cacheKey) {
|
|
6703
|
+
this._assertActive("getIfFresh");
|
|
6260
6704
|
const k = this.nk(cacheKey);
|
|
6261
6705
|
const entry = this.l1.getEntry(k);
|
|
6262
6706
|
if (!entry) return null;
|
|
@@ -6274,6 +6718,7 @@ var CacheService = class _CacheService {
|
|
|
6274
6718
|
* const val = await cache.peek<User>('user:123');
|
|
6275
6719
|
*/
|
|
6276
6720
|
async peek(cacheKey) {
|
|
6721
|
+
this._assertActive("peek");
|
|
6277
6722
|
const k = this.nk(cacheKey);
|
|
6278
6723
|
const l1Hit = this.l1.get(k);
|
|
6279
6724
|
if (l1Hit !== null) {
|
|
@@ -6283,25 +6728,32 @@ var CacheService = class _CacheService {
|
|
|
6283
6728
|
if (this.opts.frozen) deepFreeze(val);
|
|
6284
6729
|
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6285
6730
|
}
|
|
6286
|
-
if (!this._diskDisabled && this.
|
|
6287
|
-
|
|
6288
|
-
|
|
6289
|
-
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
if (
|
|
6293
|
-
const
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
);
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
this.
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
|
|
6731
|
+
if (!this._diskDisabled && !this._pendingDiskDeletes.has(k)) {
|
|
6732
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6733
|
+
try {
|
|
6734
|
+
this.disk.delete(k);
|
|
6735
|
+
} catch {
|
|
6736
|
+
}
|
|
6737
|
+
} else if (this.watchdog.isDiskAllowed()) {
|
|
6738
|
+
const diskStart = performance.now();
|
|
6739
|
+
const diskHit = this.disk.load(k);
|
|
6740
|
+
const diskElapsed = performance.now() - diskStart;
|
|
6741
|
+
this.watchdog.recordDisk(diskElapsed);
|
|
6742
|
+
this.watchdog.onCanaryResult(diskHit !== null, diskElapsed);
|
|
6743
|
+
if (diskHit !== null) {
|
|
6744
|
+
const promoted = this.l1.importEntries(
|
|
6745
|
+
[{ key: k, entry: diskHit }],
|
|
6746
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
6747
|
+
);
|
|
6748
|
+
if (promoted > 0) {
|
|
6749
|
+
const l1Check = this.l1.get(k);
|
|
6750
|
+
if (l1Check !== null) {
|
|
6751
|
+
this.counters.gets++;
|
|
6752
|
+
this.counters.diskHits++;
|
|
6753
|
+
const val = l1Check.value;
|
|
6754
|
+
if (this.opts.frozen) deepFreeze(val);
|
|
6755
|
+
return this.opts.cloneStrategy === "structuredClone" && val != null && typeof val === "object" ? structuredClone(val) : val;
|
|
6756
|
+
}
|
|
6305
6757
|
}
|
|
6306
6758
|
}
|
|
6307
6759
|
}
|
|
@@ -6339,6 +6791,7 @@ var CacheService = class _CacheService {
|
|
|
6339
6791
|
* `(key) => number` so heterogeneous TTLs can be batched in one call.
|
|
6340
6792
|
*/
|
|
6341
6793
|
async mget(keys, fetchFn, ttl = 300, priority) {
|
|
6794
|
+
this._assertActive("mget");
|
|
6342
6795
|
const span = this._startSpan("tricache.mget");
|
|
6343
6796
|
if (this.opts.tracer) {
|
|
6344
6797
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6407,8 +6860,16 @@ var CacheService = class _CacheService {
|
|
|
6407
6860
|
}
|
|
6408
6861
|
if (!this._diskDisabled && missKeys.length > 0) {
|
|
6409
6862
|
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
6410
|
-
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6411
6863
|
const k = this.nk(missKeys[j]);
|
|
6864
|
+
if (this._pendingDiskDeletes.has(k)) continue;
|
|
6865
|
+
if (this._isTombstonedByPattern(k)) {
|
|
6866
|
+
try {
|
|
6867
|
+
this.disk.delete(k);
|
|
6868
|
+
} catch {
|
|
6869
|
+
}
|
|
6870
|
+
continue;
|
|
6871
|
+
}
|
|
6872
|
+
if (!this.watchdog.isDiskAllowed()) continue;
|
|
6412
6873
|
const diskStart = performance.now();
|
|
6413
6874
|
const diskHit = this.disk.load(k);
|
|
6414
6875
|
const diskElapsed = performance.now() - diskStart;
|
|
@@ -6431,16 +6892,23 @@ var CacheService = class _CacheService {
|
|
|
6431
6892
|
}
|
|
6432
6893
|
}
|
|
6433
6894
|
}
|
|
6434
|
-
if (missKeys.length > 0) {
|
|
6895
|
+
if (missKeys.length > 0 && fetchFn) {
|
|
6435
6896
|
this.counters.fetches++;
|
|
6436
6897
|
const fetched = await fetchFn(missKeys);
|
|
6898
|
+
const isMap = fetched instanceof Map;
|
|
6437
6899
|
const setPromises = [];
|
|
6438
6900
|
for (let j = 0; j < missKeys.length; j++) {
|
|
6439
|
-
const
|
|
6901
|
+
const k = missKeys[j];
|
|
6902
|
+
const v = isMap ? fetched.get(k) : fetched[k];
|
|
6440
6903
|
result[missIndexes[j]] = v;
|
|
6441
|
-
if (v !== void 0) {
|
|
6442
|
-
const resolvedTtl = typeof ttl === "function" ? ttl(
|
|
6443
|
-
setPromises.push(this.set(
|
|
6904
|
+
if (v !== void 0 && v !== null) {
|
|
6905
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6906
|
+
setPromises.push(this.set(k, v, resolvedTtl, priority));
|
|
6907
|
+
} else if (v == null && this.opts.notFoundTtl > 0) {
|
|
6908
|
+
setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
|
|
6909
|
+
} else if (v === null) {
|
|
6910
|
+
const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
|
|
6911
|
+
setPromises.push(this.set(k, null, resolvedTtl, priority));
|
|
6444
6912
|
}
|
|
6445
6913
|
}
|
|
6446
6914
|
if (setPromises.length > 0) {
|
|
@@ -6488,6 +6956,7 @@ var CacheService = class _CacheService {
|
|
|
6488
6956
|
* });
|
|
6489
6957
|
*/
|
|
6490
6958
|
async mset(entries) {
|
|
6959
|
+
this._assertActive("mset");
|
|
6491
6960
|
const span = this._startSpan("tricache.mset");
|
|
6492
6961
|
const keys = Object.keys(entries);
|
|
6493
6962
|
if (this.opts.tracer) {
|
|
@@ -6515,6 +6984,7 @@ var CacheService = class _CacheService {
|
|
|
6515
6984
|
* await cache.mdel(['user:1', 'user:2', 'user:3']);
|
|
6516
6985
|
*/
|
|
6517
6986
|
async mdel(keys) {
|
|
6987
|
+
this._assertActive("mdel");
|
|
6518
6988
|
const span = this._startSpan("tricache.mdel");
|
|
6519
6989
|
if (this.opts.tracer) {
|
|
6520
6990
|
span.setAttribute("cache.batch.size", keys.length);
|
|
@@ -6542,6 +7012,7 @@ var CacheService = class _CacheService {
|
|
|
6542
7012
|
* console.log(`Warmed ${loaded} keys from Redis`);
|
|
6543
7013
|
*/
|
|
6544
7014
|
async warmFromL2(pattern, opts) {
|
|
7015
|
+
this._assertActive("warmFromL2");
|
|
6545
7016
|
if (this._redisDisabled) return 0;
|
|
6546
7017
|
try {
|
|
6547
7018
|
const client = await this.getRedis();
|
|
@@ -6580,20 +7051,109 @@ var CacheService = class _CacheService {
|
|
|
6580
7051
|
}
|
|
6581
7052
|
}
|
|
6582
7053
|
/**
|
|
6583
|
-
*
|
|
6584
|
-
*
|
|
7054
|
+
* Discovers all concrete tag names in the system that match `tag` either via
|
|
7055
|
+
* glob wildcards ('*' or '?') or parent-child hierarchy cascading.
|
|
7056
|
+
* Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
|
|
7057
|
+
*/
|
|
7058
|
+
async _resolveMatchingTags(tag, shouldCascade) {
|
|
7059
|
+
const isPattern = isWildcardTag(tag);
|
|
7060
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7061
|
+
const matched = /* @__PURE__ */ new Set();
|
|
7062
|
+
const tagMatches = (t) => {
|
|
7063
|
+
if (t === tag) return true;
|
|
7064
|
+
if (isPattern && matchesTagPattern(tag, t)) return true;
|
|
7065
|
+
if (shouldCascade && isChildTag(tag, t, delim)) return true;
|
|
7066
|
+
return false;
|
|
7067
|
+
};
|
|
7068
|
+
if (shouldCascade && !isPattern) {
|
|
7069
|
+
matched.add(tag);
|
|
7070
|
+
}
|
|
7071
|
+
const tagPrefix = this.nk("_tag_:");
|
|
7072
|
+
for (const tagKey of this.tagIndex.keys()) {
|
|
7073
|
+
const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
|
|
7074
|
+
if (tagMatches(t)) matched.add(t);
|
|
7075
|
+
}
|
|
7076
|
+
for (const t of this.tagVersions.keys()) {
|
|
7077
|
+
if (tagMatches(t)) matched.add(t);
|
|
7078
|
+
}
|
|
7079
|
+
this.l1.scan((_k, entry) => {
|
|
7080
|
+
if (entry.tagVersions) {
|
|
7081
|
+
for (const t of Object.keys(entry.tagVersions)) {
|
|
7082
|
+
if (tagMatches(t)) matched.add(t);
|
|
7083
|
+
}
|
|
7084
|
+
}
|
|
7085
|
+
}, 0);
|
|
7086
|
+
if (!this._redisDisabled) {
|
|
7087
|
+
try {
|
|
7088
|
+
const client = await this.getRedis();
|
|
7089
|
+
if (this.opts.tagStrategy === "generational") {
|
|
7090
|
+
const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
|
|
7091
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7092
|
+
const pfx = this.nk("tag_ver:");
|
|
7093
|
+
for (const sk of scannedKeys) {
|
|
7094
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7095
|
+
if (tagMatches(t)) matched.add(t);
|
|
7096
|
+
}
|
|
7097
|
+
} else {
|
|
7098
|
+
const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
|
|
7099
|
+
const scannedKeys = await this._scanKeys(client, redisPattern);
|
|
7100
|
+
const pfx = this.nk("_tag_:");
|
|
7101
|
+
for (const sk of scannedKeys) {
|
|
7102
|
+
const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
|
|
7103
|
+
if (tagMatches(t)) matched.add(t);
|
|
7104
|
+
}
|
|
7105
|
+
}
|
|
7106
|
+
} catch (err) {
|
|
7107
|
+
this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
|
|
7108
|
+
}
|
|
7109
|
+
}
|
|
7110
|
+
return matched;
|
|
7111
|
+
}
|
|
7112
|
+
/**
|
|
7113
|
+
* Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
|
|
7114
|
+
* Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
|
|
7115
|
+
*
|
|
7116
|
+
* @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
|
|
7117
|
+
* @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
|
|
6585
7118
|
*
|
|
6586
7119
|
* @example
|
|
6587
7120
|
* await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
|
|
6588
7121
|
* await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
|
|
7122
|
+
*
|
|
7123
|
+
* @example
|
|
7124
|
+
* // Wildcard pattern invalidation
|
|
7125
|
+
* await cache.invalidateTag('org:123:*');
|
|
7126
|
+
*
|
|
7127
|
+
* @example
|
|
7128
|
+
* // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
|
|
7129
|
+
* await cache.invalidateTag('org:123', { cascade: true });
|
|
6589
7130
|
*/
|
|
6590
|
-
async invalidateTag(tag) {
|
|
7131
|
+
async invalidateTag(tag, opts) {
|
|
7132
|
+
this._assertActive("invalidateTag");
|
|
6591
7133
|
const span = this._startSpan("tricache.invalidate_tag");
|
|
6592
7134
|
if (this.opts.tracer) {
|
|
6593
7135
|
span.setAttribute("cache.tag", tag);
|
|
6594
7136
|
span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
|
|
7137
|
+
if (opts?.cascade) span.setAttribute("cache.cascade", true);
|
|
6595
7138
|
}
|
|
6596
7139
|
try {
|
|
7140
|
+
const isPattern = isWildcardTag(tag);
|
|
7141
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7142
|
+
if (isPattern || shouldCascade) {
|
|
7143
|
+
const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
|
|
7144
|
+
const delim = this.opts.tagHierarchyDelimiter;
|
|
7145
|
+
const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
|
|
7146
|
+
if (matchedTags.size > 0) {
|
|
7147
|
+
await this.invalidateTags(Array.from(matchedTags));
|
|
7148
|
+
}
|
|
7149
|
+
const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
|
|
7150
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7151
|
+
await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
7152
|
+
} else {
|
|
7153
|
+
void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
|
|
7154
|
+
}
|
|
7155
|
+
return;
|
|
7156
|
+
}
|
|
6597
7157
|
if (this.opts.tagStrategy === "generational") {
|
|
6598
7158
|
let newVer = 1;
|
|
6599
7159
|
if (!this._redisDisabled) {
|
|
@@ -6609,15 +7169,27 @@ var CacheService = class _CacheService {
|
|
|
6609
7169
|
const current = this.tagVersions.get(tag)?.version ?? 0;
|
|
6610
7170
|
newVer = current + 1;
|
|
6611
7171
|
}
|
|
6612
|
-
this._setLocalTagVersion(tag, newVer,
|
|
6613
|
-
|
|
7172
|
+
this._setLocalTagVersion(tag, newVer, performance.now());
|
|
7173
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7174
|
+
await this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
7175
|
+
} else {
|
|
7176
|
+
void this.publishInvalidation("tag_incr", tag, newVer, false, true);
|
|
7177
|
+
}
|
|
6614
7178
|
return;
|
|
6615
7179
|
}
|
|
6616
7180
|
const tagKey = this.nk(`_tag_:${tag}`);
|
|
6617
7181
|
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
6618
7182
|
for (const k of members) {
|
|
6619
7183
|
this.l1.delete(k);
|
|
6620
|
-
|
|
7184
|
+
this._bumpKeyMutation(k);
|
|
7185
|
+
this._pendingDiskDeletes.add(k);
|
|
7186
|
+
setImmediate(() => {
|
|
7187
|
+
try {
|
|
7188
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
7189
|
+
} finally {
|
|
7190
|
+
this._pendingDiskDeletes.delete(k);
|
|
7191
|
+
}
|
|
7192
|
+
});
|
|
6621
7193
|
}
|
|
6622
7194
|
this.tagIndex.delete(tagKey);
|
|
6623
7195
|
if (!this._redisDisabled) {
|
|
@@ -6644,24 +7216,39 @@ var CacheService = class _CacheService {
|
|
|
6644
7216
|
}
|
|
6645
7217
|
/**
|
|
6646
7218
|
* Invalidate all keys associated with any of the given tags in a single operation.
|
|
6647
|
-
*
|
|
6648
|
-
*
|
|
7219
|
+
* Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
|
|
7220
|
+
* Combines multiple tag invalidations into Redis pipeline round-trips.
|
|
6649
7221
|
*
|
|
6650
|
-
*
|
|
6651
|
-
*
|
|
7222
|
+
* @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
|
|
7223
|
+
* @param opts Optional invalidation options, including `{ cascade: true }`.
|
|
6652
7224
|
*
|
|
6653
7225
|
* @example
|
|
6654
|
-
*
|
|
6655
|
-
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
|
|
7226
|
+
* await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
|
|
6656
7227
|
*/
|
|
6657
|
-
async invalidateTags(tags) {
|
|
7228
|
+
async invalidateTags(tags, opts) {
|
|
7229
|
+
this._assertActive("invalidateTags");
|
|
6658
7230
|
if (tags.length === 0) return;
|
|
7231
|
+
const hasWildcards = tags.some((t) => isWildcardTag(t));
|
|
7232
|
+
const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
|
|
7233
|
+
if (hasWildcards || shouldCascade) {
|
|
7234
|
+
const allResolvedTags = /* @__PURE__ */ new Set();
|
|
7235
|
+
for (const t of tags) {
|
|
7236
|
+
if (isWildcardTag(t) || shouldCascade) {
|
|
7237
|
+
const resolved = await this._resolveMatchingTags(t, shouldCascade);
|
|
7238
|
+
for (const rt of resolved) allResolvedTags.add(rt);
|
|
7239
|
+
} else {
|
|
7240
|
+
allResolvedTags.add(t);
|
|
7241
|
+
}
|
|
7242
|
+
}
|
|
7243
|
+
if (allResolvedTags.size === 0) return;
|
|
7244
|
+
tags = Array.from(allResolvedTags);
|
|
7245
|
+
}
|
|
6659
7246
|
if (tags.length === 1) {
|
|
6660
|
-
await this.invalidateTag(tags[0]);
|
|
7247
|
+
await this.invalidateTag(tags[0], opts);
|
|
6661
7248
|
return;
|
|
6662
7249
|
}
|
|
6663
7250
|
if (this.opts.tagStrategy === "generational") {
|
|
6664
|
-
const now =
|
|
7251
|
+
const now = performance.now();
|
|
6665
7252
|
if (!this._redisDisabled) {
|
|
6666
7253
|
try {
|
|
6667
7254
|
const client = await this.getRedis();
|
|
@@ -6672,7 +7259,11 @@ var CacheService = class _CacheService {
|
|
|
6672
7259
|
const [err, newVer] = results[i] ?? [null, null];
|
|
6673
7260
|
const ver = !err && typeof newVer === "number" ? newVer : (this.tagVersions.get(tags[i])?.version ?? 0) + 1;
|
|
6674
7261
|
this._setLocalTagVersion(tags[i], ver, now);
|
|
6675
|
-
|
|
7262
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7263
|
+
await this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
7264
|
+
} else {
|
|
7265
|
+
void this.publishInvalidation("tag_incr", tags[i], ver, false, true);
|
|
7266
|
+
}
|
|
6676
7267
|
}
|
|
6677
7268
|
return;
|
|
6678
7269
|
} catch (err) {
|
|
@@ -6682,7 +7273,11 @@ var CacheService = class _CacheService {
|
|
|
6682
7273
|
for (const tag of tags) {
|
|
6683
7274
|
const ver = (this.tagVersions.get(tag)?.version ?? 0) + 1;
|
|
6684
7275
|
this._setLocalTagVersion(tag, ver, now);
|
|
6685
|
-
|
|
7276
|
+
if (this.opts.awaitInvalidationBackplane) {
|
|
7277
|
+
await this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
7278
|
+
} else {
|
|
7279
|
+
void this.publishInvalidation("tag_incr", tag, ver, false, true);
|
|
7280
|
+
}
|
|
6686
7281
|
}
|
|
6687
7282
|
return;
|
|
6688
7283
|
}
|
|
@@ -6697,7 +7292,15 @@ var CacheService = class _CacheService {
|
|
|
6697
7292
|
}
|
|
6698
7293
|
for (const k of allMembers) {
|
|
6699
7294
|
this.l1.delete(k);
|
|
6700
|
-
this.
|
|
7295
|
+
this._bumpKeyMutation(k);
|
|
7296
|
+
this._pendingDiskDeletes.add(k);
|
|
7297
|
+
setImmediate(() => {
|
|
7298
|
+
try {
|
|
7299
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
7300
|
+
} finally {
|
|
7301
|
+
this._pendingDiskDeletes.delete(k);
|
|
7302
|
+
}
|
|
7303
|
+
});
|
|
6701
7304
|
}
|
|
6702
7305
|
if (!this._redisDisabled) {
|
|
6703
7306
|
try {
|
|
@@ -6734,6 +7337,7 @@ var CacheService = class _CacheService {
|
|
|
6734
7337
|
* `l2` is `null` when Redis is disabled.
|
|
6735
7338
|
*/
|
|
6736
7339
|
async ping() {
|
|
7340
|
+
this._assertActive("ping");
|
|
6737
7341
|
const t0 = Date.now();
|
|
6738
7342
|
this.l1.has("__ping__");
|
|
6739
7343
|
const l1 = Date.now() - t0;
|
|
@@ -6813,6 +7417,7 @@ var CacheService = class _CacheService {
|
|
|
6813
7417
|
* Returns the number of keys written.
|
|
6814
7418
|
*/
|
|
6815
7419
|
async drainToL2() {
|
|
7420
|
+
this._assertActive("drainToL2");
|
|
6816
7421
|
if (this._redisDisabled) return 0;
|
|
6817
7422
|
try {
|
|
6818
7423
|
const client = await this.getRedis();
|
|
@@ -6856,6 +7461,7 @@ var CacheService = class _CacheService {
|
|
|
6856
7461
|
* if (!claimed) return res.status(409).json({ error: 'duplicate request' });
|
|
6857
7462
|
*/
|
|
6858
7463
|
async setIfAbsent(cacheKey, value, ttlSeconds = 300, priority) {
|
|
7464
|
+
this._assertActive("setIfAbsent");
|
|
6859
7465
|
const k = this.nk(cacheKey);
|
|
6860
7466
|
if (this.l1.has(k)) return false;
|
|
6861
7467
|
if (!this._redisDisabled) {
|
|
@@ -6874,6 +7480,8 @@ var CacheService = class _CacheService {
|
|
|
6874
7480
|
}
|
|
6875
7481
|
const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
|
|
6876
7482
|
const p = priority ?? inferPriority(cacheKey);
|
|
7483
|
+
this._bumpKeyMutation(k);
|
|
7484
|
+
this._pendingDiskDeletes.delete(k);
|
|
6877
7485
|
this.l1.set(k, value, ttlMs, p);
|
|
6878
7486
|
this.counters.sets++;
|
|
6879
7487
|
return true;
|
|
@@ -6892,6 +7500,7 @@ var CacheService = class _CacheService {
|
|
|
6892
7500
|
* @param options TTL, acquire timeout, and retry polling intervals.
|
|
6893
7501
|
*/
|
|
6894
7502
|
async lock(resourceKey, fn, options) {
|
|
7503
|
+
this._assertActive("lock");
|
|
6895
7504
|
const ttlSeconds = Math.max(1, options?.ttl ?? 30);
|
|
6896
7505
|
const acquireTimeout = Math.max(0, options?.acquireTimeout ?? 5e3);
|
|
6897
7506
|
const retryInterval = Math.max(10, options?.retryInterval ?? 100);
|
|
@@ -6918,6 +7527,10 @@ var CacheService = class _CacheService {
|
|
|
6918
7527
|
}
|
|
6919
7528
|
} catch (err) {
|
|
6920
7529
|
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
7530
|
+
const failClosed = options?.failClosedOnRedisError ?? this.opts.lockFailClosed;
|
|
7531
|
+
if (failClosed) {
|
|
7532
|
+
throw new Error(`Distributed lock acquisition failed for resource "${resourceKey}" due to Redis error: ${err.message}`);
|
|
7533
|
+
}
|
|
6921
7534
|
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
6922
7535
|
resourceKey,
|
|
6923
7536
|
error: err.message
|
|
@@ -7263,6 +7876,7 @@ var CacheService = class _CacheService {
|
|
|
7263
7876
|
* the previous key for seamless fallback decryption of existing cache entries.
|
|
7264
7877
|
*/
|
|
7265
7878
|
async rotateEncryptionKey(newKeyBase64, newMode) {
|
|
7879
|
+
this._assertActive("rotateEncryptionKey");
|
|
7266
7880
|
this.enc.rotateKey(newKeyBase64, newMode);
|
|
7267
7881
|
if (this._workerPool) {
|
|
7268
7882
|
await this._workerPool.drainAndReinit(this.enc.toWorkerInit());
|
|
@@ -7272,6 +7886,8 @@ var CacheService = class _CacheService {
|
|
|
7272
7886
|
/** Close Redis connections and stop all background timers. */
|
|
7273
7887
|
async destroy() {
|
|
7274
7888
|
this._destroyed = true;
|
|
7889
|
+
this._pendingDiskDeletes.clear();
|
|
7890
|
+
this._keyMutationEpochs.clear();
|
|
7275
7891
|
const g = globalThis;
|
|
7276
7892
|
const key = _CacheService.globalKey(this.opts);
|
|
7277
7893
|
if (g[key] === this) {
|
|
@@ -7338,6 +7954,7 @@ var CacheService = class _CacheService {
|
|
|
7338
7954
|
};
|
|
7339
7955
|
|
|
7340
7956
|
// src/cli.ts
|
|
7957
|
+
var import_meta2 = {};
|
|
7341
7958
|
async function runCli(args = process.argv.slice(2)) {
|
|
7342
7959
|
const options = {
|
|
7343
7960
|
redis: { type: "string", short: "r" },
|
|
@@ -7374,7 +7991,13 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
7374
7991
|
return;
|
|
7375
7992
|
}
|
|
7376
7993
|
if (values.version || command === "version") {
|
|
7377
|
-
|
|
7994
|
+
let version = "1.0.0";
|
|
7995
|
+
try {
|
|
7996
|
+
const pkg = JSON.parse((0, import_node_fs3.readFileSync)(new URL("../package.json", import_meta2.url), "utf8"));
|
|
7997
|
+
if (pkg?.version) version = pkg.version;
|
|
7998
|
+
} catch {
|
|
7999
|
+
}
|
|
8000
|
+
console.log(`tricache v${version}`);
|
|
7378
8001
|
return;
|
|
7379
8002
|
}
|
|
7380
8003
|
if (command === "top") {
|
|
@@ -7386,10 +8009,18 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
7386
8009
|
const active = await findActiveSockets();
|
|
7387
8010
|
if (active.length > 0) {
|
|
7388
8011
|
targetSocket = active[0];
|
|
7389
|
-
} else {
|
|
7390
|
-
targetSocket = resolveIpcSocketPath(process.pid);
|
|
7391
8012
|
}
|
|
7392
8013
|
}
|
|
8014
|
+
if (!targetSocket) {
|
|
8015
|
+
console.error("No active TriCache instances found to monitor.\n");
|
|
8016
|
+
console.error("To use `tricache top`:");
|
|
8017
|
+
console.error(" 1. Ensure your running application enables IPC telemetry:");
|
|
8018
|
+
console.error(" const cache = new CacheService({ namespace: 'my-app', enableIpc: true, ... });\n");
|
|
8019
|
+
console.error(" 2. If the application is already running, specify its PID or socket:");
|
|
8020
|
+
console.error(" npx tricache top --pid <pid>");
|
|
8021
|
+
console.error(" npx tricache top --socket <path>\n");
|
|
8022
|
+
process.exit(1);
|
|
8023
|
+
}
|
|
7393
8024
|
const client = new IpcTelemetryClient(targetSocket);
|
|
7394
8025
|
const intervalMs = typeof values.interval === "string" ? Math.max(200, parseInt(values.interval, 10)) : 1e3;
|
|
7395
8026
|
const isOnce = Boolean(values.once || !process.stdout.isTTY);
|
|
@@ -7450,6 +8081,9 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
7450
8081
|
} catch (err) {
|
|
7451
8082
|
process.stdout.write(`\x1B[HConnecting to ${targetSocket}...
|
|
7452
8083
|
Error: ${err.message}
|
|
8084
|
+
|
|
8085
|
+
Waiting for TriCache IPC server. Ensure the target process is running with enableIpc: true.
|
|
8086
|
+
Press "q" or Ctrl+C to exit
|
|
7453
8087
|
`);
|
|
7454
8088
|
}
|
|
7455
8089
|
};
|