tricache 1.0.2 → 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 (101) hide show
  1. package/README.md +78 -90
  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-CWI4jkS7.d.cts → cache-service-BV5T8-20.d.cts} +122 -21
  6. package/dist/cache-service-UZXOQGEY.js +14 -0
  7. package/dist/{cache-service-B108FzER.d.ts → cache-service-tpyrXvlH.d.ts} +122 -21
  8. package/dist/{chunk-UBWLPKTI.js → chunk-EJXG7WO6.js} +152 -32
  9. package/dist/{chunk-H4GFLQ26.js → chunk-KV7KISK2.js} +47 -1
  10. package/dist/{chunk-WYF7NOAT.js → chunk-MB3DMVWN.js} +2111 -543
  11. package/dist/{chunk-OYDU3SMI.js → chunk-RBJRTGFK.js} +5 -0
  12. package/dist/chunk-S5N65I45.js +17 -0
  13. package/dist/cli.cjs +2454 -572
  14. package/dist/cli.js +186 -11
  15. package/dist/dashboard/index.d.cts +2 -2
  16. package/dist/dashboard/index.d.ts +2 -2
  17. package/dist/drizzle/index.cjs +2335 -571
  18. package/dist/drizzle/index.d.cts +2 -2
  19. package/dist/drizzle/index.d.ts +2 -2
  20. package/dist/drizzle/index.js +6 -2
  21. package/dist/edge/index.cjs +145 -43
  22. package/dist/edge/index.d.cts +11 -4
  23. package/dist/edge/index.d.ts +11 -4
  24. package/dist/edge/index.js +118 -43
  25. package/dist/hono/index.cjs +2322 -569
  26. package/dist/hono/index.d.cts +2 -2
  27. package/dist/hono/index.d.ts +2 -2
  28. package/dist/hono/index.js +2 -2
  29. package/dist/{hono-C886ok3X.d.cts → hono-CMv2VdQ6.d.cts} +18 -5
  30. package/dist/{hono-3rDMYVtY.d.ts → hono-Dvq04kX9.d.ts} +18 -5
  31. package/dist/http/index.cjs +2323 -570
  32. package/dist/http/index.d.cts +3 -3
  33. package/dist/http/index.d.ts +3 -3
  34. package/dist/http/index.js +4 -4
  35. package/dist/index.cjs +2554 -620
  36. package/dist/index.d.cts +88 -23
  37. package/dist/index.d.ts +88 -23
  38. package/dist/index.js +873 -16
  39. package/dist/{murmur3-CMGw9PbV.d.cts → murmur3-DF8BFRnu.d.cts} +1 -0
  40. package/dist/{murmur3-CMGw9PbV.d.ts → murmur3-DF8BFRnu.d.ts} +1 -0
  41. package/dist/nestjs/index.cjs +2292 -574
  42. package/dist/nestjs/index.d.cts +19 -5
  43. package/dist/nestjs/index.d.ts +19 -5
  44. package/dist/nestjs/index.js +25 -19
  45. package/dist/next/index.cjs +2306 -571
  46. package/dist/next/index.d.cts +8 -2
  47. package/dist/next/index.d.ts +8 -2
  48. package/dist/next/index.js +36 -9
  49. package/dist/prisma/index.cjs +26 -25
  50. package/dist/prisma/index.d.cts +2 -2
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +14 -25
  53. package/dist/serialize-worker.cjs +162 -39
  54. package/dist/serialize-worker.js +9 -7
  55. package/dist/{types-BA4pz1A0.d.cts → types-F8vRWMrE.d.cts} +162 -45
  56. package/dist/{types-BA4pz1A0.d.ts → types-F8vRWMrE.d.ts} +162 -45
  57. package/package.json +21 -2
  58. package/src/adapters/auto-pipeliner.ts +52 -11
  59. package/src/cache-service.ts +1537 -415
  60. package/src/cli.ts +2 -9
  61. package/src/codec.ts +3 -3
  62. package/src/compression.ts +39 -16
  63. package/src/cross-region.ts +1 -1
  64. package/src/disk-tier.ts +283 -43
  65. package/src/drizzle/index.ts +2 -1
  66. package/src/edge/adapters/cloudflare-do.ts +25 -10
  67. package/src/edge/adapters/cloudflare-kv.ts +12 -9
  68. package/src/edge/adapters/upstash.ts +27 -11
  69. package/src/edge/cache.ts +59 -17
  70. package/src/edge/types.ts +15 -5
  71. package/src/encryption.ts +50 -18
  72. package/src/env.d.ts +1 -1
  73. package/src/errors.ts +12 -0
  74. package/src/http/utils.ts +6 -0
  75. package/src/index.ts +6 -0
  76. package/src/latency-watchdog.ts +5 -1
  77. package/src/nestjs/decorators.ts +11 -6
  78. package/src/nestjs/tricache.module.ts +2 -1
  79. package/src/nestjs/tricache.store.ts +21 -9
  80. package/src/nestjs/types.ts +1 -1
  81. package/src/next/cache-handler.ts +24 -4
  82. package/src/next/types.ts +4 -0
  83. package/src/origin-capacity.ts +134 -0
  84. package/src/prisma/index.ts +14 -32
  85. package/src/remote-snapshot.ts +37 -27
  86. package/src/serialize-worker.ts +8 -5
  87. package/src/sigv4-snapshot-adapter.ts +37 -27
  88. package/src/smart-memory-cache.ts +62 -22
  89. package/src/types.ts +92 -35
  90. package/src/utils/config-comparison.ts +29 -0
  91. package/src/utils/lz4-size.ts +74 -0
  92. package/src/utils/namespace-key.ts +48 -0
  93. package/src/utils/query-key.ts +13 -0
  94. package/src/utils/snapshot-transfer.ts +83 -0
  95. package/src/utils/work-limits.ts +73 -0
  96. package/src/utils/write-revision.ts +4 -0
  97. package/src/wasm/bloom-filter-wasm.ts +16 -1
  98. package/src/worker-pool.ts +28 -8
  99. package/src/wtiny-lfu.ts +62 -14
  100. package/dist/cache-service-GYPZFB7O.js +0 -12
  101. package/dist/chunk-VNRDL5RA.js +0 -666
@@ -7,9 +7,16 @@ export interface CacheableOptions {
7
7
  * Example: (id: string) => `user:${id}`
8
8
  */
9
9
  key?: string | ((...args: any[]) => string);
10
- /** TTL in seconds (or milliseconds if specified / detected). Default: 300 s. */
10
+ /**
11
+ * TTL value. Unit is controlled by `ttlUnit` and defaults to seconds.
12
+ * Default: 300 s.
13
+ */
11
14
  ttl?: number;
12
- /** Explicit time unit for the ttl option. Default: 'seconds'. */
15
+ /**
16
+ * Explicit time unit for `ttl`. Default: `'seconds'`.
17
+ * There is no implicit unit detection: `ttl: 5000` is 5,000 seconds unless
18
+ * `ttlUnit: 'milliseconds'` is set.
19
+ */
13
20
  ttlUnit?: 'seconds' | 'milliseconds';
14
21
  /** Stale-While-Revalidate grace period in seconds. */
15
22
  swr?: number;
@@ -79,10 +86,8 @@ export function Cacheable(options: CacheableOptions = {}): MethodDecorator {
79
86
 
80
87
  let ttlSeconds = options.ttl ?? 300;
81
88
  const rawTtl = options.ttl;
82
- if (typeof rawTtl === 'number') {
83
- if (options.ttlUnit === 'milliseconds' || (rawTtl >= 1000 && rawTtl % 1000 === 0 && options.ttlUnit !== 'seconds')) {
84
- ttlSeconds = rawTtl / 1000;
85
- }
89
+ if (typeof rawTtl === 'number' && options.ttlUnit === 'milliseconds') {
90
+ ttlSeconds = rawTtl / 1000;
86
91
  }
87
92
 
88
93
  const tags = typeof options.tags === 'function' ? options.tags(...args) : options.tags;
@@ -1,4 +1,5 @@
1
- import { CacheService, type CacheOptions } from '../index.js';
1
+ import { CacheService } from '../cache-service.js';
2
+ import type { CacheOptions } from '../types.js';
2
3
  import { TriCacheStore } from './tricache.store.js';
3
4
  import {
4
5
  TRICACHE_SERVICE,
@@ -1,4 +1,5 @@
1
- import type { CacheService } from '../index.js';
1
+ import type { CacheService } from '../cache-service.js';
2
+ import { INDEFINITE_TTL_SECONDS } from '../cache-service.js';
2
3
  import type { NestCacheStore } from './types.js';
3
4
  import { EventEmitter } from 'node:events';
4
5
 
@@ -32,11 +33,11 @@ export class TriCacheStore extends EventEmitter implements NestCacheStore {
32
33
  * Set an item in the cache.
33
34
  * @param key - Cache key
34
35
  * @param value - Cache value
35
- * @param ttl - TTL in milliseconds (0 = indefinite / default engine TTL)
36
+ * @param ttl - TTL in milliseconds. Omitted uses the engine default (300 s);
37
+ * `0` means indefinite; positive values are converted to seconds.
36
38
  */
37
39
  async set<T>(key: string, value: T, ttl?: number): Promise<T> {
38
- const ttlSeconds = typeof ttl === 'number' && ttl > 0 ? ttl / 1000 : (ttl === 0 ? 0 : undefined);
39
- await this.cache.set(key, value, ttlSeconds);
40
+ await this.cache.set(key, value, this._ttlSeconds(ttl) ?? 300);
40
41
  return value;
41
42
  }
42
43
 
@@ -75,10 +76,7 @@ export class TriCacheStore extends EventEmitter implements NestCacheStore {
75
76
  if (entries.length === 0) return [];
76
77
  const batch: Record<string, { value: unknown; ttl?: number }> = {};
77
78
  for (const e of entries) {
78
- batch[e.key] = {
79
- value: e.value,
80
- ttl: typeof e.ttl === 'number' && e.ttl > 0 ? e.ttl / 1000 : (e.ttl === 0 ? 0 : undefined),
81
- };
79
+ batch[e.key] = { value: e.value, ttl: this._ttlSeconds(e.ttl) ?? 300 };
82
80
  }
83
81
  await this.cache.mset(batch);
84
82
  return entries;
@@ -116,11 +114,25 @@ export class TriCacheStore extends EventEmitter implements NestCacheStore {
116
114
  }
117
115
 
118
116
  async wrap<T>(key: string, fetch: () => T | Promise<T>, ttl?: number, refreshThreshold?: number): Promise<T> {
119
- const seconds = ttl === undefined ? 0 : ttl / 1000;
117
+ const seconds = this._ttlSeconds(ttl);
120
118
  const refreshAhead = ttl && refreshThreshold ? Math.max(0, Math.min(1, (ttl - refreshThreshold) / ttl)) : undefined;
121
119
  return this.cache.wrap(key, async () => await fetch(), { ttl: seconds, refreshAhead });
122
120
  }
123
121
 
122
+ /**
123
+ * Translate a cache-manager millisecond TTL into engine seconds using the same
124
+ * contract as `set()`: omitted keeps the engine default, `0` means indefinite,
125
+ * and positive values convert exactly (sub-second values round up).
126
+ */
127
+ private _ttlSeconds(ttl: number | undefined): number | undefined {
128
+ if (ttl === undefined) return undefined;
129
+ if (typeof ttl !== 'number' || !Number.isFinite(ttl) || ttl < 0) {
130
+ throw new TypeError('TriCacheStore TTL must be a finite non-negative number of milliseconds');
131
+ }
132
+ if (ttl === 0) return INDEFINITE_TTL_SECONDS;
133
+ return Math.max(0.001, ttl / 1000);
134
+ }
135
+
124
136
  cacheId(): string { return `tricache:${this.cache.options.namespace ?? 'default'}`; }
125
137
  get stores(): unknown[] { return [this]; }
126
138
  async clear(): Promise<boolean> { await this.reset(); return true; }
@@ -1,4 +1,4 @@
1
- import type { CacheOptions } from '../index.js';
1
+ import type { CacheOptions } from '../types.js';
2
2
 
3
3
  export const TRICACHE_SERVICE = 'TRICACHE_SERVICE';
4
4
  export const CACHE_MANAGER = 'CACHE_MANAGER';
@@ -1,6 +1,7 @@
1
1
  import { CacheService } from '../cache-service';
2
2
  import { CachePriority, consoleLogger } from '../types';
3
3
  import type { ILogger } from '../types';
4
+ import { positiveLimit, WorkLimit } from '../utils/work-limits';
4
5
  import type {
5
6
  CacheHandlerValue,
6
7
  NextCacheEntry,
@@ -56,7 +57,7 @@ export function resolveCacheLife(profileOrName?: CacheLifePreset | CacheLifeProf
56
57
  /**
57
58
  * Drain incoming web ReadableStream into a contiguous Node Buffer.
58
59
  */
59
- async function drainStream(stream: ReadableStream<Uint8Array>, maxBytes: number): Promise<Buffer> {
60
+ async function drainStream(stream: ReadableStream<Uint8Array>, maxBytes: number, reserveBytes: (bytes: number) => void): Promise<Buffer> {
60
61
  const reader = stream.getReader();
61
62
  const chunks: Uint8Array[] = [];
62
63
  let size = 0;
@@ -67,6 +68,7 @@ async function drainStream(stream: ReadableStream<Uint8Array>, maxBytes: number)
67
68
  if (value) {
68
69
  size += value.byteLength;
69
70
  if (size > maxBytes) throw new Error('RSC stream exceeds maxStreamBytes');
71
+ if (value.byteLength > 0) reserveBytes(value.byteLength);
70
72
  chunks.push(Uint8Array.from(value));
71
73
  }
72
74
  }
@@ -101,13 +103,16 @@ export class TriCacheHandler {
101
103
  protected readonly cache: CacheService;
102
104
  protected readonly logger: ILogger;
103
105
  private readonly maxStreamBytes: number;
106
+ private readonly streamBudget: { bytes: WorkLimit; streams: WorkLimit };
107
+ private static readonly streamBudgets = new WeakMap<CacheService, { bytes: WorkLimit; streams: WorkLimit }>();
104
108
  private readonly pendingSets = new Map<string, { token: symbol; completion: Promise<void> }>();
105
109
  private readonly observedTags = new Map<string, { version: number; observedAt: number }>();
106
110
 
107
111
  constructor(options: NextCacheHandlerOptions = {}) {
108
112
  this.logger = options.logger ?? consoleLogger;
109
- this.maxStreamBytes = options.maxStreamBytes ?? 16 * 1024 * 1024;
110
- if (!Number.isFinite(this.maxStreamBytes) || this.maxStreamBytes <= 0) throw new Error('maxStreamBytes must be finite and positive');
113
+ this.maxStreamBytes = positiveLimit(options.maxStreamBytes, 16 * 1024 * 1024, 'maxStreamBytes');
114
+ const maxPendingStreamBytes = positiveLimit(options.maxPendingStreamBytes, 64 * 1024 * 1024, 'maxPendingStreamBytes');
115
+ const maxConcurrentStreams = positiveLimit(options.maxConcurrentStreams, 16, 'maxConcurrentStreams');
111
116
  if (options.tagStrategy && options.tagStrategy !== 'generational') throw new Error('Next.js cache handlers require tagStrategy: generational');
112
117
 
113
118
  const isBuildPhase =
@@ -123,6 +128,13 @@ export class TriCacheHandler {
123
128
  cloneStrategy: options.cloneStrategy ?? 'none',
124
129
  disableRedis: isBuildPhase ? true : options.disableRedis,
125
130
  });
131
+ const existing = TriCacheHandler.streamBudgets.get(this.cache);
132
+ if (existing && (existing.bytes.maximum !== maxPendingStreamBytes || existing.streams.maximum !== maxConcurrentStreams)) {
133
+ throw new Error('Next handlers sharing one cache must use the same stream admission limits');
134
+ }
135
+ this.streamBudget = existing ?? { bytes: new WorkLimit(maxPendingStreamBytes, 'Next buffered stream bytes'),
136
+ streams: new WorkLimit(maxConcurrentStreams, 'Next concurrent streams') };
137
+ TriCacheHandler.streamBudgets.set(this.cache, this.streamBudget);
126
138
  }
127
139
 
128
140
  /**
@@ -208,6 +220,8 @@ export class TriCacheHandler {
208
220
  let finish!: () => void;
209
221
  const completion = new Promise<void>(resolve => { finish = resolve; });
210
222
  this.pendingSets.set(cacheKey, { token, completion });
223
+ const byteReservation = this.streamBudget.bytes.reservation();
224
+ let releaseStream: (() => void) | undefined;
211
225
  try {
212
226
  const canCommit = this.cache.captureMutationFence(cacheKey);
213
227
  const entry = await pendingEntry;
@@ -224,8 +238,12 @@ export class TriCacheHandler {
224
238
 
225
239
  if (isStream) {
226
240
  try {
227
- dataToStore = (await drainStream(dataToStore as ReadableStream<Uint8Array>, this.maxStreamBytes)).toString('base64');
241
+ releaseStream = this.streamBudget.streams.acquire();
242
+ dataToStore = (await drainStream(dataToStore as ReadableStream<Uint8Array>, this.maxStreamBytes,
243
+ bytes => byteReservation.grow(bytes))).toString('base64');
228
244
  } catch (streamErr) {
245
+ const stream = entry.value as ReadableStream<Uint8Array>;
246
+ if (!stream.locked) void stream.cancel(streamErr).catch(() => {});
229
247
  this.logger.debug('Next.js cacheHandler: stream drain failed mid-flight, skipping cache', {
230
248
  cacheKey,
231
249
  error: (streamErr as Error).message,
@@ -290,6 +308,8 @@ export class TriCacheHandler {
290
308
  // before Next could return revalidate:-1 and schedule their replacement.
291
309
  await this.cache.set(cacheKey, stored, remaining / 1000, undefined, { tags: [] });
292
310
  } finally {
311
+ byteReservation.release();
312
+ releaseStream?.();
293
313
  finish();
294
314
  if (this.pendingSets.get(cacheKey)?.token === token) this.pendingSets.delete(cacheKey);
295
315
  }
package/src/next/types.ts CHANGED
@@ -100,6 +100,10 @@ export interface NextCacheHandlerOptions extends CacheOptions {
100
100
  isBuildPhase?: boolean;
101
101
  /** Maximum buffered RSC stream size. Default: 16 MiB. */
102
102
  maxStreamBytes?: number;
103
+ /** Aggregate buffered input stream bytes per shared cache instance. Default: 64 MiB. Excludes encoded copies and caller-owned streams. */
104
+ maxPendingStreamBytes?: number;
105
+ /** Concurrent stream materializations per shared cache instance. Default: 16. Overflow skips caching and cancels that input stream. */
106
+ maxConcurrentStreams?: number;
103
107
  }
104
108
 
105
109
  /**
@@ -0,0 +1,134 @@
1
+ import { WorkLimit, positiveLimit } from './utils/work-limits.js';
2
+
3
+ export interface OriginCapacityOptions {
4
+ /** Per-process physical work budget. Batch fills reserve one slot per unique owned key. */
5
+ maxConcurrent: number;
6
+ }
7
+
8
+ export interface OriginRunOptions {
9
+ signal?: AbortSignal;
10
+ /** Caller deadline in milliseconds; zero rejects before starting work. */
11
+ timeoutMs?: number;
12
+ /** Conservative work cost; defaults to one. No queue or implicit retry. */
13
+ weight?: number;
14
+ }
15
+
16
+ export interface OriginCapacityMetrics {
17
+ active: number;
18
+ capacity: number;
19
+ rejected: number;
20
+ started: number;
21
+ completed: number;
22
+ cancelled: number;
23
+ timedOut: number;
24
+ closed: boolean;
25
+ }
26
+
27
+ /** Share one instance across cache loaders and the direct-origin route for the same origin. */
28
+ export class OriginCapacityLimiter {
29
+ private readonly work: WorkLimit;
30
+ private readonly pending = new Set<(reason: unknown) => void>();
31
+ private closed = false;
32
+ private started = 0;
33
+ private completed = 0;
34
+ private cancelled = 0;
35
+ private timedOut = 0;
36
+
37
+ constructor(options: OriginCapacityOptions) {
38
+ this.work = new WorkLimit(positiveLimit(options?.maxConcurrent, 1024, 'maxConcurrent'), 'shared origin work');
39
+ }
40
+
41
+ async run<T>(origin: (signal: AbortSignal) => T | PromiseLike<T>, options: OriginRunOptions = {}): Promise<T> {
42
+ if (typeof origin !== 'function') throw new TypeError('Origin work must be a function');
43
+ const { signal, timeoutMs, weight = 1 } = options;
44
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647)) {
45
+ throw new RangeError('timeoutMs must be finite and between 0 and 2147483647');
46
+ }
47
+ if (this.closed) throw new Error('Origin capacity limiter is closed');
48
+ if (signal?.aborted) { this.cancelled++; throw signal.reason ?? new DOMException('Origin caller cancelled', 'AbortError'); }
49
+ if (timeoutMs === 0) { this.timedOut++; throw new DOMException('Origin request deadline exceeded', 'TimeoutError'); }
50
+ const release = this.work.acquire(weight);
51
+ const controller = new AbortController();
52
+ let timer: ReturnType<typeof setTimeout> | undefined;
53
+ let abandon!: (reason: unknown) => void;
54
+ const cancelled = new Promise<never>((_resolve, reject) => {
55
+ abandon = reason => {
56
+ if (controller.signal.aborted) return;
57
+ // Reject the wait before signalling a cooperative origin that may settle synchronously.
58
+ reject(reason);
59
+ controller.abort(reason);
60
+ clearTimeout(timer);
61
+ signal?.removeEventListener('abort', onCallerAbort);
62
+ };
63
+ });
64
+ const onCallerAbort = () => {
65
+ if (controller.signal.aborted) return;
66
+ this.cancelled++;
67
+ abandon(signal?.reason ?? new DOMException('Origin caller cancelled', 'AbortError'));
68
+ };
69
+ const onClose = (reason: unknown) => {
70
+ if (controller.signal.aborted) return;
71
+ this.cancelled++;
72
+ abandon(reason);
73
+ };
74
+ this.pending.add(onClose);
75
+ signal?.addEventListener('abort', onCallerAbort, { once: true });
76
+ if (timeoutMs !== undefined) {
77
+ timer = setTimeout(() => {
78
+ if (controller.signal.aborted) return;
79
+ this.timedOut++;
80
+ abandon(new DOMException('Origin request deadline exceeded', 'TimeoutError'));
81
+ }, Math.ceil(timeoutMs));
82
+ }
83
+
84
+ this.started++;
85
+ let physical: Promise<T>;
86
+ try { physical = Promise.resolve(origin(controller.signal)); }
87
+ catch (error) { physical = Promise.reject(error); }
88
+ const finish = () => {
89
+ clearTimeout(timer);
90
+ signal?.removeEventListener('abort', onCallerAbort);
91
+ this.pending.delete(onClose);
92
+ release();
93
+ this.completed++;
94
+ };
95
+ // This handler remains attached after the caller abandons its wait. Only
96
+ // physical settlement releases capacity and observes a late rejection.
97
+ const settled = physical.then(value => { finish(); return value; }, error => { finish(); throw error; });
98
+ return Promise.race([settled, cancelled]);
99
+ }
100
+
101
+ /** Reject new work and signal active origins. Ignored cancellation still occupies capacity. */
102
+ close(): void {
103
+ if (this.closed) return;
104
+ this.closed = true;
105
+ const reason = new DOMException('Origin capacity limiter is closed', 'AbortError');
106
+ for (const abort of this.pending) abort(reason);
107
+ }
108
+
109
+ metrics(): OriginCapacityMetrics {
110
+ return { ...this.work.metrics(), started: this.started, completed: this.completed,
111
+ cancelled: this.cancelled, timedOut: this.timedOut, closed: this.closed };
112
+ }
113
+
114
+ /** Export once per shared origin budget, separately from per-namespace cache series. */
115
+ toPrometheusText(prefix = 'tricache_origin'): string {
116
+ if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(prefix)) throw new TypeError('Invalid Prometheus metric prefix');
117
+ const metrics = this.metrics();
118
+ const lines: string[] = [];
119
+ for (const [suffix, value, type, help] of [
120
+ ['active', metrics.active, 'gauge', 'Reserved physical origin work slots'],
121
+ ['capacity', metrics.capacity, 'gauge', 'Configured physical origin work capacity'],
122
+ ['closed', metrics.closed ? 1 : 0, 'gauge', 'Origin budget is closed to new work'],
123
+ ['rejections_total', metrics.rejected, 'counter', 'Origin admissions rejected at capacity'],
124
+ ['started_total', metrics.started, 'counter', 'Physical origin invocations started'],
125
+ ['completed_total', metrics.completed, 'counter', 'Physical origin invocations settled'],
126
+ ['cancelled_total', metrics.cancelled, 'counter', 'Origin waits cancelled by callers or shutdown'],
127
+ ['timeouts_total', metrics.timedOut, 'counter', 'Origin waits rejected by their deadline'],
128
+ ] as const) {
129
+ const name = `${prefix}_${suffix}`;
130
+ lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} ${type}`, `${name} ${value}`);
131
+ }
132
+ return lines.join('\n') + '\n';
133
+ }
134
+ }
@@ -23,6 +23,7 @@
23
23
  import type { CacheService } from '../cache-service.js';
24
24
  import type { WrapOptions } from '../types.js';
25
25
  import crypto from 'crypto';
26
+ import { deterministicStringify } from '../utils/query-key.js';
26
27
 
27
28
  export interface PrismaCacheQueryOptions extends WrapOptions {
28
29
  /** Explicit cache key. Defaults to SHA-256 hash of (model + operation + args). */
@@ -65,25 +66,6 @@ const MUTATION_OPERATIONS = new Set([
65
66
  'deleteMany',
66
67
  ]);
67
68
 
68
- /** Recursively sorts object keys for deterministic serialization of nested query filters */
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
- }
76
- if (val === null || typeof val !== 'object') {
77
- return JSON.stringify(val) ?? 'undefined';
78
- }
79
- if (Array.isArray(val)) {
80
- return `[${val.map(deterministicStringify).join(',')}]`;
81
- }
82
- const obj = val as Record<string, unknown>;
83
- const keys = Object.keys(obj).sort();
84
- return `{${keys.map(k => `${JSON.stringify(k)}:${deterministicStringify(obj[k])}`).join(',')}}`;
85
- }
86
-
87
69
  /** Generate a deterministic SHA-256 hash key for a Prisma query. */
88
70
  export function generatePrismaCacheKey(model: string, operation: string, args: unknown): string {
89
71
  const normalized = deterministicStringify({ model, operation, args });
@@ -108,24 +90,27 @@ export function withTriCache(options: PrismaTriCacheOptions) {
108
90
  query: (args: unknown) => Promise<unknown>;
109
91
  }) {
110
92
  const modelTag = model.toLowerCase();
93
+ const queryArgs = args ?? {};
94
+ const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
95
+ // `cache` is a TriCache-only pseudo-option. Remove it before every
96
+ // Prisma engine call, including pass-through reads and mutations when
97
+ // automatic invalidation/caching is disabled.
98
+ let cleanArgs: Record<string, unknown> | undefined = args;
99
+ if (args && Object.prototype.hasOwnProperty.call(args, 'cache')) {
100
+ const { cache: _cacheOpt, ...rest } = args;
101
+ cleanArgs = rest;
102
+ }
111
103
 
112
104
  // Auto-invalidation on write operations
113
105
  if (autoInvalidate && MUTATION_OPERATIONS.has(operation)) {
114
- // Strip the cache pseudo-option here too — the read path removes it,
115
- // but the mutation path forwarded it verbatim to the Prisma engine.
116
- const { cache: _cacheOpt, ...cleanMutationArgs } = (args ?? {}) as Record<string, unknown>;
117
- const result = await query(cleanMutationArgs);
106
+ const result = await query(cleanArgs);
118
107
  await cache.invalidateTag(modelTag);
119
108
  return result;
120
109
  }
121
110
 
122
111
  // Read operations
123
112
  if (READ_OPERATIONS.has(operation)) {
124
- const queryArgs = args ?? {};
125
- const cacheConfig = (queryArgs as { cache?: PrismaCacheQueryOptions | boolean }).cache;
126
-
127
113
  if (cacheConfig === false) {
128
- const { cache: _c, ...cleanArgs } = queryArgs;
129
114
  return query(cleanArgs);
130
115
  }
131
116
 
@@ -134,10 +119,7 @@ export function withTriCache(options: PrismaTriCacheOptions) {
134
119
  ? cacheConfig
135
120
  : {};
136
121
 
137
- // Clone args without the `cache` property to pass clean args to Prisma query engine
138
- const { cache: _c, ...cleanArgs } = queryArgs as Record<string, unknown>;
139
-
140
- const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs);
122
+ const key = opts.key ?? generatePrismaCacheKey(model, operation, cleanArgs ?? {});
141
123
  const tags = [...new Set([modelTag, ...(opts.tags ?? [])])];
142
124
 
143
125
  return cache.wrap(
@@ -157,7 +139,7 @@ export function withTriCache(options: PrismaTriCacheOptions) {
157
139
  }
158
140
  }
159
141
 
160
- return query(args);
142
+ return query(cleanArgs);
161
143
  },
162
144
  },
163
145
  },
@@ -5,17 +5,20 @@
5
5
  * to persist and hydrate L1 cache snapshots from remote object storage (S3, GCS, R2, Azure, MinIO, or HTTP).
6
6
  */
7
7
 
8
+ import { discardSnapshotResponse, readSnapshotResponse, snapshotRequest, type SnapshotRequestOptions, type SnapshotTransferOptions } from './utils/snapshot-transfer.js';
9
+ export type { SnapshotRequestOptions, SnapshotTransferOptions } from './utils/snapshot-transfer.js';
10
+
8
11
  export interface IRemoteSnapshotAdapter {
9
12
  /**
10
13
  * Read the latest snapshot blob from remote storage.
11
14
  * Returns null if no snapshot exists yet (e.g. 404 Not Found / first deploy).
12
15
  */
13
- get(): Promise<Buffer | Uint8Array | null>;
16
+ get(options?: SnapshotRequestOptions): Promise<Buffer | Uint8Array | null>;
14
17
 
15
18
  /**
16
19
  * Write the snapshot blob to remote storage.
17
20
  */
18
- put(data: Buffer): Promise<void>;
21
+ put(data: Buffer, options?: SnapshotRequestOptions): Promise<void>;
19
22
  }
20
23
 
21
24
  import type { EnvelopeEncryptionOptions } from './encryption';
@@ -53,7 +56,7 @@ export interface RemoteSnapshotOptions {
53
56
  envelope?: EnvelopeEncryptionOptions;
54
57
  }
55
58
 
56
- export interface HttpSnapshotAdapterOptions {
59
+ export interface HttpSnapshotAdapterOptions extends SnapshotTransferOptions {
57
60
  /**
58
61
  * URL to fetch the snapshot from (e.g. S3 presigned GET URL or internal blob service).
59
62
  */
@@ -80,34 +83,41 @@ export function createHttpSnapshotAdapter(options: HttpSnapshotAdapterOptions):
80
83
  const headers = options.headers ?? {};
81
84
 
82
85
  return {
83
- async get(): Promise<Buffer | null> {
84
- const res = await fetch(getUrl, {
85
- method: 'GET',
86
- headers,
86
+ async get(request): Promise<Buffer | null> {
87
+ return snapshotRequest(options, request, async (signal, maxBytes) => {
88
+ const res = await fetch(getUrl, {
89
+ method: 'GET',
90
+ headers,
91
+ signal,
92
+ });
93
+
94
+ if (res.status === 404) { discardSnapshotResponse(res); return null; }
95
+ if (!res.ok) {
96
+ discardSnapshotResponse(res);
97
+ throw new Error(`HttpSnapshotAdapter: GET failed with status ${res.status} ${res.statusText}`);
98
+ }
99
+
100
+ return readSnapshotResponse(res, signal, maxBytes);
87
101
  });
88
-
89
- if (res.status === 404) return null;
90
- if (!res.ok) {
91
- throw new Error(`HttpSnapshotAdapter: GET failed with status ${res.status} ${res.statusText}`);
92
- }
93
-
94
- const ab = await res.arrayBuffer();
95
- return Buffer.from(ab);
96
102
  },
97
103
 
98
- async put(data: Buffer): Promise<void> {
99
- const res = await fetch(putUrl, {
100
- method: 'PUT',
101
- headers: {
102
- 'Content-Type': 'application/octet-stream',
103
- ...headers,
104
- },
105
- body: data as unknown as BodyInit,
104
+ async put(data: Buffer, request): Promise<void> {
105
+ return snapshotRequest(options, request, async (signal) => {
106
+ const res = await fetch(putUrl, {
107
+ method: 'PUT',
108
+ headers: {
109
+ 'Content-Type': 'application/octet-stream',
110
+ ...headers,
111
+ },
112
+ body: data as unknown as BodyInit,
113
+ signal,
114
+ });
115
+
116
+ discardSnapshotResponse(res);
117
+ if (!res.ok) {
118
+ throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
119
+ }
106
120
  });
107
-
108
- if (!res.ok) {
109
- throw new Error(`HttpSnapshotAdapter: PUT failed with status ${res.status} ${res.statusText}`);
110
- }
111
121
  },
112
122
  };
113
123
  }
@@ -33,6 +33,7 @@ interface WorkerInit {
33
33
  prevMode: EncryptionMode | undefined;
34
34
  compression?: CompressionAlgorithm;
35
35
  compressionThresholdBytes?: number;
36
+ allowLegacyPlaintextRead?: boolean;
36
37
  }
37
38
 
38
39
  // Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
@@ -52,6 +53,7 @@ const enc = new CacheEncryption(
52
53
  mode,
53
54
  prevKeyBase64 || undefined,
54
55
  prevMode,
56
+ { allowLegacyPlaintextRead: (workerData as WorkerInit).allowLegacyPlaintextRead },
55
57
  );
56
58
 
57
59
  const cmpAlgo = compression ?? 'zstd';
@@ -59,7 +61,7 @@ const cmpThreshold = compressionThresholdBytes ?? 1024;
59
61
 
60
62
  parentPort!.on(
61
63
  'message',
62
- async ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array }) => {
64
+ async ({ id, type, payload, context }: { id: number; type: 'encrypt' | 'decrypt'; payload: string | Uint8Array; context?: string }) => {
63
65
  try {
64
66
  if (cmpAlgo === 'zstd') {
65
67
  await initZstd();
@@ -74,13 +76,13 @@ parentPort!.on(
74
76
  if (cmpAlgo !== 'none' && textPayload.length > cmpThreshold) {
75
77
  const compressed = compressBuffer(Buffer.from(textPayload, 'utf8'), cmpAlgo);
76
78
  if (enc.isEnabled) {
77
- const encrypted = enc.encryptBuffer(compressed);
79
+ const encrypted = enc.encryptBuffer(compressed, context);
78
80
  result = PREFIX_ENC_COMPRESSED + encrypted.toString('base64');
79
81
  } else {
80
82
  result = PREFIX_COMPRESSED + compressed.toString('base64');
81
83
  }
82
84
  } else {
83
- result = enc.encrypt(textPayload);
85
+ result = enc.encrypt(textPayload, context);
84
86
  }
85
87
 
86
88
  if (result.length >= 131_072) {
@@ -93,10 +95,11 @@ parentPort!.on(
93
95
  parentPort!.postMessage({ id, result });
94
96
  }
95
97
  } else {
98
+ enc.assertReadPolicy(textPayload, context);
96
99
  let result: string;
97
100
  if (textPayload.startsWith(PREFIX_ENC_COMPRESSED)) {
98
101
  const rawBuf = Buffer.from(textPayload.slice(PREFIX_ENC_COMPRESSED.length), 'base64');
99
- const decryptedBuf = enc.decryptBuffer(rawBuf);
102
+ const decryptedBuf = enc.decryptBuffer(rawBuf, context);
100
103
  const decompressed = decompressBuffer(decryptedBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
101
104
  result = decompressed.toString('utf8');
102
105
  } else if (textPayload.startsWith(PREFIX_COMPRESSED)) {
@@ -104,7 +107,7 @@ parentPort!.on(
104
107
  const decompressed = decompressBuffer(rawBuf, cmpAlgo !== 'none' ? cmpAlgo : 'brotli');
105
108
  result = decompressed.toString('utf8');
106
109
  } else {
107
- result = enc.decrypt(textPayload);
110
+ result = enc.decrypt(textPayload, context);
108
111
  }
109
112
 
110
113
  if (result.length >= 131_072) {