tricache 1.0.0 → 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.
- package/README.md +36 -28
- package/dist/{cache-service-pJ-nFcVj.d.ts → cache-service-B108FzER.d.ts} +63 -3
- package/dist/cache-service-CWI4jkS7.d.cts +963 -0
- package/dist/{cache-service-26GCO3UU.js → cache-service-GYPZFB7O.js} +2 -2
- package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
- package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
- package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
- package/dist/chunk-OYDU3SMI.js +89 -0
- package/dist/{chunk-VXFTFZ5N.js → chunk-VNRDL5RA.js} +117 -138
- package/dist/{chunk-7SZSQS55.js → chunk-WYF7NOAT.js} +1831 -759
- package/dist/cli.cjs +1757 -777
- package/dist/cli.d.cts +12 -0
- package/dist/cli.js +27 -6
- package/dist/dashboard/index.cjs +111 -29
- package/dist/dashboard/index.d.cts +185 -0
- package/dist/dashboard/index.d.ts +5 -3
- package/dist/dashboard/index.js +1 -1
- package/dist/drizzle/index.cjs +1757 -773
- package/dist/drizzle/index.d.cts +46 -0
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +280 -153
- package/dist/edge/index.d.cts +127 -0
- package/dist/edge/index.d.ts +3 -3
- package/dist/edge/index.js +254 -147
- package/dist/hono/index.cjs +1805 -793
- package/dist/hono/index.d.cts +93 -0
- package/dist/hono/index.d.ts +7 -5
- package/dist/hono/index.js +16 -9
- package/dist/{hono-DuNvciyq.d.ts → hono-3rDMYVtY.d.ts} +23 -3
- package/dist/hono-C886ok3X.d.cts +391 -0
- package/dist/http/index.cjs +1946 -842
- package/dist/http/index.d.cts +103 -0
- package/dist/http/index.d.ts +13 -5
- package/dist/http/index.js +137 -57
- package/dist/index.cjs +2073 -937
- package/dist/index.d.cts +1006 -0
- package/dist/index.d.ts +40 -8
- package/dist/index.js +8 -8
- package/dist/murmur3-CMGw9PbV.d.cts +98 -0
- package/dist/nestjs/index.cjs +1849 -806
- package/dist/nestjs/index.d.cts +285 -0
- package/dist/nestjs/index.d.ts +103 -30
- package/dist/nestjs/index.js +115 -32
- package/dist/next/index.cjs +1913 -887
- package/dist/next/index.d.cts +232 -0
- package/dist/next/index.d.ts +33 -11
- package/dist/next/index.js +174 -107
- package/dist/prisma/index.cjs +11 -1
- package/dist/prisma/index.d.cts +62 -0
- package/dist/prisma/index.d.ts +2 -2
- package/dist/prisma/index.js +11 -1
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/{types-5HXqBfAf.d.ts → types-BA4pz1A0.d.cts} +26 -9
- package/dist/types-BA4pz1A0.d.ts +1519 -0
- package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
- package/dist/utils-Bvzn-rKS.d.ts +29 -0
- package/package.json +96 -36
- package/src/adapters/auto-pipeliner.ts +107 -24
- package/src/adapters/node-redis.ts +123 -25
- package/src/cache-service.ts +1238 -659
- package/src/cli.ts +24 -6
- package/src/cross-region.ts +21 -3
- package/src/dashboard/handler.ts +26 -6
- package/src/dashboard/html.ts +35 -10
- package/src/dashboard/index.ts +35 -13
- package/src/dashboard/types.ts +3 -1
- package/src/disk-tier.ts +171 -65
- package/src/edge/cache.ts +202 -129
- package/src/edge/hono.ts +23 -6
- package/src/edge/types.ts +2 -0
- package/src/hono/index.ts +19 -9
- package/src/http/express.ts +110 -26
- package/src/http/fastify.ts +38 -28
- package/src/http/utils.ts +54 -20
- package/src/ipc-telemetry.ts +35 -9
- package/src/nestjs/decorators.ts +1 -1
- package/src/nestjs/index.ts +2 -0
- package/src/nestjs/keyv-adapter.ts +68 -0
- package/src/nestjs/tricache.module.ts +13 -11
- package/src/nestjs/tricache.store.ts +51 -20
- package/src/nestjs/types.ts +29 -15
- package/src/next/cache-handler.ts +132 -57
- package/src/next/index.ts +1 -0
- package/src/next/isr-handler.ts +1 -4
- package/src/next/types.ts +21 -0
- package/src/prisma/index.ts +12 -1
- package/src/smart-memory-cache.ts +65 -27
- package/src/types.ts +27 -2
- package/src/utils/cgroup.ts +12 -0
- package/src/utils/deadline.ts +14 -0
- package/src/utils/diagnostics.ts +27 -0
- package/src/utils/redis-slot.ts +13 -0
- package/src/wasm/bloom-filter-wasm.ts +9 -4
- package/src/worker-pool.ts +17 -8
- package/src/wtiny-lfu.ts +20 -6
- package/dist/chunk-BQRURGGD.js +0 -60
|
@@ -2,9 +2,9 @@ import {
|
|
|
2
2
|
CacheService,
|
|
3
3
|
ProcessTerminationBus,
|
|
4
4
|
deepMergeOptions
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-WYF7NOAT.js";
|
|
6
6
|
import "./chunk-UBWLPKTI.js";
|
|
7
|
-
import "./chunk-
|
|
7
|
+
import "./chunk-H4GFLQ26.js";
|
|
8
8
|
export {
|
|
9
9
|
CacheService,
|
|
10
10
|
ProcessTerminationBus,
|
|
@@ -66,7 +66,6 @@ function honoEdgeCache(options = {}) {
|
|
|
66
66
|
cache,
|
|
67
67
|
etag = true,
|
|
68
68
|
ttl = 300,
|
|
69
|
-
swr,
|
|
70
69
|
tags,
|
|
71
70
|
skipCache,
|
|
72
71
|
keyGenerator,
|
|
@@ -80,6 +79,8 @@ function honoEdgeCache(options = {}) {
|
|
|
80
79
|
if (skipCache && skipCache(c)) {
|
|
81
80
|
return await next();
|
|
82
81
|
}
|
|
82
|
+
const credentials = ["authorization", "cookie", "x-api-key", "x-auth-token"].filter((name) => c.req.header?.(name));
|
|
83
|
+
if (c.req.header?.("range") || credentials.length > 0 && (!options.cacheAuthenticated || !keyGenerator && !credentials.every((name) => headerWhitelist?.some((header) => header.toLowerCase() === name)))) return await next();
|
|
83
84
|
const cc = c.req.header?.("cache-control") || c.req.header?.("Cache-Control");
|
|
84
85
|
if (typeof cc === "string") {
|
|
85
86
|
const lower = cc.toLowerCase();
|
|
@@ -90,7 +91,12 @@ function honoEdgeCache(options = {}) {
|
|
|
90
91
|
if (!cache) {
|
|
91
92
|
return await next();
|
|
92
93
|
}
|
|
93
|
-
|
|
94
|
+
let key = buildEdgeDeterministicKey(c, { keyGenerator, headerWhitelist });
|
|
95
|
+
if (credentials.length) {
|
|
96
|
+
if (!globalThis.crypto?.subtle) return await next();
|
|
97
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
|
|
98
|
+
key = `edge:http:identity:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
99
|
+
}
|
|
94
100
|
const ifNoneMatch = c.req.header?.("if-none-match") || c.req.header?.("If-None-Match");
|
|
95
101
|
const resolvedTags = typeof tags === "function" ? tags(c) : tags;
|
|
96
102
|
let ranNext = false;
|
|
@@ -113,6 +119,10 @@ function honoEdgeCache(options = {}) {
|
|
|
113
119
|
});
|
|
114
120
|
}
|
|
115
121
|
const cc2 = res.headers?.get?.("cache-control");
|
|
122
|
+
const vary = String(res.headers?.get?.("vary") ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
|
|
123
|
+
if (res.headers?.get?.("set-cookie") || vary.includes("*") || !keyGenerator && vary.some((name) => !headerWhitelist?.some((header) => header.toLowerCase() === name))) {
|
|
124
|
+
throw new NonCacheableEdgeResponseError({ body: "", contentType, status: 0 });
|
|
125
|
+
}
|
|
116
126
|
if (cc2) {
|
|
117
127
|
const lowerCc = cc2.toLowerCase();
|
|
118
128
|
if (lowerCc.includes("no-store") || lowerCc.includes("no-cache") || lowerCc.includes("private")) {
|
|
@@ -154,9 +164,9 @@ function honoEdgeCache(options = {}) {
|
|
|
154
164
|
},
|
|
155
165
|
ttl,
|
|
156
166
|
{
|
|
157
|
-
swr,
|
|
167
|
+
swr: 0,
|
|
158
168
|
tags: resolvedTags,
|
|
159
|
-
ctx: c
|
|
169
|
+
ctx: readExecutionContext(c)
|
|
160
170
|
}
|
|
161
171
|
);
|
|
162
172
|
if (!cached) {
|
|
@@ -183,6 +193,13 @@ function honoEdgeCache(options = {}) {
|
|
|
183
193
|
}
|
|
184
194
|
};
|
|
185
195
|
}
|
|
196
|
+
function readExecutionContext(c) {
|
|
197
|
+
try {
|
|
198
|
+
return c.executionCtx;
|
|
199
|
+
} catch {
|
|
200
|
+
return void 0;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
186
203
|
function applyEdgeResponse(c, body, status, headers) {
|
|
187
204
|
const response = c.body(body, status, headers);
|
|
188
205
|
c.res = response;
|
|
@@ -37,9 +37,12 @@ function uint8ArrayToUtf8(bytes) {
|
|
|
37
37
|
var BLOOM_WASM_BASE64 = "AGFzbQEAAAABIwdgAn9/AX9gAX8AYAF/AX9gA39/fwF/YAJ/fwBgAABgAAF/AwoJAAABAgMEAAUGBQMBAAEGDQJ/AEGgjQYLfwBBBwsHMwUGbWVtb3J5AgADYWRkAAUMbWlnaHRDb250YWluAAYFcmVzZXQABwljb3VudEJpdHMACAqtAwk/AQJ/QcW78oh4IQIgACABaiEDAkADQCAAIANPDQEgAiAALQAAcyECIAJBk4OACGwhAiAAQQFqIQAMAAsLIAILOAECf0GFKiECIAAgAWohAwJAA0AgACADTw0BIAJBBXQgAmogAC0AAGohAiAAQQFqIQAMAAsLIAILHgEBfyAAQQN2IQEgASABLQAAQQEgAEEHcXRyOgAACxYAIABBA3YtAABBASAAQQdxdHFBAEcLDQAgACACIAFsaiMAcAs4AQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEAIgBEEBaiEEDAALCwtBAQN/IAAgARAAIQIgACABEAEhA0EAIQQCQANAIAQjAU8NASACIAMgBBAEEANFBEBBAA8LIARBAWohBAwACwtBAQsnAQF/QQAhAAJAA0AgAEHU4QBPDQEgAEEANgIAIABBBGohAAwACwsLSwEDf0EAIQBBACEBAkADQCAAQdThAE8NASAALQAAIQICQANAIAJFDQEgAUEBaiEBIAIgAkEBa3EhAgwACwsgAEEBaiEADAALCyABCw==";
|
|
38
38
|
var KEY_STAGING_OFFSET = 2e4;
|
|
39
39
|
var MAX_KEY_BYTES = 512;
|
|
40
|
-
var
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
var bloomWasmModule;
|
|
41
|
+
function getBloomWasmModule() {
|
|
42
|
+
return bloomWasmModule ??= new WebAssembly.Module(
|
|
43
|
+
base64ToUint8Array(BLOOM_WASM_BASE64)
|
|
44
|
+
);
|
|
45
|
+
}
|
|
43
46
|
var WasmBloomFilter = class {
|
|
44
47
|
exports;
|
|
45
48
|
mem;
|
|
@@ -51,7 +54,7 @@ var WasmBloomFilter = class {
|
|
|
51
54
|
/** Tracks total add() calls so we know when phantom bits have saturated the filter. */
|
|
52
55
|
_insertionCount = 0;
|
|
53
56
|
constructor() {
|
|
54
|
-
const instance = new WebAssembly.Instance(
|
|
57
|
+
const instance = new WebAssembly.Instance(getBloomWasmModule(), {});
|
|
55
58
|
this.exports = instance.exports;
|
|
56
59
|
this.mem = new Uint8Array(this.exports.memory.buffer);
|
|
57
60
|
this.stagingTarget = new Uint8Array(this.exports.memory.buffer, KEY_STAGING_OFFSET, MAX_KEY_BYTES);
|
|
@@ -287,7 +287,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
287
287
|
<span class="pulse-dot"></span>
|
|
288
288
|
<span id="stream-text">SSE Live</span>
|
|
289
289
|
</div>
|
|
290
|
-
<select id="peer-select" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
|
|
290
|
+
<select id="peer-select" aria-label="Switch cache instance" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
|
|
291
291
|
<option value="">Switch Pod...</option>
|
|
292
292
|
</select>
|
|
293
293
|
</div>
|
|
@@ -347,9 +347,10 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
347
347
|
|
|
348
348
|
<!-- Invalidate Modal -->
|
|
349
349
|
<div class="dialog-overlay" id="invalidate-modal">
|
|
350
|
-
<div class="dialog">
|
|
351
|
-
<h3>Invalidate Tag</h3>
|
|
350
|
+
<div class="dialog" role="dialog" aria-modal="true" aria-labelledby="invalidate-title">
|
|
351
|
+
<h3 id="invalidate-title">Invalidate Tag</h3>
|
|
352
352
|
<p>Increments generational tag version across local tiers and broadcast backplane.</p>
|
|
353
|
+
<label for="tag-input">Tag name or pattern</label>
|
|
353
354
|
<input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
|
|
354
355
|
<div class="dialog-actions">
|
|
355
356
|
<button class="btn" onclick="closeModals()">Cancel</button>
|
|
@@ -360,8 +361,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
360
361
|
|
|
361
362
|
<!-- Clear Modal -->
|
|
362
363
|
<div class="dialog-overlay" id="clear-modal">
|
|
363
|
-
<div class="dialog">
|
|
364
|
-
<h3>Clear Cache</h3>
|
|
364
|
+
<div class="dialog" role="dialog" aria-modal="true" aria-labelledby="clear-title">
|
|
365
|
+
<h3 id="clear-title">Clear Cache</h3>
|
|
365
366
|
<p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
|
|
366
367
|
<div class="dialog-actions">
|
|
367
368
|
<button class="btn" onclick="closeModals()">Cancel</button>
|
|
@@ -370,12 +371,20 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
370
371
|
</div>
|
|
371
372
|
</div>
|
|
372
373
|
|
|
373
|
-
<div id="toast"></div>
|
|
374
|
+
<div id="toast" role="status" aria-live="polite"></div>
|
|
374
375
|
|
|
375
376
|
<script>
|
|
376
377
|
(function() {
|
|
377
378
|
let isReadOnly = false;
|
|
378
379
|
let sseFailed = false;
|
|
380
|
+
let previousFocus = null;
|
|
381
|
+
const token = new URLSearchParams(window.location.search).get('token');
|
|
382
|
+
const basePath = window.location.pathname.replace(/\\/index\\.html$/, '').replace(/\\/+$/, '');
|
|
383
|
+
function apiURL(path) {
|
|
384
|
+
const url = new URL(basePath + '/' + path, window.location.origin);
|
|
385
|
+
if (token) url.searchParams.set('token', token);
|
|
386
|
+
return url.toString();
|
|
387
|
+
}
|
|
379
388
|
|
|
380
389
|
function showToast(msg, duration = 3000) {
|
|
381
390
|
const t = document.getElementById('toast');
|
|
@@ -482,7 +491,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
482
491
|
}
|
|
483
492
|
|
|
484
493
|
window.fetchMetricsSnapshot = function() {
|
|
485
|
-
fetch('api/metrics')
|
|
494
|
+
fetch(apiURL('api/metrics'))
|
|
495
|
+
.then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
|
|
486
496
|
.then(r => r.json())
|
|
487
497
|
.then(data => updateUI(data))
|
|
488
498
|
.catch(err => showToast('Failed to fetch snapshot: ' + err.message));
|
|
@@ -493,7 +503,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
493
503
|
fallbackPolling();
|
|
494
504
|
return;
|
|
495
505
|
}
|
|
496
|
-
const sse = new EventSource('api/stream');
|
|
506
|
+
const sse = new EventSource(apiURL('api/stream'));
|
|
497
507
|
sse.onmessage = function(e) {
|
|
498
508
|
try {
|
|
499
509
|
const data = JSON.parse(e.data);
|
|
@@ -518,22 +528,37 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
518
528
|
|
|
519
529
|
window.openInvalidateModal = function() {
|
|
520
530
|
if (isReadOnly) return;
|
|
531
|
+
previousFocus = document.activeElement;
|
|
521
532
|
document.getElementById('invalidate-modal').classList.add('active');
|
|
522
533
|
document.getElementById('tag-input').focus();
|
|
523
534
|
};
|
|
524
535
|
window.openClearModal = function() {
|
|
525
536
|
if (isReadOnly) return;
|
|
537
|
+
previousFocus = document.activeElement;
|
|
526
538
|
document.getElementById('clear-modal').classList.add('active');
|
|
539
|
+
document.querySelector('#clear-modal button').focus();
|
|
527
540
|
};
|
|
528
541
|
window.closeModals = function() {
|
|
529
542
|
document.getElementById('invalidate-modal').classList.remove('active');
|
|
530
543
|
document.getElementById('clear-modal').classList.remove('active');
|
|
544
|
+
if (previousFocus) previousFocus.focus();
|
|
531
545
|
};
|
|
546
|
+
document.addEventListener('keydown', function(event) {
|
|
547
|
+
const modal = document.querySelector('.dialog-overlay.active');
|
|
548
|
+
if (!modal) return;
|
|
549
|
+
if (event.key === 'Escape') { event.preventDefault(); closeModals(); }
|
|
550
|
+
if (event.key === 'Tab') {
|
|
551
|
+
const controls = modal.querySelectorAll('button, input, select, [tabindex="0"]');
|
|
552
|
+
const first = controls[0], last = controls[controls.length - 1];
|
|
553
|
+
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
|
|
554
|
+
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
|
|
555
|
+
}
|
|
556
|
+
});
|
|
532
557
|
|
|
533
558
|
window.submitTagInvalidation = function() {
|
|
534
559
|
const tag = document.getElementById('tag-input').value.trim();
|
|
535
560
|
if (!tag) return;
|
|
536
|
-
fetch('api/actions/invalidate-tag', {
|
|
561
|
+
fetch(apiURL('api/actions/invalidate-tag'), {
|
|
537
562
|
method: 'POST',
|
|
538
563
|
headers: {
|
|
539
564
|
'Content-Type': 'application/json',
|
|
@@ -556,7 +581,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
|
|
|
556
581
|
};
|
|
557
582
|
|
|
558
583
|
window.submitClear = function() {
|
|
559
|
-
fetch('api/actions/clear', {
|
|
584
|
+
fetch(apiURL('api/actions/clear'), {
|
|
560
585
|
method: 'POST',
|
|
561
586
|
headers: {
|
|
562
587
|
'Content-Type': 'application/json',
|
|
@@ -596,7 +621,7 @@ var SECURITY_HEADERS = {
|
|
|
596
621
|
"Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
|
|
597
622
|
"X-Frame-Options": "DENY",
|
|
598
623
|
"X-Content-Type-Options": "nosniff",
|
|
599
|
-
"Referrer-Policy": "
|
|
624
|
+
"Referrer-Policy": "no-referrer",
|
|
600
625
|
"Cache-Control": "no-store, no-cache, must-revalidate"
|
|
601
626
|
};
|
|
602
627
|
function resolveInstanceId(custom) {
|
|
@@ -615,7 +640,7 @@ function buildMetricsPayload(options) {
|
|
|
615
640
|
title: options.title || "TriCache Observability",
|
|
616
641
|
instanceId: resolveInstanceId(options.instanceId),
|
|
617
642
|
nodeVersion: process.version,
|
|
618
|
-
readOnly:
|
|
643
|
+
readOnly: options.readOnly ?? true,
|
|
619
644
|
peerInstances: options.peerInstances || [],
|
|
620
645
|
metrics: {
|
|
621
646
|
...metrics,
|
|
@@ -721,6 +746,7 @@ async function handleDashboardRequest(req, options) {
|
|
|
721
746
|
}
|
|
722
747
|
ticker = setInterval(() => {
|
|
723
748
|
try {
|
|
749
|
+
if ((controller.desiredSize ?? 0) <= 0) return;
|
|
724
750
|
const data = buildMetricsPayload(options);
|
|
725
751
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
|
|
726
752
|
|
|
@@ -743,7 +769,7 @@ async function handleDashboardRequest(req, options) {
|
|
|
743
769
|
controller.close();
|
|
744
770
|
} catch {
|
|
745
771
|
}
|
|
746
|
-
});
|
|
772
|
+
}, { once: true });
|
|
747
773
|
}
|
|
748
774
|
},
|
|
749
775
|
cancel() {
|
|
@@ -775,7 +801,7 @@ async function handleDashboardRequest(req, options) {
|
|
|
775
801
|
}
|
|
776
802
|
if (pathname === "/api/actions/invalidate-tag" && req.method === "POST") {
|
|
777
803
|
const clientIp = req.headers.get("x-forwarded-for") || void 0;
|
|
778
|
-
if (options.readOnly) {
|
|
804
|
+
if (options.readOnly ?? true) {
|
|
779
805
|
return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
|
|
780
806
|
status: 403,
|
|
781
807
|
headers: { "Content-Type": "application/json" }
|
|
@@ -788,7 +814,28 @@ async function handleDashboardRequest(req, options) {
|
|
|
788
814
|
});
|
|
789
815
|
}
|
|
790
816
|
try {
|
|
791
|
-
const
|
|
817
|
+
const maxBytes = options.maxRequestBytes ?? 65536;
|
|
818
|
+
if (Number(req.headers.get("content-length")) > maxBytes) return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
|
|
819
|
+
const reader = req.body?.getReader();
|
|
820
|
+
const chunks = [];
|
|
821
|
+
let bytes = 0;
|
|
822
|
+
if (reader) {
|
|
823
|
+
try {
|
|
824
|
+
while (true) {
|
|
825
|
+
const chunk = await reader.read();
|
|
826
|
+
if (chunk.done) break;
|
|
827
|
+
bytes += chunk.value.length;
|
|
828
|
+
if (bytes > maxBytes) {
|
|
829
|
+
await reader.cancel();
|
|
830
|
+
return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
|
|
831
|
+
}
|
|
832
|
+
chunks.push(chunk.value);
|
|
833
|
+
}
|
|
834
|
+
} finally {
|
|
835
|
+
reader.releaseLock();
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
792
839
|
const tag = body?.tag?.trim();
|
|
793
840
|
if (!tag) {
|
|
794
841
|
return new Response(JSON.stringify({ ok: false, error: "Tag parameter is required" }), {
|
|
@@ -827,7 +874,7 @@ async function handleDashboardRequest(req, options) {
|
|
|
827
874
|
}
|
|
828
875
|
if (pathname === "/api/actions/clear" && req.method === "POST") {
|
|
829
876
|
const clientIp = req.headers.get("x-forwarded-for") || void 0;
|
|
830
|
-
if (options.readOnly) {
|
|
877
|
+
if (options.readOnly ?? true) {
|
|
831
878
|
return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
|
|
832
879
|
status: 403,
|
|
833
880
|
headers: { "Content-Type": "application/json" }
|
|
@@ -896,7 +943,7 @@ async function handleDashboardRequest(req, options) {
|
|
|
896
943
|
}
|
|
897
944
|
|
|
898
945
|
// src/dashboard/index.ts
|
|
899
|
-
async function nodeToWebRequest(req) {
|
|
946
|
+
async function nodeToWebRequest(req, res, maxBytes) {
|
|
900
947
|
const protocol = req.socket.encrypted ? "https" : "http";
|
|
901
948
|
const host = req.headers.host || "localhost";
|
|
902
949
|
const url = new URL(req.url || "/", `${protocol}://${host}`);
|
|
@@ -912,19 +959,23 @@ async function nodeToWebRequest(req) {
|
|
|
912
959
|
let body = null;
|
|
913
960
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
914
961
|
const chunks = [];
|
|
915
|
-
|
|
916
|
-
|
|
962
|
+
let size = 0;
|
|
963
|
+
const parsed = req.body;
|
|
964
|
+
if (req.readableEnded && parsed !== void 0) chunks.push(Buffer.from(JSON.stringify(parsed)));
|
|
965
|
+
else for await (const chunk of req) {
|
|
966
|
+
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
967
|
+
size += bytes.length;
|
|
968
|
+
if (size > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
|
|
969
|
+
chunks.push(bytes);
|
|
917
970
|
}
|
|
918
971
|
if (chunks.length > 0) {
|
|
919
972
|
body = Buffer.concat(chunks);
|
|
973
|
+
if (body.length > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
|
|
920
974
|
}
|
|
921
975
|
}
|
|
922
976
|
const controller = new AbortController();
|
|
923
|
-
req.
|
|
924
|
-
|
|
925
|
-
controller.abort();
|
|
926
|
-
}
|
|
927
|
-
});
|
|
977
|
+
req.once("aborted", () => controller.abort());
|
|
978
|
+
res.once("close", () => controller.abort());
|
|
928
979
|
const init = {
|
|
929
980
|
method: req.method,
|
|
930
981
|
headers,
|
|
@@ -946,24 +997,54 @@ async function pipeWebResponseToNode(webRes, nodeRes) {
|
|
|
946
997
|
return;
|
|
947
998
|
}
|
|
948
999
|
const reader = webRes.body.getReader();
|
|
1000
|
+
const cancel = () => {
|
|
1001
|
+
void reader.cancel().catch(() => {
|
|
1002
|
+
});
|
|
1003
|
+
};
|
|
1004
|
+
nodeRes.once("close", cancel);
|
|
949
1005
|
try {
|
|
950
1006
|
while (true) {
|
|
951
1007
|
const { done, value } = await reader.read();
|
|
952
1008
|
if (done) break;
|
|
953
|
-
nodeRes.
|
|
1009
|
+
if (nodeRes.destroyed) break;
|
|
1010
|
+
if (!nodeRes.write(value)) await new Promise((resolve, reject) => {
|
|
1011
|
+
const cleanup = () => {
|
|
1012
|
+
nodeRes.off("drain", onDrain);
|
|
1013
|
+
nodeRes.off("close", onClose);
|
|
1014
|
+
};
|
|
1015
|
+
const onDrain = () => {
|
|
1016
|
+
cleanup();
|
|
1017
|
+
resolve();
|
|
1018
|
+
};
|
|
1019
|
+
const onClose = () => {
|
|
1020
|
+
cleanup();
|
|
1021
|
+
reject(new Error("Dashboard response closed"));
|
|
1022
|
+
};
|
|
1023
|
+
nodeRes.once("drain", onDrain);
|
|
1024
|
+
nodeRes.once("close", onClose);
|
|
1025
|
+
});
|
|
954
1026
|
}
|
|
955
1027
|
} finally {
|
|
956
|
-
nodeRes.
|
|
1028
|
+
nodeRes.off("close", cancel);
|
|
1029
|
+
await reader.cancel().catch(() => {
|
|
1030
|
+
});
|
|
1031
|
+
reader.releaseLock();
|
|
1032
|
+
if (!nodeRes.destroyed) nodeRes.end();
|
|
957
1033
|
}
|
|
958
1034
|
}
|
|
959
1035
|
function tricacheDashboard(options) {
|
|
960
1036
|
return async (req, res, next) => {
|
|
961
1037
|
try {
|
|
962
|
-
const webReq = await nodeToWebRequest(req);
|
|
1038
|
+
const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
|
|
963
1039
|
const webRes = await handleDashboardRequest(webReq, options);
|
|
964
1040
|
await pipeWebResponseToNode(webRes, res);
|
|
965
1041
|
} catch (err) {
|
|
966
|
-
if (
|
|
1042
|
+
if (res.destroyed) return;
|
|
1043
|
+
if (err.status === 413) {
|
|
1044
|
+
res.statusCode = 413;
|
|
1045
|
+
res.setHeader("Connection", "close");
|
|
1046
|
+
res.end(JSON.stringify({ error: "Request body too large" }));
|
|
1047
|
+
} else if (typeof next === "function") {
|
|
967
1048
|
next(err);
|
|
968
1049
|
} else {
|
|
969
1050
|
res.statusCode = 500;
|
|
@@ -982,7 +1063,7 @@ function createNextDashboardHandlers(options) {
|
|
|
982
1063
|
};
|
|
983
1064
|
}
|
|
984
1065
|
async function startDashboardServer(options) {
|
|
985
|
-
const port = options.port
|
|
1066
|
+
const port = options.port ?? 9090;
|
|
986
1067
|
const host = options.host || "127.0.0.1";
|
|
987
1068
|
const middleware = tricacheDashboard(options);
|
|
988
1069
|
const server = http.createServer((req, res) => {
|
|
@@ -1006,6 +1087,7 @@ async function startDashboardServer(options) {
|
|
|
1006
1087
|
host,
|
|
1007
1088
|
close: () => new Promise((resolve, reject) => {
|
|
1008
1089
|
server.close((err) => err ? reject(err) : resolve());
|
|
1090
|
+
server.closeAllConnections();
|
|
1009
1091
|
})
|
|
1010
1092
|
};
|
|
1011
1093
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// src/http/utils.ts
|
|
2
|
+
import crypto from "crypto";
|
|
3
|
+
function readHttpHeader(headers, name) {
|
|
4
|
+
if (!headers) return void 0;
|
|
5
|
+
if (typeof headers.get === "function") return headers.get(name);
|
|
6
|
+
const lower = name.toLowerCase();
|
|
7
|
+
return headers[lower] ?? headers[name] ?? Object.entries(headers).find(([key]) => key.toLowerCase() === lower)?.[1];
|
|
8
|
+
}
|
|
9
|
+
function hasCacheBypassDirective(value) {
|
|
10
|
+
if (value == null) return false;
|
|
11
|
+
return String(value).split(",").some((part) => /^(?:private|no-cache|no-store)(?:\s*=|\s*$)/i.test(part.trim()));
|
|
12
|
+
}
|
|
13
|
+
function isShareableHttpResponse(status, header, options = {}) {
|
|
14
|
+
if (status === 206 || hasCacheBypassDirective(header("cache-control")) || header("set-cookie")) return false;
|
|
15
|
+
if (String(header("content-type") ?? "").toLowerCase().includes("text/event-stream")) return false;
|
|
16
|
+
const vary = String(header("vary") ?? "").split(",").map((value) => value.trim().toLowerCase()).filter(Boolean);
|
|
17
|
+
const keyedHeaders = new Set(options.headerWhitelist?.map((name) => name.toLowerCase()));
|
|
18
|
+
return !vary.includes("*") && (Boolean(options.keyGenerator) || vary.every((name) => keyedHeaders.has(name)));
|
|
19
|
+
}
|
|
20
|
+
function isCacheableHttpResponse(status, header, options) {
|
|
21
|
+
return status >= 200 && status < 300 && isShareableHttpResponse(status, header, options);
|
|
22
|
+
}
|
|
23
|
+
function matchesETag(header, etag) {
|
|
24
|
+
if (header == null) return false;
|
|
25
|
+
const normalized = etag.replace(/^W\//, "");
|
|
26
|
+
return String(header).split(",").some((value) => value.trim() === "*" || value.trim().replace(/^W\//, "") === normalized);
|
|
27
|
+
}
|
|
28
|
+
function buildDeterministicKey(req, options) {
|
|
29
|
+
if (options?.keyGenerator) {
|
|
30
|
+
return options.keyGenerator(req);
|
|
31
|
+
}
|
|
32
|
+
const method = (req.method || "GET").toUpperCase();
|
|
33
|
+
const rawUrl = req.originalUrl || req.url || "/";
|
|
34
|
+
const qIdx = rawUrl.indexOf("?");
|
|
35
|
+
const path = qIdx >= 0 ? rawUrl.slice(0, qIdx) : rawUrl;
|
|
36
|
+
let queryString = "";
|
|
37
|
+
if (qIdx >= 0) {
|
|
38
|
+
const rawQuery = rawUrl.slice(qIdx + 1);
|
|
39
|
+
try {
|
|
40
|
+
const params = new URLSearchParams(rawQuery);
|
|
41
|
+
params.sort();
|
|
42
|
+
queryString = params.toString();
|
|
43
|
+
} catch {
|
|
44
|
+
queryString = rawQuery;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
let key = `http:${method}:${path}`;
|
|
48
|
+
if (queryString) {
|
|
49
|
+
key += `?${queryString}`;
|
|
50
|
+
}
|
|
51
|
+
if (options?.headerWhitelist && options.headerWhitelist.length > 0 && req.headers) {
|
|
52
|
+
const sortedHeaders = [...new Set(options.headerWhitelist.map((h) => h.toLowerCase()))].sort();
|
|
53
|
+
for (const h of sortedHeaders) {
|
|
54
|
+
const normalizedHeader = h.toLowerCase();
|
|
55
|
+
const val = readHttpHeader(req.headers, normalizedHeader);
|
|
56
|
+
if (val !== void 0 && val !== null && val !== "") {
|
|
57
|
+
const headerStr = Array.isArray(val) ? val.join(",") : String(val);
|
|
58
|
+
const identity = /authorization|cookie|token|api-key/.test(normalizedHeader) ? crypto.createHash("sha256").update(headerStr).digest("hex") : encodeURIComponent(headerStr);
|
|
59
|
+
key += `|h:${normalizedHeader}=${identity}`;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return key;
|
|
64
|
+
}
|
|
65
|
+
function shouldSkipCache(req, customSkip, options = {}) {
|
|
66
|
+
if (customSkip && customSkip(req)) return true;
|
|
67
|
+
if (hasCacheBypassDirective(readHttpHeader(req.headers, "cache-control")) || readHttpHeader(req.headers, "range")) return true;
|
|
68
|
+
const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"].filter((name) => readHttpHeader(req.headers, name));
|
|
69
|
+
if (sensitiveHeaders.length > 0) {
|
|
70
|
+
if (!options.cacheAuthenticated) return true;
|
|
71
|
+
const keyedHeaders = new Set(options.headerWhitelist?.map((name) => name.toLowerCase()));
|
|
72
|
+
if (!options.keyGenerator && !sensitiveHeaders.every((name) => keyedHeaders.has(name))) return true;
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
function generateETag(data) {
|
|
77
|
+
const bytes = Buffer.isBuffer(data) ? data : Buffer.from(typeof data === "string" ? data : JSON.stringify(data) ?? "", "utf8");
|
|
78
|
+
const hash = crypto.createHash("sha1").update(bytes).digest("hex").slice(0, 16);
|
|
79
|
+
return `W/"${bytes.length.toString(16)}-${hash}"`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export {
|
|
83
|
+
isShareableHttpResponse,
|
|
84
|
+
isCacheableHttpResponse,
|
|
85
|
+
matchesETag,
|
|
86
|
+
buildDeterministicKey,
|
|
87
|
+
shouldSkipCache,
|
|
88
|
+
generateETag
|
|
89
|
+
};
|