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
@@ -4,6 +4,8 @@ import {
4
4
  buildDeterministicKey,
5
5
  generateETag,
6
6
  shouldSkipCache,
7
+ isCacheableHttpResponse,
8
+ matchesETag,
7
9
  type KeyDerivationOptions,
8
10
  } from './utils.js';
9
11
 
@@ -16,6 +18,8 @@ export interface FastifyCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDeriv
16
18
  skipCache?: (req: any) => boolean;
17
19
  /** Dynamic tags derivation from request. */
18
20
  tags?: string[] | ((req: any) => string[]);
21
+ /** @deprecated Response refreshes run on live requests. Use data-level cache.get()/wrap() for SWR. */
22
+ swr?: number;
19
23
  }
20
24
 
21
25
  export interface CachedFastifyResponse {
@@ -23,6 +27,12 @@ export interface CachedFastifyResponse {
23
27
  contentType?: string;
24
28
  etag?: string;
25
29
  status: number;
30
+ binary?: boolean;
31
+ headers?: Record<string, string | string[]>;
32
+ }
33
+
34
+ function responseBody(entry: CachedFastifyResponse): unknown {
35
+ return entry.binary && !Buffer.isBuffer(entry.body) ? Buffer.from((entry.body as { data: number[] }).data) : entry.body;
26
36
  }
27
37
 
28
38
  /**
@@ -58,7 +68,7 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
58
68
  return;
59
69
  }
60
70
 
61
- if (shouldSkipCache(req, mergedOpts.skipCache)) {
71
+ if (shouldSkipCache(req, mergedOpts.skipCache, mergedOpts)) {
62
72
  return;
63
73
  }
64
74
 
@@ -75,9 +85,10 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
75
85
  const cached = await activeCache!.peek<CachedFastifyResponse>(key);
76
86
 
77
87
  if (cached && typeof cached === 'object' && cached.body !== null) {
88
+ for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header(name, value);
78
89
  if (cached.etag) {
79
90
  reply.header('ETag', cached.etag);
80
- if (ifNoneMatch === cached.etag) {
91
+ if (matchesETag(ifNoneMatch, cached.etag)) {
81
92
  reply.code(304);
82
93
  return reply.send();
83
94
  }
@@ -88,11 +99,12 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
88
99
  }
89
100
 
90
101
  reply.code(cached.status ?? 200);
91
- return reply.send(cached.body);
102
+ return reply.send(req.method === 'HEAD' ? undefined : responseBody(cached));
92
103
  }
93
104
 
94
105
  // Mark request for response capture in onSend
95
106
  req._tricacheKey = key;
107
+ req._tricacheCanCommit = activeCache!.captureMutationFence(key);
96
108
  const resolvedTags = typeof mergedOpts.tags === 'function'
97
109
  ? mergedOpts.tags(req)
98
110
  : mergedOpts.tags;
@@ -108,7 +120,8 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
108
120
  const statusCode = reply.statusCode ?? reply.raw?.statusCode ?? 200;
109
121
 
110
122
  // Status gate: only cache 2xx successful responses
111
- if (statusCode >= 200 && statusCode < 300 && payload !== undefined && payload !== null) {
123
+ if (req._tricacheCanCommit?.() && isCacheableHttpResponse(statusCode, name => reply.getHeader(name), mergedOpts) && payload !== undefined && payload !== null &&
124
+ !(typeof payload === 'object' && typeof (payload as { pipe?: unknown }).pipe === 'function')) {
112
125
  const payloadEtag = etag ? generateETag(payload) : undefined;
113
126
  const contentType = reply.getHeader('content-type')
114
127
  || (typeof payload === 'object' ? 'application/json' : 'text/plain');
@@ -121,22 +134,24 @@ export function createFastifyPlugin(options: FastifyCacheOptions = {}) {
121
134
  ? (req.headers['if-none-match'] || req.headers['If-None-Match'])
122
135
  : undefined;
123
136
 
124
- if (ifNoneMatch && payloadEtag && ifNoneMatch === payloadEtag) {
125
- reply.code(304);
126
- return '';
127
- }
128
-
129
137
  // Asynchronously persist to cache without delaying current onSend pipeline
130
138
  const entry: CachedFastifyResponse = {
131
139
  body: payload,
132
140
  contentType,
133
141
  etag: payloadEtag,
134
142
  status: statusCode,
143
+ binary: Buffer.isBuffer(payload),
144
+ headers: reply.getHeaders ? Object.fromEntries(Object.entries(reply.getHeaders()).filter(([name]) =>
145
+ !['content-length', 'transfer-encoding', 'connection', 'set-cookie', 'content-type', 'etag'].includes(name.toLowerCase()))) as Record<string, string | string[]> : undefined,
135
146
  };
136
147
 
137
148
  void activeCache!.set(key, entry, mergedOpts.ttl ?? ttl, undefined, {
138
149
  tags: req._tricacheTags,
139
150
  }).catch(() => {});
151
+ if (payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
152
+ reply.code(304);
153
+ return '';
154
+ }
140
155
  }
141
156
 
142
157
  return payload;
@@ -169,7 +184,7 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
169
184
  const reply = second;
170
185
 
171
186
  if (req.method !== 'GET' && req.method !== 'HEAD') return;
172
- if (shouldSkipCache(req, options.skipCache)) return;
187
+ if (shouldSkipCache(req, options.skipCache, options)) return;
173
188
 
174
189
  let activeCache = options.cache;
175
190
  if (!activeCache) {
@@ -187,16 +202,13 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
187
202
  : undefined;
188
203
 
189
204
  // Fast-path probe
190
- const cached = await activeCache.get<CachedFastifyResponse | null>(
191
- key,
192
- async () => null,
193
- 0
194
- );
205
+ const cached = await activeCache.peek<CachedFastifyResponse>(key);
195
206
 
196
207
  if (cached && typeof cached === 'object' && cached.body !== null) {
208
+ for (const [name, value] of Object.entries(cached.headers ?? {})) reply.header?.(name, value);
197
209
  if (cached.etag) {
198
210
  if (reply.header) reply.header('ETag', cached.etag);
199
- if (ifNoneMatch === cached.etag) {
211
+ if (matchesETag(ifNoneMatch, cached.etag)) {
200
212
  if (reply.code) reply.code(304);
201
213
  else if (reply.status) reply.status(304);
202
214
  if (reply.send) return reply.send();
@@ -213,11 +225,12 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
213
225
  else if (reply.status) reply.status(cached.status);
214
226
  }
215
227
 
216
- if (reply.send) return reply.send(cached.body);
228
+ if (reply.send) return reply.send(req.method === 'HEAD' ? undefined : responseBody(cached));
217
229
  return;
218
230
  }
219
231
 
220
232
  // Miss path: intercept reply.send on completion
233
+ const canCommit = activeCache.captureMutationFence(key);
221
234
  const origSend = reply.send?.bind(reply);
222
235
  if (origSend) {
223
236
  reply.send = function (resPayload: any) {
@@ -227,18 +240,19 @@ export function fastifyCache(options: FastifyCacheOptions = {}) {
227
240
  || (typeof resPayload === 'object' ? 'application/json' : 'text/plain');
228
241
 
229
242
  const respStatus = reply.statusCode ?? reply.raw?.statusCode ?? 200;
230
- if (respStatus >= 200 && respStatus < 300) {
243
+ const cacheable = isCacheableHttpResponse(respStatus, name => reply.getHeader?.(name), options);
244
+ if (cacheable && canCommit() && !(typeof resPayload === 'object' && typeof resPayload.pipe === 'function')) {
231
245
  const resolvedTags = typeof options.tags === 'function' ? options.tags(req) : options.tags;
232
246
  void activeCache!.set(
233
247
  key,
234
- { body: resPayload, contentType, etag: payloadEtag, status: respStatus },
248
+ { body: resPayload, contentType, etag: payloadEtag, status: respStatus, binary: Buffer.isBuffer(resPayload) },
235
249
  options.ttl ?? 300,
236
250
  undefined,
237
251
  { tags: resolvedTags }
238
- );
252
+ ).catch(() => {});
239
253
  }
240
254
 
241
- if (ifNoneMatch && ifNoneMatch === payloadEtag) {
255
+ if (cacheable && payloadEtag && matchesETag(ifNoneMatch, payloadEtag)) {
242
256
  if (reply.code) reply.code(304);
243
257
  else if (reply.status) reply.status(304);
244
258
  return origSend();
package/src/http/utils.ts CHANGED
@@ -5,6 +5,45 @@ export interface KeyDerivationOptions {
5
5
  keyGenerator?: (req: any) => string;
6
6
  /** Optional list of header names (case-insensitive) to include in the cache key. */
7
7
  headerWhitelist?: string[];
8
+ /** Opt in to authenticated request caching with an identity-aware key. Default: false. */
9
+ cacheAuthenticated?: boolean;
10
+ }
11
+
12
+ export type HttpHeaderValue = string | number | string[] | undefined | null;
13
+
14
+ export function readHttpHeader(headers: any, name: string): HttpHeaderValue {
15
+ if (!headers) return undefined;
16
+ if (typeof headers.get === 'function') return headers.get(name);
17
+ const lower = name.toLowerCase();
18
+ return headers[lower] ?? headers[name] ?? Object.entries(headers).find(([key]) => key.toLowerCase() === lower)?.[1] as HttpHeaderValue;
19
+ }
20
+
21
+ export function hasCacheBypassDirective(value: HttpHeaderValue): boolean {
22
+ if (value == null) return false;
23
+ return String(value).split(',').some(part => /^(?:private|no-cache|no-store)(?:\s*=|\s*$)/i.test(part.trim()));
24
+ }
25
+
26
+ /** Shared-cache safety checks applied BEFORE a response enters storage or singleflight results. */
27
+ export function isShareableHttpResponse(
28
+ status: number,
29
+ header: (name: string) => HttpHeaderValue,
30
+ options: KeyDerivationOptions = {},
31
+ ): boolean {
32
+ if (status === 206 || hasCacheBypassDirective(header('cache-control')) || header('set-cookie')) return false;
33
+ if (String(header('content-type') ?? '').toLowerCase().includes('text/event-stream')) return false;
34
+ const vary = String(header('vary') ?? '').split(',').map(value => value.trim().toLowerCase()).filter(Boolean);
35
+ const keyedHeaders = new Set(options.headerWhitelist?.map(name => name.toLowerCase()));
36
+ return !vary.includes('*') && (Boolean(options.keyGenerator) || vary.every(name => keyedHeaders.has(name)));
37
+ }
38
+
39
+ export function isCacheableHttpResponse(status: number, header: (name: string) => HttpHeaderValue, options?: KeyDerivationOptions): boolean {
40
+ return status >= 200 && status < 300 && isShareableHttpResponse(status, header, options);
41
+ }
42
+
43
+ export function matchesETag(header: HttpHeaderValue, etag: string): boolean {
44
+ if (header == null) return false;
45
+ const normalized = etag.replace(/^W\//, '');
46
+ return String(header).split(',').some(value => value.trim() === '*' || value.trim().replace(/^W\//, '') === normalized);
8
47
  }
9
48
 
10
49
  /**
@@ -39,19 +78,27 @@ export function buildDeterministicKey(req: any, options?: KeyDerivationOptions):
39
78
  }
40
79
  }
41
80
 
81
+ // Forwarded headers require an application-owned trusted-proxy policy.
82
+ const authority = readHttpHeader(req.headers, ':authority') ?? readHttpHeader(req.headers, 'host');
83
+ if (authority != null && (typeof authority !== 'string' || /[\s/\\?#@]/.test(authority))) {
84
+ throw new TypeError('HTTP cache authority must be a single valid host header');
85
+ }
42
86
  let key = `http:${method}:${path}`;
87
+ if (authority) key += `|host:${encodeURIComponent(authority.toLowerCase())}`;
43
88
  if (queryString) {
44
89
  key += `?${queryString}`;
45
90
  }
46
91
 
47
92
  if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
48
- const sortedHeaders = [...options.headerWhitelist].sort();
93
+ const sortedHeaders = [...new Set(options.headerWhitelist.map(h => h.toLowerCase()))].sort();
49
94
  for (const h of sortedHeaders) {
50
95
  const normalizedHeader = h.toLowerCase();
51
- const val = req.headers[normalizedHeader];
96
+ const val = readHttpHeader(req.headers, normalizedHeader);
52
97
  if (val !== undefined && val !== null && val !== '') {
53
98
  const headerStr = Array.isArray(val) ? val.join(',') : String(val);
54
- key += `|h:${normalizedHeader}=${headerStr}`;
99
+ const identity = /authorization|cookie|token|api-key/.test(normalizedHeader)
100
+ ? crypto.createHash('sha256').update(headerStr).digest('hex') : encodeURIComponent(headerStr);
101
+ key += `|h:${normalizedHeader}=${identity}`;
55
102
  }
56
103
  }
57
104
  }
@@ -63,17 +110,15 @@ export function buildDeterministicKey(req: any, options?: KeyDerivationOptions):
63
110
  * Checks if request specifies Cache-Control bypass directives (no-cache, no-store)
64
111
  * or matches a custom skipCache predicate.
65
112
  */
66
- export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): boolean {
113
+ export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean, options: KeyDerivationOptions = {}): boolean {
67
114
  if (customSkip && customSkip(req)) return true;
68
-
69
- const cc = req.headers ? (req.headers['cache-control'] || req.headers['Cache-Control']) : undefined;
70
- if (typeof cc === 'string') {
71
- const lower = cc.toLowerCase();
72
- if (lower.includes('no-cache') || lower.includes('no-store')) {
73
- return true;
74
- }
115
+ if (hasCacheBypassDirective(readHttpHeader(req.headers, 'cache-control')) || readHttpHeader(req.headers, 'range')) return true;
116
+ const sensitiveHeaders = ['authorization', 'cookie', 'x-api-key', 'x-auth-token'].filter(name => readHttpHeader(req.headers, name));
117
+ if (sensitiveHeaders.length > 0) {
118
+ if (!options.cacheAuthenticated) return true;
119
+ const keyedHeaders = new Set(options.headerWhitelist?.map(name => name.toLowerCase()));
120
+ if (!options.keyGenerator && !sensitiveHeaders.every(name => keyedHeaders.has(name))) return true;
75
121
  }
76
-
77
122
  return false;
78
123
  }
79
124
 
@@ -81,12 +126,7 @@ export function shouldSkipCache(req: any, customSkip?: (req: any) => boolean): b
81
126
  * Compute a weak ETag (W/"...") from string, Buffer, or JSON-serializable object.
82
127
  */
83
128
  export function generateETag(data: unknown): string {
84
- const str = typeof data === 'string'
85
- ? data
86
- : Buffer.isBuffer(data)
87
- ? data.toString('utf8')
88
- : JSON.stringify(data);
89
-
90
- const hash = crypto.createHash('sha1').update(str).digest('hex').slice(0, 16);
91
- return `W/"${str.length.toString(16)}-${hash}"`;
129
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === 'string' ? data : JSON.stringify(data) ?? '', 'utf8');
130
+ const hash = crypto.createHash('sha1').update(bytes).digest('hex').slice(0, 16);
131
+ return `W/"${bytes.length.toString(16)}-${hash}"`;
92
132
  }
package/src/index.ts CHANGED
@@ -50,6 +50,8 @@ export {
50
50
  type RemoteSnapshotOptions,
51
51
  type HttpSnapshotAdapterOptions,
52
52
  type SigV4SnapshotAdapterOptions,
53
+ type SnapshotTransferOptions,
54
+ type SnapshotRequestOptions,
53
55
  } from './remote-snapshot';
54
56
  export {
55
57
  createHttpMeshRelay,
@@ -155,3 +157,7 @@ export {
155
157
  type IIpcCacheProvider,
156
158
  } from './ipc-telemetry';
157
159
 
160
+ export { CacheCapacityError } from './utils/work-limits.js';
161
+ export { CacheInvalidationUnavailableError } from './errors.js';
162
+ export { OriginCapacityLimiter } from './origin-capacity.js';
163
+ export type { OriginCapacityOptions, OriginRunOptions, OriginCapacityMetrics } from './origin-capacity.js';
@@ -56,6 +56,8 @@ export class IpcTelemetryServer {
56
56
  private server: net.Server | null = null;
57
57
  public readonly socketPath: string;
58
58
  private _closed = false;
59
+ private _starting: Promise<void> | null = null;
60
+ private readonly sockets = new Set<net.Socket>();
59
61
  private _exitHandler: (() => void) | null = null;
60
62
  private _sigintHandler: (() => void) | null = null;
61
63
  private _sigtermHandler: (() => void) | null = null;
@@ -71,12 +73,20 @@ export class IpcTelemetryServer {
71
73
  * Start listening on the IPC socket / pipe.
72
74
  */
73
75
  async start(): Promise<void> {
74
- if (this.server && this.server.listening) return;
76
+ if (this._closed || this.server?.listening) return;
77
+ if (this._starting) return this._starting;
78
+ this._starting = this.startInternal();
79
+ try { await this._starting; }
80
+ finally { this._starting = null; }
81
+ }
82
+
83
+ private async startInternal(): Promise<void> {
75
84
 
76
85
  // Hygiene on POSIX: check if an orphaned socket file exists from a crashed run
77
86
  if (process.platform !== 'win32' && fs.existsSync(this.socketPath)) {
78
87
  await new Promise<void>((resolve) => {
79
88
  const testSocket = net.createConnection(this.socketPath);
89
+ testSocket.setTimeout(1000, () => { testSocket.destroy(); resolve(); });
80
90
  testSocket.once('connect', () => {
81
91
  testSocket.destroy();
82
92
  // Active server already listening on this socket
@@ -94,22 +104,30 @@ export class IpcTelemetryServer {
94
104
  });
95
105
  });
96
106
  }
107
+ if (this._closed) return;
97
108
 
98
109
  this.server = net.createServer((socket) => {
110
+ if (this._closed) { socket.destroy(); return; }
111
+ this.sockets.add(socket);
112
+ socket.once('close', () => this.sockets.delete(socket));
113
+ socket.setTimeout(5000, () => socket.destroy());
99
114
  let buffer = '';
115
+ let pending = 0;
100
116
 
101
117
  socket.on('data', (chunk) => {
118
+ if (Buffer.byteLength(buffer) + chunk.length > 4096 || socket.writableLength > 65536) { socket.destroy(); return; }
102
119
  buffer += chunk.toString('utf8');
103
120
  let newlineIndex: number;
104
121
  while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
105
122
  const line = buffer.slice(0, newlineIndex).trim();
106
123
  buffer = buffer.slice(newlineIndex + 1);
107
124
  if (!line) continue;
125
+ if (++pending > 8) { socket.destroy(); return; }
108
126
 
109
127
  // Non-blocking telemetry pull: pull stats snapshot on tick boundaries
110
128
  // using setImmediate so serialization never introduces event loop stalls.
111
129
  setImmediate(() => {
112
- if (socket.destroyed) return;
130
+ if (socket.destroyed) { pending--; return; }
113
131
  try {
114
132
  let cmd = line;
115
133
  try {
@@ -138,6 +156,8 @@ export class IpcTelemetryServer {
138
156
  if (!socket.destroyed) {
139
157
  socket.write(JSON.stringify({ error: (err as Error).message }) + '\n');
140
158
  }
159
+ } finally {
160
+ pending--;
141
161
  }
142
162
  });
143
163
  }
@@ -147,24 +167,29 @@ export class IpcTelemetryServer {
147
167
  // Suppress client disconnection errors on IPC socket
148
168
  });
149
169
  });
170
+ this.server.maxConnections = 128;
150
171
 
151
172
  await new Promise<void>((resolve, reject) => {
152
- this.server!.once('error', reject);
153
- this.server!.listen(this.socketPath, () => {
154
- this.server!.removeListener('error', reject);
173
+ const server = this.server!;
174
+ const cleanup = () => { server.off('error', failed); server.off('close', closed); };
175
+ const failed = (error: Error) => { cleanup(); reject(error); };
176
+ const closed = () => { cleanup(); resolve(); }; // close() can cancel listen before its callback fires.
177
+ server.once('error', failed);
178
+ server.once('close', closed);
179
+ server.listen(this.socketPath, () => {
180
+ cleanup();
155
181
  resolve();
156
182
  });
157
183
  });
184
+ if (this._closed) { if (this.server.listening) this.server.close(); return; }
158
185
 
159
186
  // Register process termination handlers to guarantee socket hygiene
160
187
  this._exitHandler = () => this._unlinkSocket();
161
188
  this._sigintHandler = () => {
162
189
  this._unlinkSocket();
163
- process.exit(0);
164
190
  };
165
191
  this._sigtermHandler = () => {
166
192
  this._unlinkSocket();
167
- process.exit(0);
168
193
  };
169
194
 
170
195
  process.once('exit', this._exitHandler);
@@ -198,6 +223,7 @@ export class IpcTelemetryServer {
198
223
  private _unlinkSocket(): void {
199
224
  if (this._closed) return;
200
225
  this._closed = true;
226
+ for (const socket of this.sockets) socket.destroy();
201
227
  try {
202
228
  this.server?.close();
203
229
  } catch {
@@ -218,6 +244,8 @@ export class IpcTelemetryServer {
218
244
  * Gracefully close the IPC telemetry server and clean up handlers and sockets.
219
245
  */
220
246
  async close(): Promise<void> {
247
+ this._unlinkSocket();
248
+ await this._starting?.catch(() => {});
221
249
  if (this._exitHandler) {
222
250
  process.removeListener('exit', this._exitHandler);
223
251
  this._exitHandler = null;
@@ -231,8 +259,6 @@ export class IpcTelemetryServer {
231
259
  this._sigtermHandler = null;
232
260
  }
233
261
 
234
- this._unlinkSocket();
235
-
236
262
  return new Promise<void>((resolve) => {
237
263
  if (!this.server || !this.server.listening) {
238
264
  resolve();
@@ -258,7 +258,11 @@ export class TierLatencyWatchdog {
258
258
  this.canaryInFlight = false;
259
259
 
260
260
  if (success && elapsedMs < this.minDiskBypassMs) {
261
- // Canary succeeded and was fast: Recover cleanly
261
+ // Retire old disk samples so a later Redis observation cannot retrip us.
262
+ this.diskRing.fill(0);
263
+ this.diskIdx = 0;
264
+ this.diskCount = 0;
265
+ this.cachedDiskP95 = 0;
262
266
  this.stage = 0;
263
267
  this.bypassedUntilMonotonic = 0;
264
268
  this.recordDisk(elapsedMs);
@@ -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 = Math.round(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;
@@ -2,6 +2,7 @@ import { TriCacheModule } from './tricache.module.js';
2
2
 
3
3
  export { TriCacheModule };
4
4
  export { TriCacheStore } from './tricache.store.js';
5
+ export { TriCacheKeyvAdapter } from './keyv-adapter.js';
5
6
  export {
6
7
  Cacheable,
7
8
  CacheEvict,
@@ -18,6 +19,7 @@ export {
18
19
  type TriCacheAsyncOptions,
19
20
  type TriCacheOptionsFactory,
20
21
  type NestCacheStore,
22
+ type TriCacheModuleOptions,
21
23
  } from './types.js';
22
24
 
23
25
  export default TriCacheModule;
@@ -0,0 +1,68 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { CacheService } from '../cache-service.js';
3
+
4
+ /**
5
+ * Relative-millisecond storage adapter for Keyv 5 / cache-manager 7.
6
+ * Wrap it in Keyv before passing it to Nest's CacheModule. Unlike TriCacheStore,
7
+ * this is a storage adapter, not the injected cache-manager facade.
8
+ * The supplied engine remains caller-owned when Keyv disconnects.
9
+ */
10
+ export class TriCacheKeyvAdapter extends EventEmitter {
11
+ private _namespace?: string;
12
+
13
+ constructor(public readonly cache: CacheService) { super(); }
14
+
15
+ get namespace(): string | undefined { return this._namespace; }
16
+ set namespace(value: string | undefined) {
17
+ if (value && ['*', '?', '[', ']', '\\'].some(character => value.includes(character))) {
18
+ throw new Error('Keyv namespace must not contain glob characters');
19
+ }
20
+ this._namespace = value;
21
+ }
22
+
23
+ async get<T = unknown>(key: string): Promise<T | undefined> {
24
+ const value = await this.cache.peek<T>(key);
25
+ return value === null ? undefined : value;
26
+ }
27
+
28
+ async set(key: string, value: unknown, ttl?: number): Promise<boolean> {
29
+ if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0)) throw new Error('Keyv TTL must be finite and non-negative');
30
+ const ttlSeconds = ttl === undefined ? 0 : ttl / 1000;
31
+ await this.cache.set(key, value, ttlSeconds);
32
+ return true;
33
+ }
34
+
35
+ async delete(key: string): Promise<boolean> {
36
+ const found = await this.has(key);
37
+ await this.cache.delete(key);
38
+ return found;
39
+ }
40
+
41
+ async clear(): Promise<void> {
42
+ await this.cache.clear(this._namespace ? `${this._namespace}:` : undefined);
43
+ }
44
+
45
+ async has(key: string): Promise<boolean> { return await this.cache.peek(key) !== null; }
46
+
47
+ async getMany<T = unknown>(keys: string[]): Promise<(T | undefined)[]> {
48
+ return this.cache.mget<T>(keys);
49
+ }
50
+
51
+ async deleteMany(keys: string[]): Promise<boolean> {
52
+ const found = await this.cache.mget(keys);
53
+ await this.cache.mdel(keys);
54
+ return found.every(value => value !== undefined && value !== null);
55
+ }
56
+
57
+ async setMany(entries: Array<{ key: string; value: unknown; ttl?: number }>): Promise<boolean[]> {
58
+ const results = await Promise.all(entries.map(entry => this.set(entry.key, entry.value, entry.ttl)));
59
+ return results;
60
+ }
61
+
62
+ async hasMany(keys: string[]): Promise<boolean[]> {
63
+ const values = await this.cache.mget(keys);
64
+ return values.map(value => value !== null && value !== undefined);
65
+ }
66
+
67
+ async disconnect(): Promise<void> { /* The caller owns and closes the shared engine. */ }
68
+ }
@@ -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,
@@ -7,6 +8,7 @@ import {
7
8
  type Provider,
8
9
  type TriCacheAsyncOptions,
9
10
  type TriCacheOptionsFactory,
11
+ type TriCacheModuleOptions,
10
12
  } from './types.js';
11
13
 
12
14
  /**
@@ -23,18 +25,18 @@ export class TriCacheModule {
23
25
  /**
24
26
  * Register TriCache module synchronously with static configuration options.
25
27
  */
26
- static register(options: CacheOptions = {}): DynamicModule {
28
+ static register(options: CacheOptions = {}, moduleOptions: TriCacheModuleOptions = {}): DynamicModule {
27
29
  const cache = CacheService.create(options);
28
- const store = new TriCacheStore(cache);
30
+ const provideCacheManager = moduleOptions.provideCacheManager ?? true;
29
31
 
30
32
  return {
31
33
  module: TriCacheModule,
32
34
  global: true,
33
35
  providers: [
34
36
  { provide: TRICACHE_SERVICE, useValue: cache },
35
- { provide: CACHE_MANAGER, useValue: store },
37
+ ...(provideCacheManager ? [{ provide: CACHE_MANAGER, useValue: new TriCacheStore(cache) }] : []),
36
38
  ],
37
- exports: [TRICACHE_SERVICE, CACHE_MANAGER],
39
+ exports: [TRICACHE_SERVICE, ...(provideCacheManager ? [CACHE_MANAGER] : [])],
38
40
  };
39
41
  }
40
42
 
@@ -43,6 +45,7 @@ export class TriCacheModule {
43
45
  */
44
46
  static registerAsync(asyncOptions: TriCacheAsyncOptions): DynamicModule {
45
47
  const asyncProviders = this.createAsyncProviders(asyncOptions);
48
+ const provideCacheManager = asyncOptions.provideCacheManager ?? true;
46
49
 
47
50
  return {
48
51
  module: TriCacheModule,
@@ -50,14 +53,14 @@ export class TriCacheModule {
50
53
  imports: asyncOptions.imports || [],
51
54
  providers: [
52
55
  ...asyncProviders,
53
- {
56
+ ...(provideCacheManager ? [{
54
57
  provide: CACHE_MANAGER,
55
- useFactory: (cache: any) => new TriCacheStore(cache as CacheService),
58
+ useFactory: (cache: CacheService) => new TriCacheStore(cache),
56
59
  inject: [TRICACHE_SERVICE],
57
- },
60
+ }] : []),
58
61
  ...(asyncOptions.extraProviders || []),
59
62
  ],
60
- exports: [TRICACHE_SERVICE, CACHE_MANAGER],
63
+ exports: [TRICACHE_SERVICE, ...(provideCacheManager ? [CACHE_MANAGER] : [])],
61
64
  };
62
65
  }
63
66
 
@@ -83,7 +86,7 @@ export class TriCacheModule {
83
86
  if (options.useFactory) {
84
87
  return {
85
88
  provide: TRICACHE_SERVICE,
86
- useFactory: async (...args: any[]) => {
89
+ useFactory: async (...args: unknown[]) => {
87
90
  const cacheOptions = await options.useFactory!(...args);
88
91
  return CacheService.create(cacheOptions);
89
92
  },
@@ -94,8 +97,8 @@ export class TriCacheModule {
94
97
  const injectToken = options.useExisting || options.useClass!;
95
98
  return {
96
99
  provide: TRICACHE_SERVICE,
97
- useFactory: async (optionsFactory: any) => {
98
- const cacheOptions = await (optionsFactory as TriCacheOptionsFactory).createTriCacheOptions();
100
+ useFactory: async (optionsFactory: TriCacheOptionsFactory) => {
101
+ const cacheOptions = await optionsFactory.createTriCacheOptions();
99
102
  return CacheService.create(cacheOptions);
100
103
  },
101
104
  inject: [injectToken],