An open-source, self-hosted system for apps built with web technologies.
Carry streams across every System boundary
zohayrslilehc3af766395ed
diff --git a/bun.lock b/bun.lockindex 33850f8..0308ba5 100644--- a/bun.lock+++ b/bun.lock@@ -10,10 +10,10 @@"@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0","@phreshos/core": "^0.1.65","@phreshos/react-ui": "^0.1.47",- "@the-link/core": "^0.3.1",- "@the-link/http": "^0.1.1",- "@the-link/ipc": "^0.2.2",- "@the-link/messagepack": "^0.1.0",+ "@the-link/core": "^0.4.0",+ "@the-link/http": "^0.2.0",+ "@the-link/ipc": "^0.3.0",+ "@the-link/messagepack": "^0.2.0","@the-link/react": "^0.2.0","cfonts": "^3.3.1","hono": "^4.13.8",@@ -274,13 +274,13 @@"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="],- "@the-link/core": ["@the-link/[email protected]", "", { "dependencies": { "uuid": "^14.0.1" } }, "sha512-jH9mPLoXb+7pCxN7yGzo6TC4E1zb8HHrR5GidStEumM9NE+pIqolehXzdcCyPTJR4KIgZ4q64cjKs8QPruwWwA=="],+ "@the-link/core": ["@the-link/[email protected]", "", { "dependencies": { "uuid": "^14.0.1" } }, "sha512-pwZsM6lq4XRudHhm4RBgmptvrHsgps0yx0EZxqGMcaaQ45usafE/WhReDAGzHtGkT4+y1ad8cNjCGYViNbug8g=="],- "@the-link/http": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.3.0", "hono": "^4.13.2", "uuid": "^14.0.1" } }, "sha512-onqoHm09iHAjPuUHVJiJOttQdEotWofbcxWcsxqe2+DzV4A8/9teF4k/tf3OeVAXqkmo+nBvtQY82lG0n4XxlQ=="],+ "@the-link/http": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.4.0", "hono": "^4.13.2", "uuid": "^14.0.1" } }, "sha512-AWDLcDs0e0ZP30vDqtkeFCjCyVZflQXvhJGvJTg1gSBm0lPvf1OS1UBHrnI3wAwgTRPkL50V+t7VfELyH0uAzA=="],- "@the-link/ipc": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.3.0" } }, "sha512-1bRTxXa29DIv96YrBKf6pO4+CGp82VxA76rIolwSfkj4RImycHvz3WzYBJDesVh+mf2uN+tgsTucf0ZGWPmZEQ=="],+ "@the-link/ipc": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.4.0" } }, "sha512-qIvn9dzoAck3AkchS5agEXCHi9083I0JXCPOXgG1GpQlm2fBoMjf5yLHeHC4hZZP1Q1gcxrYQTILJsPzWGUqtw=="],- "@the-link/messagepack": ["@the-link/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" } }, "sha512-Ktnd6sBPZKLCYl6wnxZjxnCzCBWv33k5iUXAs3hVueejj7vQ5wK5KQVPqaQmfeBFuyOo68KqtVaMxl7A1c/atg=="],+ "@the-link/messagepack": ["@the-link/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" } }, "sha512-BQ8LpIqZCUHV5dtryegDvJQa+5EwRudnMPVdmonHt4hyQteK+57BhW9GjYuNeiFI/mc/wUHhPHCXn5ohNy6aoQ=="],"@the-link/react": ["@the-link/[email protected]", "", { "peerDependencies": { "@the-link/core": "^0.2.0", "react": "^19.2.0" } }, "sha512-HhWA3s1bWkrzee5IUs122AOvdkL21ckIbqFkg2nsTsBqHuS2XapfxIeZGJw+PVB3za9aC+wSEuTcLKH75WKgVg=="],diff --git a/package.json b/package.jsonindex f85ece1..a3062fc 100644--- a/package.json+++ b/package.json@@ -39,10 +39,10 @@"@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0","@phreshos/core": "^0.1.65","@phreshos/react-ui": "^0.1.47",- "@the-link/core": "^0.3.1",- "@the-link/http": "^0.1.1",- "@the-link/ipc": "^0.2.2",- "@the-link/messagepack": "^0.1.0",+ "@the-link/core": "^0.4.0",+ "@the-link/http": "^0.2.0",+ "@the-link/ipc": "^0.3.0",+ "@the-link/messagepack": "^0.2.0","@the-link/react": "^0.2.0","cfonts": "^3.3.1","hono": "^4.13.8",diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.tsindex dd9757b..a83be73 100644--- a/source/client/view/components/desktop-host/client-host.ts+++ b/source/client/view/components/desktop-host/client-host.ts@@ -314,12 +314,20 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObjelet message: unknown- try { message = messagepack.deserialize(bytes, attachments) }+ try { message = messagepack.deserialize(bytes, { attachments, streams: boundary.relay }) }catch { return }if (!Array.isArray(message)) return+ // Stream chunks belong to the boundary's relay, not to the endpoint's routes.+ if (message[0] === "boundary" && message[1] === "relay") {++ boundary.relay.receive(message.slice(2))++ return+ }+boundary.receive(message)returndiff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex 829acf5..bcf3b73 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -1,5 +1,5 @@import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"-import { TheLink } from "@the-link/core"+import { StreamRelay, TheLink } from "@the-link/core"import host, { TransferredAnswer, type DesktopViewportHost } from "./host"import ClientTraffic from "./client-traffic"import { failed, succeeded } from "@libs/request-outcome"@@ -63,6 +63,12 @@ export default class ClientProcessBoundary extends TheLink {// as later ones.private readonly pending = new Array<unknown[]>()+ /**+ * Streams crossing to and from the current document, as references whose chunks follow as+ * boundary relay messages. Each document gets its own; its streams end with it.+ */+ public relay = this.newRelay()+private owner: string | null = nullprivate leased: string | null = null@@ -101,6 +107,9 @@ export default class ClientProcessBoundary extends TheLink {// envelopes only after the new server-host lease exists.const pending = this.pending.splice(0)+ this.relay.close(new Error("The Program's window was reloaded"))+ this.relay = this.newRelay()+this.presentation.begin(this.pane)this.resetEndpoint()@@ -151,6 +160,8 @@ export default class ClientProcessBoundary extends TheLink {this.pending.length = 0+ this.relay.close(new Error("The Program's window closed"))+if (owner) await this.authManager.processManager.releaseFrame(this.pane, owner)}@@ -379,11 +390,16 @@ export default class ClientProcessBoundary extends TheLink {const attachments = nativeAttachments(message, transfer)- const bytes = messagepack.serialize(message, attachments)+ const bytes = messagepack.serialize(message, { attachments, streams: this.relay })target.postMessage([bytes, ...attachments], "*", [bytes.buffer, ...transfer])}+ private newRelay() {++ return new StreamRelay(message => this.send(["boundary", "relay", ...message]))+ }+public impossible(subscription: string, reason: string) {this.$outbound.publish("boundary", "impossible", subscription, reason).catch(() => undefined)diff --git a/source/server/core/server-runtime/inbox.ts b/source/server/core/server-runtime/channel.tssimilarity index 59%rename from source/server/core/server-runtime/inbox.tsrename to source/server/core/server-runtime/channel.tsindex 430b13e..175a496 100644--- a/source/server/core/server-runtime/inbox.ts+++ b/source/server/core/server-runtime/channel.ts@@ -1,15 +1,35 @@import type { ServerRuntimeMessage } from "../server-runtime"+import { StreamRelay } from "@the-link/core"import messagepack from "@the-link/messagepack"type Listener = (event: string, ...values: unknown[]) => voidconst maximumPendingMessages = 256-/** Preserves ordered runtime messages until Core installs their sole listener. */-export default class RuntimeInbox {+/**+ * The System's end of one Server runtime's messages. It encodes what the System+ * sends and decodes what the runtime sends, carrying streams in either+ * direction as references whose chunks follow as boundary relay messages, and+ * preserves ordered messages until Core installs their sole listener.+ */+export default class RuntimeChannel {private listener: Listener | null = nullprivate readonly pending: ServerRuntimeMessage[] = []+ private readonly relay: StreamRelay++ /**+ * @param deliver Sends encoded bytes to the runtime+ */+ public constructor(deliver: (bytes: Uint8Array) => void) {++ this.relay = new StreamRelay(message => deliver(messagepack.serialize(["boundary", "relay", ...message])))+ }++ public encode(message: ServerRuntimeMessage) {++ return messagepack.serialize(message, { streams: this.relay })+ }public receive(message: unknown) {@@ -18,11 +38,14 @@ export default class RuntimeInbox {if (!bytes) returnlet decoded: unknown- try { decoded = messagepack.deserialize(bytes) }+ try { decoded = messagepack.deserialize(bytes, { streams: this.relay }) }catch { return }if (!Array.isArray(decoded) || typeof decoded[0] !== "string") return+ // Stream chunks belong to this channel, not to Core.+ if (decoded[0] === "boundary" && decoded[1] === "relay") return this.relay.receive(decoded.slice(2))+const envelope = decoded as ServerRuntimeMessageif (this.listener) this.listener(...envelope)@@ -37,6 +60,12 @@ export default class RuntimeInbox {for (const message of this.pending.splice(0)) listener(...message)}++ /** Ends every stream crossing this channel. */+ public close() {++ this.relay.close(new Error("The Server runtime ended"))+ }}export function runtimeMessageBytes(value: unknown) {diff --git a/source/server/core/server-runtime/command.ts b/source/server/core/server-runtime/command.tsindex 8bac7f8..e1d2f0e 100644--- a/source/server/core/server-runtime/command.ts+++ b/source/server/core/server-runtime/command.ts@@ -1,14 +1,13 @@import ProcessTree, { detachedProcessTree } from "@libs/process-tree"import type { ServerRuntime, ServerRuntimeEnding, Stream } from "../server-runtime"import { FrameReader, writeFrame } from "@the-link/ipc/framing"-import messagepack from "@the-link/messagepack"import { spawn } from "node:child_process"import { randomUUID } from "node:crypto"import { chmod, rm } from "node:fs/promises"import { createServer, type Server, type Socket } from "node:net"import { tmpdir } from "node:os"import { delimiter, join } from "node:path"-import RuntimeInbox from "./inbox"+import RuntimeChannel from "./channel"type OutputListener = (stream: Stream, text: string) => void@@ -19,7 +18,11 @@ export default class CommandServerRuntime implements ServerRuntime {public readonly finished: Promise<ServerRuntimeEnding>- private readonly inbox = new RuntimeInbox()+ private readonly channel = new RuntimeChannel(bytes => {++ if (!this.socket) this.pendingMessages.push(bytes)+ else this.write(bytes)+ })private readonly output = new Set<OutputListener>()private readonly pendingMessages: Uint8Array[] = []private readonly address = commandAddress()@@ -61,13 +64,13 @@ export default class CommandServerRuntime implements ServerRuntime {public send(event: string, ...values: unknown[]) {- const message = messagepack.serialize([event, ...values])+ const message = this.channel.encode([event, ...values])if (!this.socket) this.pendingMessages.push(message)else this.write(message)}- public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }+ public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.channel.listen(listener) }public onOutput(listener: OutputListener) { this.output.add(listener) }@@ -121,7 +124,7 @@ export default class CommandServerRuntime implements ServerRuntime {continue}- this.inbox.receive(frame)+ this.channel.receive(frame)}} catch { candidate.destroy() }})@@ -148,6 +151,8 @@ export default class CommandServerRuntime implements ServerRuntime {private async closeTransport() {+ this.channel.close()+for (const socket of this.sockets) socket.destroy()this.sockets.clear()this.socket = nulldiff --git a/source/server/core/server-runtime/thread.ts b/source/server/core/server-runtime/thread.tsindex 8e339aa..be7899b 100644--- a/source/server/core/server-runtime/thread.ts+++ b/source/server/core/server-runtime/thread.ts@@ -1,7 +1,6 @@import type { ServerRuntime, ServerRuntimeEnding, Stream } from "../server-runtime"-import messagepack from "@the-link/messagepack"import { Worker } from "node:worker_threads"-import RuntimeInbox from "./inbox"+import RuntimeChannel from "./channel"type OutputListener = (stream: Stream, text: string) => void@@ -14,7 +13,7 @@ export default abstract class ThreadServerRuntime implements ServerRuntime {private readonly worker: Worker- private readonly inbox = new RuntimeInbox()+ private readonly channel: RuntimeChannelprivate readonly output = new Set<OutputListener>()@@ -26,17 +25,19 @@ export default abstract class ThreadServerRuntime implements ServerRuntime {this.worker = new Worker(bootstrap, { stdout: true, stderr: true, workerData })- this.finished = new Promise(resolve => { this.worker.once("exit", code => resolve({ code, signal: null })) })+ this.channel = new RuntimeChannel(bytes => this.worker.postMessage(bytes))- this.worker.on("message", message => this.inbox.receive(message))+ this.finished = new Promise(resolve => { this.worker.once("exit", code => { this.channel.close(); resolve({ code, signal: null }) }) })++ this.worker.on("message", message => this.channel.receive(message))this.worker.stdout?.on("data", chunk => this.print("out", String(chunk)))this.worker.stderr?.on("data", chunk => this.print("err", String(chunk)))this.worker.on("error", error => this.print("err", `${error instanceof Error ? error.stack ?? error.message : String(error)}\n`))}- public send(event: string, ...values: unknown[]) { this.worker.postMessage(messagepack.serialize([event, ...values])) }+ public send(event: string, ...values: unknown[]) { this.worker.postMessage(this.channel.encode([event, ...values])) }- public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }+ public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.channel.listen(listener) }public onOutput(listener: OutputListener) {diff --git a/tests/runtime-channel.test.ts b/tests/runtime-channel.test.tsnew file mode 100644index 0000000..9ce0881--- /dev/null+++ b/tests/runtime-channel.test.ts@@ -0,0 +1,75 @@+import assert from "node:assert/strict"+import { test } from "vitest"+import RuntimeChannel from "@server/core/server-runtime/channel"++/** Two channels joined as the System and a Server runtime, each delivering to the other. */+function joined() {++ let system!: RuntimeChannel+ let runtime!: RuntimeChannel++ system = new RuntimeChannel(bytes => queueMicrotask(() => runtime.receive(bytes)))+ runtime = new RuntimeChannel(bytes => queueMicrotask(() => system.receive(bytes)))++ const received: unknown[][] = []++ system.listen((...message) => { received.push(message) })++ return { system, runtime, received }+}++async function bytes(stream: ReadableStream<Uint8Array>) {++ return new Uint8Array(await new Response(stream).arrayBuffer())+}++test("streams cross a runtime channel in both directions, as references with their chunks beside them", async () => {++ const { system, runtime, received } = joined()+ const runtimeReceived: unknown[][] = []++ runtime.listen((...message) => { runtimeReceived.push(message) })++ const file = new Uint8Array(3 * 1024 * 1024).map((_, index) => index % 251)++ // The runtime sends an answer carrying a stream; the System reads it.+ system.receive(runtime.encode(["answer", "question", { size: file.byteLength, content: new Blob([file]).stream() }]))++ await new Promise(resolve => setTimeout(resolve, 0))++ const [event, question, answer] = received[0] as [string, string, { size: number, content: ReadableStream<Uint8Array> }]++ assert.equal(event, "answer")+ assert.equal(question, "question")+ assert.equal(answer.size, file.byteLength)+ assert.deepEqual(await bytes(answer.content), file)++ // The System sends a stream to the runtime the same way.+ runtime.receive(system.encode(["write", new Blob(["hello"]).stream()]))++ await new Promise(resolve => setTimeout(resolve, 0))++ const [, content] = runtimeReceived[0] as [string, ReadableStream<Uint8Array>]++ assert.equal(new TextDecoder().decode(await bytes(content)), "hello")++ // Chunk messages are the channel's own and never reach Core.+ assert.equal(received.length, 1)+ assert.equal(runtimeReceived.length, 1)+})++test("closing a channel ends the streams crossing it", async () => {++ const { system, runtime, received } = joined()++ system.receive(runtime.encode(["answer", new ReadableStream({ pull(controller) { controller.enqueue(new Uint8Array(8)) } })]))++ await new Promise(resolve => setTimeout(resolve, 0))++ const reader = (received[0]![1] as ReadableStream<Uint8Array>).getReader()++ await reader.read()+ system.close()++ await assert.rejects(reader.read(), /The Server runtime ended/)+})