tricache 1.0.1 → 2.0.0

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 (127) hide show
  1. package/README.md +89 -93
  2. package/dashboards/tricache-alerts.yaml +80 -4
  3. package/dashboards/tricache-grafana.json +54 -1
  4. package/dashboards/tricache-inventory.rules.yml +21 -0
  5. package/dist/cache-service-BV5T8-20.d.cts +1064 -0
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-tpyrXvlH.d.ts} +157 -24
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  10. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  11. package/dist/{chunk-2AJKEQMZ.js → chunk-KV7KISK2.js} +54 -5
  12. package/dist/{chunk-JYQFQJNJ.js → chunk-MB3DMVWN.js} +3424 -1022
  13. package/dist/chunk-RBJRTGFK.js +94 -0
  14. package/dist/chunk-S5N65I45.js +17 -0
  15. package/dist/cli.cjs +3694 -1070
  16. package/dist/cli.d.cts +12 -0
  17. package/dist/cli.js +210 -14
  18. package/dist/dashboard/index.cjs +111 -29
  19. package/dist/dashboard/index.d.cts +185 -0
  20. package/dist/dashboard/index.d.ts +5 -3
  21. package/dist/dashboard/index.js +1 -1
  22. package/dist/drizzle/index.cjs +3578 -1068
  23. package/dist/drizzle/index.d.cts +46 -0
  24. package/dist/drizzle/index.d.ts +2 -2
  25. package/dist/drizzle/index.js +6 -2
  26. package/dist/edge/index.cjs +368 -162
  27. package/dist/edge/index.d.cts +134 -0
  28. package/dist/edge/index.d.ts +11 -4
  29. package/dist/edge/index.js +314 -155
  30. package/dist/hono/index.cjs +3614 -1087
  31. package/dist/hono/index.d.cts +93 -0
  32. package/dist/hono/index.d.ts +7 -5
  33. package/dist/hono/index.js +16 -9
  34. package/dist/hono-CMv2VdQ6.d.cts +404 -0
  35. package/dist/{hono-DSV2ve66.d.ts → hono-Dvq04kX9.d.ts} +33 -7
  36. package/dist/http/index.cjs +3712 -1124
  37. package/dist/http/index.d.cts +103 -0
  38. package/dist/http/index.d.ts +13 -5
  39. package/dist/http/index.js +92 -43
  40. package/dist/index.cjs +4067 -1252
  41. package/dist/index.d.cts +1071 -0
  42. package/dist/index.d.ts +123 -27
  43. package/dist/index.js +878 -21
  44. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.cts} +1 -0
  45. package/dist/murmur3-DF8BFRnu.d.ts +99 -0
  46. package/dist/nestjs/index.cjs +3635 -1112
  47. package/dist/nestjs/index.d.cts +299 -0
  48. package/dist/nestjs/index.d.ts +120 -33
  49. package/dist/nestjs/index.js +132 -43
  50. package/dist/next/index.cjs +3704 -1175
  51. package/dist/next/index.d.cts +238 -0
  52. package/dist/next/index.d.ts +39 -11
  53. package/dist/next/index.js +202 -102
  54. package/dist/prisma/index.cjs +29 -18
  55. package/dist/prisma/index.d.cts +62 -0
  56. package/dist/prisma/index.d.ts +2 -2
  57. package/dist/prisma/index.js +17 -18
  58. package/dist/serialize-worker.cjs +162 -39
  59. package/dist/serialize-worker.d.cts +2 -0
  60. package/dist/serialize-worker.js +9 -7
  61. package/dist/{types-Dyip5wAl.d.ts → types-F8vRWMrE.d.cts} +186 -54
  62. package/dist/types-F8vRWMrE.d.ts +1636 -0
  63. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  64. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  65. package/package.json +116 -37
  66. package/src/adapters/auto-pipeliner.ts +150 -26
  67. package/src/adapters/node-redis.ts +106 -27
  68. package/src/cache-service.ts +2215 -793
  69. package/src/cli.ts +25 -14
  70. package/src/codec.ts +3 -3
  71. package/src/compression.ts +39 -16
  72. package/src/cross-region.ts +22 -4
  73. package/src/dashboard/handler.ts +26 -6
  74. package/src/dashboard/html.ts +35 -10
  75. package/src/dashboard/index.ts +35 -13
  76. package/src/dashboard/types.ts +3 -1
  77. package/src/disk-tier.ts +448 -102
  78. package/src/drizzle/index.ts +2 -1
  79. package/src/edge/adapters/cloudflare-do.ts +25 -10
  80. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  81. package/src/edge/adapters/upstash.ts +27 -11
  82. package/src/edge/cache.ts +200 -110
  83. package/src/edge/hono.ts +23 -6
  84. package/src/edge/types.ts +17 -5
  85. package/src/encryption.ts +50 -18
  86. package/src/env.d.ts +1 -1
  87. package/src/errors.ts +12 -0
  88. package/src/hono/index.ts +19 -9
  89. package/src/http/express.ts +62 -17
  90. package/src/http/fastify.ts +35 -21
  91. package/src/http/utils.ts +60 -20
  92. package/src/index.ts +6 -0
  93. package/src/ipc-telemetry.ts +35 -9
  94. package/src/latency-watchdog.ts +5 -1
  95. package/src/nestjs/decorators.ts +11 -6
  96. package/src/nestjs/index.ts +2 -0
  97. package/src/nestjs/keyv-adapter.ts +68 -0
  98. package/src/nestjs/tricache.module.ts +15 -12
  99. package/src/nestjs/tricache.store.ts +69 -26
  100. package/src/nestjs/types.ts +30 -16
  101. package/src/next/cache-handler.ts +151 -53
  102. package/src/next/index.ts +1 -0
  103. package/src/next/types.ts +25 -0
  104. package/src/origin-capacity.ts +134 -0
  105. package/src/prisma/index.ts +17 -24
  106. package/src/remote-snapshot.ts +37 -27
  107. package/src/serialize-worker.ts +8 -5
  108. package/src/sigv4-snapshot-adapter.ts +37 -27
  109. package/src/smart-memory-cache.ts +121 -44
  110. package/src/types.ts +117 -37
  111. package/src/utils/cgroup.ts +12 -0
  112. package/src/utils/config-comparison.ts +29 -0
  113. package/src/utils/deadline.ts +14 -0
  114. package/src/utils/diagnostics.ts +27 -0
  115. package/src/utils/lz4-size.ts +74 -0
  116. package/src/utils/namespace-key.ts +48 -0
  117. package/src/utils/query-key.ts +13 -0
  118. package/src/utils/redis-slot.ts +13 -0
  119. package/src/utils/snapshot-transfer.ts +83 -0
  120. package/src/utils/work-limits.ts +73 -0
  121. package/src/utils/write-revision.ts +4 -0
  122. package/src/wasm/bloom-filter-wasm.ts +25 -5
  123. package/src/worker-pool.ts +44 -15
  124. package/src/wtiny-lfu.ts +82 -20
  125. package/dist/cache-service-MG7PN6MX.js +0 -12
  126. package/dist/chunk-3I5L7K6I.js +0 -704
  127. package/dist/chunk-BQRURGGD.js +0 -60
@@ -0,0 +1,83 @@
1
+ import { positiveLimit } from './work-limits.js';
2
+
3
+ export interface SnapshotTransferOptions {
4
+ /** Maximum downloaded snapshot bytes, enforced while streaming. Default: 220 MiB. */
5
+ maxBytes?: number;
6
+ /** Deadline covering the request and response body. Default: 30 seconds. */
7
+ timeoutMs?: number;
8
+ }
9
+
10
+ export interface SnapshotRequestOptions {
11
+ /** Cancel transport work, for example when the owning cache is destroyed. */
12
+ signal?: AbortSignal;
13
+ }
14
+
15
+ export async function snapshotRequest<T>(
16
+ options: SnapshotTransferOptions,
17
+ request: SnapshotRequestOptions | undefined,
18
+ work: (signal: AbortSignal, maxBytes: number) => Promise<T>,
19
+ ): Promise<T> {
20
+ const maxBytes = positiveLimit(options.maxBytes, 220 * 1024 * 1024, 'maxBytes');
21
+ const timeoutMs = positiveLimit(options.timeoutMs, 30_000, 'timeoutMs');
22
+ const controller = new AbortController();
23
+ const abort = () => controller.abort(request?.signal?.reason);
24
+ request?.signal?.addEventListener('abort', abort, { once: true });
25
+ if (request?.signal?.aborted) abort();
26
+ const timer = setTimeout(() => controller.abort(new Error('Snapshot request timed out')), timeoutMs);
27
+ let stopWaiting!: () => void;
28
+ const cancelled = new Promise<never>((_resolve, reject) => {
29
+ stopWaiting = () => reject(controller.signal.reason);
30
+ controller.signal.addEventListener('abort', stopWaiting, { once: true });
31
+ });
32
+ try {
33
+ controller.signal.throwIfAborted();
34
+ return await Promise.race([work(controller.signal, maxBytes), cancelled]);
35
+ } finally {
36
+ clearTimeout(timer);
37
+ request?.signal?.removeEventListener('abort', abort);
38
+ controller.signal.removeEventListener('abort', stopWaiting);
39
+ }
40
+ }
41
+
42
+ /** Cancel unused error/404/upload bodies without buffering them. */
43
+ export function discardSnapshotResponse(response: Response): void {
44
+ void response.body?.cancel().catch(() => {});
45
+ }
46
+
47
+ export async function readSnapshotResponse(response: Response, signal: AbortSignal, maxBytes: number): Promise<Buffer> {
48
+ const advertised = response.headers.get('content-length');
49
+ if (advertised !== null && Number(advertised) > maxBytes) {
50
+ discardSnapshotResponse(response);
51
+ throw new Error('Snapshot exceeds size limit');
52
+ }
53
+ // The deadline can expire after fetch resolves but before this body is read.
54
+ // Release the already-received body instead of leaking it uncancelled.
55
+ if (signal.aborted) {
56
+ discardSnapshotResponse(response);
57
+ signal.throwIfAborted();
58
+ }
59
+ if (!response.body) return Buffer.alloc(0);
60
+ const reader = response.body.getReader();
61
+ const cancel = () => { void reader.cancel(signal.reason).catch(() => {}); };
62
+ signal.addEventListener('abort', cancel, { once: true });
63
+ const chunks: Buffer[] = [];
64
+ let size = 0;
65
+ try {
66
+ while (true) {
67
+ signal.throwIfAborted();
68
+ const { done, value } = await reader.read();
69
+ signal.throwIfAborted();
70
+ if (done) break;
71
+ size += value.byteLength;
72
+ if (size > maxBytes) throw new Error('Snapshot exceeds size limit');
73
+ chunks.push(Buffer.from(value));
74
+ }
75
+ return Buffer.concat(chunks, size);
76
+ } catch (error) {
77
+ void reader.cancel(error).catch(() => {});
78
+ throw error;
79
+ } finally {
80
+ signal.removeEventListener('abort', cancel);
81
+ reader.releaseLock();
82
+ }
83
+ }
@@ -0,0 +1,73 @@
1
+ /** Fail before allocating queues or starting user work. No implicit retry. */
2
+ export class CacheCapacityError extends Error {
3
+ constructor(resource: string) {
4
+ super(`TriCache capacity exceeded: ${resource}`);
5
+ this.name = 'CacheCapacityError';
6
+ }
7
+ }
8
+
9
+ export function positiveLimit(value: number | undefined, fallback: number, name: string): number {
10
+ const limit = value ?? fallback;
11
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new RangeError(`${name} must be a positive safe integer`);
12
+ return limit;
13
+ }
14
+
15
+ export class WorkLimit {
16
+ private active = 0;
17
+ private rejected = 0;
18
+ constructor(readonly maximum: number, private readonly name: string) {}
19
+ acquire(weight = 1): () => void {
20
+ if (!Number.isSafeInteger(weight) || weight < 1) throw new RangeError('Work weight must be a positive safe integer');
21
+ if (weight > this.maximum - this.active) { this.rejected++; throw new CacheCapacityError(this.name); }
22
+ this.active += weight;
23
+ let released = false;
24
+ return () => { if (!released) { released = true; this.active -= weight; } };
25
+ }
26
+
27
+ metrics(): { active: number; capacity: number; rejected: number } {
28
+ return { active: this.active, capacity: this.maximum, rejected: this.rejected };
29
+ }
30
+
31
+ /** Grow one reservation without retaining one release closure per stream chunk. */
32
+ reservation(): { grow(weight: number): void; release(): void } {
33
+ let weight = 0;
34
+ let released = false;
35
+ return {
36
+ grow: (extra: number) => {
37
+ if (released) throw new Error('Cannot grow a released reservation');
38
+ if (!Number.isSafeInteger(extra) || extra < 1) throw new RangeError('Work weight must be a positive safe integer');
39
+ if (extra > this.maximum - this.active) { this.rejected++; throw new CacheCapacityError(this.name); }
40
+ this.active += extra;
41
+ weight += extra;
42
+ },
43
+ release: () => { if (!released) { released = true; this.active -= weight; } },
44
+ };
45
+ }
46
+ }
47
+
48
+ /** Count unique key/pattern edges shared by stored and pending registrations. */
49
+ export class DependencyBudget {
50
+ private edges = 0;
51
+ private readonly keys = new Map<string, Map<string, number>>();
52
+ constructor(private readonly maximum: number) {}
53
+ reserve(key: string, patterns: string[]): () => void {
54
+ const unique = [...new Set(patterns)];
55
+ const refs = this.keys.get(key) ?? new Map<string, number>();
56
+ const extra = unique.filter(pattern => !refs.has(pattern)).length;
57
+ if (extra > this.maximum - this.edges) throw new CacheCapacityError('dependency edges');
58
+ this.edges += extra;
59
+ if (unique.length) this.keys.set(key, refs);
60
+ for (const pattern of unique) refs.set(pattern, (refs.get(pattern) ?? 0) + 1);
61
+ let released = false;
62
+ return () => {
63
+ if (released) return;
64
+ released = true;
65
+ for (const pattern of unique) {
66
+ const count = refs.get(pattern)! - 1;
67
+ if (count > 0) refs.set(pattern, count);
68
+ else { refs.delete(pattern); this.edges--; }
69
+ }
70
+ if (!refs.size && this.keys.get(key) === refs) this.keys.delete(key);
71
+ };
72
+ }
73
+ }
@@ -0,0 +1,4 @@
1
+ /** Bound externally restored metadata; revisions are opaque equality identities. */
2
+ export function isWriteRevision(value: unknown): value is string {
3
+ return typeof value === 'string' && value.length > 0 && value.length <= 128;
4
+ }
@@ -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,
@@ -51,6 +56,7 @@ export class WasmBloomFilter {
51
56
  private readonly exports: BloomWasmExports;
52
57
  private readonly mem: Uint8Array;
53
58
  private readonly stagingTarget: Uint8Array;
59
+ private readonly stagingView: DataView;
54
60
  private readonly encoder = new TextEncoder();
55
61
  private readonly numBits = 100_000;
56
62
  /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
@@ -59,17 +65,31 @@ export class WasmBloomFilter {
59
65
  private _insertionCount = 0;
60
66
 
61
67
  constructor() {
62
- const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
68
+ const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
63
69
  this.exports = instance.exports as unknown as BloomWasmExports;
64
70
  this.mem = new Uint8Array(this.exports.memory.buffer);
65
71
  this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
72
+ this.stagingView = new DataView(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
66
73
  const k = 7, p = 0.01;
67
74
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
68
75
  }
69
76
 
70
77
  private writeKey(key: string): number {
71
78
  if (key.length === 0) return 0;
72
- return this.encoder.encodeInto(key, this.stagingTarget).written;
79
+ const encoded = this.encoder.encodeInto(key, this.stagingTarget);
80
+ if (encoded.read === key.length) return encoded.written;
81
+ // Hash the complete key when UTF-8 does not fit. 0xff cannot occur in valid
82
+ // UTF-8, so digests cannot alias a short key's staging representation.
83
+ let first = 0x811c9dc5, second = 5381;
84
+ for (let index = 0; index < key.length; index++) {
85
+ const unit = key.charCodeAt(index);
86
+ first = Math.imul(first ^ unit, 0x01000193) >>> 0;
87
+ second = (Math.imul(second, 33) ^ unit) >>> 0;
88
+ }
89
+ this.stagingTarget[0] = 0xff;
90
+ this.stagingView.setUint32(1, first, true);
91
+ this.stagingView.setUint32(5, second, true);
92
+ return 9;
73
93
  }
74
94
 
75
95
  add(key: string): void {
@@ -29,6 +29,7 @@ import { dirname, join } from 'path';
29
29
  import os from 'os';
30
30
  import type { EncryptionMode } from './encryption.js';
31
31
  import type { CompressionAlgorithm } from './compression.js';
32
+ import { positiveLimit, WorkLimit } from './utils/work-limits.js';
32
33
 
33
34
  // Locate the serialize-worker entry point.
34
35
  // Production: tsup emits compile .js files as flat siblings → use .js path.
@@ -60,7 +61,8 @@ try {
60
61
  }
61
62
  } catch {
62
63
  // CJS fallback — __dirname is available natively in CJS (and shimmed by tsup for ESM).
63
- _workerFile = join(__dirname, 'serialize-worker.js');
64
+ const sibling = join(__dirname, 'serialize-worker.js');
65
+ _workerFile = existsSync(sibling) ? sibling : join(dirname(__dirname), 'serialize-worker.js');
64
66
  }
65
67
 
66
68
  export interface WorkerPoolOptions {
@@ -69,10 +71,15 @@ export interface WorkerPoolOptions {
69
71
  mode: EncryptionMode;
70
72
  prevKeyBase64?: string;
71
73
  prevMode?: EncryptionMode;
74
+ allowLegacyPlaintextRead?: boolean;
72
75
  compression?: CompressionAlgorithm;
73
76
  compressionThresholdBytes?: number;
74
77
  /** Number of worker threads. Default: min(4, availableCPUs). */
75
78
  size?: number;
79
+ /** Bound all outstanding tasks, including retiring workers during key rotation. Default: 256. */
80
+ maxPendingTasks?: number;
81
+ /** Outstanding input/context byte admission, shared across rotations. Default: 64 MiB. Not an RSS ceiling. */
82
+ maxPendingBytes?: number;
76
83
  }
77
84
 
78
85
  type PendingEntry = { resolve: (v: string) => void; reject: (e: Error) => void };
@@ -104,6 +111,8 @@ export function getTransferableArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffe
104
111
  }
105
112
 
106
113
  export class WorkerPool {
114
+ private readonly limit: WorkLimit;
115
+ private readonly byteLimit: WorkLimit;
107
116
  private workers: Worker[] = [];
108
117
  private pending: Map<number, PendingEntry>[] = [];
109
118
  private _nextId = 0;
@@ -111,6 +120,8 @@ export class WorkerPool {
111
120
  private _available = false;
112
121
 
113
122
  constructor(opts: WorkerPoolOptions) {
123
+ this.limit = new WorkLimit(positiveLimit(opts.maxPendingTasks, 256, 'maxPendingTasks'), 'worker tasks');
124
+ this.byteLimit = new WorkLimit(positiveLimit(opts.maxPendingBytes, 64 * 1024 * 1024, 'maxPendingBytes'), 'worker input bytes');
114
125
  try {
115
126
  const { workers, pending } = this._spawnWorkers(opts);
116
127
  this.workers = workers;
@@ -125,11 +136,13 @@ export class WorkerPool {
125
136
 
126
137
  private _spawnWorkers(opts: WorkerPoolOptions): { workers: Worker[]; pending: Map<number, PendingEntry>[] } {
127
138
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
139
+ if (!Number.isInteger(size) || size > 32 || !existsSync(_workerFile)) throw new Error('Worker pool unavailable or invalid worker count');
128
140
  const workerData = {
129
141
  keyBase64: opts.keyBase64,
130
142
  mode: opts.mode,
131
143
  prevKeyBase64: opts.prevKeyBase64 ?? '',
132
144
  prevMode: opts.prevMode,
145
+ allowLegacyPlaintextRead: opts.allowLegacyPlaintextRead,
133
146
  compression: opts.compression ?? 'none',
134
147
  compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024,
135
148
  };
@@ -140,7 +153,7 @@ export class WorkerPool {
140
153
  const createWorker = (index: number): Worker => {
141
154
  const worker = new Worker(_workerFile, {
142
155
  workerData,
143
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
156
+ execArgv: _workerExecArgv, // Do not inherit --input-type/eval or application loader flags.
144
157
  });
145
158
  const pending = pendingList[index] ?? new Map<number, PendingEntry>();
146
159
  if (!pendingList[index]) pendingList[index] = pending;
@@ -175,7 +188,7 @@ export class WorkerPool {
175
188
  worker.unref();
176
189
 
177
190
  // If pool is still active and worker exited with non-zero code, auto-replace
178
- if (this._available && exitCode !== 0 && workers[index] === worker) {
191
+ if (this._available && this.workers === workers && workers[index] === worker) {
179
192
  try {
180
193
  workers[index] = createWorker(index);
181
194
  } catch { /* ok */ }
@@ -186,9 +199,11 @@ export class WorkerPool {
186
199
  return worker;
187
200
  };
188
201
 
189
- for (let i = 0; i < size; i++) {
190
- const worker = createWorker(i);
191
- workers.push(worker);
202
+ try {
203
+ for (let i = 0; i < size; i++) workers.push(createWorker(i));
204
+ } catch (error) {
205
+ for (const worker of workers) void worker.terminate().catch(() => {});
206
+ throw error;
192
207
  }
193
208
 
194
209
  return { workers, pending: pendingList };
@@ -223,32 +238,42 @@ export class WorkerPool {
223
238
  entry.reject(new Error('WorkerPool replaced during key rotation'));
224
239
  }
225
240
  oldPending[i]?.clear();
226
- oldWorkers[i]?.terminate().catch(() => {});
241
+ await oldWorkers[i]?.terminate().catch(() => {});
227
242
  }
228
243
  }
229
244
 
230
245
  get isAvailable(): boolean { return this._available; }
231
246
 
232
247
  /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
233
- encrypt(payload: string | Buffer | Uint8Array): Promise<string> {
234
- return this._dispatch('encrypt', payload);
248
+ encrypt(payload: string | Buffer | Uint8Array, context?: string): Promise<string> {
249
+ return this._dispatch('encrypt', payload, context);
235
250
  }
236
251
 
237
252
  /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
238
- decrypt(payload: string | Buffer | Uint8Array): Promise<string> {
239
- return this._dispatch('decrypt', payload);
253
+ decrypt(payload: string | Buffer | Uint8Array, context?: string): Promise<string> {
254
+ return this._dispatch('decrypt', payload, context);
240
255
  }
241
256
 
242
- private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array): Promise<string> {
257
+ private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array, context?: string): Promise<string> {
243
258
  if (!this._available || this.workers.length === 0) {
244
259
  return Promise.reject(new Error('WorkerPool is not available'));
245
260
  }
261
+ let release: () => void;
262
+ try { release = this.limit.acquire(); }
263
+ catch (error) { return Promise.reject(error); }
264
+ let releaseBytes: () => void;
265
+ try {
266
+ const stringBytes = (value: string) => Math.max(Buffer.byteLength(value, 'utf8'), value.length * 2);
267
+ const bytes = (typeof payload === 'string' ? stringBytes(payload) : payload.byteLength) + (context ? stringBytes(context) : 0);
268
+ releaseBytes = this.byteLimit.acquire(Math.max(1, bytes));
269
+ } catch (error) { release(); return Promise.reject(error); }
246
270
  const id = this._nextId++;
247
271
  const idx = this._robin;
248
272
  const worker = this.workers[idx];
249
273
  const pending = this.pending[idx];
250
274
  this._robin = (this._robin + 1) % this.workers.length;
251
275
 
276
+ return new Promise<string>((resolve, reject) => {
252
277
  let transferable: ArrayBuffer | null = null;
253
278
  let dataToSend: string | Uint8Array = typeof payload === 'string' ? payload : payload;
254
279
 
@@ -267,13 +292,17 @@ export class WorkerPool {
267
292
 
268
293
  const transferList = transferable ? [transferable] : [];
269
294
 
270
- return new Promise<string>((resolve, reject) => {
271
295
  pending.set(id, { resolve, reject });
272
296
  // Re-ref the worker while this request is in flight so the event loop
273
297
  // stays alive even in short-lived scripts (benchmarks, CLI tools).
274
298
  worker.ref();
275
- worker.postMessage({ id, type, payload: dataToSend }, transferList);
276
- });
299
+ try { worker.postMessage({ id, type, payload: dataToSend, context }, transferList); }
300
+ catch (error) {
301
+ pending.delete(id);
302
+ if (pending.size === 0) worker.unref();
303
+ reject(error);
304
+ }
305
+ }).finally(() => { release(); releaseBytes(); });
277
306
  }
278
307
 
279
308
  /** Terminate all worker threads. In-flight promises are rejected. */
package/src/wtiny-lfu.ts CHANGED
@@ -65,6 +65,36 @@ export interface EvictionResult<K, V> {
65
65
  rejected?: { key: K; value: V; segment: 'window' };
66
66
  }
67
67
 
68
+ interface SegmentCapacities {
69
+ total: number;
70
+ window: number;
71
+ probation: number;
72
+ protected: number;
73
+ }
74
+
75
+ /**
76
+ * Normalize W-TinyLFU's integer segment budgets without allowing minimum
77
+ * segment sizes to exceed the configured total. Small caches cannot always
78
+ * have a non-empty window, probation, and protected segment simultaneously.
79
+ */
80
+ function segmentCapacities(capacity: number, windowPercent = 0.01, protectedPercent = 0.80): SegmentCapacities {
81
+ const total = Number.isFinite(capacity) && capacity > 0 ? Math.floor(capacity) : 0;
82
+ if (total === 0) return { total: 0, window: 0, probation: 0, protected: 0 };
83
+
84
+ const windowRatio = Number.isFinite(windowPercent) ? Math.min(1, Math.max(0, windowPercent)) : 0.01;
85
+ const protectedRatio = Number.isFinite(protectedPercent) ? Math.min(1, Math.max(0, protectedPercent)) : 0.80;
86
+ const window = Math.min(total, Math.max(1, Math.floor(total * windowRatio)));
87
+ const main = total - window;
88
+ if (main === 0) return { total, window, probation: 0, protected: 0 };
89
+
90
+ // Keep both main segments alive when there is room, while reserving the
91
+ // sole main slot for protected entries when main capacity is one.
92
+ const protectedCapacity = main === 1
93
+ ? 1
94
+ : Math.min(main - 1, Math.max(1, Math.floor(main * protectedRatio)));
95
+ return { total, window, probation: main - protectedCapacity, protected: protectedCapacity };
96
+ }
97
+
68
98
  /**
69
99
  * 4-row Count-Min Sketch for TinyLFU frequency estimation.
70
100
  * Uses Murmur3-style bit-mixes of FNV-1a digests with periodic halving decay.
@@ -178,15 +208,11 @@ export class WTinyLfuCache<K = string, V = unknown> {
178
208
  private demotionCount = 0;
179
209
 
180
210
  constructor(options: WTinyLfuOptions) {
181
- this.maxTotal = Math.max(2, options.capacity);
182
-
183
- const winPercent = options.windowPercent ?? 0.01;
184
- this.maxWindow = Math.max(1, Math.floor(this.maxTotal * winPercent));
185
-
186
- const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
187
- const protPercent = options.protectedPercent ?? 0.80;
188
- this.maxProtected = Math.max(1, Math.floor(mainCapacity * protPercent));
189
- this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
211
+ const segments = segmentCapacities(options.capacity, options.windowPercent, options.protectedPercent);
212
+ this.maxTotal = segments.total;
213
+ this.maxWindow = segments.window;
214
+ this.maxProtected = segments.protected;
215
+ this.maxProbation = segments.probation;
190
216
 
191
217
  this.sketch = new TinyLfuSketch(options.sketchWidth ?? 1024);
192
218
  }
@@ -272,6 +298,12 @@ export class WTinyLfuCache<K = string, V = unknown> {
272
298
 
273
299
  const result: EvictionResult<K, V> = {};
274
300
 
301
+ if (this.maxTotal === 0) {
302
+ result.rejected = { key, value, segment: 'window' };
303
+ this.rejectionCount++;
304
+ return result;
305
+ }
306
+
275
307
  // ── 1. Update existing key if present in any segment ────────────────────
276
308
  if (this.window.has(key)) {
277
309
  this.window.delete(key);
@@ -305,6 +337,12 @@ export class WTinyLfuCache<K = string, V = unknown> {
305
337
  const candVal = this.window.get(candKey)!;
306
338
  this.window.delete(candKey);
307
339
 
340
+ if (this.maxProbation + this.maxProtected === 0) {
341
+ this.rejectionCount++;
342
+ result.rejected = { key: candKey, value: candVal, segment: 'window' };
343
+ return result;
344
+ }
345
+
308
346
  // If Main cache has headroom, admit candidate directly to Probation
309
347
  if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
310
348
  this.probation.set(candKey, candVal);
@@ -460,12 +498,13 @@ export class WTinyLfuPolicy {
460
498
  private readonly sketch: { estimate(key: string): number; increment(key: string): void },
461
499
  windowPercent = 0.01,
462
500
  protectedPercent = 0.80,
501
+ private readonly canEvict?: (key: string) => boolean,
463
502
  ) {
464
- this.maxTotal = Math.max(2, capacity);
465
- this.maxWindow = Math.max(1, Math.floor(this.maxTotal * windowPercent));
466
- const mainCapacity = Math.max(1, this.maxTotal - this.maxWindow);
467
- this.maxProtected = Math.max(1, Math.floor(mainCapacity * protectedPercent));
468
- this.maxProbation = Math.max(1, mainCapacity - this.maxProtected);
503
+ const segments = segmentCapacities(capacity, windowPercent, protectedPercent);
504
+ this.maxTotal = segments.total;
505
+ this.maxWindow = segments.window;
506
+ this.maxProtected = segments.protected;
507
+ this.maxProbation = segments.probation;
469
508
  }
470
509
 
471
510
  get windowSize(): number {
@@ -515,6 +554,11 @@ export class WTinyLfuPolicy {
515
554
  }
516
555
 
517
556
  onSet(key: string, isUpdate: boolean): WTinyLfuAdmissionDecision {
557
+ if (this.maxTotal === 0) {
558
+ this.rejectionCount++;
559
+ return { admit: false, candidateKey: key };
560
+ }
561
+
518
562
  if (isUpdate) {
519
563
  if (this.window.has(key)) {
520
564
  this.window.delete(key);
@@ -541,6 +585,11 @@ export class WTinyLfuPolicy {
541
585
  const candKey = this.window.values().next().value!;
542
586
  this.window.delete(candKey);
543
587
 
588
+ if (this.maxProbation + this.maxProtected === 0) {
589
+ this.rejectionCount++;
590
+ return { admit: false, candidateKey: candKey };
591
+ }
592
+
544
593
  // If main cache has headroom, admit to Probation
545
594
  if (this.probation.size + this.protected_.size < this.maxProbation + this.maxProtected) {
546
595
  this.probation.add(candKey);
@@ -549,20 +598,33 @@ export class WTinyLfuPolicy {
549
598
  }
550
599
 
551
600
  // Main space full: TinyLFU gate
552
- let victimKey: string;
601
+ let victimKey: string | undefined;
553
602
  let victimIsProbation = true;
554
603
 
555
- if (this.probation.size > 0) {
556
- victimKey = this.probation.values().next().value!;
557
- } else {
558
- victimKey = this.protected_.values().next().value!;
604
+ for (const candidate of this.probation) {
605
+ if (!this.canEvict || this.canEvict(candidate)) { victimKey = candidate; break; }
606
+ }
607
+ if (victimKey === undefined) {
608
+ for (const candidate of this.protected_) {
609
+ if (!this.canEvict || this.canEvict(candidate)) { victimKey = candidate; break; }
610
+ }
559
611
  victimIsProbation = false;
560
612
  }
561
613
 
614
+ if (victimKey === undefined) {
615
+ if (this.canEvict && !this.canEvict(candKey)) {
616
+ this.window.delete(key);
617
+ this.window.add(candKey);
618
+ return { admit: false, candidateKey: key };
619
+ }
620
+ this.rejectionCount++;
621
+ return { admit: false, candidateKey: candKey };
622
+ }
623
+
562
624
  const candFreq = this.sketch.estimate(candKey);
563
625
  const victimFreq = this.sketch.estimate(victimKey);
564
626
 
565
- if (candFreq > victimFreq) {
627
+ if ((this.canEvict && !this.canEvict(candKey)) || candFreq > victimFreq) {
566
628
  // Candidate wins: evict victim, admit candidate to Probation
567
629
  if (victimIsProbation) {
568
630
  this.probation.delete(victimKey);
@@ -1,12 +0,0 @@
1
- import {
2
- CacheService,
3
- ProcessTerminationBus,
4
- deepMergeOptions
5
- } from "./chunk-JYQFQJNJ.js";
6
- import "./chunk-UBWLPKTI.js";
7
- import "./chunk-2AJKEQMZ.js";
8
- export {
9
- CacheService,
10
- ProcessTerminationBus,
11
- deepMergeOptions
12
- };