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
package/dist/cli.d.cts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * TriCache CLI — Developer & Troubleshooting Inspector
3
+ *
4
+ * Usage:
5
+ * npx tricache top [--socket <path>] [--pid <pid>] [--interval <ms>] [--once]
6
+ * npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
7
+ * npx tricache ping [--redis redis://localhost:6379]
8
+ * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
9
+ */
10
+ declare function runCli(args?: string[]): Promise<void>;
11
+
12
+ export { runCli };
package/dist/cli.js CHANGED
@@ -4,13 +4,195 @@ import {
4
4
  findActiveSockets,
5
5
  renderTopDashboard,
6
6
  resolveIpcSocketPath
7
- } from "./chunk-JYQFQJNJ.js";
8
- import "./chunk-UBWLPKTI.js";
9
- import "./chunk-2AJKEQMZ.js";
7
+ } from "./chunk-MB3DMVWN.js";
8
+ import "./chunk-EJXG7WO6.js";
9
+ import "./chunk-KV7KISK2.js";
10
10
 
11
11
  // src/cli.ts
12
- import { readFileSync } from "fs";
13
12
  import { parseArgs } from "util";
13
+
14
+ // package.json
15
+ var package_default = {
16
+ name: "tricache",
17
+ version: "2.0.0",
18
+ description: "Node.js caching with bounded memory, Redis/Valkey sharing, tag invalidation, stale-while-revalidate, per-process request coalescing, framework adapters, and optional local disk spill.",
19
+ keywords: [
20
+ "cache",
21
+ "redis",
22
+ "valkey",
23
+ "lru",
24
+ "lfu",
25
+ "bloom-filter",
26
+ "count-min-sketch",
27
+ "swr",
28
+ "stale-while-revalidate",
29
+ "msgpack",
30
+ "aes-256-gcm",
31
+ "envelope-encryption",
32
+ "nextjs",
33
+ "express",
34
+ "fastify",
35
+ "hono",
36
+ "edge",
37
+ "cli",
38
+ "nodejs"
39
+ ],
40
+ license: "MIT",
41
+ author: "Kareem (https://github.com/Kareem411)",
42
+ repository: {
43
+ type: "git",
44
+ url: "git+https://github.com/Kareem411/TriCache.git"
45
+ },
46
+ homepage: "https://github.com/Kareem411/TriCache#readme",
47
+ packageManager: "pnpm@11.22.0",
48
+ sideEffects: false,
49
+ type: "module",
50
+ main: "./dist/index.js",
51
+ module: "./dist/index.js",
52
+ types: "./dist/index.d.ts",
53
+ bin: {
54
+ tricache: "./bin/tricache.js"
55
+ },
56
+ exports: {
57
+ ".": {
58
+ import: { types: "./dist/index.d.ts", default: "./dist/index.js" },
59
+ require: { types: "./dist/index.d.cts", default: "./dist/index.cjs" }
60
+ },
61
+ "./next": {
62
+ import: { types: "./dist/next/index.d.ts", default: "./dist/next/index.js" },
63
+ require: { types: "./dist/next/index.d.cts", default: "./dist/next/index.cjs" }
64
+ },
65
+ "./nestjs": {
66
+ import: { types: "./dist/nestjs/index.d.ts", default: "./dist/nestjs/index.js" },
67
+ require: { types: "./dist/nestjs/index.d.cts", default: "./dist/nestjs/index.cjs" }
68
+ },
69
+ "./prisma": {
70
+ import: { types: "./dist/prisma/index.d.ts", default: "./dist/prisma/index.js" },
71
+ require: { types: "./dist/prisma/index.d.cts", default: "./dist/prisma/index.cjs" }
72
+ },
73
+ "./drizzle": {
74
+ import: { types: "./dist/drizzle/index.d.ts", default: "./dist/drizzle/index.js" },
75
+ require: { types: "./dist/drizzle/index.d.cts", default: "./dist/drizzle/index.cjs" }
76
+ },
77
+ "./http": {
78
+ import: { types: "./dist/http/index.d.ts", default: "./dist/http/index.js" },
79
+ require: { types: "./dist/http/index.d.cts", default: "./dist/http/index.cjs" }
80
+ },
81
+ "./hono": {
82
+ import: { types: "./dist/hono/index.d.ts", default: "./dist/hono/index.js" },
83
+ require: { types: "./dist/hono/index.d.cts", default: "./dist/hono/index.cjs" }
84
+ },
85
+ "./dashboard": {
86
+ import: { types: "./dist/dashboard/index.d.ts", default: "./dist/dashboard/index.js" },
87
+ require: { types: "./dist/dashboard/index.d.cts", default: "./dist/dashboard/index.cjs" }
88
+ },
89
+ "./edge": {
90
+ "edge-light": { types: "./dist/edge/index.d.ts", default: "./dist/edge/index.js" },
91
+ workerd: { types: "./dist/edge/index.d.ts", default: "./dist/edge/index.js" },
92
+ import: { types: "./dist/edge/index.d.ts", default: "./dist/edge/index.js" },
93
+ require: { types: "./dist/edge/index.d.cts", default: "./dist/edge/index.cjs" },
94
+ default: "./dist/edge/index.js"
95
+ }
96
+ },
97
+ files: [
98
+ "bin",
99
+ "dashboards",
100
+ "dist",
101
+ "src",
102
+ "README.md",
103
+ "LICENSE"
104
+ ],
105
+ scripts: {
106
+ build: "tsup src/index.ts src/cli.ts src/serialize-worker.ts src/next/index.ts src/nestjs/index.ts src/prisma/index.ts src/drizzle/index.ts src/http/index.ts src/hono/index.ts src/dashboard/index.ts src/edge/index.ts --format esm,cjs --dts --clean",
107
+ dev: "tsup src/index.ts src/serialize-worker.ts --format esm,cjs --dts --watch",
108
+ typecheck: "tsc --noEmit",
109
+ "typecheck:tests": "tsc --noEmit -p tsconfig.test.json",
110
+ "typecheck:all": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
111
+ lint: "oxlint src tests scripts",
112
+ test: "vitest run",
113
+ "test:integration": "vitest run --config vitest.integration.config.ts",
114
+ "test:shutdown-docker": "node scripts/run-shutdown-probes.mjs",
115
+ "test:storage-docker": "node scripts/run-storage-permission-probes.mjs",
116
+ "test:recovery-docker": "node scripts/run-redis-recovery-probes.mjs",
117
+ "test:rollout-docker": "node scripts/run-redis-recovery-probes.mjs --rollout",
118
+ "test:watch": "vitest",
119
+ "check:package": "node scripts/check-package.mjs",
120
+ "check:release-version": "node scripts/check-release-version.mjs",
121
+ "check:production-start": "node scripts/check-production-start.mjs",
122
+ "check:rehearsal-runner": "node --test tests/rehearsal-runner.test.mjs tests/m3-protocol.test.mjs",
123
+ "check:m3-rehearsal": "node --test tests/m3-rehearsal.test.mjs tests/service-telemetry.test.mjs tests/production-service.test.mjs",
124
+ "check:spill-crash": "node scripts/check-spill-crash.mjs",
125
+ "check:edge-provider": "node scripts/check-edge-provider.mjs",
126
+ bench: "node --expose-gc --max-old-space-size=8192 --import tsx/esm bench/benchmark.ts",
127
+ "bench:roi": "tsx bench/cloud-roi-simulation.ts",
128
+ "bench:compression": "tsx bench/compression.bench.ts",
129
+ "bench:compare": "tsx bench/compare/runner.ts",
130
+ "bench:compare:smoke": "tsx bench/compare/runner.ts --quick",
131
+ "bench:tag-refresh": "node bench/tag-refresh/run.mjs",
132
+ "bench:public-trace": "tsx bench/public-trace/run-baseline.ts",
133
+ "bench:public-trace:l1": "node --import tsx/esm bench/public-trace/run-l1.ts",
134
+ "bench:public-trace:admission": "node --import tsx/esm bench/public-trace/run-admission-probe.ts",
135
+ "bench:public-trace:calibrate-admission": "node --import tsx/esm bench/public-trace/run-admission-calibration.ts",
136
+ "bench:public-trace:entry-policy": "node --import tsx/esm bench/public-trace/run-entry-policy.ts",
137
+ "bench:outage": "node bench/compare/outage-runner.ts",
138
+ "lint:bench": "oxlint bench/compare bench/tag-refresh bench/public-trace",
139
+ "docs:dev": "vitepress dev docs",
140
+ "docs:build": "vitepress build docs",
141
+ "docs:preview": "vitepress preview docs",
142
+ "docs:start": "vitepress preview docs"
143
+ },
144
+ peerDependencies: {
145
+ "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
146
+ "@nestjs/core": "^10.0.0 || ^11.0.0 || ^12.0.0",
147
+ hono: ">=3.0.0 <5.0.0"
148
+ },
149
+ peerDependenciesMeta: {
150
+ "@nestjs/common": {
151
+ optional: true
152
+ },
153
+ "@nestjs/core": {
154
+ optional: true
155
+ },
156
+ hono: {
157
+ optional: true
158
+ }
159
+ },
160
+ dependencies: {
161
+ ioredis: "6.0.0",
162
+ lz4js: "^0.2.0",
163
+ msgpackr: "2.1.2",
164
+ "zstd-codec": "^0.1.5"
165
+ },
166
+ devDependencies: {
167
+ "@nestjs/cache-manager": "12.0.5",
168
+ "@nestjs/common": "^12.5.0",
169
+ "@nestjs/core": "^12.5.0",
170
+ "@nestjs/platform-express": "^12.5.0",
171
+ "@types/node": "^26.6.2",
172
+ "@opentelemetry/api": "^1.10.0",
173
+ "cache-manager": "7.2.9",
174
+ hono: "^4.13.16",
175
+ keyv: "5.6.0",
176
+ "markdown-it-mathjax3": "^4.3.2",
177
+ next: "16.4.6",
178
+ oxlint: "^1.85.0",
179
+ redis: "^6.2.1",
180
+ "reflect-metadata": "^0.2.2",
181
+ rxjs: "^7.8.2",
182
+ tsup: "^8.5.1",
183
+ tsx: "^4.23.15",
184
+ typescript: "^6.0.3",
185
+ vite: "^8.3.5",
186
+ vitepress: "2.0.0-alpha.20",
187
+ vitest: "^4.1.12"
188
+ },
189
+ engines: {
190
+ node: ">=20.10.0"
191
+ }
192
+ };
193
+
194
+ // src/cli.ts
195
+ import { Redis } from "ioredis";
14
196
  async function runCli(args = process.argv.slice(2)) {
15
197
  const options = {
16
198
  redis: { type: "string", short: "r" },
@@ -47,13 +229,7 @@ async function runCli(args = process.argv.slice(2)) {
47
229
  return;
48
230
  }
49
231
  if (values.version || command === "version") {
50
- let version = "1.0.1";
51
- try {
52
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
53
- if (pkg?.version) version = pkg.version;
54
- } catch {
55
- }
56
- console.log(`tricache v${version}`);
232
+ console.log(`tricache v${package_default.version}`);
57
233
  return;
58
234
  }
59
235
  if (command === "top") {
@@ -150,16 +326,35 @@ Press "q" or Ctrl+C to exit
150
326
  return;
151
327
  }
152
328
  const redisStr = typeof values.redis === "string" ? values.redis : void 0;
153
- const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, "").split(":")[0] : void 0;
154
- const redisPort = typeof values.port === "string" ? parseInt(values.port, 10) : redisStr && redisStr.includes(":") ? parseInt(redisStr.split(":")[1], 10) : 6379;
329
+ let redisHost;
330
+ let redisPort = 6379;
331
+ let redisClient;
332
+ if (redisStr) {
333
+ try {
334
+ const url = new URL(redisStr.includes("://") ? redisStr : `redis://${redisStr}`);
335
+ if (url.protocol !== "redis:" && url.protocol !== "rediss:") throw new Error("Unsupported Redis URL scheme");
336
+ redisPort = Number(typeof values.port === "string" ? values.port : url.port || 6379);
337
+ if (!Number.isInteger(redisPort) || redisPort < 1 || redisPort > 65535) throw new Error("Invalid Redis port");
338
+ url.port = String(redisPort);
339
+ redisHost = url.hostname;
340
+ redisClient = new Redis(url.toString(), { lazyConnect: true, commandTimeout: 2500, maxRetriesPerRequest: 1 });
341
+ redisClient.on("error", () => {
342
+ });
343
+ } catch {
344
+ console.error("Invalid Redis host, URL, or port");
345
+ process.exitCode = 1;
346
+ return;
347
+ }
348
+ }
155
349
  const namespace = typeof values.namespace === "string" ? values.namespace : void 0;
156
350
  const diskCacheDir = typeof values.disk === "string" ? values.disk : void 0;
157
351
  const cache = new CacheService({
158
352
  redisHost,
159
353
  redisPort,
354
+ redisClient,
160
355
  namespace,
161
356
  diskCacheDir,
162
- disableRedis: !redisHost
357
+ disableRedis: !redisClient
163
358
  });
164
359
  try {
165
360
  if (command === "inspect") {
@@ -211,6 +406,7 @@ Press "q" or Ctrl+C to exit
211
406
  }
212
407
  } finally {
213
408
  await cache.destroy();
409
+ redisClient?.disconnect();
214
410
  }
215
411
  }
216
412
  function printHelp() {
@@ -329,7 +329,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
329
329
  <span class="pulse-dot"></span>
330
330
  <span id="stream-text">SSE Live</span>
331
331
  </div>
332
- <select id="peer-select" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
332
+ <select id="peer-select" aria-label="Switch cache instance" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
333
333
  <option value="">Switch Pod...</option>
334
334
  </select>
335
335
  </div>
@@ -389,9 +389,10 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
389
389
 
390
390
  <!-- Invalidate Modal -->
391
391
  <div class="dialog-overlay" id="invalidate-modal">
392
- <div class="dialog">
393
- <h3>Invalidate Tag</h3>
392
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="invalidate-title">
393
+ <h3 id="invalidate-title">Invalidate Tag</h3>
394
394
  <p>Increments generational tag version across local tiers and broadcast backplane.</p>
395
+ <label for="tag-input">Tag name or pattern</label>
395
396
  <input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
396
397
  <div class="dialog-actions">
397
398
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -402,8 +403,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
402
403
 
403
404
  <!-- Clear Modal -->
404
405
  <div class="dialog-overlay" id="clear-modal">
405
- <div class="dialog">
406
- <h3>Clear Cache</h3>
406
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="clear-title">
407
+ <h3 id="clear-title">Clear Cache</h3>
407
408
  <p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
408
409
  <div class="dialog-actions">
409
410
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -412,12 +413,20 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
412
413
  </div>
413
414
  </div>
414
415
 
415
- <div id="toast"></div>
416
+ <div id="toast" role="status" aria-live="polite"></div>
416
417
 
417
418
  <script>
418
419
  (function() {
419
420
  let isReadOnly = false;
420
421
  let sseFailed = false;
422
+ let previousFocus = null;
423
+ const token = new URLSearchParams(window.location.search).get('token');
424
+ const basePath = window.location.pathname.replace(/\\/index\\.html$/, '').replace(/\\/+$/, '');
425
+ function apiURL(path) {
426
+ const url = new URL(basePath + '/' + path, window.location.origin);
427
+ if (token) url.searchParams.set('token', token);
428
+ return url.toString();
429
+ }
421
430
 
422
431
  function showToast(msg, duration = 3000) {
423
432
  const t = document.getElementById('toast');
@@ -524,7 +533,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
524
533
  }
525
534
 
526
535
  window.fetchMetricsSnapshot = function() {
527
- fetch('api/metrics')
536
+ fetch(apiURL('api/metrics'))
537
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
528
538
  .then(r => r.json())
529
539
  .then(data => updateUI(data))
530
540
  .catch(err => showToast('Failed to fetch snapshot: ' + err.message));
@@ -535,7 +545,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
535
545
  fallbackPolling();
536
546
  return;
537
547
  }
538
- const sse = new EventSource('api/stream');
548
+ const sse = new EventSource(apiURL('api/stream'));
539
549
  sse.onmessage = function(e) {
540
550
  try {
541
551
  const data = JSON.parse(e.data);
@@ -560,22 +570,37 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
560
570
 
561
571
  window.openInvalidateModal = function() {
562
572
  if (isReadOnly) return;
573
+ previousFocus = document.activeElement;
563
574
  document.getElementById('invalidate-modal').classList.add('active');
564
575
  document.getElementById('tag-input').focus();
565
576
  };
566
577
  window.openClearModal = function() {
567
578
  if (isReadOnly) return;
579
+ previousFocus = document.activeElement;
568
580
  document.getElementById('clear-modal').classList.add('active');
581
+ document.querySelector('#clear-modal button').focus();
569
582
  };
570
583
  window.closeModals = function() {
571
584
  document.getElementById('invalidate-modal').classList.remove('active');
572
585
  document.getElementById('clear-modal').classList.remove('active');
586
+ if (previousFocus) previousFocus.focus();
573
587
  };
588
+ document.addEventListener('keydown', function(event) {
589
+ const modal = document.querySelector('.dialog-overlay.active');
590
+ if (!modal) return;
591
+ if (event.key === 'Escape') { event.preventDefault(); closeModals(); }
592
+ if (event.key === 'Tab') {
593
+ const controls = modal.querySelectorAll('button, input, select, [tabindex="0"]');
594
+ const first = controls[0], last = controls[controls.length - 1];
595
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
596
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
597
+ }
598
+ });
574
599
 
575
600
  window.submitTagInvalidation = function() {
576
601
  const tag = document.getElementById('tag-input').value.trim();
577
602
  if (!tag) return;
578
- fetch('api/actions/invalidate-tag', {
603
+ fetch(apiURL('api/actions/invalidate-tag'), {
579
604
  method: 'POST',
580
605
  headers: {
581
606
  'Content-Type': 'application/json',
@@ -598,7 +623,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
598
623
  };
599
624
 
600
625
  window.submitClear = function() {
601
- fetch('api/actions/clear', {
626
+ fetch(apiURL('api/actions/clear'), {
602
627
  method: 'POST',
603
628
  headers: {
604
629
  'Content-Type': 'application/json',
@@ -638,7 +663,7 @@ var SECURITY_HEADERS = {
638
663
  "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
639
664
  "X-Frame-Options": "DENY",
640
665
  "X-Content-Type-Options": "nosniff",
641
- "Referrer-Policy": "same-origin",
666
+ "Referrer-Policy": "no-referrer",
642
667
  "Cache-Control": "no-store, no-cache, must-revalidate"
643
668
  };
644
669
  function resolveInstanceId(custom) {
@@ -657,7 +682,7 @@ function buildMetricsPayload(options) {
657
682
  title: options.title || "TriCache Observability",
658
683
  instanceId: resolveInstanceId(options.instanceId),
659
684
  nodeVersion: process.version,
660
- readOnly: !!options.readOnly,
685
+ readOnly: options.readOnly ?? true,
661
686
  peerInstances: options.peerInstances || [],
662
687
  metrics: {
663
688
  ...metrics,
@@ -763,6 +788,7 @@ async function handleDashboardRequest(req, options) {
763
788
  }
764
789
  ticker = setInterval(() => {
765
790
  try {
791
+ if ((controller.desiredSize ?? 0) <= 0) return;
766
792
  const data = buildMetricsPayload(options);
767
793
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
768
794
 
@@ -785,7 +811,7 @@ async function handleDashboardRequest(req, options) {
785
811
  controller.close();
786
812
  } catch {
787
813
  }
788
- });
814
+ }, { once: true });
789
815
  }
790
816
  },
791
817
  cancel() {
@@ -817,7 +843,7 @@ async function handleDashboardRequest(req, options) {
817
843
  }
818
844
  if (pathname === "/api/actions/invalidate-tag" && req.method === "POST") {
819
845
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
820
- if (options.readOnly) {
846
+ if (options.readOnly ?? true) {
821
847
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
822
848
  status: 403,
823
849
  headers: { "Content-Type": "application/json" }
@@ -830,7 +856,28 @@ async function handleDashboardRequest(req, options) {
830
856
  });
831
857
  }
832
858
  try {
833
- const body = await req.json();
859
+ const maxBytes = options.maxRequestBytes ?? 65536;
860
+ if (Number(req.headers.get("content-length")) > maxBytes) return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
861
+ const reader = req.body?.getReader();
862
+ const chunks = [];
863
+ let bytes = 0;
864
+ if (reader) {
865
+ try {
866
+ while (true) {
867
+ const chunk = await reader.read();
868
+ if (chunk.done) break;
869
+ bytes += chunk.value.length;
870
+ if (bytes > maxBytes) {
871
+ await reader.cancel();
872
+ return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
873
+ }
874
+ chunks.push(chunk.value);
875
+ }
876
+ } finally {
877
+ reader.releaseLock();
878
+ }
879
+ }
880
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
834
881
  const tag = body?.tag?.trim();
835
882
  if (!tag) {
836
883
  return new Response(JSON.stringify({ ok: false, error: "Tag parameter is required" }), {
@@ -869,7 +916,7 @@ async function handleDashboardRequest(req, options) {
869
916
  }
870
917
  if (pathname === "/api/actions/clear" && req.method === "POST") {
871
918
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
872
- if (options.readOnly) {
919
+ if (options.readOnly ?? true) {
873
920
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
874
921
  status: 403,
875
922
  headers: { "Content-Type": "application/json" }
@@ -938,7 +985,7 @@ async function handleDashboardRequest(req, options) {
938
985
  }
939
986
 
940
987
  // src/dashboard/index.ts
941
- async function nodeToWebRequest(req) {
988
+ async function nodeToWebRequest(req, res, maxBytes) {
942
989
  const protocol = req.socket.encrypted ? "https" : "http";
943
990
  const host = req.headers.host || "localhost";
944
991
  const url = new URL(req.url || "/", `${protocol}://${host}`);
@@ -954,19 +1001,23 @@ async function nodeToWebRequest(req) {
954
1001
  let body = null;
955
1002
  if (req.method !== "GET" && req.method !== "HEAD") {
956
1003
  const chunks = [];
957
- for await (const chunk of req) {
958
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
1004
+ let size = 0;
1005
+ const parsed = req.body;
1006
+ if (req.readableEnded && parsed !== void 0) chunks.push(Buffer.from(JSON.stringify(parsed)));
1007
+ else for await (const chunk of req) {
1008
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
1009
+ size += bytes.length;
1010
+ if (size > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
1011
+ chunks.push(bytes);
959
1012
  }
960
1013
  if (chunks.length > 0) {
961
1014
  body = Buffer.concat(chunks);
1015
+ if (body.length > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
962
1016
  }
963
1017
  }
964
1018
  const controller = new AbortController();
965
- req.on("close", () => {
966
- if (req.destroyed || !req.complete) {
967
- controller.abort();
968
- }
969
- });
1019
+ req.once("aborted", () => controller.abort());
1020
+ res.once("close", () => controller.abort());
970
1021
  const init = {
971
1022
  method: req.method,
972
1023
  headers,
@@ -988,24 +1039,54 @@ async function pipeWebResponseToNode(webRes, nodeRes) {
988
1039
  return;
989
1040
  }
990
1041
  const reader = webRes.body.getReader();
1042
+ const cancel = () => {
1043
+ void reader.cancel().catch(() => {
1044
+ });
1045
+ };
1046
+ nodeRes.once("close", cancel);
991
1047
  try {
992
1048
  while (true) {
993
1049
  const { done, value } = await reader.read();
994
1050
  if (done) break;
995
- nodeRes.write(value);
1051
+ if (nodeRes.destroyed) break;
1052
+ if (!nodeRes.write(value)) await new Promise((resolve, reject) => {
1053
+ const cleanup = () => {
1054
+ nodeRes.off("drain", onDrain);
1055
+ nodeRes.off("close", onClose);
1056
+ };
1057
+ const onDrain = () => {
1058
+ cleanup();
1059
+ resolve();
1060
+ };
1061
+ const onClose = () => {
1062
+ cleanup();
1063
+ reject(new Error("Dashboard response closed"));
1064
+ };
1065
+ nodeRes.once("drain", onDrain);
1066
+ nodeRes.once("close", onClose);
1067
+ });
996
1068
  }
997
1069
  } finally {
998
- nodeRes.end();
1070
+ nodeRes.off("close", cancel);
1071
+ await reader.cancel().catch(() => {
1072
+ });
1073
+ reader.releaseLock();
1074
+ if (!nodeRes.destroyed) nodeRes.end();
999
1075
  }
1000
1076
  }
1001
1077
  function tricacheDashboard(options) {
1002
1078
  return async (req, res, next) => {
1003
1079
  try {
1004
- const webReq = await nodeToWebRequest(req);
1080
+ const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
1005
1081
  const webRes = await handleDashboardRequest(webReq, options);
1006
1082
  await pipeWebResponseToNode(webRes, res);
1007
1083
  } catch (err) {
1008
- if (typeof next === "function") {
1084
+ if (res.destroyed) return;
1085
+ if (err.status === 413) {
1086
+ res.statusCode = 413;
1087
+ res.setHeader("Connection", "close");
1088
+ res.end(JSON.stringify({ error: "Request body too large" }));
1089
+ } else if (typeof next === "function") {
1009
1090
  next(err);
1010
1091
  } else {
1011
1092
  res.statusCode = 500;
@@ -1024,7 +1105,7 @@ function createNextDashboardHandlers(options) {
1024
1105
  };
1025
1106
  }
1026
1107
  async function startDashboardServer(options) {
1027
- const port = options.port || 9090;
1108
+ const port = options.port ?? 9090;
1028
1109
  const host = options.host || "127.0.0.1";
1029
1110
  const middleware = tricacheDashboard(options);
1030
1111
  const server = import_node_http.default.createServer((req, res) => {
@@ -1048,6 +1129,7 @@ async function startDashboardServer(options) {
1048
1129
  host,
1049
1130
  close: () => new Promise((resolve, reject) => {
1050
1131
  server.close((err) => err ? reject(err) : resolve());
1132
+ server.closeAllConnections();
1051
1133
  })
1052
1134
  };
1053
1135
  }