@krate/runtime 0.5.0-alpha.3 → 0.5.0-alpha.4

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.
@@ -6,7 +6,30 @@ import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import vm from "node:vm";
8
8
  import { pathToFileURL } from "node:url";
9
- import { renderToString } from "./server.js";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { timingSafeEqual } from "node:crypto";
11
+ import { jsx, renderToStringAsync } from "./server.js";
12
+ import { isNotFoundSignal, parseCookieHeader, redirectTarget, thenableRecord, } from "./request-context.js";
13
+ import { cacheRuntime, installRenderStore, patchFetch, routeDataTag, withCacheScope, } from "./cache-scope.js";
14
+ // Render cache scopes (tags / revalidate windows read during a render) and the
15
+ // Next-style fetch data cache. Installed once per process; page bundles share
16
+ // the state through globalThis.
17
+ installRenderStore(new AsyncLocalStorage());
18
+ patchFetch();
19
+ // Shared secret for the mutating internal endpoints (/__krate/ssr/revalidate,
20
+ // /refresh, /invalidate, /cache-invalidate). Krate passes it from the Go host;
21
+ // a renderer started by hand without it keeps the endpoints open.
22
+ const INTERNAL_SECRET = process.env.KRATE_INTERNAL_SECRET || "";
23
+ function internalAuthorized(req) {
24
+ if (!INTERNAL_SECRET)
25
+ return true;
26
+ const got = req.headers["x-krate-internal"];
27
+ if (typeof got !== "string")
28
+ return false;
29
+ const a = Buffer.from(got);
30
+ const b = Buffer.from(INTERNAL_SECRET);
31
+ return a.length === b.length && timingSafeEqual(a, b);
32
+ }
10
33
  // Cluster across cores: page/region rendering is independent per request, so N
11
34
  // workers scale it past a single core. Krate sets KRATE_SSR_WORKERS from
12
35
  // ssr.rendererWorkers. Region/ISR caches are per-worker and ISR disk persistence
@@ -14,6 +37,10 @@ import { renderToString } from "./server.js";
14
37
  const SSR_WORKERS = Math.max(1, parseInt(process.env.KRATE_SSR_WORKERS || "1", 10) || 1);
15
38
  const isClusterPrimary = SSR_WORKERS > 1 && cluster.isPrimary;
16
39
  if (isClusterPrimary) {
40
+ // Node leaves scheduling to the OS on Windows (SCHED_NONE), where one
41
+ // worker tends to accept every connection. Round-robin keeps clustered
42
+ // caches - and therefore revalidation fan-out - reachable on every platform.
43
+ cluster.schedulingPolicy = cluster.SCHED_RR;
17
44
  for (let i = 0; i < SSR_WORKERS; i++)
18
45
  cluster.fork();
19
46
  // Restart a worker that dies, after a short delay, but give up when they
@@ -33,6 +60,40 @@ if (isClusterPrimary) {
33
60
  setTimeout(() => cluster.fork(), 100);
34
61
  });
35
62
  console.log(`[krate-ssr] primary supervising ${SSR_WORKERS} workers`);
63
+ const broadcasts = new Map();
64
+ const finish = (id) => {
65
+ const b = broadcasts.get(id);
66
+ if (!b || b.remaining.size > 0)
67
+ return;
68
+ broadcasts.delete(id);
69
+ if (b.origin.isConnected())
70
+ b.origin.send({ type: "krate:bcast-done", id, results: b.results });
71
+ };
72
+ cluster.on("message", (worker, msg) => {
73
+ if (!msg || typeof msg !== "object")
74
+ return;
75
+ if (msg.type === "krate:bcast") {
76
+ const live = Object.values(cluster.workers || {}).filter((w) => w && w.isConnected());
77
+ broadcasts.set(msg.id, { origin: worker, remaining: new Set(live.map((w) => w.id)), results: [] });
78
+ for (const w of live)
79
+ w.send({ type: "krate:apply", id: msg.id, op: msg.op, payload: msg.payload });
80
+ finish(msg.id);
81
+ }
82
+ else if (msg.type === "krate:applied") {
83
+ const b = broadcasts.get(msg.id);
84
+ if (!b)
85
+ return;
86
+ b.results.push(msg.result);
87
+ b.remaining.delete(worker.id);
88
+ finish(msg.id);
89
+ }
90
+ });
91
+ cluster.on("exit", (worker) => {
92
+ for (const [id, b] of broadcasts) {
93
+ if (b.remaining.delete(worker.id))
94
+ finish(id);
95
+ }
96
+ });
36
97
  }
37
98
  // Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
38
99
  // Must be called BEFORE the first write for it to take effect.
@@ -60,6 +121,7 @@ function variantKey(req) {
60
121
  class ISRCache {
61
122
  constructor(maxSize = 512) {
62
123
  this.cache = new Map();
124
+ this.byTag = new Map();
63
125
  this.revalidationIntervals = new Map(); // route → seconds
64
126
  this.maxSize = maxSize;
65
127
  }
@@ -70,28 +132,87 @@ class ISRCache {
70
132
  return this.cache.get(key);
71
133
  }
72
134
  set(key, entry) {
135
+ if (this.cache.has(key))
136
+ this.delete(key);
73
137
  if (this.cache.size >= this.maxSize) {
74
138
  const oldest = this.cache.keys().next().value;
75
139
  if (oldest)
76
- this.cache.delete(oldest);
140
+ this.delete(oldest);
77
141
  }
78
142
  this.cache.set(key, entry);
143
+ for (const t of entry.tags || []) {
144
+ let keys = this.byTag.get(t);
145
+ if (!keys)
146
+ this.byTag.set(t, (keys = new Set()));
147
+ keys.add(key);
148
+ }
149
+ }
150
+ delete(key) {
151
+ const entry = this.cache.get(key);
152
+ if (!entry)
153
+ return false;
154
+ this.cache.delete(key);
155
+ for (const t of entry.tags || []) {
156
+ const keys = this.byTag.get(t);
157
+ if (keys) {
158
+ keys.delete(key);
159
+ if (keys.size === 0)
160
+ this.byTag.delete(t);
161
+ }
162
+ }
163
+ return true;
164
+ }
165
+ get size() {
166
+ return this.cache.size;
79
167
  }
80
168
  isStale(key) {
81
169
  const entry = this.cache.get(key);
82
170
  const route = key.split("?")[0].split("#")[0];
83
- const interval = this.revalidationIntervals.get(route);
171
+ let interval = this.revalidationIntervals.get(route) || 0;
172
+ if (entry && entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval)) {
173
+ interval = entry.revalidate;
174
+ }
84
175
  if (!entry || !interval)
85
176
  return false;
86
177
  return (Date.now() - entry.timestamp) / 1000 > interval;
87
178
  }
88
179
  // deleteRoute removes every variant of a route (used by revalidation/invalidation).
89
180
  deleteRoute(route) {
181
+ let n = 0;
90
182
  for (const key of [...this.cache.keys()]) {
91
183
  if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
92
- this.cache.delete(key);
184
+ if (this.delete(key))
185
+ n++;
186
+ }
187
+ }
188
+ return n;
189
+ }
190
+ // deleteVariant removes one params variant of a route (every query variant
191
+ // of it), e.g. /blog/[slug] with {slug: "a"} for revalidatePath("/blog/a").
192
+ deleteVariant(route, params) {
193
+ const base = variantKey({ route, params });
194
+ let n = 0;
195
+ for (const key of [...this.cache.keys()]) {
196
+ if (key === base || key.startsWith(base + "#")) {
197
+ if (this.delete(key))
198
+ n++;
199
+ }
200
+ }
201
+ return n;
202
+ }
203
+ // deleteTags removes every entry whose render read one of tags.
204
+ deleteTags(tags) {
205
+ let n = 0;
206
+ for (const t of tags) {
207
+ const keys = this.byTag.get(t);
208
+ if (!keys)
209
+ continue;
210
+ for (const key of [...keys]) {
211
+ if (this.delete(key))
212
+ n++;
93
213
  }
94
214
  }
215
+ return n;
95
216
  }
96
217
  // entriesForRoute returns a snapshot of the cached variants for a route so a
97
218
  // background refresh can iterate them without mutating during iteration.
@@ -114,11 +235,13 @@ class ISRCache {
114
235
  return;
115
236
  for (const e of data.entries) {
116
237
  if (e && typeof e.key === "string" && typeof e.html === "string") {
117
- this.cache.set(e.key, {
238
+ this.set(e.key, {
118
239
  html: e.html,
119
240
  timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
120
241
  params: e.params && typeof e.params === "object" ? e.params : undefined,
121
242
  query: e.query && typeof e.query === "object" ? e.query : undefined,
243
+ tags: Array.isArray(e.tags) ? e.tags.filter((t) => typeof t === "string") : undefined,
244
+ revalidate: typeof e.revalidate === "number" ? e.revalidate : undefined,
122
245
  });
123
246
  }
124
247
  }
@@ -153,6 +276,23 @@ let persistTimer = null;
153
276
  function isrCachePath() {
154
277
  return isrCacheFile || path.join(root, "dist", ".krate", "isr-cache.json");
155
278
  }
279
+ function persistIsrNow() {
280
+ if (SSR_WORKERS > 1)
281
+ return;
282
+ if (persistTimer) {
283
+ clearTimeout(persistTimer);
284
+ persistTimer = null;
285
+ }
286
+ try {
287
+ const data = isrCache.serialize();
288
+ const file = isrCachePath();
289
+ fs.mkdirSync(path.dirname(file), { recursive: true });
290
+ fs.writeFileSync(file, JSON.stringify(data));
291
+ }
292
+ catch (err) {
293
+ console.error("[krate-ssr] ISR cache persist failed:", err.message);
294
+ }
295
+ }
156
296
  function scheduleIsrPersist() {
157
297
  // Clustered: multiple workers would race on the same cache file; keep the ISR
158
298
  // cache in memory only.
@@ -160,18 +300,7 @@ function scheduleIsrPersist() {
160
300
  return;
161
301
  if (persistTimer)
162
302
  clearTimeout(persistTimer);
163
- persistTimer = setTimeout(() => {
164
- persistTimer = null;
165
- try {
166
- const data = isrCache.serialize();
167
- const file = isrCachePath();
168
- fs.mkdirSync(path.dirname(file), { recursive: true });
169
- fs.writeFileSync(file, JSON.stringify(data));
170
- }
171
- catch (err) {
172
- console.error("[krate-ssr] ISR cache persist failed:", err.message);
173
- }
174
- }, 1000);
303
+ persistTimer = setTimeout(persistIsrNow, 1000);
175
304
  }
176
305
  function loadIsrCache() {
177
306
  try {
@@ -179,7 +308,7 @@ function loadIsrCache() {
179
308
  if (fs.existsSync(file)) {
180
309
  const data = JSON.parse(fs.readFileSync(file, "utf-8"));
181
310
  isrCache.hydrate(data);
182
- const n = isrCache.cache.size;
311
+ const n = isrCache.size;
183
312
  if (n > 0)
184
313
  console.log(`[krate-ssr] Loaded ${n} persisted ISR entries`);
185
314
  }
@@ -232,15 +361,63 @@ function findPage(route) {
232
361
  }
233
362
  return page;
234
363
  }
364
+ // Request scope for server components: headers()/cookies() from
365
+ // @krate/runtime/server read it through the global store symbol, so it works
366
+ // no matter which copy of the runtime a page bundle resolved.
367
+ const requestStore = (() => {
368
+ const key = Symbol.for("krate.request.store");
369
+ const g = globalThis;
370
+ if (!g[key])
371
+ g[key] = new AsyncLocalStorage();
372
+ return g[key];
373
+ })();
374
+ function requestContextFor(req) {
375
+ const h = new Headers();
376
+ for (const [k, v] of Object.entries(req.headers || {})) {
377
+ if (typeof v === "string") {
378
+ try {
379
+ h.set(k, v);
380
+ }
381
+ catch {
382
+ // skip header names the WHATWG Headers class rejects
383
+ }
384
+ }
385
+ }
386
+ return {
387
+ url: req.url || req.route,
388
+ method: req.method || "GET",
389
+ headers: h,
390
+ cookies: parseCookieHeader(h.get("cookie")),
391
+ params: { ...(req.params || {}) },
392
+ searchParams: { ...(req.query || {}) },
393
+ };
394
+ }
395
+ function withRequest(req, fn) {
396
+ return requestStore.run(requestContextFor(req), fn);
397
+ }
398
+ // renderSignal maps notFound()/redirect() thrown during a render to a response.
399
+ function renderSignal(err) {
400
+ if (isNotFoundSignal(err))
401
+ return { html: "", status: 404, notFound: true };
402
+ const to = redirectTarget(err);
403
+ if (to)
404
+ return { html: "", status: 307, redirect: to };
405
+ return null;
406
+ }
235
407
  function buildProps(req) {
236
408
  // Page-level data fetching (getStaticProps/getServerSideProps) has been
237
409
  // removed; per-request data is provided by server components (@server),
238
410
  // runtime components (@runtime), and middleware instead. Dynamic-route
239
411
  // params and query parameters extracted by the Go server are forwarded so
240
412
  // `({ params }) => ...` pages receive their real values at render time.
413
+ // params and searchParams are plain objects that can also be awaited, so
414
+ // both `params.slug` and Next.js 15's `const { slug } = await params` work.
415
+ // The Go server always forwards params (empty for static routes); a direct
416
+ // request without them keeps params undefined, as before.
241
417
  const props = {};
242
418
  if (req.params)
243
- props.params = req.params;
419
+ props.params = thenableRecord(req.params);
420
+ props.searchParams = thenableRecord(req.query);
244
421
  if (req.query)
245
422
  props.query = req.query;
246
423
  return props;
@@ -254,29 +431,37 @@ async function renderFresh(page, req) {
254
431
  if (!Component) {
255
432
  return { html: "", status: 500 };
256
433
  }
257
- const jsxNode = Component(buildProps(req));
258
- // Bound the render. renderToString is synchronous, so a page that blocks
259
- // would block the sidecar's event loop regardless; the timeout still
260
- // protects the request path when rendering is async (suspense/resource).
261
- const html = await withRenderTimeout(Promise.resolve(renderToString(jsxNode)));
434
+ // The render runs in a cache scope that records the tags / revalidate
435
+ // windows its data reads declared (fetch next options, unstable_cache).
436
+ // Async server components (and plain sync pages) render through
437
+ // renderToStringAsync inside the request scope. The timeout bounds slow
438
+ // awaits (fetch); a page that blocks synchronously still blocks the loop.
439
+ const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderToStringAsync(jsx(Component, buildProps(req))))));
262
440
  const response = {
263
441
  html,
264
442
  status: 200,
265
443
  };
266
- if (page.mode === "isr") {
444
+ // An uncacheable read (no-store) keeps the render out of the ISR cache, and
445
+ // a revalidation that landed mid-render means the HTML may be stale.
446
+ if (page.mode === "isr" && !scope.noStore && !invalidated) {
267
447
  isrCache.set(variantKey(req), {
268
448
  html,
269
449
  timestamp: Date.now(),
270
450
  params: req.params,
271
451
  query: req.query,
452
+ tags: scope.tags.size ? [...scope.tags] : undefined,
453
+ revalidate: scope.revalidate || undefined,
272
454
  });
273
455
  scheduleIsrPersist();
274
456
  }
275
457
  return response;
276
458
  }
277
459
  catch (err) {
460
+ const signal = renderSignal(err);
461
+ if (signal)
462
+ return signal;
278
463
  console.error(`[krate] Error rendering ${req.route}:`, err);
279
- return { html: "", status: 500 };
464
+ return { html: "", status: 500, error: (err && err.message) || String(err) };
280
465
  }
281
466
  }
282
467
  // Single-flight background revalidation for stale-while-revalidate. While a
@@ -392,7 +577,15 @@ function loadRuntimeRenderer(relPath) {
392
577
  return cached;
393
578
  const abs = path.resolve(root, "dist", relPath);
394
579
  const code = fs.readFileSync(abs, "utf-8");
395
- const ctx = vm.createContext({ console });
580
+ // Runtime components get the host's fetch (looked up per call, so a cache
581
+ // layer that wraps globalThis.fetch later still applies) and the web
582
+ // primitives that go with it.
583
+ const ctx = vm.createContext({
584
+ console,
585
+ fetch: (...args) => globalThis.fetch(...args),
586
+ Headers, Request, Response, URL, URLSearchParams, TextEncoder, TextDecoder,
587
+ setTimeout, clearTimeout, queueMicrotask, structuredClone, AbortController,
588
+ });
396
589
  vm.runInContext(code, ctx, { filename: relPath });
397
590
  const render = vm.runInContext("typeof globalThis.__krate_render === 'function' ? globalThis.__krate_render : typeof __krate_render === 'function' ? __krate_render : null", ctx);
398
591
  if (typeof render !== "function") {
@@ -409,22 +602,43 @@ function regionProps(region, req) {
409
602
  props.query = req.query;
410
603
  return props;
411
604
  }
412
- // Region ISR cache: region-level stale-while-revalidate, separate from the
413
- // page ISR cache. Region HTML only depends on the baked props, so it is fully
414
- // determined by (route, region id, variant) and cacheable like a page variant.
415
605
  const regionCache = new Map();
416
606
  const regionRevalidation = new Map();
417
607
  const inFlightRegionRevalidations = new Map();
418
608
  // Region cache is bounded (FIFO eviction) so a long-lived sidecar cannot grow
419
609
  // without limit across many dynamic region variants.
420
610
  const REGION_CACHE_MAX = parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512;
421
- function regionCacheSet(key, html) {
611
+ function paramsKeyOf(params) {
612
+ return variantKey({ route: "", params });
613
+ }
614
+ function regionCacheSet(key, html, page, req, scope) {
422
615
  if (regionCache.size >= REGION_CACHE_MAX && !regionCache.has(key)) {
423
616
  const oldest = regionCache.keys().next().value;
424
617
  if (oldest !== undefined)
425
618
  regionCache.delete(oldest);
426
619
  }
427
- regionCache.set(key, { html, timestamp: Date.now() });
620
+ regionCache.set(key, {
621
+ html,
622
+ timestamp: Date.now(),
623
+ route: page.route,
624
+ paramsKey: paramsKeyOf(req.params),
625
+ tags: scope && scope.tags.size ? [...scope.tags] : undefined,
626
+ });
627
+ }
628
+ // invalidateRegions removes region entries for a route (optionally one params
629
+ // variant) and/or entries whose render read one of tags.
630
+ function invalidateRegions(route, params, tags) {
631
+ const pkey = params ? paramsKeyOf(params) : null;
632
+ let n = 0;
633
+ for (const [key, e] of Array.from(regionCache.entries())) {
634
+ const routeHit = route !== null && e.route === route && (pkey === null || e.paramsKey === pkey);
635
+ const tagHit = tags.length > 0 && !!e.tags && e.tags.some((t) => tags.includes(t));
636
+ if (routeHit || tagHit) {
637
+ regionCache.delete(key);
638
+ n++;
639
+ }
640
+ }
641
+ return n;
428
642
  }
429
643
  function clearRegionCache() {
430
644
  regionCache.clear();
@@ -451,17 +665,39 @@ function regionInterval(page, region) {
451
665
  return pprRevalidate;
452
666
  return 0;
453
667
  }
454
- function renderRegionFresh(region, req) {
668
+ async function renderRegionFresh(page, region, req) {
669
+ if (region.serverExport) {
670
+ const out = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderServerExport(page, region, req))));
671
+ return { html: out.result, scope: out.scope, invalidated: out.invalidated };
672
+ }
455
673
  const render = loadRuntimeRenderer(region.bundlePath);
456
- return withRenderTimeout(Promise.resolve().then(() => render(JSON.stringify(regionProps(region, req)))));
674
+ const out = await withRenderTimeout(withCacheScope(page.route, () => render(JSON.stringify(regionProps(region, req)))));
675
+ return { html: out.result, scope: out.scope, invalidated: out.invalidated };
676
+ }
677
+ function regionCacheable(r) {
678
+ return !r.scope.noStore && !r.invalidated;
679
+ }
680
+ // renderServerExport renders an async server component region with the page's
681
+ // own server bundle, which exports the component under region.serverExport.
682
+ async function renderServerExport(page, region, req) {
683
+ const mod = await loadPageModule(page);
684
+ const Comp = mod[region.serverExport];
685
+ if (typeof Comp !== "function") {
686
+ throw new Error(`server bundle for ${page.route} does not export ${region.serverExport}`);
687
+ }
688
+ const props = regionProps(region, req);
689
+ if (props.params && typeof props.params === "object")
690
+ props.params = thenableRecord(props.params);
691
+ return renderToStringAsync(jsx(Comp, props));
457
692
  }
458
693
  function revalidateRegionInBackground(page, region, req, key) {
459
694
  if (inFlightRegionRevalidations.has(key))
460
695
  return;
461
696
  const p = (async () => {
462
697
  try {
463
- const html = await renderRegionFresh(region, req);
464
- regionCacheSet(key, html);
698
+ const r = await renderRegionFresh(page, region, req);
699
+ if (regionCacheable(r))
700
+ regionCacheSet(key, r.html, page, req, r.scope);
465
701
  console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
466
702
  }
467
703
  catch (err) {
@@ -476,8 +712,8 @@ function revalidateRegionInBackground(page, region, req, key) {
476
712
  // renderRegion renders one region, applying region-level ISR caching for ISR
477
713
  // pages. Returns an NDJSON frame.
478
714
  async function renderRegion(page, region, req) {
479
- if (!region.bundlePath) {
480
- return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle" };
715
+ if (!region.bundlePath && !region.serverExport) {
716
+ return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle", fatal: !!page.serverComponents };
481
717
  }
482
718
  const key = regionCacheKey(page, region.id, req);
483
719
  const interval = regionInterval(page, region);
@@ -495,9 +731,10 @@ async function renderRegion(page, region, req) {
495
731
  }
496
732
  }
497
733
  try {
498
- const html = await renderRegionFresh(region, req);
499
- if (cacheable) {
500
- regionCacheSet(key, html);
734
+ const r = await renderRegionFresh(page, region, req);
735
+ const html = r.html;
736
+ if (cacheable && regionCacheable(r)) {
737
+ regionCacheSet(key, html, page, req, r.scope);
501
738
  }
502
739
  const frame = { type: "region", id: region.id, status: 200, html };
503
740
  if (cacheable)
@@ -505,8 +742,19 @@ async function renderRegion(page, region, req) {
505
742
  return frame;
506
743
  }
507
744
  catch (err) {
508
- console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err.message);
509
- return { type: "error", id: region.id, status: 500, error: err.message };
745
+ const signal = renderSignal(err);
746
+ if (signal) {
747
+ const frame = { type: "region", id: region.id, status: signal.status, html: "" };
748
+ if (signal.notFound)
749
+ frame.notFound = true;
750
+ if (signal.redirect)
751
+ frame.redirect = signal.redirect;
752
+ return frame;
753
+ }
754
+ console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err);
755
+ // A server component region has no meaningful baked content, so its
756
+ // failure is fatal for the response (the Go server answers 500).
757
+ return { type: "error", id: region.id, status: 500, error: (err && err.message) || String(err), fatal: !!(region.serverExport || page.serverComponents) };
510
758
  }
511
759
  }
512
760
  function writeJsonLine(res, obj) {
@@ -532,6 +780,10 @@ async function renderPageRegion(page, id, req) {
532
780
  frame.notFound = true;
533
781
  if (result.redirect)
534
782
  frame.redirect = result.redirect;
783
+ if (result.error)
784
+ frame.error = result.error;
785
+ if (page.serverComponents && frame.status >= 500)
786
+ frame.fatal = true;
535
787
  // Title swap: the Go server replaces the baked <title> with the freshly
536
788
  // rendered one so params-driven pages update the browser tab.
537
789
  const title = extractTitle(result.html);
@@ -543,6 +795,133 @@ function extractTitle(html) {
543
795
  const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
544
796
  return match ? match[1].trim() : "";
545
797
  }
798
+ const INTERNAL_OPS = {
799
+ "/__krate/ssr/revalidate": "revalidate-route",
800
+ "/__krate/ssr/refresh": "refresh-route",
801
+ "/__krate/ssr/invalidate": "dev-invalidate",
802
+ "/__krate/ssr/cache-invalidate": "cache-invalidate",
803
+ };
804
+ function stringList(v) {
805
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
806
+ }
807
+ // applyInternalOp applies one internal operation to this process's caches.
808
+ async function applyInternalOp(op, payload) {
809
+ switch (op) {
810
+ case "revalidate-route": {
811
+ const targetRoute = String(payload.route || "");
812
+ isrCache.deleteRoute(targetRoute);
813
+ clearRegionCacheForRoute(targetRoute);
814
+ cacheRuntime().invalidate({});
815
+ persistIsrNow();
816
+ const page = findPage(targetRoute);
817
+ if (page) {
818
+ await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
819
+ }
820
+ return { ok: true };
821
+ }
822
+ case "refresh-route": {
823
+ const targetRoute = String(payload.route || "");
824
+ const page = findPage(targetRoute);
825
+ const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
826
+ clearRegionCacheForRoute(targetRoute);
827
+ return { ok: true, refreshed };
828
+ }
829
+ case "dev-invalidate": {
830
+ const { route: targetRoute, source, bundlePath } = payload;
831
+ // Invalidate ISR cache for this route (all variants)
832
+ isrCache.deleteRoute(targetRoute);
833
+ // Invalidate module cache for the source file or bundle
834
+ const key = bundlePath || source;
835
+ if (key && moduleCache.has(key)) {
836
+ moduleCache.delete(key);
837
+ console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
838
+ }
839
+ // Runtime component bundles are recompiled in place on a dev rebuild, but
840
+ // their render functions are cached for the process lifetime. Clear them
841
+ // so the next region render picks up the new code. Bundles are tiny and
842
+ // re-read on demand, so clearing all of them is cheap and avoids tracking
843
+ // which component maps to which route here.
844
+ runtimeBundleCache.clear();
845
+ clearRegionCache();
846
+ return { ok: true };
847
+ }
848
+ case "cache-invalidate": {
849
+ const tags = stringList(payload.tags);
850
+ const targets = Array.isArray(payload.targets)
851
+ ? payload.targets.filter((t) => t && typeof t.route === "string")
852
+ : [];
853
+ // Path targets also drop the data their renders cached (implicit tag).
854
+ const dataTags = tags.concat(targets.map((t) => routeDataTag(t.route)));
855
+ const { dataEntries } = cacheRuntime().invalidate({ tags: dataTags });
856
+ let isrEntries = 0;
857
+ let regionEntries = 0;
858
+ for (const t of targets) {
859
+ const params = t.params && typeof t.params === "object" ? t.params : null;
860
+ isrEntries += params ? isrCache.deleteVariant(t.route, params) : isrCache.deleteRoute(t.route);
861
+ regionEntries += invalidateRegions(t.route, params, []);
862
+ }
863
+ if (tags.length) {
864
+ isrEntries += isrCache.deleteTags(tags);
865
+ regionEntries += invalidateRegions(null, null, tags);
866
+ }
867
+ if (isrEntries > 0)
868
+ persistIsrNow();
869
+ return { ok: true, isrEntries, regionEntries, dataEntries };
870
+ }
871
+ }
872
+ }
873
+ // Cluster fan-out (worker side). broadcastInternalOp resolves with one result
874
+ // per live worker once every worker applied the operation.
875
+ let broadcastSeq = 0;
876
+ const broadcastWaiters = new Map();
877
+ if (cluster.isWorker) {
878
+ process.on("message", async (msg) => {
879
+ if (!msg || typeof msg !== "object")
880
+ return;
881
+ if (msg.type === "krate:apply") {
882
+ let result;
883
+ try {
884
+ result = await applyInternalOp(msg.op, msg.payload || {});
885
+ }
886
+ catch (err) {
887
+ result = { ok: false, error: err && err.message ? err.message : String(err) };
888
+ }
889
+ process.send({ type: "krate:applied", id: msg.id, result });
890
+ }
891
+ else if (msg.type === "krate:bcast-done") {
892
+ const done = broadcastWaiters.get(msg.id);
893
+ if (done) {
894
+ broadcastWaiters.delete(msg.id);
895
+ done(Array.isArray(msg.results) ? msg.results : []);
896
+ }
897
+ }
898
+ });
899
+ }
900
+ function broadcastInternalOp(op, payload) {
901
+ if (!cluster.isWorker || typeof process.send !== "function") {
902
+ return applyInternalOp(op, payload).then((r) => [r]);
903
+ }
904
+ const id = `${process.pid}-${++broadcastSeq}`;
905
+ return new Promise((resolve) => {
906
+ broadcastWaiters.set(id, resolve);
907
+ process.send({ type: "krate:bcast", id, op, payload });
908
+ });
909
+ }
910
+ function mergeOpResults(op, results) {
911
+ const failed = results.filter((r) => r && r.ok === false);
912
+ if (failed.length > 0) {
913
+ throw new Error(failed.map((r) => r.error).join("; "));
914
+ }
915
+ const out = { ok: true, workers: results.length };
916
+ if (op === "refresh-route")
917
+ out.refreshed = results.reduce((n, r) => n + (r.refreshed || 0), 0);
918
+ if (op === "cache-invalidate") {
919
+ for (const k of ["isrEntries", "regionEntries", "dataEntries"]) {
920
+ out[k] = results.reduce((n, r) => n + (r[k] || 0), 0);
921
+ }
922
+ }
923
+ return out;
924
+ }
546
925
  // HTTP Server
547
926
  const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
548
927
  const manifestPath = process.env.KRATE_MANIFEST || "";
@@ -583,70 +962,29 @@ const server = http.createServer(async (req, res) => {
583
962
  res.end(JSON.stringify({ ok: true, pages: manifest?.pages?.length || 0 }));
584
963
  return;
585
964
  }
586
- // ISR revalidation endpoint (called by Go server in background)
587
- if (route === "/__krate/ssr/revalidate" && req.method === "POST") {
588
- const body = await parseBody(req);
589
- try {
590
- const { route: targetRoute } = JSON.parse(body);
591
- isrCache.deleteRoute(targetRoute);
592
- clearRegionCacheForRoute(targetRoute);
593
- // Trigger re-render of the base variant.
594
- const page = findPage(targetRoute);
595
- if (page) {
596
- await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
597
- }
598
- res.writeHead(200, { "Content-Type": "application/json" });
599
- res.end(JSON.stringify({ ok: true }));
965
+ // Mutating internal endpoints. Each requires the host's shared secret and is
966
+ // applied on every clustered worker before the response is sent.
967
+ // /__krate/ssr/revalidate {route} clear a route, re-render its base variant
968
+ // /__krate/ssr/refresh {route} re-render cached variants in place (ISR timer)
969
+ // /__krate/ssr/invalidate {route, source, bundlePath} dev module reload
970
+ // /__krate/ssr/cache-invalidate {targets:[{route, params?}], tags:[]} on-demand revalidation
971
+ const internalOp = INTERNAL_OPS[route];
972
+ if (internalOp) {
973
+ if (req.method !== "POST") {
974
+ res.writeHead(405, { "Content-Type": "application/json", Allow: "POST" });
975
+ res.end(JSON.stringify({ error: "method not allowed" }));
976
+ return;
600
977
  }
601
- catch (err) {
602
- res.writeHead(500, { "Content-Type": "application/json" });
603
- res.end(JSON.stringify({ error: err.message }));
978
+ if (!internalAuthorized(req)) {
979
+ res.writeHead(403, { "Content-Type": "application/json" });
980
+ res.end(JSON.stringify({ error: "forbidden" }));
981
+ return;
604
982
  }
605
- return;
606
- }
607
- // ISR background refresh endpoint (called by the Go server on each route's
608
- // revalidation cadence). Unlike /__krate/ssr/revalidate this is
609
- // non-destructive: it re-renders every cached variant in place, so cached
610
- // dynamic variants stay fresh instead of being evicted (which would make the
611
- // next request a MISS rather than a HIT).
612
- if (route === "/__krate/ssr/refresh" && req.method === "POST") {
613
- const body = await parseBody(req);
614
983
  try {
615
- const { route: targetRoute } = JSON.parse(body);
616
- const page = findPage(targetRoute);
617
- const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
618
- clearRegionCacheForRoute(targetRoute);
984
+ const payload = JSON.parse((await parseBody(req)) || "{}");
985
+ const results = await broadcastInternalOp(internalOp, payload);
619
986
  res.writeHead(200, { "Content-Type": "application/json" });
620
- res.end(JSON.stringify({ ok: true, refreshed }));
621
- }
622
- catch (err) {
623
- res.writeHead(500, { "Content-Type": "application/json" });
624
- res.end(JSON.stringify({ error: err.message }));
625
- }
626
- return;
627
- }
628
- // Module cache invalidation (called on file change in dev mode)
629
- if (route === "/__krate/ssr/invalidate" && req.method === "POST") {
630
- const body = await parseBody(req);
631
- try {
632
- const { route: targetRoute, source, bundlePath } = JSON.parse(body);
633
- // Invalidate ISR cache for this route (all variants)
634
- isrCache.deleteRoute(targetRoute);
635
- // Invalidate module cache for the source file or bundle
636
- const key = bundlePath || source;
637
- if (key && moduleCache.has(key)) {
638
- moduleCache.delete(key);
639
- console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
640
- }
641
- // Runtime component bundles are recompiled in place on a dev rebuild, but
642
- // their render functions are cached for the process lifetime. Clear them
643
- // so the next region render picks up the new code. Bundles are tiny and
644
- // re-read on demand, so clearing all of them is cheap and avoids tracking
645
- // which component maps to which route here.
646
- runtimeBundleCache.clear();
647
- clearRegionCache();
648
- res.writeHead(200, { "Content-Type": "application/json" });
649
- res.end(JSON.stringify({ ok: true }));
987
+ res.end(JSON.stringify(mergeOpResults(internalOp, results)));
650
988
  }
651
989
  catch (err) {
652
990
  res.writeHead(500, { "Content-Type": "application/json" });
@@ -692,20 +1030,19 @@ const server = http.createServer(async (req, res) => {
692
1030
  if (regions.length === 0) {
693
1031
  regions = (manifest?.regions?.[page.route] || []).map((r) => ({ id: r.id, kind: "component" }));
694
1032
  }
695
- for (const r of regions) {
696
- if (r.kind === "page") {
697
- writeJsonLine(res, await renderPageRegion(page, r.id, renderReq));
698
- }
699
- else {
700
- const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
701
- if (region) {
702
- writeJsonLine(res, await renderRegion(page, region, renderReq));
703
- }
704
- else {
705
- // Unknown region id - keep the baked content by sending no frame.
706
- writeJsonLine(res, { type: "skip", id: r.id });
707
- }
708
- }
1033
+ // Start every region render at once (async server components await
1034
+ // I/O, so they overlap), then write the frames in document order.
1035
+ const pending = regions.map((r) => {
1036
+ if (r.kind === "page")
1037
+ return renderPageRegion(page, r.id, renderReq);
1038
+ const region = (manifest?.regions?.[page.route] || []).find((m) => m.id === r.id);
1039
+ if (region)
1040
+ return renderRegion(page, region, renderReq);
1041
+ // Unknown region id - keep the baked content by sending no frame.
1042
+ return Promise.resolve({ type: "skip", id: r.id });
1043
+ });
1044
+ for (const p of pending) {
1045
+ writeJsonLine(res, await p);
709
1046
  }
710
1047
  writeJsonLine(res, { type: "end", count: regions.length });
711
1048
  }
@@ -745,7 +1082,7 @@ const server = http.createServer(async (req, res) => {
745
1082
  return;
746
1083
  }
747
1084
  if (result.redirect) {
748
- res.writeHead(302, { Location: result.redirect });
1085
+ res.writeHead(result.status === 307 ? 307 : 302, { Location: result.redirect });
749
1086
  res.end();
750
1087
  return;
751
1088
  }