tricache 0.6.7 → 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 (55) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1428 -970
  3. package/bin/tricache.js +8 -0
  4. package/dist/cache-service-5GATUYAK.js +7 -0
  5. package/dist/cache-service-D8tIXmzb.d.ts +1498 -0
  6. package/dist/chunk-EUGYR7KR.js +4629 -0
  7. package/dist/chunk-UBSR5UYA.js +0 -0
  8. package/dist/{chunk-FKY5R3CE.js → chunk-X5AXHPVD.js} +139 -6
  9. package/dist/cli.cjs +5238 -0
  10. package/dist/cli.d.ts +11 -0
  11. package/dist/cli.js +130 -0
  12. package/dist/drizzle/index.cjs +5218 -0
  13. package/dist/drizzle/index.d.ts +44 -0
  14. package/dist/drizzle/index.js +46 -0
  15. package/dist/http/index.cjs +5374 -0
  16. package/dist/http/index.d.ts +33 -0
  17. package/dist/http/index.js +200 -0
  18. package/dist/index.cjs +1245 -209
  19. package/dist/index.d.ts +15 -1230
  20. package/dist/index.js +11 -3705
  21. package/dist/nestjs/index.cjs +5362 -0
  22. package/dist/nestjs/index.d.ts +210 -0
  23. package/dist/nestjs/index.js +250 -0
  24. package/dist/next/index.cjs +5407 -0
  25. package/dist/next/index.d.ts +208 -0
  26. package/dist/next/index.js +297 -0
  27. package/dist/prisma/index.cjs +123 -0
  28. package/dist/prisma/index.d.ts +60 -0
  29. package/dist/prisma/index.js +87 -0
  30. package/dist/serialize-worker.cjs +190 -15
  31. package/dist/serialize-worker.js +63 -12
  32. package/package.json +71 -21
  33. package/src/cache-service.ts +3294 -2429
  34. package/src/cli.ts +143 -0
  35. package/src/compression.ts +56 -0
  36. package/src/disk-tier.ts +821 -757
  37. package/src/drizzle/index.ts +86 -0
  38. package/src/encryption.ts +513 -442
  39. package/src/http/index.ts +265 -0
  40. package/src/index.ts +7 -0
  41. package/src/nestjs/decorators.ts +161 -0
  42. package/src/nestjs/index.ts +23 -0
  43. package/src/nestjs/tricache.module.ts +104 -0
  44. package/src/nestjs/tricache.store.ts +97 -0
  45. package/src/nestjs/types.ts +79 -0
  46. package/src/next/cache-handler.ts +268 -0
  47. package/src/next/index.ts +37 -0
  48. package/src/next/isr-handler.ts +105 -0
  49. package/src/next/types.ts +130 -0
  50. package/src/prisma/index.ts +154 -0
  51. package/src/serialize-worker.ts +77 -13
  52. package/src/smart-memory-cache.ts +1026 -1010
  53. package/src/types.ts +911 -732
  54. package/src/wasm/bloom-filter-wasm.ts +3 -2
  55. package/src/worker-pool.ts +156 -42
@@ -43,6 +43,7 @@ const BLOOM_WASM_MODULE = new WebAssembly.Module(Buffer.from(BLOOM_WASM_BASE64,
43
43
  export class WasmBloomFilter {
44
44
  private readonly exports: BloomWasmExports;
45
45
  private readonly mem: Uint8Array;
46
+ private readonly stagingTarget: Uint8Array;
46
47
  private readonly encoder = new TextEncoder();
47
48
  private readonly numBits = 100_000;
48
49
  /** Pre-computed — k and numBits are fixed constants; no need to recalculate on every probe. */
@@ -54,14 +55,14 @@ export class WasmBloomFilter {
54
55
  const instance = new WebAssembly.Instance(BLOOM_WASM_MODULE, {});
55
56
  this.exports = instance.exports as unknown as BloomWasmExports;
56
57
  this.mem = new Uint8Array(this.exports.memory.buffer);
58
+ this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
57
59
  const k = 7, p = 0.01;
58
60
  this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / k)) / k);
59
61
  }
60
62
 
61
63
  private writeKey(key: string): number {
62
64
  if (key.length === 0) return 0;
63
- const target = this.mem.subarray(KEY_STAGING_OFFSET, KEY_STAGING_OFFSET + MAX_KEY_BYTES);
64
- return this.encoder.encodeInto(key, target).written;
65
+ return this.encoder.encodeInto(key, this.stagingTarget).written;
65
66
  }
66
67
 
67
68
  add(key: string): void {
@@ -28,6 +28,7 @@ import { fileURLToPath } from 'url';
28
28
  import { dirname, join } from 'path';
29
29
  import os from 'os';
30
30
  import type { EncryptionMode } from './encryption.js';
31
+ import type { CompressionAlgorithm } from './compression.js';
31
32
 
32
33
  // Locate the serialize-worker entry point.
33
34
  // Production: tsup emits compile .js files as flat siblings → use .js path.
@@ -68,97 +69,210 @@ export interface WorkerPoolOptions {
68
69
  mode: EncryptionMode;
69
70
  prevKeyBase64?: string;
70
71
  prevMode?: EncryptionMode;
72
+ compression?: CompressionAlgorithm;
73
+ compressionThresholdBytes?: number;
71
74
  /** Number of worker threads. Default: min(4, availableCPUs). */
72
75
  size?: number;
73
76
  }
74
77
 
75
78
  type PendingEntry = { resolve: (v: string) => void; reject: (e: Error) => void };
76
79
 
80
+ /**
81
+ * Safely extracts or allocates a transferable ArrayBuffer for worker_threads postMessage.
82
+ *
83
+ * Prevents detach corruption on Node's shared 8 KB internal Buffer pool (Buffer.poolSize):
84
+ * - If the buffer owns the entire underlying ArrayBuffer (byteOffset === 0 && byteLength === buffer.byteLength),
85
+ * it can be transferred directly with zero copies.
86
+ * - For large pooled slices (>= 128 KB), copies to an isolated ArrayBuffer so transferring it
87
+ * detaches only the copy and never the main-thread pooled slab.
88
+ * - For smaller pooled slices (< 128 KB), returns null to let structured cloning handle it without transfer.
89
+ */
90
+ export function getTransferableArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer | null {
91
+ if (buf.buffer instanceof ArrayBuffer) {
92
+ if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
93
+ return buf.buffer;
94
+ }
95
+ }
96
+
97
+ if (buf.byteLength >= 131_072) {
98
+ const copy = new ArrayBuffer(buf.byteLength);
99
+ new Uint8Array(copy).set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
100
+ return copy;
101
+ }
102
+
103
+ return null;
104
+ }
105
+
77
106
  export class WorkerPool {
78
- private readonly workers: Worker[] = [];
79
- private readonly pending: Map<number, PendingEntry>[] = [];
107
+ private workers: Worker[] = [];
108
+ private pending: Map<number, PendingEntry>[] = [];
80
109
  private _nextId = 0;
81
110
  private _robin = 0;
82
111
  private _available = false;
83
112
 
84
113
  constructor(opts: WorkerPoolOptions) {
114
+ try {
115
+ const { workers, pending } = this._spawnWorkers(opts);
116
+ this.workers = workers;
117
+ this.pending = pending;
118
+ this._available = true;
119
+ } catch {
120
+ // Worker creation failed (e.g., missing file, restricted runtime).
121
+ // Callers check isAvailable before using the pool.
122
+ this._destroy();
123
+ }
124
+ }
125
+
126
+ private _spawnWorkers(opts: WorkerPoolOptions): { workers: Worker[]; pending: Map<number, PendingEntry>[] } {
85
127
  const size = Math.max(1, opts.size ?? Math.min(4, availableCpus()));
86
128
  const workerData = {
87
129
  keyBase64: opts.keyBase64,
88
130
  mode: opts.mode,
89
131
  prevKeyBase64: opts.prevKeyBase64 ?? '',
90
132
  prevMode: opts.prevMode,
133
+ compression: opts.compression ?? 'none',
134
+ compressionThresholdBytes: opts.compressionThresholdBytes ?? 1024,
91
135
  };
92
136
 
93
- try {
94
- for (let i = 0; i < size; i++) {
95
- const worker = new Worker(_workerFile, {
96
- workerData,
97
- execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
98
- });
99
- const pending = new Map<number, PendingEntry>();
100
-
101
- worker.on('message', (msg: { id: number; result?: string; error?: string }) => {
102
- const entry = pending.get(msg.id);
103
- if (!entry) return;
104
- pending.delete(msg.id);
105
- // Unref the worker once its queue is empty so idle workers don't
106
- // prevent the process from exiting (e.g. CLI scripts, benchmarks).
107
- if (pending.size === 0) worker.unref();
108
- if (msg.error !== undefined) {
109
- entry.reject(new Error(msg.error));
137
+ const workers: Worker[] = [];
138
+ const pendingList: Map<number, PendingEntry>[] = [];
139
+
140
+ const createWorker = (index: number): Worker => {
141
+ const worker = new Worker(_workerFile, {
142
+ workerData,
143
+ execArgv: _workerExecArgv.length > 0 ? _workerExecArgv : undefined,
144
+ });
145
+ const pending = pendingList[index] ?? new Map<number, PendingEntry>();
146
+ if (!pendingList[index]) pendingList[index] = pending;
147
+
148
+ worker.on('message', (msg: { id: number; result?: string | Uint8Array; error?: string; isTransfer?: boolean }) => {
149
+ const entry = pending.get(msg.id);
150
+ if (!entry) return;
151
+ pending.delete(msg.id);
152
+ if (pending.size === 0) worker.unref();
153
+ if (msg.error !== undefined) {
154
+ entry.reject(new Error(msg.error));
155
+ } else if (msg.result !== undefined) {
156
+ if (typeof msg.result === 'string') {
157
+ entry.resolve(msg.result);
110
158
  } else {
111
- entry.resolve(msg.result!);
159
+ entry.resolve(Buffer.from(msg.result.buffer, msg.result.byteOffset, msg.result.byteLength).toString('utf8'));
112
160
  }
113
- });
161
+ }
162
+ });
114
163
 
115
- worker.on('error', (err: Error) => {
116
- // On unhandled worker error, reject all in-flight requests for this worker.
117
- for (const [, entry] of pending) entry.reject(err);
118
- pending.clear();
119
- worker.unref();
120
- });
164
+ worker.on('error', (err: Error) => {
165
+ for (const [, entry] of pending) entry.reject(err);
166
+ pending.clear();
167
+ worker.unref();
168
+ });
121
169
 
122
- // Workers start unreffed; they are re-reffed in _dispatch while a task
123
- // is in flight, then unreffed again once the pending queue drains.
170
+ worker.on('exit', (exitCode: number) => {
171
+ for (const [, entry] of pending) {
172
+ entry.reject(new Error(`Worker thread exited unexpectedly with code ${exitCode}`));
173
+ }
174
+ pending.clear();
124
175
  worker.unref();
125
176
 
126
- this.workers.push(worker);
127
- this.pending.push(pending);
177
+ // If pool is still active and worker exited with non-zero code, auto-replace
178
+ if (this._available && exitCode !== 0 && workers[index] === worker) {
179
+ try {
180
+ workers[index] = createWorker(index);
181
+ } catch { /* ok */ }
182
+ }
183
+ });
184
+
185
+ worker.unref();
186
+ return worker;
187
+ };
188
+
189
+ for (let i = 0; i < size; i++) {
190
+ const worker = createWorker(i);
191
+ workers.push(worker);
192
+ }
193
+
194
+ return { workers, pending: pendingList };
195
+ }
196
+
197
+ /**
198
+ * Gracefully drain in-flight tasks and re-initialize workers with updated key material.
199
+ * Atomically swaps workers so new requests immediately route to new workers,
200
+ * while existing in-flight operations complete on old workers before termination.
201
+ */
202
+ async drainAndReinit(opts: WorkerPoolOptions): Promise<void> {
203
+ const { workers: newWorkers, pending: newPending } = this._spawnWorkers(opts);
204
+
205
+ // Atomically swap references
206
+ const oldWorkers = this.workers;
207
+ const oldPending = this.pending;
208
+ this.workers = newWorkers;
209
+ this.pending = newPending;
210
+ this._robin = 0;
211
+ this._available = true;
212
+
213
+ // Await drain of in-flight tasks on old workers
214
+ const start = Date.now();
215
+ while (oldPending.some(m => m.size > 0)) {
216
+ if (Date.now() - start > 5_000) break; // 5s timeout guard
217
+ await new Promise(r => setTimeout(r, 10));
218
+ }
219
+
220
+ // Cleanly terminate old workers
221
+ for (let i = 0; i < oldWorkers.length; i++) {
222
+ for (const [, entry] of oldPending[i] ?? []) {
223
+ entry.reject(new Error('WorkerPool replaced during key rotation'));
128
224
  }
129
- this._available = true;
130
- } catch {
131
- // Worker creation failed (e.g., missing file, restricted runtime).
132
- // Callers check isAvailable before using the pool.
133
- this._destroy();
225
+ oldPending[i]?.clear();
226
+ oldWorkers[i]?.terminate().catch(() => {});
134
227
  }
135
228
  }
136
229
 
137
230
  get isAvailable(): boolean { return this._available; }
138
231
 
139
- /** Encrypt a JSON string in a worker thread. Returns the same encrypted envelope string as CacheEncryption.encrypt(). */
140
- encrypt(payload: string): Promise<string> {
232
+ /** Encrypt a string or buffer in a worker thread. Returns the encrypted envelope string. */
233
+ encrypt(payload: string | Buffer | Uint8Array): Promise<string> {
141
234
  return this._dispatch('encrypt', payload);
142
235
  }
143
236
 
144
- /** Decrypt an encrypted envelope string in a worker thread. Returns the original JSON string. */
145
- decrypt(payload: string): Promise<string> {
237
+ /** Decrypt an encrypted envelope string or buffer in a worker thread. Returns the original JSON string. */
238
+ decrypt(payload: string | Buffer | Uint8Array): Promise<string> {
146
239
  return this._dispatch('decrypt', payload);
147
240
  }
148
241
 
149
- private _dispatch(type: 'encrypt' | 'decrypt', payload: string): Promise<string> {
242
+ private _dispatch(type: 'encrypt' | 'decrypt', payload: string | Buffer | Uint8Array): Promise<string> {
243
+ if (!this._available || this.workers.length === 0) {
244
+ return Promise.reject(new Error('WorkerPool is not available'));
245
+ }
150
246
  const id = this._nextId++;
151
247
  const idx = this._robin;
152
248
  const worker = this.workers[idx];
153
249
  const pending = this.pending[idx];
154
250
  this._robin = (this._robin + 1) % this.workers.length;
155
251
 
252
+ let transferable: ArrayBuffer | null = null;
253
+ let dataToSend: string | Uint8Array = typeof payload === 'string' ? payload : payload;
254
+
255
+ if (typeof payload !== 'string') {
256
+ transferable = getTransferableArrayBuffer(payload);
257
+ if (transferable) {
258
+ dataToSend = new Uint8Array(transferable);
259
+ }
260
+ } else if (payload.length >= 131_072) {
261
+ const buf = Buffer.from(payload, 'utf8');
262
+ transferable = getTransferableArrayBuffer(buf);
263
+ if (transferable) {
264
+ dataToSend = new Uint8Array(transferable);
265
+ }
266
+ }
267
+
268
+ const transferList = transferable ? [transferable] : [];
269
+
156
270
  return new Promise<string>((resolve, reject) => {
157
271
  pending.set(id, { resolve, reject });
158
272
  // Re-ref the worker while this request is in flight so the event loop
159
273
  // stays alive even in short-lived scripts (benchmarks, CLI tools).
160
274
  worker.ref();
161
- worker.postMessage({ id, type, payload });
275
+ worker.postMessage({ id, type, payload: dataToSend }, transferList);
162
276
  });
163
277
  }
164
278