tricache 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +494 -164
- package/dist/index.d.cts +125 -0
- package/dist/index.d.ts +1552 -18
- package/dist/index.js +3524 -25
- package/dist/serialize-worker.cjs +366 -0
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.d.ts +2 -0
- package/dist/serialize-worker.js +35 -0
- package/package.json +5 -5
- package/src/cache-service.ts +310 -93
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +42 -1
- package/src/types.ts +99 -1
- package/src/worker-pool.ts +190 -0
- package/dist/cache-service.d.ts +0 -419
- package/dist/cache-service.d.ts.map +0 -1
- package/dist/cache-service.js +0 -1788
- package/dist/cache-service.js.map +0 -1
- package/dist/disk-tier.d.ts +0 -150
- package/dist/disk-tier.d.ts.map +0 -1
- package/dist/disk-tier.js +0 -808
- package/dist/disk-tier.js.map +0 -1
- package/dist/encryption.d.ts +0 -90
- package/dist/encryption.d.ts.map +0 -1
- package/dist/encryption.js +0 -393
- package/dist/encryption.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/smart-memory-cache.d.ts +0 -208
- package/dist/smart-memory-cache.d.ts.map +0 -1
- package/dist/smart-memory-cache.js +0 -933
- package/dist/smart-memory-cache.js.map +0 -1
- package/dist/types.d.ts +0 -537
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -20
- package/dist/types.js.map +0 -1
- package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
- package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
- package/dist/wasm/bloom-filter-wasm.js +0 -83
- package/dist/wasm/bloom-filter-wasm.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -45,8 +45,128 @@ var import_ioredis = require("ioredis");
|
|
|
45
45
|
var import_msgpackr3 = require("msgpackr");
|
|
46
46
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
47
47
|
var import_os = __toESM(require("os"), 1);
|
|
48
|
-
|
|
49
|
-
|
|
48
|
+
|
|
49
|
+
// src/worker-pool.ts
|
|
50
|
+
var import_worker_threads = require("worker_threads");
|
|
51
|
+
var import_url = require("url");
|
|
52
|
+
var import_path = require("path");
|
|
53
|
+
var import_fs = require("fs");
|
|
54
|
+
var import_meta = {};
|
|
55
|
+
var _workerFile;
|
|
56
|
+
var _workerExecArgv = [];
|
|
57
|
+
try {
|
|
58
|
+
const dir = (0, import_path.dirname)((0, import_url.fileURLToPath)(import_meta.url));
|
|
59
|
+
const jsPath = (0, import_path.join)(dir, "serialize-worker.js");
|
|
60
|
+
const tsPath = (0, import_path.join)(dir, "serialize-worker.ts");
|
|
61
|
+
if ((0, import_fs.existsSync)(jsPath)) {
|
|
62
|
+
_workerFile = jsPath;
|
|
63
|
+
} else if ((0, import_fs.existsSync)(tsPath)) {
|
|
64
|
+
_workerFile = tsPath;
|
|
65
|
+
_workerExecArgv = ["--import", "tsx"];
|
|
66
|
+
} else {
|
|
67
|
+
_workerFile = jsPath;
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
_workerFile = (0, import_path.join)(__dirname, "serialize-worker.js");
|
|
71
|
+
}
|
|
72
|
+
var WorkerPool = class {
|
|
73
|
+
workers = [];
|
|
74
|
+
pending = [];
|
|
75
|
+
_nextId = 0;
|
|
76
|
+
_robin = 0;
|
|
77
|
+
_available = false;
|
|
78
|
+
constructor(opts) {
|
|
79
|
+
const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
|
|
80
|
+
const workerData = {
|
|
81
|
+
keyBase64: opts.keyBase64,
|
|
82
|
+
mode: opts.mode,
|
|
83
|
+
prevKeyBase64: opts.prevKeyBase64 ?? "",
|
|
84
|
+
prevMode: opts.prevMode
|
|
85
|
+
};
|
|
86
|
+
try {
|
|
87
|
+
for (let i = 0; i < size; i++) {
|
|
88
|
+
const worker = new import_worker_threads.Worker(_workerFile, {
|
|
89
|
+
workerData,
|
|
90
|
+
execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : void 0
|
|
91
|
+
});
|
|
92
|
+
const pending = /* @__PURE__ */ new Map();
|
|
93
|
+
worker.on("message", (msg) => {
|
|
94
|
+
const entry = pending.get(msg.id);
|
|
95
|
+
if (!entry) return;
|
|
96
|
+
pending.delete(msg.id);
|
|
97
|
+
if (pending.size === 0) worker.unref();
|
|
98
|
+
if (msg.error !== void 0) {
|
|
99
|
+
entry.reject(new Error(msg.error));
|
|
100
|
+
} else {
|
|
101
|
+
entry.resolve(msg.result);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
worker.on("error", (err) => {
|
|
105
|
+
for (const [, entry] of pending) entry.reject(err);
|
|
106
|
+
pending.clear();
|
|
107
|
+
worker.unref();
|
|
108
|
+
});
|
|
109
|
+
worker.unref();
|
|
110
|
+
this.workers.push(worker);
|
|
111
|
+
this.pending.push(pending);
|
|
112
|
+
}
|
|
113
|
+
this._available = true;
|
|
114
|
+
} catch {
|
|
115
|
+
this._destroy();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
get isAvailable() {
|
|
119
|
+
return this._available;
|
|
120
|
+
}
|
|
121
|
+
/** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
|
|
122
|
+
encrypt(payload) {
|
|
123
|
+
return this._dispatch("encrypt", payload);
|
|
124
|
+
}
|
|
125
|
+
/** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
|
|
126
|
+
decrypt(payload) {
|
|
127
|
+
return this._dispatch("decrypt", payload);
|
|
128
|
+
}
|
|
129
|
+
_dispatch(type, payload) {
|
|
130
|
+
const id = this._nextId++;
|
|
131
|
+
const idx = this._robin;
|
|
132
|
+
const worker = this.workers[idx];
|
|
133
|
+
const pending = this.pending[idx];
|
|
134
|
+
this._robin = (this._robin + 1) % this.workers.length;
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
pending.set(id, { resolve, reject });
|
|
137
|
+
worker.ref();
|
|
138
|
+
worker.postMessage({ id, type, payload });
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/** Terminate all worker threads. In-flight promises are rejected. */
|
|
142
|
+
async destroy() {
|
|
143
|
+
this._available = false;
|
|
144
|
+
this._destroy();
|
|
145
|
+
}
|
|
146
|
+
_destroy() {
|
|
147
|
+
for (let i = 0; i < this.workers.length; i++) {
|
|
148
|
+
for (const [, entry] of this.pending[i] ?? []) {
|
|
149
|
+
entry.reject(new Error("WorkerPool destroyed"));
|
|
150
|
+
}
|
|
151
|
+
this.pending[i]?.clear();
|
|
152
|
+
this.workers[i]?.terminate().catch(() => {
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
function availableCpus() {
|
|
158
|
+
try {
|
|
159
|
+
const os2 = require("os");
|
|
160
|
+
return os2.availableParallelism?.() ?? os2.cpus().length;
|
|
161
|
+
} catch {
|
|
162
|
+
return 2;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/cache-service.ts
|
|
167
|
+
var import_node_v8 = __toESM(require("v8"), 1);
|
|
168
|
+
var import_fs3 = __toESM(require("fs"), 1);
|
|
169
|
+
var import_path3 = __toESM(require("path"), 1);
|
|
50
170
|
|
|
51
171
|
// src/types.ts
|
|
52
172
|
var consoleLogger = {
|
|
@@ -1038,7 +1158,39 @@ var SmartMemoryCache = class {
|
|
|
1038
1158
|
}
|
|
1039
1159
|
return cleaned;
|
|
1040
1160
|
}
|
|
1041
|
-
|
|
1161
|
+
/**
|
|
1162
|
+
* Evict all non-CRITICAL L1 entries that were written before `cutoffMs`.
|
|
1163
|
+
*
|
|
1164
|
+
* Called by the backplane staleness fence when the Pub/Sub subscriber
|
|
1165
|
+
* reconnects after a disconnect gap that exceeded `backplaneMaxStalenessMs`.
|
|
1166
|
+
* Entries written before the disconnect started may have been invalidated by
|
|
1167
|
+
* peers while the backplane was down; evicting them forces a controlled
|
|
1168
|
+
* cold-start re-fetch from L2 rather than serving silently stale data.
|
|
1169
|
+
*
|
|
1170
|
+
* Write-time is approximated as `entry.expiresAt - entry.ttlMs`.
|
|
1171
|
+
* Entries with no stored `ttlMs` (e.g. legacy snapshot imports) are evicted
|
|
1172
|
+
* conservatively.
|
|
1173
|
+
*
|
|
1174
|
+
* @param cutoffMs - Unix timestamp in milliseconds; entries written before
|
|
1175
|
+
* this time are evicted.
|
|
1176
|
+
* @returns Number of entries evicted.
|
|
1177
|
+
*/
|
|
1178
|
+
evictSetBefore(cutoffMs) {
|
|
1179
|
+
let evicted = 0;
|
|
1180
|
+
for (const [key, entry] of this.cache) {
|
|
1181
|
+
if (entry.priority === 4 && entry.expiresAt > Date.now()) continue;
|
|
1182
|
+
const setAt = entry.ttlMs != null ? entry.expiresAt - entry.ttlMs : 0;
|
|
1183
|
+
if (setAt < cutoffMs) {
|
|
1184
|
+
this._delete(key, "manual");
|
|
1185
|
+
evicted++;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
if (evicted > 0) {
|
|
1189
|
+
this.bloom.rebuild(this.cache.keys());
|
|
1190
|
+
this._bloomDirtyCount = 0;
|
|
1191
|
+
}
|
|
1192
|
+
return evicted;
|
|
1193
|
+
}
|
|
1042
1194
|
exportEntries(forbiddenPrefixes) {
|
|
1043
1195
|
const now = Date.now();
|
|
1044
1196
|
const out = [];
|
|
@@ -1232,15 +1384,15 @@ var SmartMemoryCache = class {
|
|
|
1232
1384
|
};
|
|
1233
1385
|
|
|
1234
1386
|
// src/disk-tier.ts
|
|
1235
|
-
var
|
|
1236
|
-
var
|
|
1387
|
+
var import_fs2 = __toESM(require("fs"), 1);
|
|
1388
|
+
var import_path2 = __toESM(require("path"), 1);
|
|
1237
1389
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1238
1390
|
var import_module = require("module");
|
|
1239
1391
|
var import_msgpackr2 = require("msgpackr");
|
|
1240
|
-
var
|
|
1392
|
+
var import_meta2 = {};
|
|
1241
1393
|
var _SqliteDB = null;
|
|
1242
1394
|
try {
|
|
1243
|
-
const _req = (0, import_module.createRequire)(
|
|
1395
|
+
const _req = (0, import_module.createRequire)(import_meta2.url);
|
|
1244
1396
|
_SqliteDB = _req("node:sqlite").DatabaseSync;
|
|
1245
1397
|
} catch {
|
|
1246
1398
|
}
|
|
@@ -1281,7 +1433,7 @@ var DiskTier = class {
|
|
|
1281
1433
|
ensureDir() {
|
|
1282
1434
|
if (this.dirReady) return;
|
|
1283
1435
|
try {
|
|
1284
|
-
|
|
1436
|
+
import_fs2.default.mkdirSync(this.opts.dir, { recursive: true, mode: 448 });
|
|
1285
1437
|
this.dirReady = true;
|
|
1286
1438
|
this._initSqlite();
|
|
1287
1439
|
} catch (err) {
|
|
@@ -1303,7 +1455,7 @@ var DiskTier = class {
|
|
|
1303
1455
|
_initSqlite() {
|
|
1304
1456
|
if (!_SqliteDB) return;
|
|
1305
1457
|
try {
|
|
1306
|
-
const dbPath =
|
|
1458
|
+
const dbPath = import_path2.default.join(this.opts.dir, "meta.db");
|
|
1307
1459
|
this._db = new _SqliteDB(dbPath);
|
|
1308
1460
|
this._db.exec(`
|
|
1309
1461
|
PRAGMA journal_mode = WAL;
|
|
@@ -1354,7 +1506,7 @@ var DiskTier = class {
|
|
|
1354
1506
|
this.fileCount = files.length;
|
|
1355
1507
|
for (const filePath of files) {
|
|
1356
1508
|
try {
|
|
1357
|
-
total +=
|
|
1509
|
+
total += import_fs2.default.statSync(filePath).size;
|
|
1358
1510
|
} catch {
|
|
1359
1511
|
}
|
|
1360
1512
|
}
|
|
@@ -1383,7 +1535,7 @@ var DiskTier = class {
|
|
|
1383
1535
|
* 12 hex digits ≈ 6 bytes ≈ year 10889 max. Padded so length is always 77 chars.
|
|
1384
1536
|
*/
|
|
1385
1537
|
hashToWritePath(hash, expiresAt) {
|
|
1386
|
-
return
|
|
1538
|
+
return import_path2.default.join(this.opts.dir, hash.slice(0, 2), `${hash}_${expiresAt.toString(16).padStart(12, "0")}`);
|
|
1387
1539
|
}
|
|
1388
1540
|
/**
|
|
1389
1541
|
* Find the on-disk file for a key hash, handling all filename generations:
|
|
@@ -1392,10 +1544,10 @@ var DiskTier = class {
|
|
|
1392
1544
|
* Returns null when the bucket dir does not exist or the key is absent.
|
|
1393
1545
|
*/
|
|
1394
1546
|
findFilePath(hash) {
|
|
1395
|
-
const bucketPath =
|
|
1547
|
+
const bucketPath = import_path2.default.join(this.opts.dir, hash.slice(0, 2));
|
|
1396
1548
|
let files;
|
|
1397
1549
|
try {
|
|
1398
|
-
files =
|
|
1550
|
+
files = import_fs2.default.readdirSync(bucketPath);
|
|
1399
1551
|
} catch {
|
|
1400
1552
|
return null;
|
|
1401
1553
|
}
|
|
@@ -1404,7 +1556,7 @@ var DiskTier = class {
|
|
|
1404
1556
|
if ((f === hash || f.startsWith(hash + "_")) && (!match || f > match)) match = f;
|
|
1405
1557
|
}
|
|
1406
1558
|
if (!match) return null;
|
|
1407
|
-
return
|
|
1559
|
+
return import_path2.default.join(bucketPath, match);
|
|
1408
1560
|
}
|
|
1409
1561
|
/**
|
|
1410
1562
|
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
@@ -1415,16 +1567,16 @@ var DiskTier = class {
|
|
|
1415
1567
|
const results = [];
|
|
1416
1568
|
let topEntries;
|
|
1417
1569
|
try {
|
|
1418
|
-
topEntries =
|
|
1570
|
+
topEntries = import_fs2.default.readdirSync(this.opts.dir);
|
|
1419
1571
|
} catch {
|
|
1420
1572
|
return results;
|
|
1421
1573
|
}
|
|
1422
1574
|
for (const top of topEntries) {
|
|
1423
|
-
const topPath =
|
|
1575
|
+
const topPath = import_path2.default.join(this.opts.dir, top);
|
|
1424
1576
|
try {
|
|
1425
|
-
if (!
|
|
1426
|
-
for (const file of
|
|
1427
|
-
results.push(
|
|
1577
|
+
if (!import_fs2.default.statSync(topPath).isDirectory()) continue;
|
|
1578
|
+
for (const file of import_fs2.default.readdirSync(topPath)) {
|
|
1579
|
+
results.push(import_path2.default.join(topPath, file));
|
|
1428
1580
|
}
|
|
1429
1581
|
} catch {
|
|
1430
1582
|
}
|
|
@@ -1532,8 +1684,8 @@ var DiskTier = class {
|
|
|
1532
1684
|
this.diskUsageBytes += final.length;
|
|
1533
1685
|
this.fileCount++;
|
|
1534
1686
|
try {
|
|
1535
|
-
await
|
|
1536
|
-
await
|
|
1687
|
+
await import_fs2.default.promises.mkdir(import_path2.default.dirname(filePath), { recursive: true });
|
|
1688
|
+
await import_fs2.default.promises.writeFile(filePath, final, { mode: 384 });
|
|
1537
1689
|
if (this._db) {
|
|
1538
1690
|
this._stmtInsert.run(hash, filePath, entry.expiresAt, final.length);
|
|
1539
1691
|
}
|
|
@@ -1561,8 +1713,8 @@ var DiskTier = class {
|
|
|
1561
1713
|
if (row.expires_at <= Date.now()) {
|
|
1562
1714
|
this._stmtDelete.run(hash);
|
|
1563
1715
|
try {
|
|
1564
|
-
const sz =
|
|
1565
|
-
|
|
1716
|
+
const sz = import_fs2.default.statSync(row.file_path).size;
|
|
1717
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
1566
1718
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1567
1719
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1568
1720
|
} catch {
|
|
@@ -1576,13 +1728,13 @@ var DiskTier = class {
|
|
|
1576
1728
|
}
|
|
1577
1729
|
try {
|
|
1578
1730
|
if (!this._db) {
|
|
1579
|
-
const filename =
|
|
1731
|
+
const filename = import_path2.default.basename(filePath);
|
|
1580
1732
|
if (filename.length === 77 && filename[64] === "_") {
|
|
1581
1733
|
const expiresAt = parseInt(filename.slice(65), 16);
|
|
1582
1734
|
if (expiresAt <= Date.now()) {
|
|
1583
1735
|
try {
|
|
1584
|
-
const sz =
|
|
1585
|
-
|
|
1736
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
1737
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1586
1738
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1587
1739
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1588
1740
|
} catch {
|
|
@@ -1591,16 +1743,16 @@ var DiskTier = class {
|
|
|
1591
1743
|
}
|
|
1592
1744
|
}
|
|
1593
1745
|
}
|
|
1594
|
-
const stat =
|
|
1746
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1595
1747
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
1596
|
-
|
|
1748
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1597
1749
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1598
1750
|
if (this._db) this._stmtDelete.run(hash);
|
|
1599
1751
|
return null;
|
|
1600
1752
|
}
|
|
1601
|
-
const raw =
|
|
1753
|
+
const raw = import_fs2.default.readFileSync(filePath);
|
|
1602
1754
|
try {
|
|
1603
|
-
|
|
1755
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1604
1756
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1605
1757
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1606
1758
|
} catch {
|
|
@@ -1651,8 +1803,8 @@ var DiskTier = class {
|
|
|
1651
1803
|
}
|
|
1652
1804
|
if (!filePath) return;
|
|
1653
1805
|
try {
|
|
1654
|
-
const stat =
|
|
1655
|
-
|
|
1806
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1807
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1656
1808
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1657
1809
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1658
1810
|
} catch {
|
|
@@ -1667,7 +1819,7 @@ var DiskTier = class {
|
|
|
1667
1819
|
const expired = this._stmtExpire.all(now2);
|
|
1668
1820
|
for (const row of expired) {
|
|
1669
1821
|
try {
|
|
1670
|
-
|
|
1822
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
1671
1823
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1672
1824
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1673
1825
|
} catch {
|
|
@@ -1680,13 +1832,13 @@ var DiskTier = class {
|
|
|
1680
1832
|
let purged = 0;
|
|
1681
1833
|
const headerBuf = Buffer.allocUnsafe(V2_HEADER_LEN);
|
|
1682
1834
|
for (const filePath of this.walkCacheFiles()) {
|
|
1683
|
-
const filename =
|
|
1835
|
+
const filename = import_path2.default.basename(filePath);
|
|
1684
1836
|
if (filename.length === 77 && filename[64] === "_") {
|
|
1685
1837
|
const expiresAt = parseInt(filename.slice(65), 16);
|
|
1686
1838
|
if (expiresAt <= now) {
|
|
1687
1839
|
try {
|
|
1688
|
-
const sz =
|
|
1689
|
-
|
|
1840
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
1841
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1690
1842
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1691
1843
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1692
1844
|
purged++;
|
|
@@ -1697,16 +1849,16 @@ var DiskTier = class {
|
|
|
1697
1849
|
}
|
|
1698
1850
|
let fd = -1;
|
|
1699
1851
|
try {
|
|
1700
|
-
fd =
|
|
1701
|
-
const bytesRead =
|
|
1702
|
-
|
|
1852
|
+
fd = import_fs2.default.openSync(filePath, "r");
|
|
1853
|
+
const bytesRead = import_fs2.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
1854
|
+
import_fs2.default.closeSync(fd);
|
|
1703
1855
|
fd = -1;
|
|
1704
1856
|
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1705
1857
|
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
1706
1858
|
if (expiresAt <= now) {
|
|
1707
1859
|
try {
|
|
1708
|
-
const sz =
|
|
1709
|
-
|
|
1860
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
1861
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1710
1862
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1711
1863
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1712
1864
|
purged++;
|
|
@@ -1715,27 +1867,27 @@ var DiskTier = class {
|
|
|
1715
1867
|
}
|
|
1716
1868
|
continue;
|
|
1717
1869
|
}
|
|
1718
|
-
const stat =
|
|
1870
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1719
1871
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
1720
|
-
|
|
1872
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1721
1873
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1722
1874
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1723
1875
|
purged++;
|
|
1724
1876
|
continue;
|
|
1725
1877
|
}
|
|
1726
|
-
const raw =
|
|
1878
|
+
const raw = import_fs2.default.readFileSync(filePath);
|
|
1727
1879
|
let dec;
|
|
1728
1880
|
try {
|
|
1729
1881
|
dec = this.decrypt(raw);
|
|
1730
1882
|
} catch {
|
|
1731
|
-
|
|
1883
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1732
1884
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1733
1885
|
purged++;
|
|
1734
1886
|
continue;
|
|
1735
1887
|
}
|
|
1736
1888
|
const payload = (0, import_msgpackr2.unpack)(dec);
|
|
1737
1889
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1738
|
-
|
|
1890
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1739
1891
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1740
1892
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1741
1893
|
purged++;
|
|
@@ -1743,7 +1895,7 @@ var DiskTier = class {
|
|
|
1743
1895
|
} catch {
|
|
1744
1896
|
} finally {
|
|
1745
1897
|
if (fd >= 0) try {
|
|
1746
|
-
|
|
1898
|
+
import_fs2.default.closeSync(fd);
|
|
1747
1899
|
} catch {
|
|
1748
1900
|
}
|
|
1749
1901
|
}
|
|
@@ -1774,7 +1926,7 @@ var DiskTier = class {
|
|
|
1774
1926
|
const expired = this._stmtExpire.all(now2);
|
|
1775
1927
|
for (const row of expired) {
|
|
1776
1928
|
try {
|
|
1777
|
-
|
|
1929
|
+
import_fs2.default.unlinkSync(row.file_path);
|
|
1778
1930
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
1779
1931
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1780
1932
|
} catch {
|
|
@@ -1782,10 +1934,10 @@ var DiskTier = class {
|
|
|
1782
1934
|
}
|
|
1783
1935
|
if (expired.length > 0) this._stmtDelExp.run(now2);
|
|
1784
1936
|
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
1785
|
-
const orphanBucketP =
|
|
1937
|
+
const orphanBucketP = import_path2.default.join(this.opts.dir, orphanBucket.toString(16).padStart(2, "0"));
|
|
1786
1938
|
let orphanFiles;
|
|
1787
1939
|
try {
|
|
1788
|
-
orphanFiles =
|
|
1940
|
+
orphanFiles = import_fs2.default.readdirSync(orphanBucketP);
|
|
1789
1941
|
} catch {
|
|
1790
1942
|
return expired.length;
|
|
1791
1943
|
}
|
|
@@ -1793,10 +1945,10 @@ var DiskTier = class {
|
|
|
1793
1945
|
if (file.length === 77 && file[64] === "_") {
|
|
1794
1946
|
const expiresAt = parseInt(file.slice(65), 16);
|
|
1795
1947
|
if (expiresAt <= now2) {
|
|
1796
|
-
const fp =
|
|
1948
|
+
const fp = import_path2.default.join(orphanBucketP, file);
|
|
1797
1949
|
try {
|
|
1798
|
-
const sz =
|
|
1799
|
-
|
|
1950
|
+
const sz = import_fs2.default.statSync(fp).size;
|
|
1951
|
+
import_fs2.default.unlinkSync(fp);
|
|
1800
1952
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1801
1953
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1802
1954
|
} catch {
|
|
@@ -1808,10 +1960,10 @@ var DiskTier = class {
|
|
|
1808
1960
|
}
|
|
1809
1961
|
const bucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
1810
1962
|
const bucketHex = bucket.toString(16).padStart(2, "0");
|
|
1811
|
-
const bucketPath =
|
|
1963
|
+
const bucketPath = import_path2.default.join(this.opts.dir, bucketHex);
|
|
1812
1964
|
let files;
|
|
1813
1965
|
try {
|
|
1814
|
-
files =
|
|
1966
|
+
files = import_fs2.default.readdirSync(bucketPath);
|
|
1815
1967
|
} catch {
|
|
1816
1968
|
return 0;
|
|
1817
1969
|
}
|
|
@@ -1822,10 +1974,10 @@ var DiskTier = class {
|
|
|
1822
1974
|
if (file.length === 77 && file[64] === "_") {
|
|
1823
1975
|
const expiresAt = parseInt(file.slice(65), 16);
|
|
1824
1976
|
if (expiresAt <= now) {
|
|
1825
|
-
const filePath2 =
|
|
1977
|
+
const filePath2 = import_path2.default.join(bucketPath, file);
|
|
1826
1978
|
try {
|
|
1827
|
-
const sz =
|
|
1828
|
-
|
|
1979
|
+
const sz = import_fs2.default.statSync(filePath2).size;
|
|
1980
|
+
import_fs2.default.unlinkSync(filePath2);
|
|
1829
1981
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1830
1982
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1831
1983
|
purged++;
|
|
@@ -1834,19 +1986,19 @@ var DiskTier = class {
|
|
|
1834
1986
|
}
|
|
1835
1987
|
continue;
|
|
1836
1988
|
}
|
|
1837
|
-
const filePath =
|
|
1989
|
+
const filePath = import_path2.default.join(bucketPath, file);
|
|
1838
1990
|
let fd = -1;
|
|
1839
1991
|
try {
|
|
1840
|
-
fd =
|
|
1841
|
-
const bytesRead =
|
|
1842
|
-
|
|
1992
|
+
fd = import_fs2.default.openSync(filePath, "r");
|
|
1993
|
+
const bytesRead = import_fs2.default.readSync(fd, headerBuf, 0, V2_HEADER_LEN, 0);
|
|
1994
|
+
import_fs2.default.closeSync(fd);
|
|
1843
1995
|
fd = -1;
|
|
1844
1996
|
if (bytesRead === V2_HEADER_LEN && headerBuf.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
1845
1997
|
const expiresAt = Number(headerBuf.readBigUInt64LE(8));
|
|
1846
1998
|
if (expiresAt <= now) {
|
|
1847
1999
|
try {
|
|
1848
|
-
const sz =
|
|
1849
|
-
|
|
2000
|
+
const sz = import_fs2.default.statSync(filePath).size;
|
|
2001
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1850
2002
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
1851
2003
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1852
2004
|
purged++;
|
|
@@ -1855,27 +2007,27 @@ var DiskTier = class {
|
|
|
1855
2007
|
}
|
|
1856
2008
|
continue;
|
|
1857
2009
|
}
|
|
1858
|
-
const stat =
|
|
2010
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
1859
2011
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
1860
|
-
|
|
2012
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1861
2013
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1862
2014
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1863
2015
|
purged++;
|
|
1864
2016
|
continue;
|
|
1865
2017
|
}
|
|
1866
|
-
const raw =
|
|
2018
|
+
const raw = import_fs2.default.readFileSync(filePath);
|
|
1867
2019
|
let dec;
|
|
1868
2020
|
try {
|
|
1869
2021
|
dec = this.decrypt(raw);
|
|
1870
2022
|
} catch {
|
|
1871
|
-
|
|
2023
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1872
2024
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1873
2025
|
purged++;
|
|
1874
2026
|
continue;
|
|
1875
2027
|
}
|
|
1876
2028
|
const payload = (0, import_msgpackr2.unpack)(dec);
|
|
1877
2029
|
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= now) {
|
|
1878
|
-
|
|
2030
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1879
2031
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1880
2032
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1881
2033
|
purged++;
|
|
@@ -1883,7 +2035,7 @@ var DiskTier = class {
|
|
|
1883
2035
|
} catch {
|
|
1884
2036
|
} finally {
|
|
1885
2037
|
if (fd >= 0) try {
|
|
1886
|
-
|
|
2038
|
+
import_fs2.default.closeSync(fd);
|
|
1887
2039
|
} catch {
|
|
1888
2040
|
}
|
|
1889
2041
|
}
|
|
@@ -1897,8 +2049,8 @@ var DiskTier = class {
|
|
|
1897
2049
|
let cleared = 0;
|
|
1898
2050
|
for (const filePath of this.walkCacheFiles()) {
|
|
1899
2051
|
try {
|
|
1900
|
-
const stat =
|
|
1901
|
-
|
|
2052
|
+
const stat = import_fs2.default.statSync(filePath);
|
|
2053
|
+
import_fs2.default.unlinkSync(filePath);
|
|
1902
2054
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
1903
2055
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
1904
2056
|
cleared++;
|
|
@@ -2081,11 +2233,25 @@ function inferPriority(cacheKey) {
|
|
|
2081
2233
|
return 2 /* NORMAL */;
|
|
2082
2234
|
}
|
|
2083
2235
|
var GLOBAL_KEY = "__tricache_instance__";
|
|
2236
|
+
function detectServerlessRuntime() {
|
|
2237
|
+
if (process.env["AWS_LAMBDA_FUNCTION_NAME"]) return "AWS Lambda";
|
|
2238
|
+
if (process.env["K_SERVICE"]) return "Google Cloud Run";
|
|
2239
|
+
if (process.env["FUNCTION_TARGET"]) return "Google Cloud Functions";
|
|
2240
|
+
if (process.env["WEBSITE_INSTANCE_ID"]) return "Azure Functions";
|
|
2241
|
+
if (process.env["FLY_APP_NAME"]) return "Fly.io";
|
|
2242
|
+
if (process.env["RAILWAY_ENVIRONMENT"]) return "Railway";
|
|
2243
|
+
if (process.env["VERCEL"]) return "Vercel";
|
|
2244
|
+
return null;
|
|
2245
|
+
}
|
|
2084
2246
|
var CacheService = class _CacheService {
|
|
2085
2247
|
logger;
|
|
2086
2248
|
enc;
|
|
2087
2249
|
l1;
|
|
2088
2250
|
disk;
|
|
2251
|
+
/** When true, all disk-tier and snapshot operations are skipped. */
|
|
2252
|
+
_diskDisabled = false;
|
|
2253
|
+
/** Worker pool for off-main-thread AES-GCM (null when workerThreads is false or unavailable). */
|
|
2254
|
+
_workerPool = null;
|
|
2089
2255
|
opts;
|
|
2090
2256
|
/** Pre-computed once — opts.namespace never changes after construction. */
|
|
2091
2257
|
_namespace;
|
|
@@ -2115,6 +2281,8 @@ var CacheService = class _CacheService {
|
|
|
2115
2281
|
instanceId;
|
|
2116
2282
|
backplaneChannel;
|
|
2117
2283
|
subClient = null;
|
|
2284
|
+
/** Timestamp (Date.now()) when the backplane subscriber last lost its connection. */
|
|
2285
|
+
_subDisconnectedAt = null;
|
|
2118
2286
|
counters = {
|
|
2119
2287
|
gets: 0,
|
|
2120
2288
|
l1Hits: 0,
|
|
@@ -2156,7 +2324,7 @@ var CacheService = class _CacheService {
|
|
|
2156
2324
|
forbiddenSnapshotPrefixes: forbiddenPrefixes,
|
|
2157
2325
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2158
2326
|
// two instances with different namespaces never share cache files.
|
|
2159
|
-
diskCacheDir: options.diskCacheDir ??
|
|
2327
|
+
diskCacheDir: options.diskCacheDir ?? import_path3.default.join(
|
|
2160
2328
|
import_os.default.tmpdir(),
|
|
2161
2329
|
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2162
2330
|
),
|
|
@@ -2167,7 +2335,7 @@ var CacheService = class _CacheService {
|
|
|
2167
2335
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2168
2336
|
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
2169
2337
|
encryptionKey: encKeyRaw,
|
|
2170
|
-
snapshotPath: options.snapshotPath ??
|
|
2338
|
+
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2171
2339
|
import_os.default.tmpdir(),
|
|
2172
2340
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2173
2341
|
),
|
|
@@ -2193,7 +2361,16 @@ var CacheService = class _CacheService {
|
|
|
2193
2361
|
adaptiveTtl: options.adaptiveTtl ?? false,
|
|
2194
2362
|
adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1e3,
|
|
2195
2363
|
adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86400) * 1e3,
|
|
2196
|
-
adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20
|
|
2364
|
+
adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
|
|
2365
|
+
workerThreads: options.workerThreads ?? false,
|
|
2366
|
+
workerThresholdBytes: options.workerThresholdBytes ?? 131072,
|
|
2367
|
+
// 128 KB
|
|
2368
|
+
workerPoolSize: options.workerPoolSize ?? 0,
|
|
2369
|
+
// 0 = auto (min(4, cpus))
|
|
2370
|
+
backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
|
|
2371
|
+
disableDisk: options.disableDisk ?? false,
|
|
2372
|
+
redisClusterNodes: options.redisClusterNodes,
|
|
2373
|
+
redisSentinel: options.redisSentinel
|
|
2197
2374
|
};
|
|
2198
2375
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2199
2376
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
@@ -2203,6 +2380,20 @@ var CacheService = class _CacheService {
|
|
|
2203
2380
|
const maxKeys = options.adaptiveTtlMaxKeys ?? 5e3;
|
|
2204
2381
|
this.latencyTracker = new LatencyTracker(samples, maxKeys);
|
|
2205
2382
|
}
|
|
2383
|
+
let diskDisabled = this.opts.disableDisk;
|
|
2384
|
+
if (options.disableDisk === void 0) {
|
|
2385
|
+
const serverless = detectServerlessRuntime();
|
|
2386
|
+
if (serverless !== null) {
|
|
2387
|
+
diskDisabled = true;
|
|
2388
|
+
logger.warn("tricache: disk tier auto-disabled (ephemeral filesystem detected)", {
|
|
2389
|
+
runtime: serverless,
|
|
2390
|
+
hint: "Set disableDisk: false to override, or disableDisk: true to silence this warning"
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
} else if (diskDisabled) {
|
|
2394
|
+
logger.info("tricache: disk tier explicitly disabled (disableDisk: true)");
|
|
2395
|
+
}
|
|
2396
|
+
this._diskDisabled = diskDisabled;
|
|
2206
2397
|
this.disk = new DiskTier({
|
|
2207
2398
|
dir: this.opts.diskCacheDir,
|
|
2208
2399
|
maxBytes: this.opts.diskMaxBytes,
|
|
@@ -2212,13 +2403,14 @@ var CacheService = class _CacheService {
|
|
|
2212
2403
|
logger
|
|
2213
2404
|
});
|
|
2214
2405
|
this._namespace = ns;
|
|
2215
|
-
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost;
|
|
2406
|
+
this._redisDisabled = this.opts.disableRedis || !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
|
|
2216
2407
|
this.l1 = new SmartMemoryCache({
|
|
2217
2408
|
maxBytes: this.opts.l1MaxBytes,
|
|
2218
2409
|
maxEntries: this.opts.l1MaxEntries,
|
|
2219
2410
|
categories: this.opts.categoryLimits,
|
|
2220
2411
|
evictionWatermark: this.opts.l1EvictionWatermark,
|
|
2221
2412
|
diskSpill: (key, entry) => {
|
|
2413
|
+
if (this._diskDisabled) return;
|
|
2222
2414
|
setImmediate(() => {
|
|
2223
2415
|
void this.disk.save(key, entry);
|
|
2224
2416
|
});
|
|
@@ -2228,28 +2420,53 @@ var CacheService = class _CacheService {
|
|
|
2228
2420
|
});
|
|
2229
2421
|
if (!this.snapshotLoaded) {
|
|
2230
2422
|
this.snapshotLoaded = true;
|
|
2231
|
-
this.loadSnapshot();
|
|
2423
|
+
if (!this._diskDisabled) this.loadSnapshot();
|
|
2232
2424
|
}
|
|
2233
2425
|
this._shutdownHandler = () => {
|
|
2234
|
-
this.writeSnapshot();
|
|
2426
|
+
if (!this._diskDisabled) this.writeSnapshot();
|
|
2235
2427
|
process.exit(0);
|
|
2236
2428
|
};
|
|
2237
2429
|
process.once("SIGTERM", this._shutdownHandler);
|
|
2238
2430
|
process.once("SIGINT", this._shutdownHandler);
|
|
2431
|
+
if (this.opts.workerThreads && this.enc.isEnabled) {
|
|
2432
|
+
try {
|
|
2433
|
+
const encRef = this.enc;
|
|
2434
|
+
this._workerPool = new WorkerPool({
|
|
2435
|
+
keyBase64: encRef._key ? encRef._key.toString("base64") : "",
|
|
2436
|
+
mode: encRef._mode,
|
|
2437
|
+
prevKeyBase64: encRef._prevKey ? encRef._prevKey.toString("base64") : void 0,
|
|
2438
|
+
prevMode: encRef._prevMode,
|
|
2439
|
+
size: this.opts.workerPoolSize || void 0
|
|
2440
|
+
});
|
|
2441
|
+
if (this._workerPool.isAvailable) {
|
|
2442
|
+
logger.info("tricache: worker-thread encryption pool active", {
|
|
2443
|
+
threshold: `${this.opts.workerThresholdBytes / 1024} KB`
|
|
2444
|
+
});
|
|
2445
|
+
} else {
|
|
2446
|
+
this._workerPool = null;
|
|
2447
|
+
logger.warn("tricache: worker-thread pool requested but unavailable; using main-thread crypto");
|
|
2448
|
+
}
|
|
2449
|
+
} catch {
|
|
2450
|
+
this._workerPool = null;
|
|
2451
|
+
logger.warn("tricache: worker-thread pool init failed; using main-thread crypto");
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2239
2454
|
this.cleanupInterval = setInterval(() => {
|
|
2240
2455
|
const cleaned = this.l1.cleanup();
|
|
2241
2456
|
if (cleaned > 0) this.logger.debug("Periodic L1 cleanup", { cleaned });
|
|
2242
2457
|
}, 5 * 60 * 1e3);
|
|
2243
2458
|
if (this.cleanupInterval.unref) this.cleanupInterval.unref();
|
|
2244
|
-
this.
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2459
|
+
if (!this._diskDisabled) {
|
|
2460
|
+
this.diskJanitorInterval = setInterval(() => {
|
|
2461
|
+
const purged = this.disk.purgeNextBucket();
|
|
2462
|
+
if (purged > 0) this.logger.debug("Disk janitor tick", { purged });
|
|
2463
|
+
}, 3e4);
|
|
2464
|
+
if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
|
|
2465
|
+
}
|
|
2249
2466
|
if (this.opts.oomProtection) {
|
|
2250
2467
|
this.oomInterval = setInterval(() => {
|
|
2251
|
-
const
|
|
2252
|
-
const used =
|
|
2468
|
+
const heap = import_node_v8.default.getHeapStatistics();
|
|
2469
|
+
const used = heap.used_heap_size / heap.heap_size_limit;
|
|
2253
2470
|
if (used >= this.opts.oomHeapThreshold) {
|
|
2254
2471
|
const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
|
|
2255
2472
|
this.counters.oomEvictions++;
|
|
@@ -2357,18 +2574,60 @@ var CacheService = class _CacheService {
|
|
|
2357
2574
|
initBackplane() {
|
|
2358
2575
|
if (!this.opts.invalidationBackplane || this._redisDisabled) return;
|
|
2359
2576
|
if (this.subClient) return;
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2577
|
+
let sub;
|
|
2578
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
2579
|
+
sub = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
2580
|
+
redisOptions: {
|
|
2581
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2582
|
+
connectTimeout: 1e4,
|
|
2583
|
+
maxRetriesPerRequest: null
|
|
2584
|
+
}
|
|
2585
|
+
});
|
|
2586
|
+
} else if (this.opts.redisSentinel) {
|
|
2587
|
+
sub = new import_ioredis.Redis({
|
|
2588
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
2589
|
+
name: this.opts.redisSentinel.name,
|
|
2590
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2591
|
+
connectTimeout: 1e4,
|
|
2592
|
+
lazyConnect: true,
|
|
2593
|
+
maxRetriesPerRequest: null,
|
|
2594
|
+
enableAutoPipelining: false,
|
|
2595
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2596
|
+
});
|
|
2597
|
+
} else {
|
|
2598
|
+
sub = new import_ioredis.Redis({
|
|
2599
|
+
host: this.opts.redisHost,
|
|
2600
|
+
port: this.opts.redisPort,
|
|
2601
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2602
|
+
connectTimeout: 1e4,
|
|
2603
|
+
lazyConnect: true,
|
|
2604
|
+
maxRetriesPerRequest: null,
|
|
2605
|
+
enableAutoPipelining: false,
|
|
2606
|
+
family: 4,
|
|
2607
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2371
2610
|
sub.on("error", (e) => this.logger.debug("Backplane subscriber error", { error: e.message }));
|
|
2611
|
+
sub.on("close", () => {
|
|
2612
|
+
if (this._subDisconnectedAt === null) {
|
|
2613
|
+
this._subDisconnectedAt = Date.now();
|
|
2614
|
+
this.logger.debug("Backplane: subscriber disconnected", { at: this._subDisconnectedAt });
|
|
2615
|
+
}
|
|
2616
|
+
});
|
|
2617
|
+
sub.on("ready", () => {
|
|
2618
|
+
if (this._subDisconnectedAt !== null && this.opts.backplaneMaxStalenessMs > 0) {
|
|
2619
|
+
const gapMs = Date.now() - this._subDisconnectedAt;
|
|
2620
|
+
if (gapMs > this.opts.backplaneMaxStalenessMs) {
|
|
2621
|
+
const evicted = this.l1.evictSetBefore(this._subDisconnectedAt);
|
|
2622
|
+
this.logger.warn("Backplane: reconnect after gap \u2014 flushed potentially stale L1 entries", {
|
|
2623
|
+
gapMs,
|
|
2624
|
+
evicted,
|
|
2625
|
+
hint: "Increase backplaneMaxStalenessMs or set to 0 to disable the fence"
|
|
2626
|
+
});
|
|
2627
|
+
}
|
|
2628
|
+
this._subDisconnectedAt = null;
|
|
2629
|
+
}
|
|
2630
|
+
});
|
|
2372
2631
|
sub.on("message", (_channel, message) => {
|
|
2373
2632
|
this._handleBackplaneMessage(message);
|
|
2374
2633
|
});
|
|
@@ -2391,7 +2650,9 @@ var CacheService = class _CacheService {
|
|
|
2391
2650
|
this.counters.invReceived++;
|
|
2392
2651
|
if (msg.op === "del") {
|
|
2393
2652
|
this.l1.delete(msg.key);
|
|
2394
|
-
setImmediate(() =>
|
|
2653
|
+
setImmediate(() => {
|
|
2654
|
+
if (!this._diskDisabled) this.disk.delete(msg.key);
|
|
2655
|
+
});
|
|
2395
2656
|
this._cascadeDependencies(msg.key);
|
|
2396
2657
|
} else if (msg.op === "del-glob") {
|
|
2397
2658
|
this.l1.deletePattern(msg.key);
|
|
@@ -2415,26 +2676,85 @@ var CacheService = class _CacheService {
|
|
|
2415
2676
|
} catch {
|
|
2416
2677
|
}
|
|
2417
2678
|
}
|
|
2679
|
+
/**
|
|
2680
|
+
* Scan all keys matching `pattern` across single-node or Cluster clients.
|
|
2681
|
+
* For Cluster, iterates every master node independently (SCAN is node-local).
|
|
2682
|
+
*/
|
|
2683
|
+
async _scanKeys(client, pattern) {
|
|
2684
|
+
const keys = [];
|
|
2685
|
+
if (client instanceof import_ioredis.Cluster) {
|
|
2686
|
+
const masters = client.nodes("master");
|
|
2687
|
+
await Promise.all(masters.map(
|
|
2688
|
+
(node) => new Promise((resolve, reject) => {
|
|
2689
|
+
const stream = node.scanStream({ match: pattern, count: 100 });
|
|
2690
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2691
|
+
stream.on("end", resolve);
|
|
2692
|
+
stream.on("error", reject);
|
|
2693
|
+
})
|
|
2694
|
+
));
|
|
2695
|
+
} else {
|
|
2696
|
+
await new Promise((resolve, reject) => {
|
|
2697
|
+
const stream = client.scanStream({ match: pattern, count: 100 });
|
|
2698
|
+
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2699
|
+
stream.on("end", resolve);
|
|
2700
|
+
stream.on("error", reject);
|
|
2701
|
+
});
|
|
2702
|
+
}
|
|
2703
|
+
return keys;
|
|
2704
|
+
}
|
|
2418
2705
|
async getRedis() {
|
|
2419
2706
|
if (!this.cb.isAllowed()) throw new Error("tricache: L2 circuit breaker is open");
|
|
2420
2707
|
if (this.redisConnecting) return this.redisConnecting;
|
|
2421
2708
|
this.redisConnecting = (async () => {
|
|
2422
2709
|
try {
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2710
|
+
let client;
|
|
2711
|
+
if (this.opts.redisClusterNodes?.length) {
|
|
2712
|
+
client = new import_ioredis.Cluster(this.opts.redisClusterNodes, {
|
|
2713
|
+
redisOptions: {
|
|
2714
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2715
|
+
connectTimeout: 1e4,
|
|
2716
|
+
maxRetriesPerRequest: 3,
|
|
2717
|
+
keepAlive: 3e4
|
|
2718
|
+
},
|
|
2719
|
+
enableAutoPipelining: true,
|
|
2720
|
+
retryDelayOnClusterDown: 200,
|
|
2721
|
+
retryDelayOnFailover: 1e3
|
|
2722
|
+
});
|
|
2723
|
+
client.on("connect", () => this.logger.info("Redis Cluster connected"));
|
|
2724
|
+
client.on("error", (e) => this.logger.error("Redis Cluster error", {}, e));
|
|
2725
|
+
client.on("reconnecting", () => this.logger.debug("Redis Cluster reconnecting"));
|
|
2726
|
+
} else if (this.opts.redisSentinel) {
|
|
2727
|
+
client = new import_ioredis.Redis({
|
|
2728
|
+
sentinels: this.opts.redisSentinel.sentinels,
|
|
2729
|
+
name: this.opts.redisSentinel.name,
|
|
2730
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2731
|
+
connectTimeout: 1e4,
|
|
2732
|
+
lazyConnect: false,
|
|
2733
|
+
maxRetriesPerRequest: 3,
|
|
2734
|
+
enableAutoPipelining: true,
|
|
2735
|
+
keepAlive: 3e4,
|
|
2736
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2737
|
+
});
|
|
2738
|
+
client.on("connect", () => this.logger.info("Redis Sentinel connected", { name: this.opts.redisSentinel.name }));
|
|
2739
|
+
client.on("error", (e) => this.logger.error("Redis Sentinel error", { name: this.opts.redisSentinel.name }, e));
|
|
2740
|
+
client.on("reconnecting", () => this.logger.debug("Redis Sentinel reconnecting"));
|
|
2741
|
+
} else {
|
|
2742
|
+
client = new import_ioredis.Redis({
|
|
2743
|
+
host: this.opts.redisHost,
|
|
2744
|
+
port: this.opts.redisPort,
|
|
2745
|
+
tls: this.opts.redisTls ? {} : void 0,
|
|
2746
|
+
connectTimeout: 1e4,
|
|
2747
|
+
lazyConnect: false,
|
|
2748
|
+
maxRetriesPerRequest: 3,
|
|
2749
|
+
enableAutoPipelining: true,
|
|
2750
|
+
keepAlive: 3e4,
|
|
2751
|
+
family: 4,
|
|
2752
|
+
retryStrategy: (times) => Math.min(times * 50, 2e3)
|
|
2753
|
+
});
|
|
2754
|
+
client.on("connect", () => this.logger.info("Redis connected", { host: this.opts.redisHost }));
|
|
2755
|
+
client.on("error", (e) => this.logger.error("Redis error", { host: this.opts.redisHost }, e));
|
|
2756
|
+
client.on("reconnecting", () => this.logger.debug("Redis reconnecting"));
|
|
2757
|
+
}
|
|
2438
2758
|
await new Promise((resolve, reject) => {
|
|
2439
2759
|
client.once("ready", resolve);
|
|
2440
2760
|
client.once("error", reject);
|
|
@@ -2461,7 +2781,7 @@ var CacheService = class _CacheService {
|
|
|
2461
2781
|
const packed = (0, import_msgpackr3.pack)(payload);
|
|
2462
2782
|
const final = this.enc.isEnabled ? this.enc.encryptBuffer(packed) : packed;
|
|
2463
2783
|
const dest = altPath ?? this.opts.snapshotPath;
|
|
2464
|
-
|
|
2784
|
+
import_fs3.default.writeFileSync(dest, final, { mode: 384 });
|
|
2465
2785
|
this.logger.info("Cache snapshot written", {
|
|
2466
2786
|
path: dest,
|
|
2467
2787
|
entries: entries.length,
|
|
@@ -2475,15 +2795,15 @@ var CacheService = class _CacheService {
|
|
|
2475
2795
|
loadSnapshot() {
|
|
2476
2796
|
const snapshotPath = this.opts.snapshotPath;
|
|
2477
2797
|
try {
|
|
2478
|
-
if (!
|
|
2479
|
-
const stat =
|
|
2798
|
+
if (!import_fs3.default.existsSync(snapshotPath)) return;
|
|
2799
|
+
const stat = import_fs3.default.statSync(snapshotPath);
|
|
2480
2800
|
if (stat.size > SNAPSHOT_MAX_FILE_BYTES) {
|
|
2481
2801
|
this.logger.warn("Snapshot rejected: exceeds size limit", { sizeBytes: stat.size });
|
|
2482
|
-
|
|
2802
|
+
import_fs3.default.unlinkSync(snapshotPath);
|
|
2483
2803
|
return;
|
|
2484
2804
|
}
|
|
2485
|
-
const raw =
|
|
2486
|
-
|
|
2805
|
+
const raw = import_fs3.default.readFileSync(snapshotPath);
|
|
2806
|
+
import_fs3.default.unlinkSync(snapshotPath);
|
|
2487
2807
|
let buf;
|
|
2488
2808
|
try {
|
|
2489
2809
|
buf = this.enc.decryptBuffer(raw);
|
|
@@ -2514,7 +2834,7 @@ var CacheService = class _CacheService {
|
|
|
2514
2834
|
} catch (err) {
|
|
2515
2835
|
this.logger.warn("Snapshot load failed \u2014 starting cold", { error: err.message });
|
|
2516
2836
|
try {
|
|
2517
|
-
|
|
2837
|
+
import_fs3.default.unlinkSync(snapshotPath);
|
|
2518
2838
|
} catch {
|
|
2519
2839
|
}
|
|
2520
2840
|
}
|
|
@@ -2600,7 +2920,12 @@ var CacheService = class _CacheService {
|
|
|
2600
2920
|
const raw = await client.get(k);
|
|
2601
2921
|
this.cb.onSuccess();
|
|
2602
2922
|
if (raw) {
|
|
2603
|
-
|
|
2923
|
+
let decrypted;
|
|
2924
|
+
if (this._workerPool && this.enc.isEnabled && raw.length > this.opts.workerThresholdBytes) {
|
|
2925
|
+
decrypted = await this._workerPool.decrypt(raw);
|
|
2926
|
+
} else {
|
|
2927
|
+
decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
2928
|
+
}
|
|
2604
2929
|
const parsed = JSON.parse(decrypted);
|
|
2605
2930
|
this.l1.set(k, parsed, ttlMs, priority);
|
|
2606
2931
|
this.counters.l2Hits++;
|
|
@@ -2614,20 +2939,22 @@ var CacheService = class _CacheService {
|
|
|
2614
2939
|
this.logger.debug("Redis unavailable, continuing to fetch", { cacheKey, error: err.message });
|
|
2615
2940
|
}
|
|
2616
2941
|
}
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2942
|
+
if (!this._diskDisabled) {
|
|
2943
|
+
const diskHit = this.disk.load(k);
|
|
2944
|
+
if (diskHit !== null) {
|
|
2945
|
+
const promoted = this.l1.importEntries(
|
|
2946
|
+
[{ key: k, entry: diskHit }],
|
|
2947
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
2948
|
+
);
|
|
2949
|
+
if (promoted > 0) {
|
|
2950
|
+
const l1Check = this.l1.get(k);
|
|
2951
|
+
if (l1Check !== null) {
|
|
2952
|
+
this.counters.diskHits++;
|
|
2953
|
+
this.opts.onHit?.(cacheKey, "disk");
|
|
2954
|
+
this.logger.debug("L1.5 hit (disk \u2192 L1)", { cacheKey });
|
|
2955
|
+
span.setAttribute("cache.hit", "disk").end();
|
|
2956
|
+
return l1Check.value;
|
|
2957
|
+
}
|
|
2631
2958
|
}
|
|
2632
2959
|
}
|
|
2633
2960
|
}
|
|
@@ -2667,7 +2994,12 @@ var CacheService = class _CacheService {
|
|
|
2667
2994
|
try {
|
|
2668
2995
|
const client = await this.getRedis();
|
|
2669
2996
|
const serialized = JSON.stringify(data);
|
|
2670
|
-
|
|
2997
|
+
let toStore;
|
|
2998
|
+
if (this._workerPool && this.enc.isEnabled && serialized.length > this.opts.workerThresholdBytes) {
|
|
2999
|
+
toStore = await this._workerPool.encrypt(serialized);
|
|
3000
|
+
} else {
|
|
3001
|
+
toStore = this.enc.isEnabled ? this.enc.encrypt(serialized) : serialized;
|
|
3002
|
+
}
|
|
2671
3003
|
await client.setex(k, Math.ceil(effectiveTtl / 1e3), toStore);
|
|
2672
3004
|
this.cb.onSuccess();
|
|
2673
3005
|
this.logger.debug("Cached L1+L2", { cacheKey, ttlSeconds, encrypted: this.enc.isEnabled });
|
|
@@ -2699,7 +3031,12 @@ var CacheService = class _CacheService {
|
|
|
2699
3031
|
try {
|
|
2700
3032
|
const client = await this.getRedis();
|
|
2701
3033
|
const s = JSON.stringify(data);
|
|
2702
|
-
|
|
3034
|
+
let stored;
|
|
3035
|
+
if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
|
|
3036
|
+
stored = await this._workerPool.encrypt(s);
|
|
3037
|
+
} else {
|
|
3038
|
+
stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
3039
|
+
}
|
|
2703
3040
|
await client.setex(cacheKey, Math.ceil(ttlMs / 1e3), stored);
|
|
2704
3041
|
} catch {
|
|
2705
3042
|
}
|
|
@@ -2746,7 +3083,12 @@ var CacheService = class _CacheService {
|
|
|
2746
3083
|
try {
|
|
2747
3084
|
const client = await this.getRedis();
|
|
2748
3085
|
const s = JSON.stringify(data);
|
|
2749
|
-
|
|
3086
|
+
let stored;
|
|
3087
|
+
if (this._workerPool && this.enc.isEnabled && s.length > this.opts.workerThresholdBytes) {
|
|
3088
|
+
stored = await this._workerPool.encrypt(s);
|
|
3089
|
+
} else {
|
|
3090
|
+
stored = this.enc.isEnabled ? this.enc.encrypt(s) : s;
|
|
3091
|
+
}
|
|
2750
3092
|
await client.setex(k, Math.ceil(ttlMs / 1e3), stored);
|
|
2751
3093
|
this.cb.onSuccess();
|
|
2752
3094
|
} catch (err) {
|
|
@@ -2804,7 +3146,9 @@ var CacheService = class _CacheService {
|
|
|
2804
3146
|
this.l1.deletePattern(k);
|
|
2805
3147
|
} else {
|
|
2806
3148
|
this.l1.delete(k);
|
|
2807
|
-
setImmediate(() =>
|
|
3149
|
+
setImmediate(() => {
|
|
3150
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
3151
|
+
});
|
|
2808
3152
|
this._cascadeDependencies(k);
|
|
2809
3153
|
for (const [, dependents] of this.dependencyIndex) dependents.delete(k);
|
|
2810
3154
|
}
|
|
@@ -2812,13 +3156,7 @@ var CacheService = class _CacheService {
|
|
|
2812
3156
|
try {
|
|
2813
3157
|
const client = await this.getRedis();
|
|
2814
3158
|
if (isPattern) {
|
|
2815
|
-
const
|
|
2816
|
-
const keys = [];
|
|
2817
|
-
await new Promise((resolve, reject) => {
|
|
2818
|
-
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2819
|
-
stream.on("end", resolve);
|
|
2820
|
-
stream.on("error", reject);
|
|
2821
|
-
});
|
|
3159
|
+
const keys = await this._scanKeys(client, k);
|
|
2822
3160
|
if (keys.length > 0) await client.del(...keys);
|
|
2823
3161
|
} else {
|
|
2824
3162
|
await client.del(k);
|
|
@@ -2875,7 +3213,7 @@ var CacheService = class _CacheService {
|
|
|
2875
3213
|
this.l1.deletePattern(k);
|
|
2876
3214
|
} else {
|
|
2877
3215
|
this.l1.clear();
|
|
2878
|
-
this.disk.clear();
|
|
3216
|
+
if (!this._diskDisabled) this.disk.clear();
|
|
2879
3217
|
this._l1Counters.clear();
|
|
2880
3218
|
this.tagIndex.clear();
|
|
2881
3219
|
}
|
|
@@ -2883,13 +3221,7 @@ var CacheService = class _CacheService {
|
|
|
2883
3221
|
try {
|
|
2884
3222
|
const client = await this.getRedis();
|
|
2885
3223
|
const pattern = k ?? (this._namespace ? `${this._namespace}:*` : "*");
|
|
2886
|
-
const
|
|
2887
|
-
const keys = [];
|
|
2888
|
-
await new Promise((resolve, reject) => {
|
|
2889
|
-
stream.on("data", (chunk) => keys.push(...chunk));
|
|
2890
|
-
stream.on("end", resolve);
|
|
2891
|
-
stream.on("error", reject);
|
|
2892
|
-
});
|
|
3224
|
+
const keys = await this._scanKeys(client, pattern);
|
|
2893
3225
|
if (keys.length > 0) await client.del(...keys);
|
|
2894
3226
|
} catch (err) {
|
|
2895
3227
|
this.logger.debug("clear: Redis unavailable", { error: err.message });
|
|
@@ -3117,13 +3449,7 @@ var CacheService = class _CacheService {
|
|
|
3117
3449
|
try {
|
|
3118
3450
|
const client = await this.getRedis();
|
|
3119
3451
|
const nsPattern = this.nk(pattern);
|
|
3120
|
-
const matchedKeys =
|
|
3121
|
-
const stream = client.scanStream({ match: nsPattern, count: 100 });
|
|
3122
|
-
await new Promise((resolve, reject) => {
|
|
3123
|
-
stream.on("data", (chunk) => matchedKeys.push(...chunk));
|
|
3124
|
-
stream.on("end", resolve);
|
|
3125
|
-
stream.on("error", reject);
|
|
3126
|
-
});
|
|
3452
|
+
const matchedKeys = await this._scanKeys(client, nsPattern);
|
|
3127
3453
|
if (matchedKeys.length === 0) {
|
|
3128
3454
|
this.cb.onSuccess();
|
|
3129
3455
|
return 0;
|
|
@@ -3173,7 +3499,7 @@ var CacheService = class _CacheService {
|
|
|
3173
3499
|
const members = this.tagIndex.get(tagKey) ?? /* @__PURE__ */ new Set();
|
|
3174
3500
|
for (const k of members) {
|
|
3175
3501
|
this.l1.delete(k);
|
|
3176
|
-
this.disk.delete(k);
|
|
3502
|
+
if (!this._diskDisabled) this.disk.delete(k);
|
|
3177
3503
|
}
|
|
3178
3504
|
this.tagIndex.delete(tagKey);
|
|
3179
3505
|
if (!this._redisDisabled) {
|
|
@@ -3384,7 +3710,7 @@ var CacheService = class _CacheService {
|
|
|
3384
3710
|
for (const dep of dependents) {
|
|
3385
3711
|
if (dep === deletedKey) continue;
|
|
3386
3712
|
this.l1.delete(dep);
|
|
3387
|
-
this.disk.delete(dep);
|
|
3713
|
+
if (!this._diskDisabled) this.disk.delete(dep);
|
|
3388
3714
|
void this.publishInvalidation("del", dep);
|
|
3389
3715
|
this.logger.debug("Dependency cascade: invalidated dependent key", {
|
|
3390
3716
|
trigger: deletedKey.slice(0, 60),
|
|
@@ -3446,7 +3772,7 @@ var CacheService = class _CacheService {
|
|
|
3446
3772
|
sizeBytes: this.l1.memoryUsage,
|
|
3447
3773
|
maxBytes: this.opts.l1MaxBytes
|
|
3448
3774
|
},
|
|
3449
|
-
disk: this.disk.stats,
|
|
3775
|
+
disk: { ...this.disk.stats, disabled: this._diskDisabled },
|
|
3450
3776
|
...this.latencyTracker && {
|
|
3451
3777
|
adaptiveTtl: {
|
|
3452
3778
|
enabled: true,
|
|
@@ -3536,6 +3862,10 @@ var CacheService = class _CacheService {
|
|
|
3536
3862
|
process.off("SIGINT", this._shutdownHandler);
|
|
3537
3863
|
this._shutdownHandler = null;
|
|
3538
3864
|
}
|
|
3865
|
+
if (this._workerPool) {
|
|
3866
|
+
await this._workerPool.destroy();
|
|
3867
|
+
this._workerPool = null;
|
|
3868
|
+
}
|
|
3539
3869
|
if (this.subClient) {
|
|
3540
3870
|
try {
|
|
3541
3871
|
await this.subClient.quit();
|
|
@@ -3550,7 +3880,7 @@ var CacheService = class _CacheService {
|
|
|
3550
3880
|
}
|
|
3551
3881
|
this.redis = null;
|
|
3552
3882
|
}
|
|
3553
|
-
this.disk.close();
|
|
3883
|
+
if (!this._diskDisabled) this.disk.close();
|
|
3554
3884
|
}
|
|
3555
3885
|
};
|
|
3556
3886
|
// Annotate the CommonJS export names for ESM import in node:
|