tricache 0.7.0 → 0.7.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 +1428 -1428
- package/bin/tricache.js +8 -8
- package/dist/cache-service-5GATUYAK.js +7 -0
- package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
- package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
- package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
- package/dist/cli.cjs +113 -56
- package/dist/cli.js +3 -3
- package/dist/drizzle/index.cjs +114 -57
- package/dist/drizzle/index.d.ts +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/http/index.cjs +149 -64
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.js +38 -10
- package/dist/index.cjs +112 -55
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/nestjs/index.cjs +112 -55
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +2 -2
- package/dist/next/index.cjs +143 -63
- package/dist/next/index.d.ts +10 -6
- package/dist/next/index.js +33 -10
- package/dist/prisma/index.cjs +2 -1
- package/dist/prisma/index.d.ts +1 -1
- package/dist/prisma/index.js +2 -1
- package/dist/serialize-worker.cjs +26 -15
- package/dist/serialize-worker.js +1 -1
- package/package.json +4 -2
- package/src/cache-service.ts +3294 -3226
- package/src/cli.ts +143 -143
- package/src/compression.ts +56 -63
- package/src/disk-tier.ts +821 -821
- package/src/encryption.ts +513 -493
- package/src/http/index.ts +265 -223
- package/src/next/cache-handler.ts +268 -244
- package/src/prisma/index.ts +154 -151
- package/src/smart-memory-cache.ts +1026 -1024
- package/src/types.ts +911 -902
- package/dist/cache-service-AJASH5FX.js +0 -7
package/dist/cli.cjs
CHANGED
|
@@ -278,6 +278,8 @@ var CacheEncryption = class {
|
|
|
278
278
|
_keyObj = null;
|
|
279
279
|
// parsed KeyObject — used for all AES modes
|
|
280
280
|
_mode;
|
|
281
|
+
/** Fail-closed on invalid key material when opted in via constructor opts. */
|
|
282
|
+
_strictKeyValidation;
|
|
281
283
|
_prevKey = null;
|
|
282
284
|
_prevKeyObj = null;
|
|
283
285
|
_prevMode = "aes-256-gcm";
|
|
@@ -343,11 +345,12 @@ var CacheEncryption = class {
|
|
|
343
345
|
}
|
|
344
346
|
return out;
|
|
345
347
|
}
|
|
346
|
-
constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
|
|
348
|
+
constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
|
|
347
349
|
const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
|
|
348
350
|
const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
|
|
351
|
+
this._strictKeyValidation = opts?.strictKeyValidation ?? false;
|
|
349
352
|
this._mode = resolvedMode;
|
|
350
|
-
if (
|
|
353
|
+
if (keyBase64 === void 0 || keyBase64 === null) {
|
|
351
354
|
if (process.env.NODE_ENV === "production") {
|
|
352
355
|
logger.warn(
|
|
353
356
|
"SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
|
|
@@ -356,11 +359,17 @@ var CacheEncryption = class {
|
|
|
356
359
|
}
|
|
357
360
|
return;
|
|
358
361
|
}
|
|
362
|
+
if (keyBase64 === "") {
|
|
363
|
+
const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
|
|
364
|
+
if (this._strictKeyValidation) throw err;
|
|
365
|
+
logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
359
368
|
try {
|
|
360
369
|
const buf = Buffer.from(keyBase64, "base64");
|
|
361
370
|
const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
|
|
362
371
|
if (requiredLen > 0 && buf.length !== requiredLen) {
|
|
363
|
-
throw new Error(`${
|
|
372
|
+
throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
|
|
364
373
|
}
|
|
365
374
|
if (buf.length < 1) {
|
|
366
375
|
throw new Error("XOR key must be at least 1 byte");
|
|
@@ -384,6 +393,9 @@ var CacheEncryption = class {
|
|
|
384
393
|
logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
|
|
385
394
|
}
|
|
386
395
|
} catch (err) {
|
|
396
|
+
if (this._strictKeyValidation) {
|
|
397
|
+
throw err;
|
|
398
|
+
}
|
|
387
399
|
logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
|
|
388
400
|
}
|
|
389
401
|
if (previousKeyBase64) {
|
|
@@ -710,7 +722,6 @@ var WasmBloomFilter = class {
|
|
|
710
722
|
};
|
|
711
723
|
|
|
712
724
|
// src/smart-memory-cache.ts
|
|
713
|
-
var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
|
|
714
725
|
var LARGE_VALUE_BYTES = 16384;
|
|
715
726
|
var EVICTION_BATCH_PERCENT = 0.2;
|
|
716
727
|
var EVICTION_SAMPLE = 16;
|
|
@@ -1113,15 +1124,17 @@ var SmartMemoryCache = class {
|
|
|
1113
1124
|
entry.lastAccess = now;
|
|
1114
1125
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
1115
1126
|
const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1127
|
+
const hit = {
|
|
1128
|
+
value,
|
|
1129
|
+
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
1130
|
+
expiresAt: entry.expiresAt,
|
|
1131
|
+
ttlMs: entry.ttlMs,
|
|
1132
|
+
delta: entry.delta,
|
|
1133
|
+
fetchedAt: now,
|
|
1134
|
+
tagVersions: entry.tagVersions,
|
|
1135
|
+
setAt: entry.setAt
|
|
1136
|
+
};
|
|
1137
|
+
return hit;
|
|
1125
1138
|
}
|
|
1126
1139
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1127
1140
|
const packed = (0, import_msgpackr.pack)(data);
|
|
@@ -1576,26 +1589,25 @@ function compressBuffer(buf, algorithm) {
|
|
|
1576
1589
|
return buf;
|
|
1577
1590
|
}
|
|
1578
1591
|
function decompressBuffer(buf, algorithm = "brotli") {
|
|
1579
|
-
|
|
1592
|
+
const tryBrotli = () => {
|
|
1580
1593
|
try {
|
|
1581
|
-
return import_zlib.default.
|
|
1594
|
+
return import_zlib.default.brotliDecompressSync(buf);
|
|
1582
1595
|
} catch {
|
|
1583
|
-
|
|
1584
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1585
|
-
} catch {
|
|
1586
|
-
return buf;
|
|
1587
|
-
}
|
|
1596
|
+
return null;
|
|
1588
1597
|
}
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1592
|
-
} catch {
|
|
1598
|
+
};
|
|
1599
|
+
const tryGzip = () => {
|
|
1593
1600
|
try {
|
|
1594
1601
|
return import_zlib.default.gunzipSync(buf);
|
|
1595
1602
|
} catch {
|
|
1596
|
-
return
|
|
1603
|
+
return null;
|
|
1597
1604
|
}
|
|
1605
|
+
};
|
|
1606
|
+
const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
|
|
1607
|
+
if (result === null) {
|
|
1608
|
+
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
1598
1609
|
}
|
|
1610
|
+
return result;
|
|
1599
1611
|
}
|
|
1600
1612
|
function compressWithHeader(buf, algorithm) {
|
|
1601
1613
|
if (algorithm === "none") return buf;
|
|
@@ -2109,6 +2121,7 @@ var DiskTier = class {
|
|
|
2109
2121
|
dec = this.decrypt(raw);
|
|
2110
2122
|
} catch {
|
|
2111
2123
|
import_fs2.default.unlinkSync(filePath);
|
|
2124
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2112
2125
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2113
2126
|
purged++;
|
|
2114
2127
|
continue;
|
|
@@ -2272,6 +2285,7 @@ var DiskTier = class {
|
|
|
2272
2285
|
dec = this.decrypt(raw);
|
|
2273
2286
|
} catch {
|
|
2274
2287
|
import_fs2.default.unlinkSync(filePath);
|
|
2288
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2275
2289
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2276
2290
|
purged++;
|
|
2277
2291
|
continue;
|
|
@@ -2349,6 +2363,7 @@ return 0
|
|
|
2349
2363
|
`;
|
|
2350
2364
|
var SNAPSHOT_VERSION = 1;
|
|
2351
2365
|
var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
2366
|
+
var INDEFINITE_TTL_SECONDS = 31536e3;
|
|
2352
2367
|
var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
2353
2368
|
var DEFAULT_CATEGORY_LIMITS = {
|
|
2354
2369
|
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
@@ -2623,7 +2638,8 @@ var CacheService = class _CacheService {
|
|
|
2623
2638
|
logger,
|
|
2624
2639
|
options.encryptionMode,
|
|
2625
2640
|
options.previousEncryptionKey,
|
|
2626
|
-
options.previousEncryptionMode
|
|
2641
|
+
options.previousEncryptionMode,
|
|
2642
|
+
{ strictKeyValidation: options.strictKeyValidation ?? false }
|
|
2627
2643
|
);
|
|
2628
2644
|
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
2629
2645
|
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
@@ -2645,8 +2661,14 @@ var CacheService = class _CacheService {
|
|
|
2645
2661
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
2646
2662
|
redisPort: options.redisPort ?? 6379,
|
|
2647
2663
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2648
|
-
disableRedis: options.disableRedis ??
|
|
2664
|
+
disableRedis: options.disableRedis ?? (() => {
|
|
2665
|
+
const explicitConfig = Boolean(
|
|
2666
|
+
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2667
|
+
);
|
|
2668
|
+
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2669
|
+
})(),
|
|
2649
2670
|
encryptionKey: encKeyRaw,
|
|
2671
|
+
encryptionMode: options.encryptionMode,
|
|
2650
2672
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2651
2673
|
import_os2.default.tmpdir(),
|
|
2652
2674
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
@@ -2752,7 +2774,6 @@ var CacheService = class _CacheService {
|
|
|
2752
2774
|
}
|
|
2753
2775
|
this._shutdownHandler = () => {
|
|
2754
2776
|
if (!this._diskDisabled) this.writeSnapshot();
|
|
2755
|
-
process.exit(0);
|
|
2756
2777
|
};
|
|
2757
2778
|
process.once("SIGTERM", this._shutdownHandler);
|
|
2758
2779
|
process.once("SIGINT", this._shutdownHandler);
|
|
@@ -2931,7 +2952,10 @@ var CacheService = class _CacheService {
|
|
|
2931
2952
|
disableRedis: this._redisDisabled,
|
|
2932
2953
|
redisClusterNodes: o.redisClusterNodes,
|
|
2933
2954
|
redisSentinel: o.redisSentinel,
|
|
2934
|
-
|
|
2955
|
+
// Never surface key material through diagnostics — a JSON.stringify of
|
|
2956
|
+
// this object previously leaked the raw encryption key.
|
|
2957
|
+
encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
|
|
2958
|
+
encryptionMode: o.encryptionMode,
|
|
2935
2959
|
l2WriteMode: o.l2WriteMode,
|
|
2936
2960
|
instanceName: o.instanceName,
|
|
2937
2961
|
frozen: o.frozen,
|
|
@@ -3136,24 +3160,7 @@ var CacheService = class _CacheService {
|
|
|
3136
3160
|
for (const [id, fields] of entries) {
|
|
3137
3161
|
this._lastStreamId = id;
|
|
3138
3162
|
this.counters.streamEntriesReceived++;
|
|
3139
|
-
|
|
3140
|
-
let key = "";
|
|
3141
|
-
let src = "";
|
|
3142
|
-
let tagVersion;
|
|
3143
|
-
for (let i = 0; i < fields.length; i += 2) {
|
|
3144
|
-
const f = fields[i];
|
|
3145
|
-
const v = fields[i + 1];
|
|
3146
|
-
if (f === "op") op = v;
|
|
3147
|
-
else if (f === "key") key = v;
|
|
3148
|
-
else if (f === "src") src = v;
|
|
3149
|
-
else if (f === "tagVersion") tagVersion = parseInt(v, 10);
|
|
3150
|
-
}
|
|
3151
|
-
if (src === this.instanceId) {
|
|
3152
|
-
this.counters.invSkipped++;
|
|
3153
|
-
continue;
|
|
3154
|
-
}
|
|
3155
|
-
this.counters.invReceived++;
|
|
3156
|
-
this._applyInvalidationEvent(op, key, tagVersion);
|
|
3163
|
+
this._processStreamEntry(fields);
|
|
3157
3164
|
}
|
|
3158
3165
|
}
|
|
3159
3166
|
}
|
|
@@ -3174,6 +3181,51 @@ var CacheService = class _CacheService {
|
|
|
3174
3181
|
};
|
|
3175
3182
|
void runLoop();
|
|
3176
3183
|
}
|
|
3184
|
+
/**
|
|
3185
|
+
* Validate + apply one XREAD stream entry. `fields` is the flat ioredis
|
|
3186
|
+
* shape [name, value, name, value, …]. Mirrors the schema rules of the
|
|
3187
|
+
* pubsub path (`_handleBackplaneMessage`): op must be a known operation,
|
|
3188
|
+
* key/src must be non-empty strings, tagVersion must parse to a finite
|
|
3189
|
+
* number. Invalid entries are logged and dropped — never applied.
|
|
3190
|
+
*/
|
|
3191
|
+
/** @internal Exposed for testing. */
|
|
3192
|
+
_processStreamEntry(fields) {
|
|
3193
|
+
let op = "";
|
|
3194
|
+
let key = "";
|
|
3195
|
+
let src = "";
|
|
3196
|
+
let tagVersionRaw;
|
|
3197
|
+
for (let i = 0; i + 1 < fields.length; i += 2) {
|
|
3198
|
+
const f = fields[i];
|
|
3199
|
+
const v = fields[i + 1];
|
|
3200
|
+
if (f === "op") op = v;
|
|
3201
|
+
else if (f === "key") key = v;
|
|
3202
|
+
else if (f === "src") src = v;
|
|
3203
|
+
else if (f === "tagVersion") tagVersionRaw = v;
|
|
3204
|
+
}
|
|
3205
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
3206
|
+
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
3207
|
+
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
3208
|
+
op: String(op).slice(0, 40),
|
|
3209
|
+
key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
|
|
3210
|
+
});
|
|
3211
|
+
return;
|
|
3212
|
+
}
|
|
3213
|
+
let tagVersion;
|
|
3214
|
+
if (tagVersionRaw !== void 0) {
|
|
3215
|
+
const parsed = parseInt(tagVersionRaw, 10);
|
|
3216
|
+
if (!Number.isFinite(parsed)) {
|
|
3217
|
+
this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
|
|
3218
|
+
return;
|
|
3219
|
+
}
|
|
3220
|
+
tagVersion = parsed;
|
|
3221
|
+
}
|
|
3222
|
+
if (src === this.instanceId) {
|
|
3223
|
+
this.counters.invSkipped++;
|
|
3224
|
+
return;
|
|
3225
|
+
}
|
|
3226
|
+
this.counters.invReceived++;
|
|
3227
|
+
this._applyInvalidationEvent(op, key, tagVersion);
|
|
3228
|
+
}
|
|
3177
3229
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
3178
3230
|
if (op === "del") {
|
|
3179
3231
|
this.l1.delete(key);
|
|
@@ -3860,7 +3912,8 @@ var CacheService = class _CacheService {
|
|
|
3860
3912
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
3861
3913
|
const span = this._startSpan("tricache.set");
|
|
3862
3914
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3863
|
-
const
|
|
3915
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
3916
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
3864
3917
|
const p = priority ?? inferPriority(cacheKey);
|
|
3865
3918
|
const k = this.nk(cacheKey);
|
|
3866
3919
|
this.counters.sets++;
|
|
@@ -4702,8 +4755,9 @@ var CacheService = class _CacheService {
|
|
|
4702
4755
|
const deadline = Date.now() + acquireTimeout;
|
|
4703
4756
|
let acquired = false;
|
|
4704
4757
|
if (!this._redisDisabled) {
|
|
4758
|
+
let client = null;
|
|
4705
4759
|
try {
|
|
4706
|
-
|
|
4760
|
+
client = await this.getRedis();
|
|
4707
4761
|
while (Date.now() <= deadline) {
|
|
4708
4762
|
const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
|
|
4709
4763
|
if (res === "OK") {
|
|
@@ -4717,6 +4771,15 @@ var CacheService = class _CacheService {
|
|
|
4717
4771
|
if (!acquired) {
|
|
4718
4772
|
throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
|
|
4719
4773
|
}
|
|
4774
|
+
} catch (err) {
|
|
4775
|
+
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
4776
|
+
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4777
|
+
resourceKey,
|
|
4778
|
+
error: err.message
|
|
4779
|
+
});
|
|
4780
|
+
client = null;
|
|
4781
|
+
}
|
|
4782
|
+
if (client !== null && acquired) {
|
|
4720
4783
|
try {
|
|
4721
4784
|
return await fn();
|
|
4722
4785
|
} finally {
|
|
@@ -4732,12 +4795,6 @@ var CacheService = class _CacheService {
|
|
|
4732
4795
|
} catch {
|
|
4733
4796
|
}
|
|
4734
4797
|
}
|
|
4735
|
-
} catch (err) {
|
|
4736
|
-
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
4737
|
-
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4738
|
-
resourceKey,
|
|
4739
|
-
error: err.message
|
|
4740
|
-
});
|
|
4741
4798
|
}
|
|
4742
4799
|
}
|
|
4743
4800
|
let unlock = () => {
|
|
@@ -5086,7 +5143,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
5086
5143
|
return;
|
|
5087
5144
|
}
|
|
5088
5145
|
if (values.version || command === "version") {
|
|
5089
|
-
console.log("tricache v0.7.
|
|
5146
|
+
console.log("tricache v0.7.1");
|
|
5090
5147
|
return;
|
|
5091
5148
|
}
|
|
5092
5149
|
const redisStr = typeof values.redis === "string" ? values.redis : void 0;
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CacheService
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-EUGYR7KR.js";
|
|
4
|
+
import "./chunk-X5AXHPVD.js";
|
|
5
5
|
|
|
6
6
|
// src/cli.ts
|
|
7
7
|
import { parseArgs } from "util";
|
|
@@ -36,7 +36,7 @@ async function runCli(args = process.argv.slice(2)) {
|
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
38
|
if (values.version || command === "version") {
|
|
39
|
-
console.log("tricache v0.7.
|
|
39
|
+
console.log("tricache v0.7.1");
|
|
40
40
|
return;
|
|
41
41
|
}
|
|
42
42
|
const redisStr = typeof values.redis === "string" ? values.redis : void 0;
|
package/dist/drizzle/index.cjs
CHANGED
|
@@ -283,6 +283,8 @@ var init_encryption = __esm({
|
|
|
283
283
|
_keyObj = null;
|
|
284
284
|
// parsed KeyObject — used for all AES modes
|
|
285
285
|
_mode;
|
|
286
|
+
/** Fail-closed on invalid key material when opted in via constructor opts. */
|
|
287
|
+
_strictKeyValidation;
|
|
286
288
|
_prevKey = null;
|
|
287
289
|
_prevKeyObj = null;
|
|
288
290
|
_prevMode = "aes-256-gcm";
|
|
@@ -348,11 +350,12 @@ var init_encryption = __esm({
|
|
|
348
350
|
}
|
|
349
351
|
return out;
|
|
350
352
|
}
|
|
351
|
-
constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
|
|
353
|
+
constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
|
|
352
354
|
const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
|
|
353
355
|
const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
|
|
356
|
+
this._strictKeyValidation = opts?.strictKeyValidation ?? false;
|
|
354
357
|
this._mode = resolvedMode;
|
|
355
|
-
if (
|
|
358
|
+
if (keyBase64 === void 0 || keyBase64 === null) {
|
|
356
359
|
if (process.env.NODE_ENV === "production") {
|
|
357
360
|
logger.warn(
|
|
358
361
|
"SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
|
|
@@ -361,11 +364,17 @@ var init_encryption = __esm({
|
|
|
361
364
|
}
|
|
362
365
|
return;
|
|
363
366
|
}
|
|
367
|
+
if (keyBase64 === "") {
|
|
368
|
+
const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
|
|
369
|
+
if (this._strictKeyValidation) throw err;
|
|
370
|
+
logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
364
373
|
try {
|
|
365
374
|
const buf = Buffer.from(keyBase64, "base64");
|
|
366
375
|
const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
|
|
367
376
|
if (requiredLen > 0 && buf.length !== requiredLen) {
|
|
368
|
-
throw new Error(`${
|
|
377
|
+
throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
|
|
369
378
|
}
|
|
370
379
|
if (buf.length < 1) {
|
|
371
380
|
throw new Error("XOR key must be at least 1 byte");
|
|
@@ -389,6 +398,9 @@ var init_encryption = __esm({
|
|
|
389
398
|
logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
|
|
390
399
|
}
|
|
391
400
|
} catch (err) {
|
|
401
|
+
if (this._strictKeyValidation) {
|
|
402
|
+
throw err;
|
|
403
|
+
}
|
|
392
404
|
logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
|
|
393
405
|
}
|
|
394
406
|
if (previousKeyBase64) {
|
|
@@ -755,13 +767,12 @@ function globMatchParts(parts, first, last, key) {
|
|
|
755
767
|
}
|
|
756
768
|
return true;
|
|
757
769
|
}
|
|
758
|
-
var import_msgpackr,
|
|
770
|
+
var import_msgpackr, LARGE_VALUE_BYTES, EVICTION_BATCH_PERCENT, EVICTION_SAMPLE, EVICT_COUNT, JsBloomFilter, SKETCH_ROWS, SKETCH_WIDTH, SKETCH_MASK, SKETCH_DECAY_THRESHOLD, CountMinSketch, SmartMemoryCache;
|
|
759
771
|
var init_smart_memory_cache = __esm({
|
|
760
772
|
"src/smart-memory-cache.ts"() {
|
|
761
773
|
"use strict";
|
|
762
774
|
import_msgpackr = require("msgpackr");
|
|
763
775
|
init_bloom_filter_wasm();
|
|
764
|
-
_hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
|
|
765
776
|
LARGE_VALUE_BYTES = 16384;
|
|
766
777
|
EVICTION_BATCH_PERCENT = 0.2;
|
|
767
778
|
EVICTION_SAMPLE = 16;
|
|
@@ -1129,15 +1140,17 @@ var init_smart_memory_cache = __esm({
|
|
|
1129
1140
|
entry.lastAccess = now;
|
|
1130
1141
|
if ((entry.hits & 3) === 0) this.sketch.increment(key);
|
|
1131
1142
|
const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1143
|
+
const hit = {
|
|
1144
|
+
value,
|
|
1145
|
+
isStale: entry.staleAt !== void 0 && now > entry.staleAt,
|
|
1146
|
+
expiresAt: entry.expiresAt,
|
|
1147
|
+
ttlMs: entry.ttlMs,
|
|
1148
|
+
delta: entry.delta,
|
|
1149
|
+
fetchedAt: now,
|
|
1150
|
+
tagVersions: entry.tagVersions,
|
|
1151
|
+
setAt: entry.setAt
|
|
1152
|
+
};
|
|
1153
|
+
return hit;
|
|
1141
1154
|
}
|
|
1142
1155
|
set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
|
|
1143
1156
|
const packed = (0, import_msgpackr.pack)(data);
|
|
@@ -1584,26 +1597,25 @@ function compressBuffer(buf, algorithm) {
|
|
|
1584
1597
|
return buf;
|
|
1585
1598
|
}
|
|
1586
1599
|
function decompressBuffer(buf, algorithm = "brotli") {
|
|
1587
|
-
|
|
1600
|
+
const tryBrotli = () => {
|
|
1588
1601
|
try {
|
|
1589
|
-
return import_zlib.default.
|
|
1602
|
+
return import_zlib.default.brotliDecompressSync(buf);
|
|
1590
1603
|
} catch {
|
|
1591
|
-
|
|
1592
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1593
|
-
} catch {
|
|
1594
|
-
return buf;
|
|
1595
|
-
}
|
|
1604
|
+
return null;
|
|
1596
1605
|
}
|
|
1597
|
-
}
|
|
1598
|
-
|
|
1599
|
-
return import_zlib.default.brotliDecompressSync(buf);
|
|
1600
|
-
} catch {
|
|
1606
|
+
};
|
|
1607
|
+
const tryGzip = () => {
|
|
1601
1608
|
try {
|
|
1602
1609
|
return import_zlib.default.gunzipSync(buf);
|
|
1603
1610
|
} catch {
|
|
1604
|
-
return
|
|
1611
|
+
return null;
|
|
1605
1612
|
}
|
|
1613
|
+
};
|
|
1614
|
+
const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
|
|
1615
|
+
if (result === null) {
|
|
1616
|
+
throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
|
|
1606
1617
|
}
|
|
1618
|
+
return result;
|
|
1607
1619
|
}
|
|
1608
1620
|
function compressWithHeader(buf, algorithm) {
|
|
1609
1621
|
if (algorithm === "none") return buf;
|
|
@@ -2136,6 +2148,7 @@ var init_disk_tier = __esm({
|
|
|
2136
2148
|
dec = this.decrypt(raw);
|
|
2137
2149
|
} catch {
|
|
2138
2150
|
import_fs2.default.unlinkSync(filePath);
|
|
2151
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2139
2152
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2140
2153
|
purged++;
|
|
2141
2154
|
continue;
|
|
@@ -2299,6 +2312,7 @@ var init_disk_tier = __esm({
|
|
|
2299
2312
|
dec = this.decrypt(raw);
|
|
2300
2313
|
} catch {
|
|
2301
2314
|
import_fs2.default.unlinkSync(filePath);
|
|
2315
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
2302
2316
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
2303
2317
|
purged++;
|
|
2304
2318
|
continue;
|
|
@@ -2411,7 +2425,7 @@ function detectServerlessRuntime() {
|
|
|
2411
2425
|
if (process.env["VERCEL"]) return "Vercel";
|
|
2412
2426
|
return null;
|
|
2413
2427
|
}
|
|
2414
|
-
var import_ioredis, import_msgpackr3, import_crypto3, import_os2, import_node_v8, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, CacheService;
|
|
2428
|
+
var import_ioredis, import_msgpackr3, import_crypto3, import_os2, import_node_v8, import_fs3, import_path3, LUA_COMPARE_AND_DELETE, SNAPSHOT_VERSION, DEFAULT_SNAPSHOT_MAX_AGE, INDEFINITE_TTL_SECONDS, SNAPSHOT_MAX_FILE_BYTES, DEFAULT_CATEGORY_LIMITS, DEFAULT_FORBIDDEN_PREFIXES, DEFAULT_COUNTER_TTL_SECONDS, GLOB_REGEX_CACHE_MAX, globRegexCache, L2CircuitBreaker, LatencyTracker, GLOBAL_KEY, CacheService;
|
|
2415
2429
|
var init_cache_service = __esm({
|
|
2416
2430
|
"src/cache-service.ts"() {
|
|
2417
2431
|
"use strict";
|
|
@@ -2437,6 +2451,7 @@ return 0
|
|
|
2437
2451
|
`;
|
|
2438
2452
|
SNAPSHOT_VERSION = 1;
|
|
2439
2453
|
DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
|
|
2454
|
+
INDEFINITE_TTL_SECONDS = 31536e3;
|
|
2440
2455
|
SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
|
|
2441
2456
|
DEFAULT_CATEGORY_LIMITS = {
|
|
2442
2457
|
"default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
|
|
@@ -2673,7 +2688,8 @@ return 0
|
|
|
2673
2688
|
logger,
|
|
2674
2689
|
options.encryptionMode,
|
|
2675
2690
|
options.previousEncryptionKey,
|
|
2676
|
-
options.previousEncryptionMode
|
|
2691
|
+
options.previousEncryptionMode,
|
|
2692
|
+
{ strictKeyValidation: options.strictKeyValidation ?? false }
|
|
2677
2693
|
);
|
|
2678
2694
|
const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
|
|
2679
2695
|
const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
|
|
@@ -2695,8 +2711,14 @@ return 0
|
|
|
2695
2711
|
redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
|
|
2696
2712
|
redisPort: options.redisPort ?? 6379,
|
|
2697
2713
|
redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
|
|
2698
|
-
disableRedis: options.disableRedis ??
|
|
2714
|
+
disableRedis: options.disableRedis ?? (() => {
|
|
2715
|
+
const explicitConfig = Boolean(
|
|
2716
|
+
options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
|
|
2717
|
+
);
|
|
2718
|
+
return !explicitConfig && process.env.NODE_ENV !== "production";
|
|
2719
|
+
})(),
|
|
2699
2720
|
encryptionKey: encKeyRaw,
|
|
2721
|
+
encryptionMode: options.encryptionMode,
|
|
2700
2722
|
snapshotPath: options.snapshotPath ?? import_path3.default.join(
|
|
2701
2723
|
import_os2.default.tmpdir(),
|
|
2702
2724
|
ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
|
|
@@ -2802,7 +2824,6 @@ return 0
|
|
|
2802
2824
|
}
|
|
2803
2825
|
this._shutdownHandler = () => {
|
|
2804
2826
|
if (!this._diskDisabled) this.writeSnapshot();
|
|
2805
|
-
process.exit(0);
|
|
2806
2827
|
};
|
|
2807
2828
|
process.once("SIGTERM", this._shutdownHandler);
|
|
2808
2829
|
process.once("SIGINT", this._shutdownHandler);
|
|
@@ -2981,7 +3002,10 @@ return 0
|
|
|
2981
3002
|
disableRedis: this._redisDisabled,
|
|
2982
3003
|
redisClusterNodes: o.redisClusterNodes,
|
|
2983
3004
|
redisSentinel: o.redisSentinel,
|
|
2984
|
-
|
|
3005
|
+
// Never surface key material through diagnostics — a JSON.stringify of
|
|
3006
|
+
// this object previously leaked the raw encryption key.
|
|
3007
|
+
encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
|
|
3008
|
+
encryptionMode: o.encryptionMode,
|
|
2985
3009
|
l2WriteMode: o.l2WriteMode,
|
|
2986
3010
|
instanceName: o.instanceName,
|
|
2987
3011
|
frozen: o.frozen,
|
|
@@ -3186,24 +3210,7 @@ return 0
|
|
|
3186
3210
|
for (const [id, fields] of entries) {
|
|
3187
3211
|
this._lastStreamId = id;
|
|
3188
3212
|
this.counters.streamEntriesReceived++;
|
|
3189
|
-
|
|
3190
|
-
let key = "";
|
|
3191
|
-
let src = "";
|
|
3192
|
-
let tagVersion;
|
|
3193
|
-
for (let i = 0; i < fields.length; i += 2) {
|
|
3194
|
-
const f = fields[i];
|
|
3195
|
-
const v = fields[i + 1];
|
|
3196
|
-
if (f === "op") op = v;
|
|
3197
|
-
else if (f === "key") key = v;
|
|
3198
|
-
else if (f === "src") src = v;
|
|
3199
|
-
else if (f === "tagVersion") tagVersion = parseInt(v, 10);
|
|
3200
|
-
}
|
|
3201
|
-
if (src === this.instanceId) {
|
|
3202
|
-
this.counters.invSkipped++;
|
|
3203
|
-
continue;
|
|
3204
|
-
}
|
|
3205
|
-
this.counters.invReceived++;
|
|
3206
|
-
this._applyInvalidationEvent(op, key, tagVersion);
|
|
3213
|
+
this._processStreamEntry(fields);
|
|
3207
3214
|
}
|
|
3208
3215
|
}
|
|
3209
3216
|
}
|
|
@@ -3224,6 +3231,51 @@ return 0
|
|
|
3224
3231
|
};
|
|
3225
3232
|
void runLoop();
|
|
3226
3233
|
}
|
|
3234
|
+
/**
|
|
3235
|
+
* Validate + apply one XREAD stream entry. `fields` is the flat ioredis
|
|
3236
|
+
* shape [name, value, name, value, …]. Mirrors the schema rules of the
|
|
3237
|
+
* pubsub path (`_handleBackplaneMessage`): op must be a known operation,
|
|
3238
|
+
* key/src must be non-empty strings, tagVersion must parse to a finite
|
|
3239
|
+
* number. Invalid entries are logged and dropped — never applied.
|
|
3240
|
+
*/
|
|
3241
|
+
/** @internal Exposed for testing. */
|
|
3242
|
+
_processStreamEntry(fields) {
|
|
3243
|
+
let op = "";
|
|
3244
|
+
let key = "";
|
|
3245
|
+
let src = "";
|
|
3246
|
+
let tagVersionRaw;
|
|
3247
|
+
for (let i = 0; i + 1 < fields.length; i += 2) {
|
|
3248
|
+
const f = fields[i];
|
|
3249
|
+
const v = fields[i + 1];
|
|
3250
|
+
if (f === "op") op = v;
|
|
3251
|
+
else if (f === "key") key = v;
|
|
3252
|
+
else if (f === "src") src = v;
|
|
3253
|
+
else if (f === "tagVersion") tagVersionRaw = v;
|
|
3254
|
+
}
|
|
3255
|
+
const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
|
|
3256
|
+
if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
|
|
3257
|
+
this.logger.warn("Backplane: rejected invalid stream entry", {
|
|
3258
|
+
op: String(op).slice(0, 40),
|
|
3259
|
+
key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
|
|
3260
|
+
});
|
|
3261
|
+
return;
|
|
3262
|
+
}
|
|
3263
|
+
let tagVersion;
|
|
3264
|
+
if (tagVersionRaw !== void 0) {
|
|
3265
|
+
const parsed = parseInt(tagVersionRaw, 10);
|
|
3266
|
+
if (!Number.isFinite(parsed)) {
|
|
3267
|
+
this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
|
|
3268
|
+
return;
|
|
3269
|
+
}
|
|
3270
|
+
tagVersion = parsed;
|
|
3271
|
+
}
|
|
3272
|
+
if (src === this.instanceId) {
|
|
3273
|
+
this.counters.invSkipped++;
|
|
3274
|
+
return;
|
|
3275
|
+
}
|
|
3276
|
+
this.counters.invReceived++;
|
|
3277
|
+
this._applyInvalidationEvent(op, key, tagVersion);
|
|
3278
|
+
}
|
|
3227
3279
|
_applyInvalidationEvent(op, key, tagVersion) {
|
|
3228
3280
|
if (op === "del") {
|
|
3229
3281
|
this.l1.delete(key);
|
|
@@ -3910,7 +3962,8 @@ return 0
|
|
|
3910
3962
|
async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
|
|
3911
3963
|
const span = this._startSpan("tricache.set");
|
|
3912
3964
|
if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
|
|
3913
|
-
const
|
|
3965
|
+
const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
|
|
3966
|
+
const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
|
|
3914
3967
|
const p = priority ?? inferPriority(cacheKey);
|
|
3915
3968
|
const k = this.nk(cacheKey);
|
|
3916
3969
|
this.counters.sets++;
|
|
@@ -4752,8 +4805,9 @@ return 0
|
|
|
4752
4805
|
const deadline = Date.now() + acquireTimeout;
|
|
4753
4806
|
let acquired = false;
|
|
4754
4807
|
if (!this._redisDisabled) {
|
|
4808
|
+
let client = null;
|
|
4755
4809
|
try {
|
|
4756
|
-
|
|
4810
|
+
client = await this.getRedis();
|
|
4757
4811
|
while (Date.now() <= deadline) {
|
|
4758
4812
|
const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
|
|
4759
4813
|
if (res === "OK") {
|
|
@@ -4767,6 +4821,15 @@ return 0
|
|
|
4767
4821
|
if (!acquired) {
|
|
4768
4822
|
throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
|
|
4769
4823
|
}
|
|
4824
|
+
} catch (err) {
|
|
4825
|
+
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
4826
|
+
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4827
|
+
resourceKey,
|
|
4828
|
+
error: err.message
|
|
4829
|
+
});
|
|
4830
|
+
client = null;
|
|
4831
|
+
}
|
|
4832
|
+
if (client !== null && acquired) {
|
|
4770
4833
|
try {
|
|
4771
4834
|
return await fn();
|
|
4772
4835
|
} finally {
|
|
@@ -4782,12 +4845,6 @@ return 0
|
|
|
4782
4845
|
} catch {
|
|
4783
4846
|
}
|
|
4784
4847
|
}
|
|
4785
|
-
} catch (err) {
|
|
4786
|
-
if (err.message.startsWith("Failed to acquire lock")) throw err;
|
|
4787
|
-
this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
|
|
4788
|
-
resourceKey,
|
|
4789
|
-
error: err.message
|
|
4790
|
-
});
|
|
4791
4848
|
}
|
|
4792
4849
|
}
|
|
4793
4850
|
let unlock = () => {
|