tricache 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
package/src/cli.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  import { readFileSync } from 'node:fs';
12
12
  import { parseArgs } from 'node:util';
13
13
  import { CacheService } from './cache-service.js';
14
+ import { Redis } from 'ioredis';
14
15
  import {
15
16
  IpcTelemetryClient,
16
17
  resolveIpcSocketPath,
@@ -60,7 +61,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
60
61
  // (bin/tricache.js). Output must go directly to process stdout without logger prefixes
61
62
  // to support UNIX pipes, terminal formatting, and automated tooling.
62
63
  if (values.version || command === 'version') {
63
- let version = '1.0.1';
64
+ let version = '1.0.2';
64
65
  try {
65
66
  const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
66
67
  if (pkg?.version) version = pkg.version;
@@ -178,19 +179,35 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
178
179
  }
179
180
 
180
181
  const redisStr = typeof values.redis === 'string' ? values.redis : undefined;
181
- const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, '').split(':')[0] : undefined;
182
- const redisPort = typeof values.port === 'string'
183
- ? parseInt(values.port, 10)
184
- : (redisStr && redisStr.includes(':') ? parseInt(redisStr.split(':')[1], 10) : 6379);
182
+ let redisHost: string | undefined;
183
+ let redisPort = 6379;
184
+ let redisClient: Redis | undefined;
185
+ if (redisStr) {
186
+ try {
187
+ const url = new URL(redisStr.includes('://') ? redisStr : `redis://${redisStr}`);
188
+ if (url.protocol !== 'redis:' && url.protocol !== 'rediss:') throw new Error('Unsupported Redis URL scheme');
189
+ redisPort = Number(typeof values.port === 'string' ? values.port : url.port || 6379);
190
+ if (!Number.isInteger(redisPort) || redisPort < 1 || redisPort > 65535) throw new Error('Invalid Redis port');
191
+ url.port = String(redisPort);
192
+ redisHost = url.hostname;
193
+ redisClient = new Redis(url.toString(), { lazyConnect: true, commandTimeout: 2500, maxRetriesPerRequest: 1 });
194
+ redisClient.on('error', () => {}); // CacheService reports operation failures without exposing credentials.
195
+ } catch {
196
+ console.error('Invalid Redis host, URL, or port');
197
+ process.exitCode = 1;
198
+ return;
199
+ }
200
+ }
185
201
  const namespace = typeof values.namespace === 'string' ? values.namespace : undefined;
186
202
  const diskCacheDir = typeof values.disk === 'string' ? values.disk : undefined;
187
203
 
188
204
  const cache = new CacheService({
189
205
  redisHost,
190
206
  redisPort,
207
+ redisClient,
191
208
  namespace,
192
209
  diskCacheDir,
193
- disableRedis: !redisHost,
210
+ disableRedis: !redisClient,
194
211
  });
195
212
 
196
213
  try {
@@ -245,6 +262,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
245
262
  }
246
263
  } finally {
247
264
  await cache.destroy();
265
+ redisClient?.disconnect();
248
266
  }
249
267
  }
250
268
 
@@ -6,6 +6,19 @@
6
6
  * active-active Redis Enterprise licenses.
7
7
  */
8
8
 
9
+ import { createHash, timingSafeEqual } from 'node:crypto';
10
+
11
+ export function isCrossRegionInvalidationEvent(value: unknown): value is CrossRegionInvalidationEvent {
12
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
13
+ const event = value as Record<string, unknown>;
14
+ const text = (key: string, max: number) => typeof event[key] === 'string' && (event[key] as string).length > 0 && (event[key] as string).length <= max;
15
+ return text('id', 256) && text('originRegion', 128) && text('originInstanceId', 256) && text('key', 8192) &&
16
+ typeof event.op === 'string' && ['del', 'del-glob', 'tag_incr', 'tag_pattern_incr', 'tag_pattern_del'].includes(event.op) &&
17
+ typeof event.timestamp === 'number' && Number.isFinite(event.timestamp) && event.timestamp >= 0 &&
18
+ (event.namespace === undefined || typeof event.namespace === 'string') &&
19
+ (event.tagVersion === undefined || Number.isSafeInteger(event.tagVersion) && Number(event.tagVersion) >= 0);
20
+ }
21
+
9
22
  export interface CrossRegionInvalidationEvent {
10
23
  /** Unique ID of this invalidation event (UUIDv4) */
11
24
  id: string;
@@ -109,7 +122,7 @@ export function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegion
109
122
  if (!peerUrls.length) return;
110
123
 
111
124
  const body = JSON.stringify(event);
112
- await Promise.allSettled(
125
+ const results = await Promise.allSettled(
113
126
  peerUrls.map(async (url) => {
114
127
  const res = await fetcher(url, {
115
128
  method: 'POST',
@@ -122,6 +135,8 @@ export function createHttpMeshRelay(options: HttpMeshRelayOptions): ICrossRegion
122
135
  }
123
136
  }),
124
137
  );
138
+ const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
139
+ if (failures.length) throw new AggregateError(failures.map(result => result.reason), `Cross-region delivery failed for ${failures.length} peer(s)`);
125
140
  },
126
141
  };
127
142
  }
@@ -156,7 +171,9 @@ export function createMemoryCrossRegionRelay(): ICrossRegionRelay & {
156
171
  }
157
172
  }
158
173
  }
159
- await Promise.allSettled(promises);
174
+ const results = await Promise.allSettled(promises);
175
+ const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
176
+ if (failures.length) throw new AggregateError(failures.map(result => result.reason), 'Cross-region handler failed');
160
177
  },
161
178
 
162
179
  register(region: string, handler: (event: CrossRegionInvalidationEvent) => Promise<unknown> | unknown): () => void {
@@ -209,7 +226,7 @@ export function createCrossRegionWebhookHandler(
209
226
 
210
227
  const provided = (typeof customHeader === 'string' ? customHeader : bearer);
211
228
 
212
- if (!provided || provided !== options.authSecret) {
229
+ if (typeof provided !== 'string' || !timingSafeEqual(createHash('sha256').update(provided).digest(), createHash('sha256').update(options.authSecret).digest())) {
213
230
  return {
214
231
  status: 401,
215
232
  body: { ok: false, message: 'Unauthorized: invalid or missing auth secret' },
@@ -230,6 +247,7 @@ export function createCrossRegionWebhookHandler(
230
247
  };
231
248
  }
232
249
 
250
+ if (!isCrossRegionInvalidationEvent(event)) return { status: 400, body: { ok: false, message: 'Invalid invalidation event' } };
233
251
  const accepted = await cache.receiveCrossRegionInvalidation(event);
234
252
  return {
235
253
  status: 200,
@@ -21,7 +21,7 @@ const SECURITY_HEADERS: Record<string, string> = {
21
21
  'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
22
22
  'X-Frame-Options': 'DENY',
23
23
  'X-Content-Type-Options': 'nosniff',
24
- 'Referrer-Policy': 'same-origin',
24
+ 'Referrer-Policy': 'no-referrer',
25
25
  'Cache-Control': 'no-store, no-cache, must-revalidate',
26
26
  };
27
27
 
@@ -48,7 +48,7 @@ export function buildMetricsPayload(options: DashboardOptions): Record<string, u
48
48
  title: options.title || 'TriCache Observability',
49
49
  instanceId: resolveInstanceId(options.instanceId),
50
50
  nodeVersion: process.version,
51
- readOnly: !!options.readOnly,
51
+ readOnly: options.readOnly ?? true,
52
52
  peerInstances: options.peerInstances || [],
53
53
  metrics: {
54
54
  ...metrics,
@@ -192,6 +192,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
192
192
  // Start periodic broadcast ticker
193
193
  ticker = setInterval(() => {
194
194
  try {
195
+ if ((controller.desiredSize ?? 0) <= 0) return; // Drop snapshots instead of buffering for slow readers.
195
196
  const data = buildMetricsPayload(options);
196
197
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
197
198
  } catch {
@@ -208,7 +209,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
208
209
  ticker = null;
209
210
  }
210
211
  try { controller.close(); } catch { /* ignore */ }
211
- });
212
+ }, { once: true });
212
213
  }
213
214
  },
214
215
  cancel() {
@@ -247,7 +248,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
247
248
  const clientIp = req.headers.get('x-forwarded-for') || undefined;
248
249
 
249
250
  // Check Read-Only Mode
250
- if (options.readOnly) {
251
+ if (options.readOnly ?? true) {
251
252
  return new Response(JSON.stringify({ ok: false, error: 'Dashboard is in read-only mode' }), {
252
253
  status: 403,
253
254
  headers: { 'Content-Type': 'application/json' },
@@ -263,7 +264,26 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
263
264
  }
264
265
 
265
266
  try {
266
- const body = await req.json() as { tag?: string };
267
+ const maxBytes = options.maxRequestBytes ?? 65536;
268
+ if (Number(req.headers.get('content-length')) > maxBytes) return new Response(JSON.stringify({ error: 'Request body too large' }), { status: 413 });
269
+ const reader = req.body?.getReader();
270
+ const chunks: Uint8Array[] = [];
271
+ let bytes = 0;
272
+ if (reader) {
273
+ try {
274
+ while (true) {
275
+ const chunk = await reader.read();
276
+ if (chunk.done) break;
277
+ bytes += chunk.value.length;
278
+ if (bytes > maxBytes) {
279
+ await reader.cancel();
280
+ return new Response(JSON.stringify({ error: 'Request body too large' }), { status: 413 });
281
+ }
282
+ chunks.push(chunk.value);
283
+ }
284
+ } finally { reader.releaseLock(); }
285
+ }
286
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { tag?: string };
267
287
  const tag = body?.tag?.trim();
268
288
  if (!tag) {
269
289
  return new Response(JSON.stringify({ ok: false, error: 'Tag parameter is required' }), {
@@ -310,7 +330,7 @@ export async function handleDashboardRequest(req: Request, options: DashboardOpt
310
330
  const clientIp = req.headers.get('x-forwarded-for') || undefined;
311
331
 
312
332
  // Check Read-Only Mode
313
- if (options.readOnly) {
333
+ if (options.readOnly ?? true) {
314
334
  return new Response(JSON.stringify({ ok: false, error: 'Dashboard is in read-only mode' }), {
315
335
  status: 403,
316
336
  headers: { 'Content-Type': 'application/json' },
@@ -290,7 +290,7 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
290
290
  <span class="pulse-dot"></span>
291
291
  <span id="stream-text">SSE Live</span>
292
292
  </div>
293
- <select id="peer-select" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
293
+ <select id="peer-select" aria-label="Switch cache instance" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
294
294
  <option value="">Switch Pod...</option>
295
295
  </select>
296
296
  </div>
@@ -350,9 +350,10 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
350
350
 
351
351
  <!-- Invalidate Modal -->
352
352
  <div class="dialog-overlay" id="invalidate-modal">
353
- <div class="dialog">
354
- <h3>Invalidate Tag</h3>
353
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="invalidate-title">
354
+ <h3 id="invalidate-title">Invalidate Tag</h3>
355
355
  <p>Increments generational tag version across local tiers and broadcast backplane.</p>
356
+ <label for="tag-input">Tag name or pattern</label>
356
357
  <input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
357
358
  <div class="dialog-actions">
358
359
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -363,8 +364,8 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
363
364
 
364
365
  <!-- Clear Modal -->
365
366
  <div class="dialog-overlay" id="clear-modal">
366
- <div class="dialog">
367
- <h3>Clear Cache</h3>
367
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="clear-title">
368
+ <h3 id="clear-title">Clear Cache</h3>
368
369
  <p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
369
370
  <div class="dialog-actions">
370
371
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -373,12 +374,20 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
373
374
  </div>
374
375
  </div>
375
376
 
376
- <div id="toast"></div>
377
+ <div id="toast" role="status" aria-live="polite"></div>
377
378
 
378
379
  <script>
379
380
  (function() {
380
381
  let isReadOnly = false;
381
382
  let sseFailed = false;
383
+ let previousFocus = null;
384
+ const token = new URLSearchParams(window.location.search).get('token');
385
+ const basePath = window.location.pathname.replace(/\\/index\\.html$/, '').replace(/\\/+$/, '');
386
+ function apiURL(path) {
387
+ const url = new URL(basePath + '/' + path, window.location.origin);
388
+ if (token) url.searchParams.set('token', token);
389
+ return url.toString();
390
+ }
382
391
 
383
392
  function showToast(msg, duration = 3000) {
384
393
  const t = document.getElementById('toast');
@@ -485,7 +494,8 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
485
494
  }
486
495
 
487
496
  window.fetchMetricsSnapshot = function() {
488
- fetch('api/metrics')
497
+ fetch(apiURL('api/metrics'))
498
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
489
499
  .then(r => r.json())
490
500
  .then(data => updateUI(data))
491
501
  .catch(err => showToast('Failed to fetch snapshot: ' + err.message));
@@ -496,7 +506,7 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
496
506
  fallbackPolling();
497
507
  return;
498
508
  }
499
- const sse = new EventSource('api/stream');
509
+ const sse = new EventSource(apiURL('api/stream'));
500
510
  sse.onmessage = function(e) {
501
511
  try {
502
512
  const data = JSON.parse(e.data);
@@ -521,22 +531,37 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
521
531
 
522
532
  window.openInvalidateModal = function() {
523
533
  if (isReadOnly) return;
534
+ previousFocus = document.activeElement;
524
535
  document.getElementById('invalidate-modal').classList.add('active');
525
536
  document.getElementById('tag-input').focus();
526
537
  };
527
538
  window.openClearModal = function() {
528
539
  if (isReadOnly) return;
540
+ previousFocus = document.activeElement;
529
541
  document.getElementById('clear-modal').classList.add('active');
542
+ document.querySelector('#clear-modal button').focus();
530
543
  };
531
544
  window.closeModals = function() {
532
545
  document.getElementById('invalidate-modal').classList.remove('active');
533
546
  document.getElementById('clear-modal').classList.remove('active');
547
+ if (previousFocus) previousFocus.focus();
534
548
  };
549
+ document.addEventListener('keydown', function(event) {
550
+ const modal = document.querySelector('.dialog-overlay.active');
551
+ if (!modal) return;
552
+ if (event.key === 'Escape') { event.preventDefault(); closeModals(); }
553
+ if (event.key === 'Tab') {
554
+ const controls = modal.querySelectorAll('button, input, select, [tabindex="0"]');
555
+ const first = controls[0], last = controls[controls.length - 1];
556
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
557
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
558
+ }
559
+ });
535
560
 
536
561
  window.submitTagInvalidation = function() {
537
562
  const tag = document.getElementById('tag-input').value.trim();
538
563
  if (!tag) return;
539
- fetch('api/actions/invalidate-tag', {
564
+ fetch(apiURL('api/actions/invalidate-tag'), {
540
565
  method: 'POST',
541
566
  headers: {
542
567
  'Content-Type': 'application/json',
@@ -559,7 +584,7 @@ export const DASHBOARD_HTML: string = `<!DOCTYPE html>
559
584
  };
560
585
 
561
586
  window.submitClear = function() {
562
- fetch('api/actions/clear', {
587
+ fetch(apiURL('api/actions/clear'), {
563
588
  method: 'POST',
564
589
  headers: {
565
590
  'Content-Type': 'application/json',
@@ -10,7 +10,7 @@ export { DASHBOARD_HTML, DASHBOARD_GZIP_BUFFER } from './html.js';
10
10
  /**
11
11
  * Convert a Node.js IncomingMessage into a Web Standards Request.
12
12
  */
13
- async function nodeToWebRequest(req: IncomingMessage): Promise<Request> {
13
+ async function nodeToWebRequest(req: IncomingMessage, res: ServerResponse, maxBytes: number): Promise<Request> {
14
14
  const protocol = (req.socket as { encrypted?: boolean }).encrypted ? 'https' : 'http';
15
15
  const host = req.headers.host || 'localhost';
16
16
  const url = new URL(req.url || '/', `${protocol}://${host}`);
@@ -28,20 +28,24 @@ async function nodeToWebRequest(req: IncomingMessage): Promise<Request> {
28
28
  let body: Uint8Array | null = null;
29
29
  if (req.method !== 'GET' && req.method !== 'HEAD') {
30
30
  const chunks: Buffer[] = [];
31
- for await (const chunk of req) {
32
- chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
31
+ let size = 0;
32
+ const parsed = (req as IncomingMessage & { body?: unknown }).body;
33
+ if (req.readableEnded && parsed !== undefined) chunks.push(Buffer.from(JSON.stringify(parsed)));
34
+ else for await (const chunk of req) {
35
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
36
+ size += bytes.length;
37
+ if (size > maxBytes) throw Object.assign(new Error('Request body exceeds dashboard limit'), { status: 413 });
38
+ chunks.push(bytes);
33
39
  }
34
40
  if (chunks.length > 0) {
35
41
  body = Buffer.concat(chunks);
42
+ if (body.length > maxBytes) throw Object.assign(new Error('Request body exceeds dashboard limit'), { status: 413 });
36
43
  }
37
44
  }
38
45
 
39
46
  const controller = new AbortController();
40
- req.on('close', () => {
41
- if (req.destroyed || !req.complete) {
42
- controller.abort();
43
- }
44
- });
47
+ req.once('aborted', () => controller.abort());
48
+ res.once('close', () => controller.abort());
45
49
 
46
50
  const init: RequestInit & { duplex?: string } = {
47
51
  method: req.method,
@@ -71,14 +75,26 @@ async function pipeWebResponseToNode(webRes: Response, nodeRes: ServerResponse):
71
75
  }
72
76
 
73
77
  const reader = webRes.body.getReader();
78
+ const cancel = () => { void reader.cancel().catch(() => {}); };
79
+ nodeRes.once('close', cancel);
74
80
  try {
75
81
  while (true) {
76
82
  const { done, value } = await reader.read();
77
83
  if (done) break;
78
- nodeRes.write(value);
84
+ if (nodeRes.destroyed) break;
85
+ if (!nodeRes.write(value)) await new Promise<void>((resolve, reject) => {
86
+ const cleanup = () => { nodeRes.off('drain', onDrain); nodeRes.off('close', onClose); };
87
+ const onDrain = () => { cleanup(); resolve(); };
88
+ const onClose = () => { cleanup(); reject(new Error('Dashboard response closed')); };
89
+ nodeRes.once('drain', onDrain);
90
+ nodeRes.once('close', onClose);
91
+ });
79
92
  }
80
93
  } finally {
81
- nodeRes.end();
94
+ nodeRes.off('close', cancel);
95
+ await reader.cancel().catch(() => {});
96
+ reader.releaseLock();
97
+ if (!nodeRes.destroyed) nodeRes.end();
82
98
  }
83
99
  }
84
100
 
@@ -99,11 +115,16 @@ async function pipeWebResponseToNode(webRes: Response, nodeRes: ServerResponse):
99
115
  export function tricacheDashboard(options: DashboardOptions) {
100
116
  return async (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void): Promise<void> => {
101
117
  try {
102
- const webReq = await nodeToWebRequest(req);
118
+ const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
103
119
  const webRes = await handleDashboardRequest(webReq, options);
104
120
  await pipeWebResponseToNode(webRes, res);
105
121
  } catch (err) {
106
- if (typeof next === 'function') {
122
+ if (res.destroyed) return;
123
+ if ((err as { status?: number }).status === 413) {
124
+ res.statusCode = 413;
125
+ res.setHeader('Connection', 'close');
126
+ res.end(JSON.stringify({ error: 'Request body too large' }));
127
+ } else if (typeof next === 'function') {
107
128
  next(err);
108
129
  } else {
109
130
  res.statusCode = 500;
@@ -162,7 +183,7 @@ export async function startDashboardServer(options: StandaloneDashboardOptions):
162
183
  host: string;
163
184
  close: () => Promise<void>;
164
185
  }> {
165
- const port = options.port || 9090;
186
+ const port = options.port ?? 9090;
166
187
  const host = options.host || '127.0.0.1';
167
188
 
168
189
  const middleware = tricacheDashboard(options);
@@ -190,6 +211,7 @@ export async function startDashboardServer(options: StandaloneDashboardOptions):
190
211
  host,
191
212
  close: () => new Promise<void>((resolve, reject) => {
192
213
  server.close(err => (err ? reject(err) : resolve()));
214
+ server.closeAllConnections();
193
215
  }),
194
216
  };
195
217
  }
@@ -63,7 +63,7 @@ export interface DashboardOptions {
63
63
  /**
64
64
  * Enforces read-only mode: disables and blocks all mutating operations
65
65
  * (e.g. invalidate tag, clear cache tier). Mutating endpoints return 403 Forbidden.
66
- * @default false
66
+ * @default true
67
67
  */
68
68
  readOnly?: boolean;
69
69
 
@@ -72,6 +72,8 @@ export interface DashboardOptions {
72
72
  * @default 2000
73
73
  */
74
74
  streamIntervalMs?: number;
75
+ /** Maximum administrative request body size. Default: 64 KiB. */
76
+ maxRequestBytes?: number;
75
77
 
76
78
  /**
77
79
  * Enterprise audit logging hook invoked when an administrative action is attempted.