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.
Files changed (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
package/dist/index.cjs CHANGED
@@ -290,6 +290,8 @@ var CacheEncryption = class {
290
290
  _keyObj = null;
291
291
  // parsed KeyObject — used for all AES modes
292
292
  _mode;
293
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
294
+ _strictKeyValidation;
293
295
  _prevKey = null;
294
296
  _prevKeyObj = null;
295
297
  _prevMode = "aes-256-gcm";
@@ -355,11 +357,12 @@ var CacheEncryption = class {
355
357
  }
356
358
  return out;
357
359
  }
358
- constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
360
+ constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
359
361
  const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
360
362
  const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
363
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
361
364
  this._mode = resolvedMode;
362
- if (!keyBase64) {
365
+ if (keyBase64 === void 0 || keyBase64 === null) {
363
366
  if (process.env.NODE_ENV === "production") {
364
367
  logger.warn(
365
368
  "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
@@ -368,11 +371,17 @@ var CacheEncryption = class {
368
371
  }
369
372
  return;
370
373
  }
374
+ if (keyBase64 === "") {
375
+ const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
376
+ if (this._strictKeyValidation) throw err;
377
+ logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
378
+ return;
379
+ }
371
380
  try {
372
381
  const buf = Buffer.from(keyBase64, "base64");
373
382
  const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
374
383
  if (requiredLen > 0 && buf.length !== requiredLen) {
375
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
384
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
376
385
  }
377
386
  if (buf.length < 1) {
378
387
  throw new Error("XOR key must be at least 1 byte");
@@ -396,6 +405,9 @@ var CacheEncryption = class {
396
405
  logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
397
406
  }
398
407
  } catch (err) {
408
+ if (this._strictKeyValidation) {
409
+ throw err;
410
+ }
399
411
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
400
412
  }
401
413
  if (previousKeyBase64) {
@@ -722,7 +734,6 @@ var WasmBloomFilter = class {
722
734
  };
723
735
 
724
736
  // src/smart-memory-cache.ts
725
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
726
737
  var LARGE_VALUE_BYTES = 16384;
727
738
  var EVICTION_BATCH_PERCENT = 0.2;
728
739
  var EVICTION_SAMPLE = 16;
@@ -1125,15 +1136,17 @@ var SmartMemoryCache = class {
1125
1136
  entry.lastAccess = now;
1126
1137
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
1127
1138
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
1128
- _hit.value = value;
1129
- _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
1130
- _hit.expiresAt = entry.expiresAt;
1131
- _hit.ttlMs = entry.ttlMs;
1132
- _hit.delta = entry.delta;
1133
- _hit.fetchedAt = now;
1134
- _hit.tagVersions = entry.tagVersions;
1135
- _hit.setAt = entry.setAt;
1136
- return _hit;
1139
+ const hit = {
1140
+ value,
1141
+ isStale: entry.staleAt !== void 0 && now > entry.staleAt,
1142
+ expiresAt: entry.expiresAt,
1143
+ ttlMs: entry.ttlMs,
1144
+ delta: entry.delta,
1145
+ fetchedAt: now,
1146
+ tagVersions: entry.tagVersions,
1147
+ setAt: entry.setAt
1148
+ };
1149
+ return hit;
1137
1150
  }
1138
1151
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1139
1152
  const packed = (0, import_msgpackr.pack)(data);
@@ -1588,26 +1601,25 @@ function compressBuffer(buf, algorithm) {
1588
1601
  return buf;
1589
1602
  }
1590
1603
  function decompressBuffer(buf, algorithm = "brotli") {
1591
- if (algorithm === "gzip") {
1604
+ const tryBrotli = () => {
1592
1605
  try {
1593
- return import_zlib.default.gunzipSync(buf);
1606
+ return import_zlib.default.brotliDecompressSync(buf);
1594
1607
  } catch {
1595
- try {
1596
- return import_zlib.default.brotliDecompressSync(buf);
1597
- } catch {
1598
- return buf;
1599
- }
1608
+ return null;
1600
1609
  }
1601
- }
1602
- try {
1603
- return import_zlib.default.brotliDecompressSync(buf);
1604
- } catch {
1610
+ };
1611
+ const tryGzip = () => {
1605
1612
  try {
1606
1613
  return import_zlib.default.gunzipSync(buf);
1607
1614
  } catch {
1608
- return buf;
1615
+ return null;
1609
1616
  }
1617
+ };
1618
+ const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
1619
+ if (result === null) {
1620
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1610
1621
  }
1622
+ return result;
1611
1623
  }
1612
1624
  function compressWithHeader(buf, algorithm) {
1613
1625
  if (algorithm === "none") return buf;
@@ -2121,6 +2133,7 @@ var DiskTier = class {
2121
2133
  dec = this.decrypt(raw);
2122
2134
  } catch {
2123
2135
  import_fs2.default.unlinkSync(filePath);
2136
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2124
2137
  this.fileCount = Math.max(0, this.fileCount - 1);
2125
2138
  purged++;
2126
2139
  continue;
@@ -2284,6 +2297,7 @@ var DiskTier = class {
2284
2297
  dec = this.decrypt(raw);
2285
2298
  } catch {
2286
2299
  import_fs2.default.unlinkSync(filePath);
2300
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2287
2301
  this.fileCount = Math.max(0, this.fileCount - 1);
2288
2302
  purged++;
2289
2303
  continue;
@@ -2361,6 +2375,7 @@ return 0
2361
2375
  `;
2362
2376
  var SNAPSHOT_VERSION = 1;
2363
2377
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
2378
+ var INDEFINITE_TTL_SECONDS = 31536e3;
2364
2379
  var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
2365
2380
  var DEFAULT_CATEGORY_LIMITS = {
2366
2381
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
@@ -2635,7 +2650,8 @@ var CacheService = class _CacheService {
2635
2650
  logger,
2636
2651
  options.encryptionMode,
2637
2652
  options.previousEncryptionKey,
2638
- options.previousEncryptionMode
2653
+ options.previousEncryptionMode,
2654
+ { strictKeyValidation: options.strictKeyValidation ?? false }
2639
2655
  );
2640
2656
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2641
2657
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
@@ -2657,8 +2673,14 @@ var CacheService = class _CacheService {
2657
2673
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2658
2674
  redisPort: options.redisPort ?? 6379,
2659
2675
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2660
- disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
2676
+ disableRedis: options.disableRedis ?? (() => {
2677
+ const explicitConfig = Boolean(
2678
+ options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2679
+ );
2680
+ return !explicitConfig && process.env.NODE_ENV !== "production";
2681
+ })(),
2661
2682
  encryptionKey: encKeyRaw,
2683
+ encryptionMode: options.encryptionMode,
2662
2684
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2663
2685
  import_os2.default.tmpdir(),
2664
2686
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
@@ -2764,7 +2786,6 @@ var CacheService = class _CacheService {
2764
2786
  }
2765
2787
  this._shutdownHandler = () => {
2766
2788
  if (!this._diskDisabled) this.writeSnapshot();
2767
- process.exit(0);
2768
2789
  };
2769
2790
  process.once("SIGTERM", this._shutdownHandler);
2770
2791
  process.once("SIGINT", this._shutdownHandler);
@@ -2943,7 +2964,10 @@ var CacheService = class _CacheService {
2943
2964
  disableRedis: this._redisDisabled,
2944
2965
  redisClusterNodes: o.redisClusterNodes,
2945
2966
  redisSentinel: o.redisSentinel,
2946
- encryptionKey: o.encryptionKey,
2967
+ // Never surface key material through diagnostics — a JSON.stringify of
2968
+ // this object previously leaked the raw encryption key.
2969
+ encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
2970
+ encryptionMode: o.encryptionMode,
2947
2971
  l2WriteMode: o.l2WriteMode,
2948
2972
  instanceName: o.instanceName,
2949
2973
  frozen: o.frozen,
@@ -3148,24 +3172,7 @@ var CacheService = class _CacheService {
3148
3172
  for (const [id, fields] of entries) {
3149
3173
  this._lastStreamId = id;
3150
3174
  this.counters.streamEntriesReceived++;
3151
- let op = "";
3152
- let key = "";
3153
- let src = "";
3154
- let tagVersion;
3155
- for (let i = 0; i < fields.length; i += 2) {
3156
- const f = fields[i];
3157
- const v = fields[i + 1];
3158
- if (f === "op") op = v;
3159
- else if (f === "key") key = v;
3160
- else if (f === "src") src = v;
3161
- else if (f === "tagVersion") tagVersion = parseInt(v, 10);
3162
- }
3163
- if (src === this.instanceId) {
3164
- this.counters.invSkipped++;
3165
- continue;
3166
- }
3167
- this.counters.invReceived++;
3168
- this._applyInvalidationEvent(op, key, tagVersion);
3175
+ this._processStreamEntry(fields);
3169
3176
  }
3170
3177
  }
3171
3178
  }
@@ -3186,6 +3193,51 @@ var CacheService = class _CacheService {
3186
3193
  };
3187
3194
  void runLoop();
3188
3195
  }
3196
+ /**
3197
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
3198
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
3199
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
3200
+ * key/src must be non-empty strings, tagVersion must parse to a finite
3201
+ * number. Invalid entries are logged and dropped — never applied.
3202
+ */
3203
+ /** @internal Exposed for testing. */
3204
+ _processStreamEntry(fields) {
3205
+ let op = "";
3206
+ let key = "";
3207
+ let src = "";
3208
+ let tagVersionRaw;
3209
+ for (let i = 0; i + 1 < fields.length; i += 2) {
3210
+ const f = fields[i];
3211
+ const v = fields[i + 1];
3212
+ if (f === "op") op = v;
3213
+ else if (f === "key") key = v;
3214
+ else if (f === "src") src = v;
3215
+ else if (f === "tagVersion") tagVersionRaw = v;
3216
+ }
3217
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
3218
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
3219
+ this.logger.warn("Backplane: rejected invalid stream entry", {
3220
+ op: String(op).slice(0, 40),
3221
+ key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
3222
+ });
3223
+ return;
3224
+ }
3225
+ let tagVersion;
3226
+ if (tagVersionRaw !== void 0) {
3227
+ const parsed = parseInt(tagVersionRaw, 10);
3228
+ if (!Number.isFinite(parsed)) {
3229
+ this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
3230
+ return;
3231
+ }
3232
+ tagVersion = parsed;
3233
+ }
3234
+ if (src === this.instanceId) {
3235
+ this.counters.invSkipped++;
3236
+ return;
3237
+ }
3238
+ this.counters.invReceived++;
3239
+ this._applyInvalidationEvent(op, key, tagVersion);
3240
+ }
3189
3241
  _applyInvalidationEvent(op, key, tagVersion) {
3190
3242
  if (op === "del") {
3191
3243
  this.l1.delete(key);
@@ -3872,7 +3924,8 @@ var CacheService = class _CacheService {
3872
3924
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3873
3925
  const span = this._startSpan("tricache.set");
3874
3926
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3875
- const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3927
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3928
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3876
3929
  const p = priority ?? inferPriority(cacheKey);
3877
3930
  const k = this.nk(cacheKey);
3878
3931
  this.counters.sets++;
@@ -4714,8 +4767,9 @@ var CacheService = class _CacheService {
4714
4767
  const deadline = Date.now() + acquireTimeout;
4715
4768
  let acquired = false;
4716
4769
  if (!this._redisDisabled) {
4770
+ let client = null;
4717
4771
  try {
4718
- const client = await this.getRedis();
4772
+ client = await this.getRedis();
4719
4773
  while (Date.now() <= deadline) {
4720
4774
  const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4721
4775
  if (res === "OK") {
@@ -4729,6 +4783,15 @@ var CacheService = class _CacheService {
4729
4783
  if (!acquired) {
4730
4784
  throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4731
4785
  }
4786
+ } catch (err) {
4787
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4788
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4789
+ resourceKey,
4790
+ error: err.message
4791
+ });
4792
+ client = null;
4793
+ }
4794
+ if (client !== null && acquired) {
4732
4795
  try {
4733
4796
  return await fn();
4734
4797
  } finally {
@@ -4744,12 +4807,6 @@ var CacheService = class _CacheService {
4744
4807
  } catch {
4745
4808
  }
4746
4809
  }
4747
- } catch (err) {
4748
- if (err.message.startsWith("Failed to acquire lock")) throw err;
4749
- this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4750
- resourceKey,
4751
- error: err.message
4752
- });
4753
4810
  }
4754
4811
  }
4755
4812
  let unlock = () => {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as CategoryLimit, S as SmartCacheEntry, E as EvictionReason, I as ILogger, b as CacheHit, c as CachePriority, d as CacheEncryption, D as DiskCacheEntry } from './cache-service-BblHuF3i.js';
2
- export { e as CacheMetrics, f as CacheOptions, g as CachePingResult, C as CacheService, h as EncryptionMode, i as ICacheBatchObservableCallback, j as ICacheCounter, k as ICacheMeter, l as ICacheObservableGauge, m as ICacheSpan, n as ICacheTracer, L as LockOptions, W as WrapOptions, o as consoleLogger } from './cache-service-BblHuF3i.js';
1
+ import { a as CategoryLimit, S as SmartCacheEntry, E as EvictionReason, I as ILogger, b as CacheHit, c as CachePriority, d as CacheEncryption, D as DiskCacheEntry } from './cache-service-D8tIXmzb.js';
2
+ export { e as CacheMetrics, f as CacheOptions, g as CachePingResult, C as CacheService, h as EncryptionMode, i as ICacheBatchObservableCallback, j as ICacheCounter, k as ICacheMeter, l as ICacheObservableGauge, m as ICacheSpan, n as ICacheTracer, L as LockOptions, W as WrapOptions, o as consoleLogger } from './cache-service-D8tIXmzb.js';
3
3
 
4
4
  /**
5
5
  * SmartMemoryCache — L1 in-process cache with adaptive LFU/LRU hybrid eviction.
package/dist/index.js CHANGED
@@ -4,12 +4,12 @@ import {
4
4
  DiskTier,
5
5
  SmartMemoryCache,
6
6
  WasmBloomFilter
7
- } from "./chunk-3XQUQBOZ.js";
7
+ } from "./chunk-EUGYR7KR.js";
8
8
  import {
9
9
  CacheEncryption,
10
10
  CachePriority,
11
11
  consoleLogger
12
- } from "./chunk-PFB5FMEY.js";
12
+ } from "./chunk-X5AXHPVD.js";
13
13
  export {
14
14
  CacheEncryption,
15
15
  CachePriority,
@@ -283,6 +283,8 @@ var CacheEncryption = class {
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 CacheEncryption = class {
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 (!keyBase64) {
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 CacheEncryption = class {
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(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
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 CacheEncryption = class {
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) {
@@ -715,7 +727,6 @@ var WasmBloomFilter = class {
715
727
  };
716
728
 
717
729
  // src/smart-memory-cache.ts
718
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
719
730
  var LARGE_VALUE_BYTES = 16384;
720
731
  var EVICTION_BATCH_PERCENT = 0.2;
721
732
  var EVICTION_SAMPLE = 16;
@@ -1118,15 +1129,17 @@ var SmartMemoryCache = class {
1118
1129
  entry.lastAccess = now;
1119
1130
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
1120
1131
  const value = entry.value !== void 0 ? entry.value : (0, import_msgpackr.unpack)(entry.data);
1121
- _hit.value = value;
1122
- _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
1123
- _hit.expiresAt = entry.expiresAt;
1124
- _hit.ttlMs = entry.ttlMs;
1125
- _hit.delta = entry.delta;
1126
- _hit.fetchedAt = now;
1127
- _hit.tagVersions = entry.tagVersions;
1128
- _hit.setAt = entry.setAt;
1129
- return _hit;
1132
+ const hit = {
1133
+ value,
1134
+ isStale: entry.staleAt !== void 0 && now > entry.staleAt,
1135
+ expiresAt: entry.expiresAt,
1136
+ ttlMs: entry.ttlMs,
1137
+ delta: entry.delta,
1138
+ fetchedAt: now,
1139
+ tagVersions: entry.tagVersions,
1140
+ setAt: entry.setAt
1141
+ };
1142
+ return hit;
1130
1143
  }
1131
1144
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
1132
1145
  const packed = (0, import_msgpackr.pack)(data);
@@ -1581,26 +1594,25 @@ function compressBuffer(buf, algorithm) {
1581
1594
  return buf;
1582
1595
  }
1583
1596
  function decompressBuffer(buf, algorithm = "brotli") {
1584
- if (algorithm === "gzip") {
1597
+ const tryBrotli = () => {
1585
1598
  try {
1586
- return import_zlib.default.gunzipSync(buf);
1599
+ return import_zlib.default.brotliDecompressSync(buf);
1587
1600
  } catch {
1588
- try {
1589
- return import_zlib.default.brotliDecompressSync(buf);
1590
- } catch {
1591
- return buf;
1592
- }
1601
+ return null;
1593
1602
  }
1594
- }
1595
- try {
1596
- return import_zlib.default.brotliDecompressSync(buf);
1597
- } catch {
1603
+ };
1604
+ const tryGzip = () => {
1598
1605
  try {
1599
1606
  return import_zlib.default.gunzipSync(buf);
1600
1607
  } catch {
1601
- return buf;
1608
+ return null;
1602
1609
  }
1610
+ };
1611
+ const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
1612
+ if (result === null) {
1613
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1603
1614
  }
1615
+ return result;
1604
1616
  }
1605
1617
  function compressWithHeader(buf, algorithm) {
1606
1618
  if (algorithm === "none") return buf;
@@ -2114,6 +2126,7 @@ var DiskTier = class {
2114
2126
  dec = this.decrypt(raw);
2115
2127
  } catch {
2116
2128
  import_fs2.default.unlinkSync(filePath);
2129
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2117
2130
  this.fileCount = Math.max(0, this.fileCount - 1);
2118
2131
  purged++;
2119
2132
  continue;
@@ -2277,6 +2290,7 @@ var DiskTier = class {
2277
2290
  dec = this.decrypt(raw);
2278
2291
  } catch {
2279
2292
  import_fs2.default.unlinkSync(filePath);
2293
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
2280
2294
  this.fileCount = Math.max(0, this.fileCount - 1);
2281
2295
  purged++;
2282
2296
  continue;
@@ -2354,6 +2368,7 @@ return 0
2354
2368
  `;
2355
2369
  var SNAPSHOT_VERSION = 1;
2356
2370
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
2371
+ var INDEFINITE_TTL_SECONDS = 31536e3;
2357
2372
  var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
2358
2373
  var DEFAULT_CATEGORY_LIMITS = {
2359
2374
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
@@ -2628,7 +2643,8 @@ var CacheService = class _CacheService {
2628
2643
  logger,
2629
2644
  options.encryptionMode,
2630
2645
  options.previousEncryptionKey,
2631
- options.previousEncryptionMode
2646
+ options.previousEncryptionMode,
2647
+ { strictKeyValidation: options.strictKeyValidation ?? false }
2632
2648
  );
2633
2649
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2634
2650
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
@@ -2650,8 +2666,14 @@ var CacheService = class _CacheService {
2650
2666
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2651
2667
  redisPort: options.redisPort ?? 6379,
2652
2668
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2653
- disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
2669
+ disableRedis: options.disableRedis ?? (() => {
2670
+ const explicitConfig = Boolean(
2671
+ options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2672
+ );
2673
+ return !explicitConfig && process.env.NODE_ENV !== "production";
2674
+ })(),
2654
2675
  encryptionKey: encKeyRaw,
2676
+ encryptionMode: options.encryptionMode,
2655
2677
  snapshotPath: options.snapshotPath ?? import_path3.default.join(
2656
2678
  import_os2.default.tmpdir(),
2657
2679
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
@@ -2757,7 +2779,6 @@ var CacheService = class _CacheService {
2757
2779
  }
2758
2780
  this._shutdownHandler = () => {
2759
2781
  if (!this._diskDisabled) this.writeSnapshot();
2760
- process.exit(0);
2761
2782
  };
2762
2783
  process.once("SIGTERM", this._shutdownHandler);
2763
2784
  process.once("SIGINT", this._shutdownHandler);
@@ -2936,7 +2957,10 @@ var CacheService = class _CacheService {
2936
2957
  disableRedis: this._redisDisabled,
2937
2958
  redisClusterNodes: o.redisClusterNodes,
2938
2959
  redisSentinel: o.redisSentinel,
2939
- encryptionKey: o.encryptionKey,
2960
+ // Never surface key material through diagnostics — a JSON.stringify of
2961
+ // this object previously leaked the raw encryption key.
2962
+ encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
2963
+ encryptionMode: o.encryptionMode,
2940
2964
  l2WriteMode: o.l2WriteMode,
2941
2965
  instanceName: o.instanceName,
2942
2966
  frozen: o.frozen,
@@ -3141,24 +3165,7 @@ var CacheService = class _CacheService {
3141
3165
  for (const [id, fields] of entries) {
3142
3166
  this._lastStreamId = id;
3143
3167
  this.counters.streamEntriesReceived++;
3144
- let op = "";
3145
- let key = "";
3146
- let src = "";
3147
- let tagVersion;
3148
- for (let i = 0; i < fields.length; i += 2) {
3149
- const f = fields[i];
3150
- const v = fields[i + 1];
3151
- if (f === "op") op = v;
3152
- else if (f === "key") key = v;
3153
- else if (f === "src") src = v;
3154
- else if (f === "tagVersion") tagVersion = parseInt(v, 10);
3155
- }
3156
- if (src === this.instanceId) {
3157
- this.counters.invSkipped++;
3158
- continue;
3159
- }
3160
- this.counters.invReceived++;
3161
- this._applyInvalidationEvent(op, key, tagVersion);
3168
+ this._processStreamEntry(fields);
3162
3169
  }
3163
3170
  }
3164
3171
  }
@@ -3179,6 +3186,51 @@ var CacheService = class _CacheService {
3179
3186
  };
3180
3187
  void runLoop();
3181
3188
  }
3189
+ /**
3190
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
3191
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
3192
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
3193
+ * key/src must be non-empty strings, tagVersion must parse to a finite
3194
+ * number. Invalid entries are logged and dropped — never applied.
3195
+ */
3196
+ /** @internal Exposed for testing. */
3197
+ _processStreamEntry(fields) {
3198
+ let op = "";
3199
+ let key = "";
3200
+ let src = "";
3201
+ let tagVersionRaw;
3202
+ for (let i = 0; i + 1 < fields.length; i += 2) {
3203
+ const f = fields[i];
3204
+ const v = fields[i + 1];
3205
+ if (f === "op") op = v;
3206
+ else if (f === "key") key = v;
3207
+ else if (f === "src") src = v;
3208
+ else if (f === "tagVersion") tagVersionRaw = v;
3209
+ }
3210
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
3211
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
3212
+ this.logger.warn("Backplane: rejected invalid stream entry", {
3213
+ op: String(op).slice(0, 40),
3214
+ key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
3215
+ });
3216
+ return;
3217
+ }
3218
+ let tagVersion;
3219
+ if (tagVersionRaw !== void 0) {
3220
+ const parsed = parseInt(tagVersionRaw, 10);
3221
+ if (!Number.isFinite(parsed)) {
3222
+ this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
3223
+ return;
3224
+ }
3225
+ tagVersion = parsed;
3226
+ }
3227
+ if (src === this.instanceId) {
3228
+ this.counters.invSkipped++;
3229
+ return;
3230
+ }
3231
+ this.counters.invReceived++;
3232
+ this._applyInvalidationEvent(op, key, tagVersion);
3233
+ }
3182
3234
  _applyInvalidationEvent(op, key, tagVersion) {
3183
3235
  if (op === "del") {
3184
3236
  this.l1.delete(key);
@@ -3865,7 +3917,8 @@ var CacheService = class _CacheService {
3865
3917
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3866
3918
  const span = this._startSpan("tricache.set");
3867
3919
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3868
- const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3920
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3921
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3869
3922
  const p = priority ?? inferPriority(cacheKey);
3870
3923
  const k = this.nk(cacheKey);
3871
3924
  this.counters.sets++;
@@ -4707,8 +4760,9 @@ var CacheService = class _CacheService {
4707
4760
  const deadline = Date.now() + acquireTimeout;
4708
4761
  let acquired = false;
4709
4762
  if (!this._redisDisabled) {
4763
+ let client = null;
4710
4764
  try {
4711
- const client = await this.getRedis();
4765
+ client = await this.getRedis();
4712
4766
  while (Date.now() <= deadline) {
4713
4767
  const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4714
4768
  if (res === "OK") {
@@ -4722,6 +4776,15 @@ var CacheService = class _CacheService {
4722
4776
  if (!acquired) {
4723
4777
  throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4724
4778
  }
4779
+ } catch (err) {
4780
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4781
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4782
+ resourceKey,
4783
+ error: err.message
4784
+ });
4785
+ client = null;
4786
+ }
4787
+ if (client !== null && acquired) {
4725
4788
  try {
4726
4789
  return await fn();
4727
4790
  } finally {
@@ -4737,12 +4800,6 @@ var CacheService = class _CacheService {
4737
4800
  } catch {
4738
4801
  }
4739
4802
  }
4740
- } catch (err) {
4741
- if (err.message.startsWith("Failed to acquire lock")) throw err;
4742
- this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4743
- resourceKey,
4744
- error: err.message
4745
- });
4746
4803
  }
4747
4804
  }
4748
4805
  let unlock = () => {
@@ -1,4 +1,4 @@
1
- import { f as CacheOptions, C as CacheService, c as CachePriority } from '../cache-service-BblHuF3i.js';
1
+ import { f as CacheOptions, C as CacheService, c as CachePriority } from '../cache-service-D8tIXmzb.js';
2
2
 
3
3
  declare const TRICACHE_SERVICE = "TRICACHE_SERVICE";
4
4
  declare const CACHE_MANAGER = "CACHE_MANAGER";
@@ -1,8 +1,8 @@
1
1
  import "../chunk-UBSR5UYA.js";
2
2
  import {
3
3
  CacheService
4
- } from "../chunk-3XQUQBOZ.js";
5
- import "../chunk-PFB5FMEY.js";
4
+ } from "../chunk-EUGYR7KR.js";
5
+ import "../chunk-X5AXHPVD.js";
6
6
 
7
7
  // src/nestjs/tricache.store.ts
8
8
  var TriCacheStore = class {