tricache 0.6.4 → 0.6.6
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 +27 -13
- package/dist/{chunk-F24NEZGQ.js → chunk-FKY5R3CE.js} +17 -13
- package/dist/index.cjs +264 -77
- package/dist/index.d.ts +84 -11
- package/dist/index.js +249 -74
- package/dist/serialize-worker.cjs +17 -5
- package/dist/serialize-worker.js +1 -1
- package/package.json +13 -13
- package/src/cache-service.ts +227 -21
- package/src/disk-tier.ts +31 -44
- package/src/encryption.ts +23 -4
- package/src/smart-memory-cache.ts +19 -3
- package/src/types.ts +29 -0
- package/src/wasm/bloom-filter-wasm.ts +2 -2
- package/src/worker-pool.ts +3 -8
- package/dist/index.d.cts +0 -1570
- package/dist/serialize-worker.d.cts +0 -2
package/dist/index.cjs
CHANGED
|
@@ -44,12 +44,13 @@ module.exports = __toCommonJS(index_exports);
|
|
|
44
44
|
var import_ioredis = require("ioredis");
|
|
45
45
|
var import_msgpackr3 = require("msgpackr");
|
|
46
46
|
var import_crypto3 = __toESM(require("crypto"), 1);
|
|
47
|
-
var
|
|
47
|
+
var import_os2 = __toESM(require("os"), 1);
|
|
48
48
|
|
|
49
49
|
// src/worker-pool.ts
|
|
50
50
|
var import_worker_threads = require("worker_threads");
|
|
51
51
|
var import_url = require("url");
|
|
52
52
|
var import_path = require("path");
|
|
53
|
+
var import_os = __toESM(require("os"), 1);
|
|
53
54
|
var import_fs = require("fs");
|
|
54
55
|
var import_meta = {};
|
|
55
56
|
var _workerFile;
|
|
@@ -155,12 +156,7 @@ var WorkerPool = class {
|
|
|
155
156
|
}
|
|
156
157
|
};
|
|
157
158
|
function availableCpus() {
|
|
158
|
-
|
|
159
|
-
const os2 = require("os");
|
|
160
|
-
return os2.availableParallelism?.() ?? os2.cpus().length;
|
|
161
|
-
} catch {
|
|
162
|
-
return 2;
|
|
163
|
-
}
|
|
159
|
+
return import_os.default.availableParallelism?.() ?? import_os.default.cpus().length;
|
|
164
160
|
}
|
|
165
161
|
|
|
166
162
|
// src/cache-service.ts
|
|
@@ -334,6 +330,20 @@ var CacheEncryption = class {
|
|
|
334
330
|
get isEnabled() {
|
|
335
331
|
return this._key !== null;
|
|
336
332
|
}
|
|
333
|
+
/**
|
|
334
|
+
* Snapshot the key material needed to spin up an off-main-thread worker pool.
|
|
335
|
+
* Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
|
|
336
|
+
* cast in cache-service.ts — the worker pool reads these via this accessor
|
|
337
|
+
* instead of reaching into underscore-prefixed internals.
|
|
338
|
+
*/
|
|
339
|
+
toWorkerInit() {
|
|
340
|
+
return {
|
|
341
|
+
keyBase64: this._key ? this._key.toString("base64") : "",
|
|
342
|
+
mode: this._mode,
|
|
343
|
+
prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
|
|
344
|
+
prevMode: this._prevMode
|
|
345
|
+
};
|
|
346
|
+
}
|
|
337
347
|
// ── String (Redis) ────────────────────────────────────────────────────────
|
|
338
348
|
/**
|
|
339
349
|
* Encrypt a string for Redis storage.
|
|
@@ -376,18 +386,18 @@ var CacheEncryption = class {
|
|
|
376
386
|
*/
|
|
377
387
|
decrypt(value) {
|
|
378
388
|
try {
|
|
379
|
-
return this._decryptWithKey(value, this._key, this._keyObj
|
|
389
|
+
return this._decryptWithKey(value, this._key, this._keyObj);
|
|
380
390
|
} catch (primaryErr) {
|
|
381
391
|
if (this._prevKey) {
|
|
382
392
|
try {
|
|
383
|
-
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj
|
|
393
|
+
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
|
|
384
394
|
} catch {
|
|
385
395
|
}
|
|
386
396
|
}
|
|
387
397
|
throw primaryErr;
|
|
388
398
|
}
|
|
389
399
|
}
|
|
390
|
-
_decryptWithKey(value, key, keyObj
|
|
400
|
+
_decryptWithKey(value, key, keyObj) {
|
|
391
401
|
if (value.startsWith(PREFIX_XOR)) {
|
|
392
402
|
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
393
403
|
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
@@ -422,8 +432,6 @@ var CacheEncryption = class {
|
|
|
422
432
|
const plain = d.update(ct);
|
|
423
433
|
d.final();
|
|
424
434
|
return plain.toString("utf8");
|
|
425
|
-
void mode;
|
|
426
|
-
void key;
|
|
427
435
|
}
|
|
428
436
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
429
437
|
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
@@ -573,8 +581,8 @@ var WasmBloomFilter = class {
|
|
|
573
581
|
}
|
|
574
582
|
/**
|
|
575
583
|
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
576
|
-
* Exact formula for k=7 hash rounds, m=100 000 bits
|
|
577
|
-
* n_max = -m * ln(1 - p^(1/k)) / k ≈
|
|
584
|
+
* Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
|
|
585
|
+
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
|
|
578
586
|
*/
|
|
579
587
|
get maxCapacity() {
|
|
580
588
|
return this._maxCapacity;
|
|
@@ -843,8 +851,8 @@ var SmartMemoryCache = class {
|
|
|
843
851
|
const lim = this.getCategoryLimit(category);
|
|
844
852
|
const catCnt = this.categoryCount.get(category) ?? 0;
|
|
845
853
|
const catSz = this.categorySize.get(category) ?? 0;
|
|
846
|
-
|
|
847
|
-
|
|
854
|
+
let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
855
|
+
let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
848
856
|
if (!catOvf && !glbOvf) {
|
|
849
857
|
const wm = this.opts.evictionWatermark ?? 0.9;
|
|
850
858
|
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
|
|
@@ -854,7 +862,17 @@ var SmartMemoryCache = class {
|
|
|
854
862
|
}
|
|
855
863
|
return;
|
|
856
864
|
}
|
|
857
|
-
|
|
865
|
+
const MAX_EVICT_PASSES = 64;
|
|
866
|
+
let passes = 0;
|
|
867
|
+
do {
|
|
868
|
+
this.smartEvict(category, catOvf);
|
|
869
|
+
const lim2 = this.getCategoryLimit(category);
|
|
870
|
+
const catCnt2 = this.categoryCount.get(category) ?? 0;
|
|
871
|
+
const catSz2 = this.categorySize.get(category) ?? 0;
|
|
872
|
+
catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
|
|
873
|
+
glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
874
|
+
passes++;
|
|
875
|
+
} while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
|
|
858
876
|
}
|
|
859
877
|
score(entry, catBonus, now, key) {
|
|
860
878
|
const age = now - entry.lastAccess;
|
|
@@ -1395,18 +1413,13 @@ var SmartMemoryCache = class {
|
|
|
1395
1413
|
var import_fs2 = __toESM(require("fs"), 1);
|
|
1396
1414
|
var import_path2 = __toESM(require("path"), 1);
|
|
1397
1415
|
var import_crypto2 = __toESM(require("crypto"), 1);
|
|
1398
|
-
var import_module = require("module");
|
|
1399
1416
|
var import_msgpackr2 = require("msgpackr");
|
|
1400
|
-
var import_meta2 = {};
|
|
1401
1417
|
var _SqliteDB = null;
|
|
1402
1418
|
try {
|
|
1403
|
-
const
|
|
1404
|
-
_SqliteDB =
|
|
1419
|
+
const sqlite = process.getBuiltinModule("node:sqlite");
|
|
1420
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1405
1421
|
} catch {
|
|
1406
1422
|
}
|
|
1407
|
-
var AES_ALGO = "aes-256-gcm";
|
|
1408
|
-
var IV_BYTES2 = 12;
|
|
1409
|
-
var TAG_BYTES2 = 16;
|
|
1410
1423
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1411
1424
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1412
1425
|
var V2_HEADER_LEN = 16;
|
|
@@ -1595,54 +1608,33 @@ var DiskTier = class {
|
|
|
1595
1608
|
return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
|
|
1596
1609
|
}
|
|
1597
1610
|
encrypt(data) {
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
const iv = import_crypto2.default.randomBytes(IV_BYTES2);
|
|
1601
|
-
const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
|
|
1602
|
-
const enc = Buffer.concat([c.update(data), c.final()]);
|
|
1603
|
-
const tag = c.getAuthTag();
|
|
1604
|
-
return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
|
|
1611
|
+
if (!this.opts.encryption) return data;
|
|
1612
|
+
return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
|
|
1605
1613
|
}
|
|
1606
1614
|
decrypt(data) {
|
|
1607
1615
|
const mLen = DISK_MAGIC.length;
|
|
1608
1616
|
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
const iv = data.subarray(mLen, mLen + IV_BYTES2);
|
|
1612
|
-
const tag = data.subarray(mLen + IV_BYTES2, mLen + IV_BYTES2 + TAG_BYTES2);
|
|
1613
|
-
const ct = data.subarray(mLen + IV_BYTES2 + TAG_BYTES2);
|
|
1614
|
-
const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
|
|
1615
|
-
d.setAuthTag(tag);
|
|
1616
|
-
return Buffer.concat([d.update(ct), d.final()]);
|
|
1617
|
+
if (!this.opts.encryption) throw new Error("DiskTier: entry is encrypted but no encryption configured");
|
|
1618
|
+
return this.opts.encryption.decryptBuffer(data.subarray(mLen));
|
|
1617
1619
|
}
|
|
1618
1620
|
/**
|
|
1619
|
-
* V2 encryption — returns
|
|
1620
|
-
* the outer 16-byte header
|
|
1621
|
-
* Returns the buffer unchanged when no encryption
|
|
1621
|
+
* V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
|
|
1622
|
+
* magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
|
|
1623
|
+
* Returns the buffer unchanged when no encryption instance is configured.
|
|
1622
1624
|
*/
|
|
1623
1625
|
encryptV2(data) {
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
const iv = import_crypto2.default.randomBytes(IV_BYTES2);
|
|
1627
|
-
const c = import_crypto2.default.createCipheriv(AES_ALGO, key, iv);
|
|
1628
|
-
const enc = Buffer.concat([c.update(data), c.final()]);
|
|
1629
|
-
const tag = c.getAuthTag();
|
|
1630
|
-
return Buffer.concat([iv, tag, enc]);
|
|
1626
|
+
if (!this.opts.encryption) return data;
|
|
1627
|
+
return this.opts.encryption.encryptBuffer(data);
|
|
1631
1628
|
}
|
|
1632
1629
|
/**
|
|
1633
1630
|
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
1634
|
-
* When
|
|
1635
|
-
*
|
|
1631
|
+
* When an encryption instance is configured the format is the mode-aware
|
|
1632
|
+
* CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
|
|
1633
|
+
* without one the payload is raw msgpack.
|
|
1636
1634
|
*/
|
|
1637
1635
|
decryptV2(inner) {
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
const iv = inner.subarray(0, IV_BYTES2);
|
|
1641
|
-
const tag = inner.subarray(IV_BYTES2, IV_BYTES2 + TAG_BYTES2);
|
|
1642
|
-
const ct = inner.subarray(IV_BYTES2 + TAG_BYTES2);
|
|
1643
|
-
const d = import_crypto2.default.createDecipheriv(AES_ALGO, key, iv);
|
|
1644
|
-
d.setAuthTag(tag);
|
|
1645
|
-
return Buffer.concat([d.update(ct), d.final()]);
|
|
1636
|
+
if (!this.opts.encryption) return inner;
|
|
1637
|
+
return this.opts.encryption.decryptBuffer(inner);
|
|
1646
1638
|
}
|
|
1647
1639
|
// ── Public API ────────────────────────────────────────────────────────────
|
|
1648
1640
|
/**
|
|
@@ -2114,12 +2106,24 @@ var L2CircuitBreaker = class {
|
|
|
2114
2106
|
state = 0 /* CLOSED */;
|
|
2115
2107
|
failures = 0;
|
|
2116
2108
|
openedAt = 0;
|
|
2117
|
-
/**
|
|
2109
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
2110
|
+
probing = false;
|
|
2111
|
+
/**
|
|
2112
|
+
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
2113
|
+
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
2114
|
+
* arriving while a probe is outstanding are rejected (return false) so a
|
|
2115
|
+
* recovering Redis node is not stampeded.
|
|
2116
|
+
*/
|
|
2118
2117
|
isAllowed() {
|
|
2119
2118
|
if (this.state === 0 /* CLOSED */) return true;
|
|
2120
|
-
if (this.state === 2 /* HALF_OPEN */)
|
|
2119
|
+
if (this.state === 2 /* HALF_OPEN */) {
|
|
2120
|
+
if (this.probing) return false;
|
|
2121
|
+
this.probing = true;
|
|
2122
|
+
return true;
|
|
2123
|
+
}
|
|
2121
2124
|
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
2122
2125
|
this.state = 2 /* HALF_OPEN */;
|
|
2126
|
+
this.probing = true;
|
|
2123
2127
|
return true;
|
|
2124
2128
|
}
|
|
2125
2129
|
return false;
|
|
@@ -2127,11 +2131,13 @@ var L2CircuitBreaker = class {
|
|
|
2127
2131
|
/** Call on Redis success. */
|
|
2128
2132
|
onSuccess() {
|
|
2129
2133
|
this.failures = 0;
|
|
2134
|
+
this.probing = false;
|
|
2130
2135
|
this.state = 0 /* CLOSED */;
|
|
2131
2136
|
}
|
|
2132
2137
|
/** Call on Redis failure. */
|
|
2133
2138
|
onFailure() {
|
|
2134
2139
|
this.failures++;
|
|
2140
|
+
this.probing = false;
|
|
2135
2141
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
2136
2142
|
this.state = 1 /* OPEN */;
|
|
2137
2143
|
this.openedAt = Date.now();
|
|
@@ -2306,8 +2312,14 @@ var CacheService = class _CacheService {
|
|
|
2306
2312
|
invSkipped: 0,
|
|
2307
2313
|
oomEvictions: 0,
|
|
2308
2314
|
oomLastAt: null,
|
|
2315
|
+
/** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
|
|
2316
|
+
counterErrors: 0,
|
|
2317
|
+
/** Times a later `create(ns)` call passed options differing from the live singleton. */
|
|
2318
|
+
singletonDivergences: 0,
|
|
2309
2319
|
startedAt: Date.now()
|
|
2310
2320
|
};
|
|
2321
|
+
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
2322
|
+
_incrementFallbackWarned = false;
|
|
2311
2323
|
// ── Constructor (use CacheService.create() for the recommended singleton) ──
|
|
2312
2324
|
constructor(options = {}) {
|
|
2313
2325
|
const logger = options.logger ?? consoleLogger;
|
|
@@ -2333,7 +2345,7 @@ var CacheService = class _CacheService {
|
|
|
2333
2345
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
2334
2346
|
// two instances with different namespaces never share cache files.
|
|
2335
2347
|
diskCacheDir: options.diskCacheDir ?? import_path3.default.join(
|
|
2336
|
-
|
|
2348
|
+
import_os2.default.tmpdir(),
|
|
2337
2349
|
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
2338
2350
|
),
|
|
2339
2351
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
@@ -2344,7 +2356,7 @@ var CacheService = class _CacheService {
|
|
|
2344
2356
|
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
2345
2357
|
encryptionKey: encKeyRaw,
|
|
2346
2358
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2347
|
-
|
|
2359
|
+
import_os2.default.tmpdir(),
|
|
2348
2360
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
2349
2361
|
),
|
|
2350
2362
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -2378,7 +2390,9 @@ var CacheService = class _CacheService {
|
|
|
2378
2390
|
backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
|
|
2379
2391
|
disableDisk: options.disableDisk ?? false,
|
|
2380
2392
|
redisClusterNodes: options.redisClusterNodes,
|
|
2381
|
-
redisSentinel: options.redisSentinel
|
|
2393
|
+
redisSentinel: options.redisSentinel,
|
|
2394
|
+
strictSingleton: options.strictSingleton ?? false,
|
|
2395
|
+
failClosed: options.failClosed ?? false
|
|
2382
2396
|
};
|
|
2383
2397
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2384
2398
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
@@ -2407,7 +2421,7 @@ var CacheService = class _CacheService {
|
|
|
2407
2421
|
maxBytes: this.opts.diskMaxBytes,
|
|
2408
2422
|
entryMaxBytes: this.opts.diskEntryMaxBytes,
|
|
2409
2423
|
forbiddenPrefixes,
|
|
2410
|
-
|
|
2424
|
+
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2411
2425
|
logger
|
|
2412
2426
|
});
|
|
2413
2427
|
this._namespace = ns;
|
|
@@ -2438,12 +2452,12 @@ var CacheService = class _CacheService {
|
|
|
2438
2452
|
process.once("SIGINT", this._shutdownHandler);
|
|
2439
2453
|
if (this.opts.workerThreads && this.enc.isEnabled) {
|
|
2440
2454
|
try {
|
|
2441
|
-
const encRef = this.enc;
|
|
2455
|
+
const encRef = this.enc.toWorkerInit();
|
|
2442
2456
|
this._workerPool = new WorkerPool({
|
|
2443
|
-
keyBase64: encRef.
|
|
2444
|
-
mode: encRef.
|
|
2445
|
-
prevKeyBase64: encRef.
|
|
2446
|
-
prevMode: encRef.
|
|
2457
|
+
keyBase64: encRef.keyBase64,
|
|
2458
|
+
mode: encRef.mode,
|
|
2459
|
+
prevKeyBase64: encRef.prevKeyBase64,
|
|
2460
|
+
prevMode: encRef.prevMode,
|
|
2447
2461
|
size: this.opts.workerPoolSize || void 0
|
|
2448
2462
|
});
|
|
2449
2463
|
if (this._workerPool.isAvailable) {
|
|
@@ -2509,7 +2523,10 @@ var CacheService = class _CacheService {
|
|
|
2509
2523
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2510
2524
|
*
|
|
2511
2525
|
* Options are only applied on first call — subsequent calls return the
|
|
2512
|
-
* existing instance regardless of options passed.
|
|
2526
|
+
* existing instance regardless of options passed. When the new options differ
|
|
2527
|
+
* from what the existing singleton was built with, this is a silent no-op by
|
|
2528
|
+
* default; set `strictSingleton: true` to throw instead, or watch the
|
|
2529
|
+
* `singletonDivergences` metric for detection.
|
|
2513
2530
|
*
|
|
2514
2531
|
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
2515
2532
|
* with different namespaces return independent instances.
|
|
@@ -2517,8 +2534,83 @@ var CacheService = class _CacheService {
|
|
|
2517
2534
|
static create(options) {
|
|
2518
2535
|
const g = globalThis;
|
|
2519
2536
|
const key = _CacheService.globalKey(options);
|
|
2520
|
-
if (!g[key])
|
|
2521
|
-
|
|
2537
|
+
if (!g[key]) {
|
|
2538
|
+
g[key] = new _CacheService(options);
|
|
2539
|
+
return g[key];
|
|
2540
|
+
}
|
|
2541
|
+
const existing = g[key];
|
|
2542
|
+
const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
|
|
2543
|
+
if (diff.length > 0) {
|
|
2544
|
+
existing.bumpSingletonDivergence();
|
|
2545
|
+
const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
|
|
2546
|
+
if (existing.options.strictSingleton) {
|
|
2547
|
+
throw new Error(`strictSingleton: ${msg}`);
|
|
2548
|
+
}
|
|
2549
|
+
(existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
|
|
2550
|
+
}
|
|
2551
|
+
return existing;
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* Keys that, if set differently on a later `create()` call, represent a
|
|
2555
|
+
* meaningful configuration divergence worth flagging (security/correctness
|
|
2556
|
+
* relevant — not cosmetic, e.g. log level).
|
|
2557
|
+
*/
|
|
2558
|
+
static DIVERGENT_KEYS = [
|
|
2559
|
+
"redisHost",
|
|
2560
|
+
"redisPort",
|
|
2561
|
+
"redisTls",
|
|
2562
|
+
"disableRedis",
|
|
2563
|
+
"redisClusterNodes",
|
|
2564
|
+
"redisSentinel",
|
|
2565
|
+
"encryptionKey",
|
|
2566
|
+
"encryptionMode",
|
|
2567
|
+
"l1MaxBytes",
|
|
2568
|
+
"l1MaxEntries",
|
|
2569
|
+
"namespace",
|
|
2570
|
+
"frozen",
|
|
2571
|
+
"adaptiveTtl",
|
|
2572
|
+
"l2WriteMode",
|
|
2573
|
+
"instanceName",
|
|
2574
|
+
"invalidationBackplane"
|
|
2575
|
+
];
|
|
2576
|
+
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
2577
|
+
static optionsDiff(a, b) {
|
|
2578
|
+
const out = [];
|
|
2579
|
+
for (const k of _CacheService.DIVERGENT_KEYS) {
|
|
2580
|
+
const av = a[k];
|
|
2581
|
+
const bv = b[k];
|
|
2582
|
+
if (av === void 0) continue;
|
|
2583
|
+
const same = JSON.stringify(av) === JSON.stringify(bv) || k === "encryptionKey" && av === bv;
|
|
2584
|
+
if (!same) out.push(String(k));
|
|
2585
|
+
}
|
|
2586
|
+
return out;
|
|
2587
|
+
}
|
|
2588
|
+
/** Increment the singleton-divergence counter (surfaced in `metrics()`). */
|
|
2589
|
+
bumpSingletonDivergence() {
|
|
2590
|
+
this.counters.singletonDivergences++;
|
|
2591
|
+
}
|
|
2592
|
+
/** Read-only view of the options the singleton was constructed with. */
|
|
2593
|
+
get options() {
|
|
2594
|
+
const o = this.opts;
|
|
2595
|
+
return {
|
|
2596
|
+
namespace: o.namespace,
|
|
2597
|
+
logger: o.logger,
|
|
2598
|
+
l1MaxBytes: o.l1MaxBytes,
|
|
2599
|
+
l1MaxEntries: o.l1MaxEntries,
|
|
2600
|
+
redisHost: o.redisHost,
|
|
2601
|
+
redisPort: o.redisPort,
|
|
2602
|
+
redisTls: o.redisTls,
|
|
2603
|
+
disableRedis: this._redisDisabled,
|
|
2604
|
+
redisClusterNodes: o.redisClusterNodes,
|
|
2605
|
+
redisSentinel: o.redisSentinel,
|
|
2606
|
+
encryptionKey: o.encryptionKey,
|
|
2607
|
+
l2WriteMode: o.l2WriteMode,
|
|
2608
|
+
instanceName: o.instanceName,
|
|
2609
|
+
frozen: o.frozen,
|
|
2610
|
+
adaptiveTtl: o.adaptiveTtl,
|
|
2611
|
+
invalidationBackplane: o.invalidationBackplane,
|
|
2612
|
+
strictSingleton: o.strictSingleton
|
|
2613
|
+
};
|
|
2522
2614
|
}
|
|
2523
2615
|
/**
|
|
2524
2616
|
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
@@ -2556,6 +2648,10 @@ var CacheService = class _CacheService {
|
|
|
2556
2648
|
nk(key) {
|
|
2557
2649
|
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
2558
2650
|
}
|
|
2651
|
+
/** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
|
|
2652
|
+
unnk(key) {
|
|
2653
|
+
return this._namespace ? key.slice(this._namespace.length + 1) : key;
|
|
2654
|
+
}
|
|
2559
2655
|
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
2560
2656
|
_jitterTtl(ttlMs) {
|
|
2561
2657
|
const j = this.opts.ttlJitterFactor;
|
|
@@ -3180,12 +3276,31 @@ var CacheService = class _CacheService {
|
|
|
3180
3276
|
}
|
|
3181
3277
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
3182
3278
|
/**
|
|
3183
|
-
*
|
|
3184
|
-
*
|
|
3279
|
+
* Distributed counter.
|
|
3280
|
+
*
|
|
3281
|
+
* When Redis is active, atomically increments the key via `INCR` and returns
|
|
3282
|
+
* the new (fleet-wide) value. On a Redis error it increments `counters.errors`
|
|
3283
|
+
* and, by default, fails OPEN — returning `0` so a caller's
|
|
3284
|
+
* `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
|
|
3285
|
+
* `failClosed: true` to re-throw the error instead, enforcing the limit even
|
|
3286
|
+
* when Redis is unavailable.
|
|
3287
|
+
*
|
|
3288
|
+
* When Redis is disabled (or `disableRedis: true`), this maintains an
|
|
3289
|
+
* IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
|
|
3290
|
+
* works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
|
|
3291
|
+
* a one-time warning is logged because rate-limiting is then per-instance, not
|
|
3292
|
+
* fleet-wide.
|
|
3185
3293
|
*/
|
|
3186
3294
|
async increment(cacheKey, ttlSeconds) {
|
|
3187
3295
|
const k = this.nk(cacheKey);
|
|
3188
3296
|
if (this._redisDisabled) {
|
|
3297
|
+
if (!this._incrementFallbackWarned) {
|
|
3298
|
+
this._incrementFallbackWarned = true;
|
|
3299
|
+
this.logger.warn(
|
|
3300
|
+
"tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
|
|
3301
|
+
{ cacheKey }
|
|
3302
|
+
);
|
|
3303
|
+
}
|
|
3189
3304
|
const now = Date.now();
|
|
3190
3305
|
const ttlMs = (ttlSeconds ?? 60) * 1e3;
|
|
3191
3306
|
const entry = this._l1Counters.get(k);
|
|
@@ -3202,7 +3317,10 @@ var CacheService = class _CacheService {
|
|
|
3202
3317
|
if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
|
|
3203
3318
|
return count;
|
|
3204
3319
|
} catch (err) {
|
|
3320
|
+
this.counters.counterErrors++;
|
|
3321
|
+
this.cb.onFailure();
|
|
3205
3322
|
this.logger.error("increment: Redis error", { cacheKey }, err);
|
|
3323
|
+
if (this.opts.failClosed) throw err;
|
|
3206
3324
|
return 0;
|
|
3207
3325
|
}
|
|
3208
3326
|
}
|
|
@@ -3376,7 +3494,8 @@ var CacheService = class _CacheService {
|
|
|
3376
3494
|
const missIndexes = [];
|
|
3377
3495
|
const missKeys = [];
|
|
3378
3496
|
for (let i = 0; i < keys.length; i++) {
|
|
3379
|
-
const
|
|
3497
|
+
const k = this.nk(keys[i]);
|
|
3498
|
+
const entry = this.l1.getEntry(k);
|
|
3380
3499
|
if (entry && entry.expiresAt > Date.now()) {
|
|
3381
3500
|
result[i] = entry.value !== void 0 ? entry.value : (0, import_msgpackr3.unpack)(entry.data);
|
|
3382
3501
|
this.counters.l1Hits++;
|
|
@@ -3385,7 +3504,71 @@ var CacheService = class _CacheService {
|
|
|
3385
3504
|
missKeys.push(keys[i]);
|
|
3386
3505
|
}
|
|
3387
3506
|
}
|
|
3507
|
+
if (missKeys.length === 0) return result;
|
|
3508
|
+
if (!this._redisDisabled) {
|
|
3509
|
+
try {
|
|
3510
|
+
const client = await this.getRedis();
|
|
3511
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
3512
|
+
const pipeline = client.multi();
|
|
3513
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
3514
|
+
const raws = await pipeline.exec();
|
|
3515
|
+
this.cb.onSuccess();
|
|
3516
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
3517
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
3518
|
+
const idx = missIndexes[j];
|
|
3519
|
+
if (raw) {
|
|
3520
|
+
let parsed;
|
|
3521
|
+
if (this.enc.isEnabled) {
|
|
3522
|
+
const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
|
|
3523
|
+
parsed = JSON.parse(decrypted);
|
|
3524
|
+
} else {
|
|
3525
|
+
parsed = JSON.parse(raw);
|
|
3526
|
+
}
|
|
3527
|
+
const k = nsKeys[j];
|
|
3528
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
3529
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
3530
|
+
this.counters.l2Hits++;
|
|
3531
|
+
result[idx] = parsed;
|
|
3532
|
+
missIndexes[j] = -1;
|
|
3533
|
+
missKeys[j] = "";
|
|
3534
|
+
}
|
|
3535
|
+
}
|
|
3536
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
3537
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
3538
|
+
missIndexes.length = 0;
|
|
3539
|
+
missKeys.length = 0;
|
|
3540
|
+
missIndexes.push(...remainingIdx);
|
|
3541
|
+
missKeys.push(...remainingKeys);
|
|
3542
|
+
if (missKeys.length === 0) return result;
|
|
3543
|
+
} catch (err) {
|
|
3544
|
+
this.cb.onFailure();
|
|
3545
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
3548
|
+
if (!this._diskDisabled) {
|
|
3549
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
3550
|
+
const k = this.nk(missKeys[j]);
|
|
3551
|
+
const diskHit = this.disk.load(k);
|
|
3552
|
+
if (diskHit !== null) {
|
|
3553
|
+
const promoted = this.l1.importEntries(
|
|
3554
|
+
[{ key: k, entry: diskHit }],
|
|
3555
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
3556
|
+
);
|
|
3557
|
+
if (promoted > 0) {
|
|
3558
|
+
const l1Check = this.l1.get(k);
|
|
3559
|
+
if (l1Check !== null) {
|
|
3560
|
+
this.counters.diskHits++;
|
|
3561
|
+
result[missIndexes[j]] = l1Check.value;
|
|
3562
|
+
missIndexes.splice(j, 1);
|
|
3563
|
+
missKeys.splice(j, 1);
|
|
3564
|
+
}
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
}
|
|
3568
|
+
if (missKeys.length === 0) return result;
|
|
3569
|
+
}
|
|
3388
3570
|
if (missKeys.length > 0) {
|
|
3571
|
+
this.counters.fetches++;
|
|
3389
3572
|
const fetched = await fetchFn(missKeys);
|
|
3390
3573
|
for (let j = 0; j < missKeys.length; j++) {
|
|
3391
3574
|
const v = fetched[missKeys[j]];
|
|
@@ -3475,7 +3658,7 @@ var CacheService = class _CacheService {
|
|
|
3475
3658
|
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
3476
3659
|
const parsed = JSON.parse(decrypted);
|
|
3477
3660
|
const remainingMs = 10 * 60 * 1e3;
|
|
3478
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
|
|
3661
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
|
|
3479
3662
|
loaded++;
|
|
3480
3663
|
;
|
|
3481
3664
|
} catch {
|
|
@@ -3751,6 +3934,10 @@ var CacheService = class _CacheService {
|
|
|
3751
3934
|
sets: { total: c.sets },
|
|
3752
3935
|
deletes: { total: c.deletes },
|
|
3753
3936
|
revalidations: { total: c.swrRevalidations },
|
|
3937
|
+
counters: {
|
|
3938
|
+
errors: c.counterErrors,
|
|
3939
|
+
singletonDivergences: c.singletonDivergences
|
|
3940
|
+
},
|
|
3754
3941
|
bloom: {
|
|
3755
3942
|
checksTotal: l1s.bloom.checks,
|
|
3756
3943
|
falsePositives: l1s.bloom.falsePositives,
|