tricache 1.0.1 → 1.0.2

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 (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
package/src/next/index.ts CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  export { TriCacheISRHandler } from './isr-handler';
8
8
  export type {
9
9
  CacheHandlerValue,
10
+ NextCacheEntry,
10
11
  StoredNextCacheEntry,
11
12
  CacheHandlerContext,
12
13
  NextCacheHandlerOptions,
package/src/next/types.ts CHANGED
@@ -20,6 +20,20 @@ export interface CacheHandlerValue {
20
20
  * Remaining / configured TTL (seconds).
21
21
  */
22
22
  ttl?: number;
23
+ /** Native Next.js CacheEntry timing fields, in seconds. */
24
+ stale?: number;
25
+ revalidate?: number;
26
+ expire?: number;
27
+ }
28
+
29
+ /** Complete native Next.js CacheEntry output, structurally checked against Next in tests. */
30
+ export interface NextCacheEntry {
31
+ value: ReadableStream<Uint8Array>;
32
+ tags: string[];
33
+ timestamp: number;
34
+ stale: number;
35
+ revalidate: number;
36
+ expire: number;
23
37
  }
24
38
 
25
39
  /**
@@ -38,6 +52,11 @@ export interface StoredNextCacheEntry {
38
52
  ttl: number;
39
53
  /** Captured soft tag versions at write time */
40
54
  softTagVersions?: Record<string, number>;
55
+ generations?: Record<string, number>;
56
+ stale?: number;
57
+ revalidate?: number;
58
+ expire?: number;
59
+ streamEncoding?: 'base64';
41
60
  }
42
61
 
43
62
  export type CacheLifePreset =
@@ -79,6 +98,8 @@ export interface NextCacheHandlerOptions extends CacheOptions {
79
98
  * or `process.env.NEXT_PHASE === 'phase-export'`.
80
99
  */
81
100
  isBuildPhase?: boolean;
101
+ /** Maximum buffered RSC stream size. Default: 16 MiB. */
102
+ maxStreamBytes?: number;
82
103
  }
83
104
 
84
105
  /**
@@ -67,8 +67,14 @@ const MUTATION_OPERATIONS = new Set([
67
67
 
68
68
  /** Recursively sorts object keys for deterministic serialization of nested query filters */
69
69
  function deterministicStringify(val: unknown): string {
70
+ if (val instanceof Date) return `date:${JSON.stringify(val.toISOString())}`;
71
+ if (typeof val === 'bigint') return `bigint:${val}`;
72
+ if (val instanceof Uint8Array) return `binary:${Buffer.from(val.buffer, val.byteOffset, val.byteLength).toString('base64')}`;
73
+ if (val && typeof val === 'object' && typeof (val as { toJSON?: unknown }).toJSON === 'function') {
74
+ return deterministicStringify((val as { toJSON(): unknown }).toJSON());
75
+ }
70
76
  if (val === null || typeof val !== 'object') {
71
- return JSON.stringify(val);
77
+ return JSON.stringify(val) ?? 'undefined';
72
78
  }
73
79
  if (Array.isArray(val)) {
74
80
  return `[${val.map(deterministicStringify).join(',')}]`;
@@ -118,6 +124,11 @@ export function withTriCache(options: PrismaTriCacheOptions) {
118
124
  const queryArgs = args ?? {};
119
125
  const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
120
126
 
127
+ if (cacheConfig === false) {
128
+ const { cache: _c, ...cleanArgs } = queryArgs;
129
+ return query(cleanArgs);
130
+ }
131
+
121
132
  if (cacheConfig !== undefined || autoCache) {
122
133
  const opts: PrismaCacheQueryOptions = typeof cacheConfig === 'object' && cacheConfig !== null
123
134
  ? cacheConfig
@@ -119,8 +119,9 @@ type AnyBloomFilter = JsBloomFilter | WasmBloomFilter;
119
119
  function createBloomFilter(logger: ILogger, maxEntries: number): AnyBloomFilter {
120
120
  // Compute optimal bit-count for p = 1 % and the requested entry ceiling.
121
121
  const LN2_SQ = Math.LN2 * Math.LN2; // (ln 2)² ≈ 0.4804
122
- const optimalBits = Math.ceil(-maxEntries * Math.log(0.01) / LN2_SQ);
123
- const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / maxEntries)));
122
+ const capacity = Math.max(1, maxEntries);
123
+ const optimalBits = Math.ceil(-capacity * Math.log(0.01) / LN2_SQ);
124
+ const optimalK = Math.max(4, Math.min(10, Math.round(Math.LN2 * optimalBits / capacity)));
124
125
 
125
126
  try {
126
127
  const wasm = new WasmBloomFilter();
@@ -310,7 +311,10 @@ export class SmartMemoryCache {
310
311
  this.bloom = createBloomFilter(opts.logger, opts.maxEntries);
311
312
  this.categoryPrefixes = Object.keys(opts.categories).filter(k => k !== 'default');
312
313
  if (opts.admissionPolicy === 'wtinylfu') {
313
- this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch);
314
+ this.wtinyPolicy = new WTinyLfuPolicy(opts.maxEntries, this.sketch, 0.01, 0.80, key => {
315
+ const entry = this.cache.get(key);
316
+ return !entry || entry.priority !== 4 || entry.expiresAt <= Date.now();
317
+ });
314
318
  }
315
319
 
316
320
  if (existing) {
@@ -403,6 +407,7 @@ export class SmartMemoryCache {
403
407
  const MAX_EVICT_PASSES = 64;
404
408
  let passes = 0;
405
409
  do {
410
+ const before = this.cache.size;
406
411
  this.smartEvict(category, catOvf);
407
412
  const lim2 = this.getCategoryLimit(category);
408
413
  const catCnt2 = this.categoryCount.get(category) ?? 0;
@@ -410,6 +415,7 @@ export class SmartMemoryCache {
410
415
  catOvf = catCnt2 >= lim2.maxEntries || catSz2 + neededSize > lim2.maxSizeBytes;
411
416
  glbOvf = this.cache.size >= this.opts.maxEntries || this.totalSize + neededSize > this.opts.maxBytes;
412
417
  passes++;
418
+ if (this.cache.size === before) break; // Only protected entries remain.
413
419
  } while ((catOvf || glbOvf) && passes < MAX_EVICT_PASSES);
414
420
  }
415
421
 
@@ -564,6 +570,8 @@ export class SmartMemoryCache {
564
570
  fetchedAt: now,
565
571
  tagVersions: entry.tagVersions,
566
572
  setAt: entry.setAt,
573
+ tags: entry.tags,
574
+ dependsOn: entry.dependsOn,
567
575
  };
568
576
  return hit;
569
577
  }
@@ -577,10 +585,20 @@ export class SmartMemoryCache {
577
585
  delta?: number,
578
586
  tagVersions?: Record<string, number>,
579
587
  setAt?: number,
580
- ): void {
588
+ tags?: string[],
589
+ dependsOn?: string[],
590
+ ): boolean {
581
591
  // Single serialization pass — always msgpackr. Eliminates the prior JSON.stringify
582
592
  // "size probe" that was discarded for large payloads (the double-pass).
583
593
  const packed = this.codec.encode(data);
594
+ return this.storePacked(key, packed, data, ttlMs, priority, staleAt, delta, tagVersions, setAt, tags, dependsOn);
595
+ }
596
+
597
+ private storePacked(
598
+ key: string, packed: Buffer, data: unknown, ttlMs: number, priority: CachePriority,
599
+ staleAt?: number, delta?: number, tagVersions?: Record<string, number>, setAt?: number,
600
+ tags?: string[], dependsOn?: string[],
601
+ ): boolean {
584
602
  const size = packed.byteLength;
585
603
  this.compressions++;
586
604
  this.sketch.increment(key);
@@ -588,9 +606,11 @@ export class SmartMemoryCache {
588
606
  const cat = this.getCategory(key);
589
607
  const lim = this.getCategoryLimit(cat);
590
608
 
591
- if (size > lim.maxSizeBytes * 0.5) {
609
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || this.opts.maxEntries <= 0 || lim.maxEntries <= 0 ||
610
+ size > this.opts.maxBytes || size > lim.maxSizeBytes * 0.5) {
611
+ this.delete(key); // An oversized replacement must not leave the old value readable.
592
612
  this.opts.logger.debug('SmartMemoryCache: entry too large, skipping', { key, sizeBytes: size });
593
- return;
613
+ return false;
594
614
  }
595
615
 
596
616
  // Single Map.get replaces Map.has + _delete's Map.get (saves one lookup on overwrite).
@@ -624,9 +644,11 @@ export class SmartMemoryCache {
624
644
  delta,
625
645
  setAt: setAt ?? now,
626
646
  tagVersions,
647
+ tags,
648
+ dependsOn,
627
649
  });
628
650
  }
629
- return;
651
+ return false;
630
652
  } else if (decision.candidateKey) {
631
653
  // An older window candidate was rejected to make room for key
632
654
  const candEntry = this.cache.get(decision.candidateKey);
@@ -644,21 +666,28 @@ export class SmartMemoryCache {
644
666
  this._delete(decision.evictKey, 'capacity');
645
667
  }
646
668
 
647
- // Check category byte limit or total byte limit
669
+ // Count and byte limits apply to TinyLFU too, including category quotas.
648
670
  const catSz = this.categorySize.get(cat) ?? 0;
649
- if (catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
671
+ if ((this.categoryCount.get(cat) ?? 0) >= lim.maxEntries || this.cache.size >= this.opts.maxEntries ||
672
+ catSz + size > lim.maxSizeBytes || this.totalSize + size > this.opts.maxBytes) {
650
673
  this.ensureCapacity(cat, size);
651
674
  }
652
675
  } else {
653
676
  this.ensureCapacity(cat, size);
654
677
  }
655
678
 
679
+ if (this.cache.size >= this.opts.maxEntries || (this.categoryCount.get(cat) ?? 0) >= lim.maxEntries ||
680
+ this.totalSize + size > this.opts.maxBytes || (this.categorySize.get(cat) ?? 0) + size > lim.maxSizeBytes) {
681
+ this.wtinyPolicy?.onDelete(key);
682
+ return false;
683
+ }
684
+
656
685
  const now = Date.now();
657
686
  // Only cache the live object for small entries — large entries would store the packed
658
687
  // buffer AND a potentially much-larger deserialized object simultaneously (double-heap).
659
688
  // For large entries, get() falls back to the unpack() path transparently.
660
689
  const liveValue = size <= LARGE_VALUE_BYTES ? data : undefined;
661
- this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions });
690
+ this.cache.set(key, { data: packed, value: liveValue, isCompressed: true, expiresAt: now + ttlMs, staleAt, size, hits: 1, lastAccess: now, priority, ttlMs, delta, setAt: setAt ?? now, tagVersions, tags, dependsOn });
662
691
  // Only add new keys to the bloom — overwrites already have their bits set.
663
692
  // Re-adding inflates the insertions counter, delaying trigger-2 phantom detection.
664
693
  if (!existingEntry) this.bloom.add(key);
@@ -669,6 +698,7 @@ export class SmartMemoryCache {
669
698
  let ks = this.categoryKeys.get(cat);
670
699
  if (!ks) { ks = new Set(); this.categoryKeys.set(cat, ks); }
671
700
  ks.add(key);
701
+ return true;
672
702
  }
673
703
 
674
704
  delete(key: string): boolean {
@@ -901,7 +931,8 @@ export class SmartMemoryCache {
901
931
  if (entry.expiresAt <= now) continue;
902
932
  if (entry.priority === 4 /* CRITICAL */) continue;
903
933
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
904
- out.push({ key, entry: { ...entry } });
934
+ const { value: _value, ...stored } = entry;
935
+ out.push({ key, entry: { ...stored } });
905
936
  }
906
937
  return out;
907
938
  }
@@ -909,24 +940,30 @@ export class SmartMemoryCache {
909
940
  importEntries(entries: Array<{ key: string; entry: SmartCacheEntry }>, forbiddenPrefixes: readonly string[]): number {
910
941
  const now = Date.now();
911
942
  let loaded = 0;
912
- for (const { key, entry } of entries) {
913
- if (entry.expiresAt <= now) continue;
943
+ for (const item of entries) {
944
+ if (!item || typeof item.key !== 'string' || !item.entry) continue;
945
+ const { key, entry } = item;
946
+ if (!Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) continue;
914
947
  if (forbiddenPrefixes.some(p => key.startsWith(p))) continue;
915
948
  if (this.cache.has(key)) continue;
916
- const rawData = entry.data;
917
- // Handle both legacy (isCompressed=false, data=JSON string) and current (data=Buffer) formats.
918
- const data: Buffer = !entry.isCompressed
919
- ? this.codec.encode(JSON.parse(rawData as unknown as string)) // legacy: re-encode JSON → msgpackr
920
- : rawData instanceof Uint8Array
921
- ? Buffer.from(rawData) // msgpackr Uint8Array → Buffer
922
- : rawData as Buffer; // already a Buffer
923
- // Cache the live object for small entries only — large entries skip double-heap storage.
924
- const value = entry.size <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
925
- this.cache.set(key, { ...entry, data, value, isCompressed: true });
926
- this.bloom.add(key);
927
- loaded++;
949
+ try {
950
+ const rawData = entry.data;
951
+ const data = !entry.isCompressed
952
+ ? this.codec.encode(JSON.parse(rawData as unknown as string))
953
+ : rawData instanceof Uint8Array ? Buffer.from(rawData) : null;
954
+ if (!data) continue;
955
+ const value = data.length <= LARGE_VALUE_BYTES ? this.codec.decode(data) : undefined;
956
+ if (this.storePacked(key, data, value, entry.expiresAt - now, entry.priority, entry.staleAt,
957
+ entry.delta, entry.tagVersions, entry.setAt, entry.tags, entry.dependsOn)) {
958
+ const restored = this.cache.get(key)!;
959
+ restored.expiresAt = entry.expiresAt;
960
+ restored.ttlMs = entry.ttlMs ?? entry.expiresAt - now;
961
+ restored.hits = Number.isFinite(entry.hits) ? Math.max(1, entry.hits) : 1;
962
+ restored.lastAccess = Number.isFinite(entry.lastAccess) ? entry.lastAccess : now;
963
+ loaded++;
964
+ }
965
+ } catch { /* One corrupt snapshot entry must not discard the healthy entries. */ }
928
966
  }
929
- this.recalculateStats();
930
967
  return loaded;
931
968
  }
932
969
 
package/src/types.ts CHANGED
@@ -25,7 +25,7 @@ export interface ICacheSpanLink {
25
25
  export interface ICacheSpan {
26
26
  setAttribute(key: string, value: string | number | boolean): this;
27
27
  setStatus(status: { code: 0 | 1 | 2; message?: string }): this;
28
- recordException?(err: Error | unknown): this;
28
+ recordException?(err: unknown): void;
29
29
  end(): void;
30
30
  }
31
31
 
@@ -127,6 +127,9 @@ export interface SmartCacheEntry {
127
127
  setAt?: number;
128
128
  /** Active tag versions at write time (used when tagStrategy === 'generational') */
129
129
  tagVersions?: Record<string, number>;
130
+ /** Set-based tags and dependency patterns preserved through disk/snapshot promotion. */
131
+ tags?: string[];
132
+ dependsOn?: string[];
130
133
  }
131
134
 
132
135
  /** Returned by SmartMemoryCache.get() — distinguishes "cached null" from a real miss */
@@ -148,6 +151,8 @@ export interface CacheHit {
148
151
  tagVersions?: Record<string, number>;
149
152
  /** Timestamp (ms) when this entry was written into memory */
150
153
  setAt?: number;
154
+ tags?: string[];
155
+ dependsOn?: string[];
151
156
  }
152
157
 
153
158
  // ─── Disk tier ───────────────────────────────────────────────────────────────
@@ -165,6 +170,12 @@ export interface DiskCacheEntry {
165
170
  priority: number;
166
171
  /** Active tag versions at write time (used when tagStrategy === 'generational') */
167
172
  tagVersions?: Record<string, number>;
173
+ /** Original write time and TTL, preserved on spill and promotion. */
174
+ setAt?: number;
175
+ ttlMs?: number;
176
+ delta?: number;
177
+ tags?: string[];
178
+ dependsOn?: string[];
168
179
  }
169
180
 
170
181
  // ─── Metrics snapshot ────────────────────────────────────────────────────────
@@ -1169,8 +1180,13 @@ export interface ICacheCounter {
1169
1180
  add(value: number, attributes?: Record<string, string | number | boolean>): void;
1170
1181
  }
1171
1182
 
1183
+ export type ICacheObservableCallback = (result: {
1184
+ observe(value: number, attributes?: Record<string, string | number | boolean>): void;
1185
+ }) => void | Promise<void>;
1186
+
1172
1187
  export interface ICacheObservableGauge {
1173
- readonly _isGauge?: true;
1188
+ addCallback(callback: ICacheObservableCallback): void;
1189
+ removeCallback(callback: ICacheObservableCallback): void;
1174
1190
  }
1175
1191
 
1176
1192
  export interface ICacheBatchObservableCallback {
@@ -1183,6 +1199,7 @@ export interface ICacheMeter {
1183
1199
  createCounter(name: string, options?: { description?: string; unit?: string }): ICacheCounter;
1184
1200
  createObservableGauge(name: string, options?: { description?: string; unit?: string }): ICacheObservableGauge;
1185
1201
  addBatchObservableCallback(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
1202
+ removeBatchObservableCallback?(callback: ICacheBatchObservableCallback, observables: ICacheObservableGauge[]): void;
1186
1203
  }
1187
1204
 
1188
1205
  /**
@@ -1199,6 +1216,9 @@ export interface IRedisPipeline {
1199
1216
  smembers(key: string): this;
1200
1217
  hset(key: string, value: Record<string, string>): this;
1201
1218
  hgetall?(key: string): this;
1219
+ /** Remaining TTL in milliseconds; enables atomic value + expiry reads. */
1220
+ pttl?(key: string): this;
1221
+ eval?(script: string, numkeys: number, ...args: (string | number)[]): this;
1202
1222
  exec(): Promise<Array<[Error | null, any]> | null>;
1203
1223
  }
1204
1224
 
@@ -1212,6 +1232,7 @@ export interface IRedisDriver {
1212
1232
  setex?(key: string, seconds: number, value: string): Promise<unknown>;
1213
1233
  del(...keys: string[]): Promise<number>;
1214
1234
  ping(): Promise<string>;
1235
+ pttl?(key: string): Promise<number>;
1215
1236
  expire(key: string, seconds: number): Promise<number | boolean>;
1216
1237
  incr(key: string): Promise<number>;
1217
1238
  eval(script: string, numkeys: number, ...args: (string | number)[]): Promise<unknown>;
@@ -1225,6 +1246,8 @@ export interface IRedisDriver {
1225
1246
  hgetall?(key: string): Promise<Record<string, string>>;
1226
1247
  publish?(channel: string, message: string): Promise<number>;
1227
1248
  subscribe?(...channels: string[]): Promise<unknown>;
1249
+ unsubscribe?(...channels: string[]): Promise<unknown>;
1250
+ removeListener?(event: string, listener: (...args: any[]) => void): this | unknown;
1228
1251
  disconnect(): Promise<void> | void;
1229
1252
  quit?(): Promise<void> | void;
1230
1253
  duplicate?(): IRedisDriver;
@@ -53,6 +53,18 @@ export function readCgroupMemoryLimit(): number {
53
53
  return Infinity;
54
54
  }
55
55
 
56
+ /** Current cgroup usage includes tmpfs/page-cache charges that are absent from process RSS. */
57
+ export function readCgroupMemoryUsage(): number | null {
58
+ if (process.platform !== 'linux') return null;
59
+ for (const file of ['/sys/fs/cgroup/memory.current', '/sys/fs/cgroup/memory/memory.usage_in_bytes']) {
60
+ try {
61
+ const value = Number(fs.readFileSync(file, 'utf8').trim());
62
+ if (Number.isFinite(value) && value >= 0) return value;
63
+ } catch { /* unavailable or unreadable */ }
64
+ }
65
+ return null;
66
+ }
67
+
56
68
  /**
57
69
  * Returns the V8 JavaScript heap size limit in bytes.
58
70
  * Safely guards against missing or mock environments.
@@ -0,0 +1,14 @@
1
+ /** Bound library-owned I/O without leaking timeout handles after success or failure. */
2
+ export async function withDeadline<T>(operation: Promise<T>, timeoutMs: number, label: string): Promise<T> {
3
+ let timer: ReturnType<typeof setTimeout> | undefined;
4
+ try {
5
+ return await Promise.race([
6
+ operation,
7
+ new Promise<never>((_resolve, reject) => {
8
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
9
+ }),
10
+ ]);
11
+ } finally {
12
+ if (timer) clearTimeout(timer);
13
+ }
14
+ }
@@ -0,0 +1,27 @@
1
+ /** Produce a bounded, JSON-safe diagnostic view without retaining opaque credential holders. */
2
+ export function redactDiagnostics(value: unknown, seen = new WeakSet<object>(), depth = 0): unknown {
3
+ if (typeof value === 'string' && /^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
4
+ try {
5
+ const url = new URL(value);
6
+ if (url.username) url.username = '[REDACTED]';
7
+ if (url.password) url.password = '[REDACTED]';
8
+ for (const key of url.searchParams.keys()) {
9
+ if (/key|token|secret|password|credential|authorization|cookie/i.test(key)) url.searchParams.set(key, '[REDACTED]');
10
+ }
11
+ return url.toString();
12
+ } catch { return '[REDACTED URL]'; }
13
+ }
14
+ if (value == null || typeof value !== 'object') return typeof value === 'function' ? undefined : value;
15
+ if (depth >= 8) return '[OMITTED]';
16
+ if (seen.has(value)) return '[CIRCULAR]';
17
+ seen.add(value);
18
+ if (Array.isArray(value)) return value.map(item => redactDiagnostics(item, seen, depth + 1));
19
+ const result: Record<string, unknown> = {};
20
+ for (const [key, item] of Object.entries(value)) {
21
+ if (typeof item === 'function') continue; // In particular, never preserve an opaque toJSON().
22
+ result[key] = /key|token|secret|password|credential|authorization|cookie|headers/i.test(key)
23
+ ? item == null ? item : '[REDACTED]'
24
+ : redactDiagnostics(item, seen, depth + 1);
25
+ }
26
+ return result;
27
+ }
@@ -0,0 +1,13 @@
1
+ /** Redis Cluster CRC16/XMODEM hash slots, including the first non-empty hash tag. */
2
+ export function redisHashSlot(key: string): number {
3
+ const open = key.indexOf('{');
4
+ const close = open < 0 ? -1 : key.indexOf('}', open + 1);
5
+ const bytes = Buffer.from(close > open + 1 ? key.slice(open + 1, close) : key, 'utf8');
6
+ let crc = 0;
7
+ for (const byte of bytes) {
8
+ crc ^= byte << 8;
9
+ for (let bit = 0; bit < 8; bit++) crc = (crc << 1) ^ ((crc & 0x8000) ? 0x1021 : 0);
10
+ crc &= 0xffff;
11
+ }
12
+ return crc & 0x3fff;
13
+ }
@@ -40,9 +40,14 @@ interface BloomWasmExports {
40
40
 
41
41
  import { base64ToUint8Array } from '../edge/utils/base64';
42
42
 
43
- const BLOOM_WASM_MODULE = new WebAssembly.Module(
44
- base64ToUint8Array(BLOOM_WASM_BASE64) as unknown as BufferSource,
45
- );
43
+ let bloomWasmModule: WebAssembly.Module | undefined;
44
+
45
+ function getBloomWasmModule(): WebAssembly.Module {
46
+ // Compile lazily so importing an edge bundle does not bypass the JS fallback.
47
+ return bloomWasmModule ??= new WebAssembly.Module(
48
+ base64ToUint8Array(BLOOM_WASM_BASE64) as unknown as BufferSource,
49
+ );
50
+ }
46
51
 
47
52
  // NOTE: WasmBloomFilter initializes 100% synchronously in its constructor from
48
53
  // pre-compiled WebAssembly bytecode (BLOOM_WASM_MODULE). There is no async init() promise,
@@ -59,7 +64,7 @@ export class WasmBloomFilter {
59
64
  private _insertionCount = 0;
60
65
 
61
66
  constructor() {
62
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
67
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
63
68
  this.exports = instance.exports as unknown as BloomWasmExports;
64
69
  this.mem = new Uint8Array(this.exports.memory.buffer);
65
70
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
@@ -60,7 +60,8 @@ try {
60
60
  }
61
61
  } catch {
62
62
  // CJS fallback — __dirname is available natively in CJS (and shimmed by tsup for ESM).
63
- _workerFile = join(__dirname, 'serialize-worker.js');
63
+ const sibling = join(__dirname, 'serialize-worker.js');
64
+ _workerFile = existsSync(sibling) ? sibling : join(dirname(__dirname), 'serialize-worker.js');
64
65
  }
65
66
 
66
67
  export interface WorkerPoolOptions {
@@ -125,6 +126,7 @@ export class WorkerPool {
125
126
 
126
127
  private _spawnWorkers(opts: WorkerPoolOptions): { workers: Worker[]; pending: Map<number, PendingEntry>[] } {
127
128
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
129
+ if (!Number.isInteger(size) || size > 32 || !existsSync(_workerFile)) throw new Error('Worker pool unavailable or invalid worker count');
128
130
  const workerData = {
129
131
  keyBase64: opts.keyBase64,
130
132
  mode: opts.mode,
@@ -140,7 +142,7 @@ export class WorkerPool {
140
142
  const createWorker = (index: number): Worker => {
141
143
  const worker = new Worker(_workerFile, {
142
144
  workerData,
143
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
145
+ execArgv: _workerExecArgv, // Do not inherit --input-type/eval or application loader flags.
144
146
  });
145
147
  const pending = pendingList[index] ?? new Map<number, PendingEntry>();
146
148
  if (!pendingList[index]) pendingList[index] = pending;
@@ -175,7 +177,7 @@ export class WorkerPool {
175
177
  worker.unref();
176
178
 
177
179
  // If pool is still active and worker exited with non-zero code, auto-replace
178
- if (this._available && exitCode !== 0 && workers[index] === worker) {
180
+ if (this._available && this.workers === workers && workers[index] === worker) {
179
181
  try {
180
182
  workers[index] = createWorker(index);
181
183
  } catch { /* ok */ }
@@ -186,9 +188,11 @@ export class WorkerPool {
186
188
  return worker;
187
189
  };
188
190
 
189
- for (let i = 0; i < size; i++) {
190
- const worker = createWorker(i);
191
- workers.push(worker);
191
+ try {
192
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
193
+ } catch (error) {
194
+ for (const worker of workers) void worker.terminate().catch(() => {});
195
+ throw error;
192
196
  }
193
197
 
194
198
  return { workers, pending: pendingList };
@@ -223,7 +227,7 @@ export class WorkerPool {
223
227
  entry.reject(new Error('WorkerPool replaced during key rotation'));
224
228
  }
225
229
  oldPending[i]?.clear();
226
- oldWorkers[i]?.terminate().catch(() => {});
230
+ await oldWorkers[i]?.terminate().catch(() => {});
227
231
  }
228
232
  }
229
233
 
@@ -272,7 +276,12 @@ export class WorkerPool {
272
276
  // Re-ref the worker while this request is in flight so the event loop
273
277
  // stays alive even in short-lived scripts (benchmarks, CLI tools).
274
278
  worker.ref();
275
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
279
+ try { worker.postMessage({ id, type, payload: dataToSend }, transferList); }
280
+ catch (error) {
281
+ pending.delete(id);
282
+ if (pending.size === 0) worker.unref();
283
+ reject(error);
284
+ }
276
285
  });
277
286
  }
278
287
 
package/src/wtiny-lfu.ts CHANGED
@@ -460,6 +460,7 @@ export class WTinyLfuPolicy {
460
460
  private readonly sketch: { estimate(key: string): number; increment(key: string): void },
461
461
  windowPercent = 0.01,
462
462
  protectedPercent = 0.80,
463
+ private readonly canEvict?: (key: string) => boolean,
463
464
  ) {
464
465
  this.maxTotal = Math.max(2, capacity);
465
466
  this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
@@ -549,20 +550,33 @@ export class WTinyLfuPolicy {
549
550
  }
550
551
 
551
552
  // Main space full: TinyLFU gate
552
- let victimKey: string;
553
+ let victimKey: string | undefined;
553
554
  let victimIsProbation = true;
554
555
 
555
- if (this.probation.size > 0) {
556
- victimKey = this.probation.values().next().value!;
557
- } else {
558
- victimKey = this.protected_.values().next().value!;
556
+ for (const candidate of this.probation) {
557
+ if (!this.canEvict || this.canEvict(candidate)) { victimKey = candidate; break; }
558
+ }
559
+ if (victimKey === undefined) {
560
+ for (const candidate of this.protected_) {
561
+ if (!this.canEvict || this.canEvict(candidate)) { victimKey = candidate; break; }
562
+ }
559
563
  victimIsProbation = false;
560
564
  }
561
565
 
566
+ if (victimKey === undefined) {
567
+ if (this.canEvict && !this.canEvict(candKey)) {
568
+ this.window.delete(key);
569
+ this.window.add(candKey);
570
+ return { admit: false, candidateKey: key };
571
+ }
572
+ this.rejectionCount++;
573
+ return { admit: false, candidateKey: candKey };
574
+ }
575
+
562
576
  const candFreq = this.sketch.estimate(candKey);
563
577
  const victimFreq = this.sketch.estimate(victimKey);
564
578
 
565
- if (candFreq > victimFreq) {
579
+ if ((this.canEvict && !this.canEvict(candKey)) || candFreq > victimFreq) {
566
580
  // Candidate wins: evict victim, admit candidate to Probation
567
581
  if (victimIsProbation) {
568
582
  this.probation.delete(victimKey);
@@ -1,60 +0,0 @@
1
- // src/http/utils.ts
2
- import crypto from "crypto";
3
- function buildDeterministicKey(req, options) {
4
- if (options?.keyGenerator) {
5
- return options.keyGenerator(req);
6
- }
7
- const method = (req.method || "GET").toUpperCase();
8
- const rawUrl = req.originalUrl || req.url || "/";
9
- const qIdx = rawUrl.indexOf("?");
10
- const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
11
- let queryString = "";
12
- if (qIdx >= 0) {
13
- const rawQuery = rawUrl.slice(qIdx + 1);
14
- try {
15
- const params = new URLSearchParams(rawQuery);
16
- params.sort();
17
- queryString = params.toString();
18
- } catch {
19
- queryString = rawQuery;
20
- }
21
- }
22
- let key = `http:${method}:${path}`;
23
- if (queryString) {
24
- key += `?${queryString}`;
25
- }
26
- if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
27
- const sortedHeaders = [...options.headerWhitelist].sort();
28
- for (const h of sortedHeaders) {
29
- const normalizedHeader = h.toLowerCase();
30
- const val = req.headers[normalizedHeader];
31
- if (val !== void 0 && val !== null && val !== "") {
32
- const headerStr = Array.isArray(val) ? val.join(",") : String(val);
33
- key += `|h:${normalizedHeader}=${headerStr}`;
34
- }
35
- }
36
- }
37
- return key;
38
- }
39
- function shouldSkipCache(req, customSkip) {
40
- if (customSkip && customSkip(req)) return true;
41
- const cc = req.headers ? req.headers["cache-control"] || req.headers["Cache-Control"] : void 0;
42
- if (typeof cc === "string") {
43
- const lower = cc.toLowerCase();
44
- if (lower.includes("no-cache") || lower.includes("no-store")) {
45
- return true;
46
- }
47
- }
48
- return false;
49
- }
50
- function generateETag(data) {
51
- const str = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : JSON.stringify(data);
52
- const hash = crypto.createHash("sha1").update(str).digest("hex").slice(0, 16);
53
- return `W/"${str.length.toString(16)}-${hash}"`;
54
- }
55
-
56
- export {
57
- buildDeterministicKey,
58
- shouldSkipCache,
59
- generateETag
60
- };