@krate/runtime 0.4.0-rc.5 → 0.4.0-rc.6

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.
@@ -1,11 +1,27 @@
1
1
  // @krate/runtime/server-renderer - Node.js HTTP server for SSR/ISR/Streaming
2
2
  // Receives render requests from the Go server and returns HTML.
3
3
  import http from "node:http";
4
+ import cluster from "node:cluster";
4
5
  import fs from "node:fs";
5
6
  import path from "node:path";
6
7
  import vm from "node:vm";
7
8
  import { pathToFileURL } from "node:url";
8
9
  import { renderToString } from "./server.js";
10
+ // Cluster across cores: page/region rendering is independent per request, so N
11
+ // workers scale it past a single core. Krate sets KRATE_SSR_WORKERS from
12
+ // ssr.rendererWorkers. Region/ISR caches are per-worker and ISR disk persistence
13
+ // is disabled when clustered (the primary never serves).
14
+ const SSR_WORKERS = Math.max(1, parseInt(process.env.KRATE_SSR_WORKERS || "1", 10) || 1);
15
+ const isClusterPrimary = SSR_WORKERS > 1 && cluster.isPrimary;
16
+ if (isClusterPrimary) {
17
+ for (let i = 0; i < SSR_WORKERS; i++)
18
+ cluster.fork();
19
+ cluster.on("exit", (worker) => {
20
+ console.log(`[krate-ssr] worker ${worker.process.pid} exited; restarting`);
21
+ cluster.fork();
22
+ });
23
+ console.log(`[krate-ssr] primary supervising ${SSR_WORKERS} workers`);
24
+ }
9
25
  // Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
10
26
  // Must be called BEFORE the first write for it to take effect.
11
27
  function setupStream(res) {
@@ -126,6 +142,10 @@ function isrCachePath() {
126
142
  return isrCacheFile || path.join(root, "dist", ".krate", "isr-cache.json");
127
143
  }
128
144
  function scheduleIsrPersist() {
145
+ // Clustered: multiple workers would race on the same cache file; keep the ISR
146
+ // cache in memory only.
147
+ if (SSR_WORKERS > 1)
148
+ return;
129
149
  if (persistTimer)
130
150
  clearTimeout(persistTimer);
131
151
  persistTimer = setTimeout(() => {
@@ -741,6 +761,11 @@ const server = http.createServer(async (req, res) => {
741
761
  res.writeHead(result.status, headers_extra);
742
762
  res.end(result.html);
743
763
  });
744
- server.listen(PORT, () => {
745
- console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
746
- });
764
+ if (isClusterPrimary) {
765
+ // The primary only supervises; workers own the listening socket.
766
+ }
767
+ else {
768
+ server.listen(PORT, () => {
769
+ console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
770
+ });
771
+ }
package/dist/server.d.ts CHANGED
@@ -6,6 +6,7 @@ export declare function onMount(_fn: () => void): void;
6
6
  interface RawHTML {
7
7
  __raw: string;
8
8
  }
9
+ export declare function goComponent(name: string, tier: string, baked: Record<string, string> | null | undefined, props: Record<string, any> | undefined, revalidate?: number): JSXNode;
9
10
  type JSXNode = string | number | boolean | null | undefined | JSXNode[] | JSXElement | RawHTML;
10
11
  interface JSXElement {
11
12
  type: string | Function;
package/dist/server.js CHANGED
@@ -33,6 +33,37 @@ export function onMount(_fn) {
33
33
  // and crash.
34
34
  }
35
35
  function raw(html) { return { __raw: html }; }
36
+ // goComponent is the SSR bridge for Go-authored components (see the compiler's
37
+ // server-bundle esbuild plugin). A server-tier component inlines its build-time
38
+ // baked HTML when the call site was annotated with __krateGoId; otherwise (and
39
+ // always for runtime-tier) it emits a marker the Go server resolves by calling
40
+ // the Go host at request time. revalidate is the component file's cache window,
41
+ // carried in the marker so the Go server needn't look it up by name.
42
+ export function goComponent(name, tier, baked, props, revalidate = 0) {
43
+ const p = props || {};
44
+ const id = p.__krateGoId;
45
+ if (tier === "server" && baked && id && Object.prototype.hasOwnProperty.call(baked, id)) {
46
+ return raw(baked[id]);
47
+ }
48
+ const rest = {};
49
+ for (const k in p) {
50
+ if (k !== "__krateGoId" && k !== "children")
51
+ rest[k] = p[k];
52
+ }
53
+ if (p.children != null) {
54
+ const kids = renderToString(p.children);
55
+ if (kids !== "")
56
+ rest["children"] = kids;
57
+ }
58
+ return raw("<!--krate-go:" + name + ":" + (revalidate > 0 ? revalidate : 0) + ":" + base64url(JSON.stringify(rest)) + "-->");
59
+ }
60
+ function base64url(s) {
61
+ const bytes = new TextEncoder().encode(s);
62
+ let bin = "";
63
+ for (let i = 0; i < bytes.length; i++)
64
+ bin += String.fromCharCode(bytes[i]);
65
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
66
+ }
36
67
  export function Fragment(_props) {
37
68
  return _props.children ?? [];
38
69
  }
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { jsx, renderToString } from './server';
2
+ import { jsx, renderToString, goComponent } from './server';
3
3
  describe('renderToString', () => {
4
4
  it('renders nested elements and escapes text', () => {
5
5
  const node = jsx('div', { class: 'x', children: [jsx('span', { children: 'a & b' })] });
@@ -24,3 +24,25 @@ describe('renderToString', () => {
24
24
  expect(renderToString({ __raw: '<b>hi</b>' })).toBe('<b>hi</b>');
25
25
  });
26
26
  });
27
+ describe('goComponent', () => {
28
+ it('inlines baked HTML for an annotated server-tier call site', () => {
29
+ const baked = { 'gc3_5_Badge': '<span class="badge">Hi</span>' };
30
+ const node = goComponent('Badge', 'server', baked, { __krateGoId: 'gc3_5_Badge', label: 'Hi' });
31
+ expect(renderToString(node)).toBe('<span class="badge">Hi</span>');
32
+ });
33
+ it('emits a marker for runtime-tier calls, encoding props + children', () => {
34
+ const node = goComponent('Clock', 'runtime', null, { zone: 'UTC', children: ['a ', jsx('b', { children: 'c' })] }, 45);
35
+ const html = renderToString(node);
36
+ const m = html.match(/^<!--krate-go:Clock:(\d+):([A-Za-z0-9_-]+)-->$/);
37
+ expect(m).not.toBeNull();
38
+ expect(m[1]).toBe('45');
39
+ const b64 = m[2].replace(/-/g, '+').replace(/_/g, '/');
40
+ const payload = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
41
+ expect(payload.zone).toBe('UTC');
42
+ expect(payload.children).toBe('a <b>c</b>');
43
+ });
44
+ it('falls back to a marker when a server call site is not in the baked map', () => {
45
+ const node = goComponent('Badge', 'server', {}, { __krateGoId: 'missing', label: 'Hi' });
46
+ expect(renderToString(node)).toMatch(/^<!--krate-go:Badge:0:/);
47
+ });
48
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.4.0-rc.5",
3
+ "version": "0.4.0-rc.6",
4
4
  "description": "Client-side runtime for Krate — signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",