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.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
-
CacheEncryption
|
|
3
|
-
|
|
4
|
-
} from "./chunk-F24NEZGQ.js";
|
|
2
|
+
CacheEncryption
|
|
3
|
+
} from "./chunk-FKY5R3CE.js";
|
|
5
4
|
|
|
6
5
|
// src/cache-service.ts
|
|
7
6
|
import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
|
|
8
7
|
import { pack as pack3, unpack as unpack3 } from "msgpackr";
|
|
9
8
|
import crypto2 from "crypto";
|
|
10
|
-
import
|
|
9
|
+
import os2 from "os";
|
|
11
10
|
|
|
12
11
|
// src/worker-pool.ts
|
|
13
12
|
import { Worker } from "worker_threads";
|
|
14
13
|
import { fileURLToPath } from "url";
|
|
15
14
|
import { dirname, join } from "path";
|
|
15
|
+
import os from "os";
|
|
16
16
|
import { existsSync } from "fs";
|
|
17
17
|
var _workerFile;
|
|
18
18
|
var _workerExecArgv = [];
|
|
@@ -117,12 +117,7 @@ var WorkerPool = class {
|
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
119
|
function availableCpus() {
|
|
120
|
-
|
|
121
|
-
const os2 = __require("os");
|
|
122
|
-
return os2.availableParallelism?.() ?? os2.cpus().length;
|
|
123
|
-
} catch {
|
|
124
|
-
return 2;
|
|
125
|
-
}
|
|
120
|
+
return os.availableParallelism?.() ?? os.cpus().length;
|
|
126
121
|
}
|
|
127
122
|
|
|
128
123
|
// src/cache-service.ts
|
|
@@ -204,8 +199,8 @@ var WasmBloomFilter = class {
|
|
|
204
199
|
}
|
|
205
200
|
/**
|
|
206
201
|
* Maximum safe insertions before false-positive rate exceeds ~1 %.
|
|
207
|
-
* Exact formula for k=7 hash rounds, m=100 000 bits
|
|
208
|
-
* n_max = -m * ln(1 - p^(1/k)) / k ≈
|
|
202
|
+
* Exact formula for k=7 hash rounds, m=100 000 bits, p=1%:
|
|
203
|
+
* n_max = -m * ln(1 - p^(1/k)) / k ≈ 10 434
|
|
209
204
|
*/
|
|
210
205
|
get maxCapacity() {
|
|
211
206
|
return this._maxCapacity;
|
|
@@ -474,8 +469,8 @@ var SmartMemoryCache = class {
|
|
|
474
469
|
const lim = this.getCategoryLimit(category);
|
|
475
470
|
const catCnt = this.categoryCount.get(category) ?? 0;
|
|
476
471
|
const catSz = this.categorySize.get(category) ?? 0;
|
|
477
|
-
|
|
478
|
-
|
|
472
|
+
let catOvf = catCnt >= lim.maxEntries || catSz + neededSize > lim.maxSizeBytes;
|
|
473
|
+
let glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
479
474
|
if (!catOvf && !glbOvf) {
|
|
480
475
|
const wm = this.opts.evictionWatermark ?? 0.9;
|
|
481
476
|
const entryWatermark = this.cache.size >= Math.floor(this.opts.maxEntries * wm);
|
|
@@ -485,7 +480,17 @@ var SmartMemoryCache = class {
|
|
|
485
480
|
}
|
|
486
481
|
return;
|
|
487
482
|
}
|
|
488
|
-
|
|
483
|
+
const MAX_EVICT_PASSES = 64;
|
|
484
|
+
let passes = 0;
|
|
485
|
+
do {
|
|
486
|
+
this.smartEvict(category, catOvf);
|
|
487
|
+
const lim2 = this.getCategoryLimit(category);
|
|
488
|
+
const catCnt2 = this.categoryCount.get(category) ?? 0;
|
|
489
|
+
const catSz2 = this.categorySize.get(category) ?? 0;
|
|
490
|
+
catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
|
|
491
|
+
glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
|
|
492
|
+
passes++;
|
|
493
|
+
} while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
|
|
489
494
|
}
|
|
490
495
|
score(entry, catBonus, now, key) {
|
|
491
496
|
const age = now - entry.lastAccess;
|
|
@@ -1026,17 +1031,13 @@ var SmartMemoryCache = class {
|
|
|
1026
1031
|
import fs from "fs";
|
|
1027
1032
|
import path from "path";
|
|
1028
1033
|
import crypto from "crypto";
|
|
1029
|
-
import { createRequire } from "module";
|
|
1030
1034
|
import { pack as pack2, unpack as unpack2 } from "msgpackr";
|
|
1031
1035
|
var _SqliteDB = null;
|
|
1032
1036
|
try {
|
|
1033
|
-
const
|
|
1034
|
-
_SqliteDB =
|
|
1037
|
+
const sqlite = process.getBuiltinModule("node:sqlite");
|
|
1038
|
+
_SqliteDB = sqlite?.DatabaseSync ?? null;
|
|
1035
1039
|
} catch {
|
|
1036
1040
|
}
|
|
1037
|
-
var AES_ALGO = "aes-256-gcm";
|
|
1038
|
-
var IV_BYTES = 12;
|
|
1039
|
-
var TAG_BYTES = 16;
|
|
1040
1041
|
var DISK_MAGIC = Buffer.from([68, 84, 73, 69, 82, 86, 49, 0]);
|
|
1041
1042
|
var DISK_MAGIC_V2 = Buffer.from([68, 84, 73, 69, 82, 86, 50, 0]);
|
|
1042
1043
|
var V2_HEADER_LEN = 16;
|
|
@@ -1225,54 +1226,33 @@ var DiskTier = class {
|
|
|
1225
1226
|
return this.opts.forbiddenPrefixes.some((p) => key.startsWith(p));
|
|
1226
1227
|
}
|
|
1227
1228
|
encrypt(data) {
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
const iv = crypto.randomBytes(IV_BYTES);
|
|
1231
|
-
const c = crypto.createCipheriv(AES_ALGO, key, iv);
|
|
1232
|
-
const enc = Buffer.concat([c.update(data), c.final()]);
|
|
1233
|
-
const tag = c.getAuthTag();
|
|
1234
|
-
return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
|
|
1229
|
+
if (!this.opts.encryption) return data;
|
|
1230
|
+
return Buffer.concat([DISK_MAGIC, this.opts.encryption.encryptBuffer(data)]);
|
|
1235
1231
|
}
|
|
1236
1232
|
decrypt(data) {
|
|
1237
1233
|
const mLen = DISK_MAGIC.length;
|
|
1238
1234
|
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
const iv = data.subarray(mLen, mLen + IV_BYTES);
|
|
1242
|
-
const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
|
|
1243
|
-
const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
|
|
1244
|
-
const d = crypto.createDecipheriv(AES_ALGO, key, iv);
|
|
1245
|
-
d.setAuthTag(tag);
|
|
1246
|
-
return Buffer.concat([d.update(ct), d.final()]);
|
|
1235
|
+
if (!this.opts.encryption) throw new Error("DiskTier: entry is encrypted but no encryption configured");
|
|
1236
|
+
return this.opts.encryption.decryptBuffer(data.subarray(mLen));
|
|
1247
1237
|
}
|
|
1248
1238
|
/**
|
|
1249
|
-
* V2 encryption — returns
|
|
1250
|
-
* the outer 16-byte header
|
|
1251
|
-
* Returns the buffer unchanged when no encryption
|
|
1239
|
+
* V2 encryption — returns the mode-aware encrypted payload (no magic prefix; the
|
|
1240
|
+
* magic + plaintext expiresAt live in the outer 16-byte header written by `save`).
|
|
1241
|
+
* Returns the buffer unchanged when no encryption instance is configured.
|
|
1252
1242
|
*/
|
|
1253
1243
|
encryptV2(data) {
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
const iv = crypto.randomBytes(IV_BYTES);
|
|
1257
|
-
const c = crypto.createCipheriv(AES_ALGO, key, iv);
|
|
1258
|
-
const enc = Buffer.concat([c.update(data), c.final()]);
|
|
1259
|
-
const tag = c.getAuthTag();
|
|
1260
|
-
return Buffer.concat([iv, tag, enc]);
|
|
1244
|
+
if (!this.opts.encryption) return data;
|
|
1245
|
+
return this.opts.encryption.encryptBuffer(data);
|
|
1261
1246
|
}
|
|
1262
1247
|
/**
|
|
1263
1248
|
* V2 decryption — inner payload after stripping the 16-byte header.
|
|
1264
|
-
* When
|
|
1265
|
-
*
|
|
1249
|
+
* When an encryption instance is configured the format is the mode-aware
|
|
1250
|
+
* CacheEncryption blob (IV|TAG|CT for GCM, IV|CT for CTR, key⊕data for XOR);
|
|
1251
|
+
* without one the payload is raw msgpack.
|
|
1266
1252
|
*/
|
|
1267
1253
|
decryptV2(inner) {
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
const iv = inner.subarray(0, IV_BYTES);
|
|
1271
|
-
const tag = inner.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
1272
|
-
const ct = inner.subarray(IV_BYTES + TAG_BYTES);
|
|
1273
|
-
const d = crypto.createDecipheriv(AES_ALGO, key, iv);
|
|
1274
|
-
d.setAuthTag(tag);
|
|
1275
|
-
return Buffer.concat([d.update(ct), d.final()]);
|
|
1254
|
+
if (!this.opts.encryption) return inner;
|
|
1255
|
+
return this.opts.encryption.decryptBuffer(inner);
|
|
1276
1256
|
}
|
|
1277
1257
|
// ── Public API ────────────────────────────────────────────────────────────
|
|
1278
1258
|
/**
|
|
@@ -1744,12 +1724,24 @@ var L2CircuitBreaker = class {
|
|
|
1744
1724
|
state = 0 /* CLOSED */;
|
|
1745
1725
|
failures = 0;
|
|
1746
1726
|
openedAt = 0;
|
|
1747
|
-
/**
|
|
1727
|
+
/** True while the single permitted HALF_OPEN probe is in flight. */
|
|
1728
|
+
probing = false;
|
|
1729
|
+
/**
|
|
1730
|
+
* Call before each Redis attempt. Returns false when the circuit is open.
|
|
1731
|
+
* In HALF_OPEN, only ONE probe is permitted at a time — concurrent callers
|
|
1732
|
+
* arriving while a probe is outstanding are rejected (return false) so a
|
|
1733
|
+
* recovering Redis node is not stampeded.
|
|
1734
|
+
*/
|
|
1748
1735
|
isAllowed() {
|
|
1749
1736
|
if (this.state === 0 /* CLOSED */) return true;
|
|
1750
|
-
if (this.state === 2 /* HALF_OPEN */)
|
|
1737
|
+
if (this.state === 2 /* HALF_OPEN */) {
|
|
1738
|
+
if (this.probing) return false;
|
|
1739
|
+
this.probing = true;
|
|
1740
|
+
return true;
|
|
1741
|
+
}
|
|
1751
1742
|
if (Date.now() - this.openedAt >= this.cooldownMs) {
|
|
1752
1743
|
this.state = 2 /* HALF_OPEN */;
|
|
1744
|
+
this.probing = true;
|
|
1753
1745
|
return true;
|
|
1754
1746
|
}
|
|
1755
1747
|
return false;
|
|
@@ -1757,11 +1749,13 @@ var L2CircuitBreaker = class {
|
|
|
1757
1749
|
/** Call on Redis success. */
|
|
1758
1750
|
onSuccess() {
|
|
1759
1751
|
this.failures = 0;
|
|
1752
|
+
this.probing = false;
|
|
1760
1753
|
this.state = 0 /* CLOSED */;
|
|
1761
1754
|
}
|
|
1762
1755
|
/** Call on Redis failure. */
|
|
1763
1756
|
onFailure() {
|
|
1764
1757
|
this.failures++;
|
|
1758
|
+
this.probing = false;
|
|
1765
1759
|
if (this.state === 2 /* HALF_OPEN */ || this.failures >= this.threshold) {
|
|
1766
1760
|
this.state = 1 /* OPEN */;
|
|
1767
1761
|
this.openedAt = Date.now();
|
|
@@ -1936,8 +1930,14 @@ var CacheService = class _CacheService {
|
|
|
1936
1930
|
invSkipped: 0,
|
|
1937
1931
|
oomEvictions: 0,
|
|
1938
1932
|
oomLastAt: null,
|
|
1933
|
+
/** Times `increment()` hit a Redis error (fail-open by default, or fail-closed re-throw). */
|
|
1934
|
+
counterErrors: 0,
|
|
1935
|
+
/** Times a later `create(ns)` call passed options differing from the live singleton. */
|
|
1936
|
+
singletonDivergences: 0,
|
|
1939
1937
|
startedAt: Date.now()
|
|
1940
1938
|
};
|
|
1939
|
+
/** One-time guard so the in-process increment() fallback warning fires only once. */
|
|
1940
|
+
_incrementFallbackWarned = false;
|
|
1941
1941
|
// ── Constructor (use CacheService.create() for the recommended singleton) ──
|
|
1942
1942
|
constructor(options = {}) {
|
|
1943
1943
|
const logger = options.logger ?? consoleLogger;
|
|
@@ -1963,7 +1963,7 @@ var CacheService = class _CacheService {
|
|
|
1963
1963
|
// Namespace-isolated defaults: separate dir / snapshot per namespace so
|
|
1964
1964
|
// two instances with different namespaces never share cache files.
|
|
1965
1965
|
diskCacheDir: options.diskCacheDir ?? path2.join(
|
|
1966
|
-
|
|
1966
|
+
os2.tmpdir(),
|
|
1967
1967
|
ns ? `tricache-disk-${ns}` : "tricache-disk"
|
|
1968
1968
|
),
|
|
1969
1969
|
diskMaxBytes: options.diskMaxBytes ?? 500 * 1024 * 1024,
|
|
@@ -1974,7 +1974,7 @@ var CacheService = class _CacheService {
|
|
|
1974
1974
|
disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
|
|
1975
1975
|
encryptionKey: encKeyRaw,
|
|
1976
1976
|
snapshotPath: options.snapshotPath ?? path2.join(
|
|
1977
|
-
|
|
1977
|
+
os2.tmpdir(),
|
|
1978
1978
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
1979
1979
|
),
|
|
1980
1980
|
snapshotMaxAgeMs: options.snapshotMaxAgeMs ?? DEFAULT_SNAPSHOT_MAX_AGE,
|
|
@@ -2008,7 +2008,9 @@ var CacheService = class _CacheService {
|
|
|
2008
2008
|
backplaneMaxStalenessMs: options.backplaneMaxStalenessMs ?? 5e3,
|
|
2009
2009
|
disableDisk: options.disableDisk ?? false,
|
|
2010
2010
|
redisClusterNodes: options.redisClusterNodes,
|
|
2011
|
-
redisSentinel: options.redisSentinel
|
|
2011
|
+
redisSentinel: options.redisSentinel,
|
|
2012
|
+
strictSingleton: options.strictSingleton ?? false,
|
|
2013
|
+
failClosed: options.failClosed ?? false
|
|
2012
2014
|
};
|
|
2013
2015
|
const cbThreshold = options.l2CircuitBreakerThreshold ?? 5;
|
|
2014
2016
|
const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 3e4;
|
|
@@ -2037,7 +2039,7 @@ var CacheService = class _CacheService {
|
|
|
2037
2039
|
maxBytes: this.opts.diskMaxBytes,
|
|
2038
2040
|
entryMaxBytes: this.opts.diskEntryMaxBytes,
|
|
2039
2041
|
forbiddenPrefixes,
|
|
2040
|
-
|
|
2042
|
+
encryption: this.enc.isEnabled ? this.enc : null,
|
|
2041
2043
|
logger
|
|
2042
2044
|
});
|
|
2043
2045
|
this._namespace = ns;
|
|
@@ -2068,12 +2070,12 @@ var CacheService = class _CacheService {
|
|
|
2068
2070
|
process.once("SIGINT", this._shutdownHandler);
|
|
2069
2071
|
if (this.opts.workerThreads && this.enc.isEnabled) {
|
|
2070
2072
|
try {
|
|
2071
|
-
const encRef = this.enc;
|
|
2073
|
+
const encRef = this.enc.toWorkerInit();
|
|
2072
2074
|
this._workerPool = new WorkerPool({
|
|
2073
|
-
keyBase64: encRef.
|
|
2074
|
-
mode: encRef.
|
|
2075
|
-
prevKeyBase64: encRef.
|
|
2076
|
-
prevMode: encRef.
|
|
2075
|
+
keyBase64: encRef.keyBase64,
|
|
2076
|
+
mode: encRef.mode,
|
|
2077
|
+
prevKeyBase64: encRef.prevKeyBase64,
|
|
2078
|
+
prevMode: encRef.prevMode,
|
|
2077
2079
|
size: this.opts.workerPoolSize || void 0
|
|
2078
2080
|
});
|
|
2079
2081
|
if (this._workerPool.isAvailable) {
|
|
@@ -2139,7 +2141,10 @@ var CacheService = class _CacheService {
|
|
|
2139
2141
|
* Get (or create) the process-level singleton CacheService instance.
|
|
2140
2142
|
*
|
|
2141
2143
|
* Options are only applied on first call — subsequent calls return the
|
|
2142
|
-
* existing instance regardless of options passed.
|
|
2144
|
+
* existing instance regardless of options passed. When the new options differ
|
|
2145
|
+
* from what the existing singleton was built with, this is a silent no-op by
|
|
2146
|
+
* default; set `strictSingleton: true` to throw instead, or watch the
|
|
2147
|
+
* `singletonDivergences` metric for detection.
|
|
2143
2148
|
*
|
|
2144
2149
|
* When `namespace` is set the singleton is keyed by namespace, so two calls
|
|
2145
2150
|
* with different namespaces return independent instances.
|
|
@@ -2147,8 +2152,83 @@ var CacheService = class _CacheService {
|
|
|
2147
2152
|
static create(options) {
|
|
2148
2153
|
const g = globalThis;
|
|
2149
2154
|
const key = _CacheService.globalKey(options);
|
|
2150
|
-
if (!g[key])
|
|
2151
|
-
|
|
2155
|
+
if (!g[key]) {
|
|
2156
|
+
g[key] = new _CacheService(options);
|
|
2157
|
+
return g[key];
|
|
2158
|
+
}
|
|
2159
|
+
const existing = g[key];
|
|
2160
|
+
const diff = _CacheService.optionsDiff(options ?? {}, existing.options);
|
|
2161
|
+
if (diff.length > 0) {
|
|
2162
|
+
existing.bumpSingletonDivergence();
|
|
2163
|
+
const msg = `tricache: singleton already initialised for namespace '${existing.options.namespace || "(default)"}' \u2014 ignoring divergent options: ${diff.join(", ")}`;
|
|
2164
|
+
if (existing.options.strictSingleton) {
|
|
2165
|
+
throw new Error(`strictSingleton: ${msg}`);
|
|
2166
|
+
}
|
|
2167
|
+
(existing.options.logger ?? consoleLogger).warn(msg, { divergentOptions: diff });
|
|
2168
|
+
}
|
|
2169
|
+
return existing;
|
|
2170
|
+
}
|
|
2171
|
+
/**
|
|
2172
|
+
* Keys that, if set differently on a later `create()` call, represent a
|
|
2173
|
+
* meaningful configuration divergence worth flagging (security/correctness
|
|
2174
|
+
* relevant — not cosmetic, e.g. log level).
|
|
2175
|
+
*/
|
|
2176
|
+
static DIVERGENT_KEYS = [
|
|
2177
|
+
"redisHost",
|
|
2178
|
+
"redisPort",
|
|
2179
|
+
"redisTls",
|
|
2180
|
+
"disableRedis",
|
|
2181
|
+
"redisClusterNodes",
|
|
2182
|
+
"redisSentinel",
|
|
2183
|
+
"encryptionKey",
|
|
2184
|
+
"encryptionMode",
|
|
2185
|
+
"l1MaxBytes",
|
|
2186
|
+
"l1MaxEntries",
|
|
2187
|
+
"namespace",
|
|
2188
|
+
"frozen",
|
|
2189
|
+
"adaptiveTtl",
|
|
2190
|
+
"l2WriteMode",
|
|
2191
|
+
"instanceName",
|
|
2192
|
+
"invalidationBackplane"
|
|
2193
|
+
];
|
|
2194
|
+
/** Returns the names of options that differ between `a` and the live `b`. */
|
|
2195
|
+
static optionsDiff(a, b) {
|
|
2196
|
+
const out = [];
|
|
2197
|
+
for (const k of _CacheService.DIVERGENT_KEYS) {
|
|
2198
|
+
const av = a[k];
|
|
2199
|
+
const bv = b[k];
|
|
2200
|
+
if (av === void 0) continue;
|
|
2201
|
+
const same = JSON.stringify(av) === JSON.stringify(bv) || k === "encryptionKey" && av === bv;
|
|
2202
|
+
if (!same) out.push(String(k));
|
|
2203
|
+
}
|
|
2204
|
+
return out;
|
|
2205
|
+
}
|
|
2206
|
+
/** Increment the singleton-divergence counter (surfaced in `metrics()`). */
|
|
2207
|
+
bumpSingletonDivergence() {
|
|
2208
|
+
this.counters.singletonDivergences++;
|
|
2209
|
+
}
|
|
2210
|
+
/** Read-only view of the options the singleton was constructed with. */
|
|
2211
|
+
get options() {
|
|
2212
|
+
const o = this.opts;
|
|
2213
|
+
return {
|
|
2214
|
+
namespace: o.namespace,
|
|
2215
|
+
logger: o.logger,
|
|
2216
|
+
l1MaxBytes: o.l1MaxBytes,
|
|
2217
|
+
l1MaxEntries: o.l1MaxEntries,
|
|
2218
|
+
redisHost: o.redisHost,
|
|
2219
|
+
redisPort: o.redisPort,
|
|
2220
|
+
redisTls: o.redisTls,
|
|
2221
|
+
disableRedis: this._redisDisabled,
|
|
2222
|
+
redisClusterNodes: o.redisClusterNodes,
|
|
2223
|
+
redisSentinel: o.redisSentinel,
|
|
2224
|
+
encryptionKey: o.encryptionKey,
|
|
2225
|
+
l2WriteMode: o.l2WriteMode,
|
|
2226
|
+
instanceName: o.instanceName,
|
|
2227
|
+
frozen: o.frozen,
|
|
2228
|
+
adaptiveTtl: o.adaptiveTtl,
|
|
2229
|
+
invalidationBackplane: o.invalidationBackplane,
|
|
2230
|
+
strictSingleton: o.strictSingleton
|
|
2231
|
+
};
|
|
2152
2232
|
}
|
|
2153
2233
|
/**
|
|
2154
2234
|
* Async factory — accepts a Promise that resolves to CacheOptions.
|
|
@@ -2186,6 +2266,10 @@ var CacheService = class _CacheService {
|
|
|
2186
2266
|
nk(key) {
|
|
2187
2267
|
return this._namespace ? `${this._namespace}:${key}` : key;
|
|
2188
2268
|
}
|
|
2269
|
+
/** Strip the instance namespace prefix from a namespaced key (inverse of `nk`). */
|
|
2270
|
+
unnk(key) {
|
|
2271
|
+
return this._namespace ? key.slice(this._namespace.length + 1) : key;
|
|
2272
|
+
}
|
|
2189
2273
|
/** Apply TTL jitter: multiply ttlMs by (1 ± jitterFactor). */
|
|
2190
2274
|
_jitterTtl(ttlMs) {
|
|
2191
2275
|
const j = this.opts.ttlJitterFactor;
|
|
@@ -2810,12 +2894,31 @@ var CacheService = class _CacheService {
|
|
|
2810
2894
|
}
|
|
2811
2895
|
// ── Counter (distributed rate limiting) ──────────────────────────────────
|
|
2812
2896
|
/**
|
|
2813
|
-
*
|
|
2814
|
-
*
|
|
2897
|
+
* Distributed counter.
|
|
2898
|
+
*
|
|
2899
|
+
* When Redis is active, atomically increments the key via `INCR` and returns
|
|
2900
|
+
* the new (fleet-wide) value. On a Redis error it increments `counters.errors`
|
|
2901
|
+
* and, by default, fails OPEN — returning `0` so a caller's
|
|
2902
|
+
* `if (count > LIMIT) reject()` guard does NOT reject during an outage. Set
|
|
2903
|
+
* `failClosed: true` to re-throw the error instead, enforcing the limit even
|
|
2904
|
+
* when Redis is unavailable.
|
|
2905
|
+
*
|
|
2906
|
+
* When Redis is disabled (or `disableRedis: true`), this maintains an
|
|
2907
|
+
* IN-PROCESS counter with the same TTL semantics so dev/test rate-limiting
|
|
2908
|
+
* works locally. The returned value is the local count (1, 2, 3, …), NOT 0 —
|
|
2909
|
+
* a one-time warning is logged because rate-limiting is then per-instance, not
|
|
2910
|
+
* fleet-wide.
|
|
2815
2911
|
*/
|
|
2816
2912
|
async increment(cacheKey, ttlSeconds) {
|
|
2817
2913
|
const k = this.nk(cacheKey);
|
|
2818
2914
|
if (this._redisDisabled) {
|
|
2915
|
+
if (!this._incrementFallbackWarned) {
|
|
2916
|
+
this._incrementFallbackWarned = true;
|
|
2917
|
+
this.logger.warn(
|
|
2918
|
+
"tricache: increment() using in-process counter \u2014 rate limiting is NOT fleet-wide (Redis disabled)",
|
|
2919
|
+
{ cacheKey }
|
|
2920
|
+
);
|
|
2921
|
+
}
|
|
2819
2922
|
const now = Date.now();
|
|
2820
2923
|
const ttlMs = (ttlSeconds ?? 60) * 1e3;
|
|
2821
2924
|
const entry = this._l1Counters.get(k);
|
|
@@ -2832,7 +2935,10 @@ var CacheService = class _CacheService {
|
|
|
2832
2935
|
if (count === 1 && ttlSeconds) await client.expire(k, ttlSeconds);
|
|
2833
2936
|
return count;
|
|
2834
2937
|
} catch (err) {
|
|
2938
|
+
this.counters.counterErrors++;
|
|
2939
|
+
this.cb.onFailure();
|
|
2835
2940
|
this.logger.error("increment: Redis error", { cacheKey }, err);
|
|
2941
|
+
if (this.opts.failClosed) throw err;
|
|
2836
2942
|
return 0;
|
|
2837
2943
|
}
|
|
2838
2944
|
}
|
|
@@ -3006,7 +3112,8 @@ var CacheService = class _CacheService {
|
|
|
3006
3112
|
const missIndexes = [];
|
|
3007
3113
|
const missKeys = [];
|
|
3008
3114
|
for (let i = 0; i < keys.length; i++) {
|
|
3009
|
-
const
|
|
3115
|
+
const k = this.nk(keys[i]);
|
|
3116
|
+
const entry = this.l1.getEntry(k);
|
|
3010
3117
|
if (entry && entry.expiresAt > Date.now()) {
|
|
3011
3118
|
result[i] = entry.value !== void 0 ? entry.value : unpack3(entry.data);
|
|
3012
3119
|
this.counters.l1Hits++;
|
|
@@ -3015,7 +3122,71 @@ var CacheService = class _CacheService {
|
|
|
3015
3122
|
missKeys.push(keys[i]);
|
|
3016
3123
|
}
|
|
3017
3124
|
}
|
|
3125
|
+
if (missKeys.length === 0) return result;
|
|
3126
|
+
if (!this._redisDisabled) {
|
|
3127
|
+
try {
|
|
3128
|
+
const client = await this.getRedis();
|
|
3129
|
+
const nsKeys = missKeys.map((k) => this.nk(k));
|
|
3130
|
+
const pipeline = client.multi();
|
|
3131
|
+
for (const nk of nsKeys) pipeline.get(nk);
|
|
3132
|
+
const raws = await pipeline.exec();
|
|
3133
|
+
this.cb.onSuccess();
|
|
3134
|
+
for (let j = 0; j < missKeys.length; j++) {
|
|
3135
|
+
const raw = raws[j] ? raws[j][1] : null;
|
|
3136
|
+
const idx = missIndexes[j];
|
|
3137
|
+
if (raw) {
|
|
3138
|
+
let parsed;
|
|
3139
|
+
if (this.enc.isEnabled) {
|
|
3140
|
+
const decrypted = this._workerPool && raw.length > this.opts.workerThresholdBytes ? await this._workerPool.decrypt(raw) : this.enc.decrypt(raw);
|
|
3141
|
+
parsed = JSON.parse(decrypted);
|
|
3142
|
+
} else {
|
|
3143
|
+
parsed = JSON.parse(raw);
|
|
3144
|
+
}
|
|
3145
|
+
const k = nsKeys[j];
|
|
3146
|
+
const p = priority ?? inferPriority(missKeys[j]);
|
|
3147
|
+
this.l1.set(k, parsed, this._jitterTtl((typeof ttl === "function" ? ttl(missKeys[j]) : ttl) * 1e3), p);
|
|
3148
|
+
this.counters.l2Hits++;
|
|
3149
|
+
result[idx] = parsed;
|
|
3150
|
+
missIndexes[j] = -1;
|
|
3151
|
+
missKeys[j] = "";
|
|
3152
|
+
}
|
|
3153
|
+
}
|
|
3154
|
+
const remainingIdx = missIndexes.filter((i) => i >= 0);
|
|
3155
|
+
const remainingKeys = missKeys.filter((k) => k !== "");
|
|
3156
|
+
missIndexes.length = 0;
|
|
3157
|
+
missKeys.length = 0;
|
|
3158
|
+
missIndexes.push(...remainingIdx);
|
|
3159
|
+
missKeys.push(...remainingKeys);
|
|
3160
|
+
if (missKeys.length === 0) return result;
|
|
3161
|
+
} catch (err) {
|
|
3162
|
+
this.cb.onFailure();
|
|
3163
|
+
this.logger.debug("mget: Redis unavailable, continuing to disk/fetch", { error: err.message });
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
if (!this._diskDisabled) {
|
|
3167
|
+
for (let j = missKeys.length - 1; j >= 0; j--) {
|
|
3168
|
+
const k = this.nk(missKeys[j]);
|
|
3169
|
+
const diskHit = this.disk.load(k);
|
|
3170
|
+
if (diskHit !== null) {
|
|
3171
|
+
const promoted = this.l1.importEntries(
|
|
3172
|
+
[{ key: k, entry: diskHit }],
|
|
3173
|
+
this.opts.forbiddenSnapshotPrefixes
|
|
3174
|
+
);
|
|
3175
|
+
if (promoted > 0) {
|
|
3176
|
+
const l1Check = this.l1.get(k);
|
|
3177
|
+
if (l1Check !== null) {
|
|
3178
|
+
this.counters.diskHits++;
|
|
3179
|
+
result[missIndexes[j]] = l1Check.value;
|
|
3180
|
+
missIndexes.splice(j, 1);
|
|
3181
|
+
missKeys.splice(j, 1);
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
if (missKeys.length === 0) return result;
|
|
3187
|
+
}
|
|
3018
3188
|
if (missKeys.length > 0) {
|
|
3189
|
+
this.counters.fetches++;
|
|
3019
3190
|
const fetched = await fetchFn(missKeys);
|
|
3020
3191
|
for (let j = 0; j < missKeys.length; j++) {
|
|
3021
3192
|
const v = fetched[missKeys[j]];
|
|
@@ -3105,7 +3276,7 @@ var CacheService = class _CacheService {
|
|
|
3105
3276
|
const decrypted = this.enc.isEnabled ? this.enc.decrypt(raw) : raw;
|
|
3106
3277
|
const parsed = JSON.parse(decrypted);
|
|
3107
3278
|
const remainingMs = 10 * 60 * 1e3;
|
|
3108
|
-
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
|
|
3279
|
+
this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(this.unnk(matchedKeys[i])));
|
|
3109
3280
|
loaded++;
|
|
3110
3281
|
;
|
|
3111
3282
|
} catch {
|
|
@@ -3381,6 +3552,10 @@ var CacheService = class _CacheService {
|
|
|
3381
3552
|
sets: { total: c.sets },
|
|
3382
3553
|
deletes: { total: c.deletes },
|
|
3383
3554
|
revalidations: { total: c.swrRevalidations },
|
|
3555
|
+
counters: {
|
|
3556
|
+
errors: c.counterErrors,
|
|
3557
|
+
singletonDivergences: c.singletonDivergences
|
|
3558
|
+
},
|
|
3384
3559
|
bloom: {
|
|
3385
3560
|
checksTotal: l1s.bloom.checks,
|
|
3386
3561
|
falsePositives: l1s.bloom.falsePositives,
|
|
@@ -153,6 +153,20 @@ var CacheEncryption = class {
|
|
|
153
153
|
get isEnabled() {
|
|
154
154
|
return this._key !== null;
|
|
155
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Snapshot the key material needed to spin up an off-main-thread worker pool.
|
|
158
|
+
* Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
|
|
159
|
+
* cast in cache-service.ts — the worker pool reads these via this accessor
|
|
160
|
+
* instead of reaching into underscore-prefixed internals.
|
|
161
|
+
*/
|
|
162
|
+
toWorkerInit() {
|
|
163
|
+
return {
|
|
164
|
+
keyBase64: this._key ? this._key.toString("base64") : "",
|
|
165
|
+
mode: this._mode,
|
|
166
|
+
prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
|
|
167
|
+
prevMode: this._prevMode
|
|
168
|
+
};
|
|
169
|
+
}
|
|
156
170
|
// ── String (Redis) ────────────────────────────────────────────────────────
|
|
157
171
|
/**
|
|
158
172
|
* Encrypt a string for Redis storage.
|
|
@@ -195,18 +209,18 @@ var CacheEncryption = class {
|
|
|
195
209
|
*/
|
|
196
210
|
decrypt(value) {
|
|
197
211
|
try {
|
|
198
|
-
return this._decryptWithKey(value, this._key, this._keyObj
|
|
212
|
+
return this._decryptWithKey(value, this._key, this._keyObj);
|
|
199
213
|
} catch (primaryErr) {
|
|
200
214
|
if (this._prevKey) {
|
|
201
215
|
try {
|
|
202
|
-
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj
|
|
216
|
+
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
|
|
203
217
|
} catch {
|
|
204
218
|
}
|
|
205
219
|
}
|
|
206
220
|
throw primaryErr;
|
|
207
221
|
}
|
|
208
222
|
}
|
|
209
|
-
_decryptWithKey(value, key, keyObj
|
|
223
|
+
_decryptWithKey(value, key, keyObj) {
|
|
210
224
|
if (value.startsWith(PREFIX_XOR)) {
|
|
211
225
|
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
212
226
|
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
@@ -241,8 +255,6 @@ var CacheEncryption = class {
|
|
|
241
255
|
const plain = d.update(ct);
|
|
242
256
|
d.final();
|
|
243
257
|
return plain.toString("utf8");
|
|
244
|
-
void mode2;
|
|
245
|
-
void key;
|
|
246
258
|
}
|
|
247
259
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
248
260
|
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
package/dist/serialize-worker.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tricache",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.6",
|
|
4
4
|
"description": "Three-tier Node.js cache: L1 smart RAM (adaptive LFU/LRU + Count-Min Sketch) → L1.5 NVMe disk spill → L2 Redis/Valkey. Includes AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, and thundering-herd prevention.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cache",
|
|
@@ -18,7 +18,6 @@
|
|
|
18
18
|
"nodejs"
|
|
19
19
|
],
|
|
20
20
|
"license": "MIT",
|
|
21
|
-
"packageManager": "pnpm@11.3.0",
|
|
22
21
|
"type": "module",
|
|
23
22
|
"main": "./dist/index.js",
|
|
24
23
|
"module": "./dist/index.js",
|
|
@@ -36,17 +35,9 @@
|
|
|
36
35
|
"README.md",
|
|
37
36
|
"LICENSE"
|
|
38
37
|
],
|
|
39
|
-
"scripts": {
|
|
40
|
-
"build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
|
|
41
|
-
"dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
|
|
42
|
-
"typecheck": "tsc --noEmit",
|
|
43
|
-
"test": "vitest run",
|
|
44
|
-
"test:watch": "vitest",
|
|
45
|
-
"bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
|
|
46
|
-
},
|
|
47
38
|
"dependencies": {
|
|
48
|
-
"ioredis": "
|
|
49
|
-
"msgpackr": "
|
|
39
|
+
"ioredis": "5.11.1",
|
|
40
|
+
"msgpackr": "2.0.4"
|
|
50
41
|
},
|
|
51
42
|
"devDependencies": {
|
|
52
43
|
"@types/node": "^24.0.0",
|
|
@@ -62,5 +53,14 @@
|
|
|
62
53
|
"repository": {
|
|
63
54
|
"type": "git",
|
|
64
55
|
"url": "git+https://github.com/Kareem411/TriCache.git"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --clean",
|
|
59
|
+
"postbuild": "node --input-type=module -e \"import{rmSync}from'fs';['dist/index.d.cts','dist/serialize-worker.d.cts'].forEach(f=>rmSync(f,{force:true}));\"",
|
|
60
|
+
"dev": "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
|
|
61
|
+
"typecheck": "tsc --noEmit",
|
|
62
|
+
"test": "vitest run",
|
|
63
|
+
"test:watch": "vitest",
|
|
64
|
+
"bench": "node --expose-gc --import tsx/esm bench/benchmark.ts"
|
|
65
65
|
}
|
|
66
|
-
}
|
|
66
|
+
}
|