An open-source, self-hosted system for apps built with web technologies.
Route command endpoints over local IPC
zohayrslilehdf575530ee6e
diff --git a/bun.lock b/bun.lockindex 8c2cd82..10b0dab 100644--- a/bun.lock+++ b/bun.lock@@ -12,7 +12,7 @@"@phreshos/react-ui": "^0.1.32","@the-link/core": "^0.3.1","@the-link/http": "^0.1.1",- "@the-link/ipc": "^0.2.1",+ "@the-link/ipc": "^0.2.2","@the-link/messagepack": "^0.1.0","@the-link/react": "^0.2.0","cfonts": "^3.3.1",@@ -277,7 +277,7 @@"@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/ipc": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.3.0" } }, "sha512-5sPn0y4kDSYulG8pTmzxdAPscqS1S+K8pLOlLHDUnCzEzlytY6a3rvK2PYD1neBaKkUsWml64lrRkzp8d2nkdA=="],+ "@the-link/ipc": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.3.0" } }, "sha512-1bRTxXa29DIv96YrBKf6pO4+CGp82VxA76rIolwSfkj4RImycHvz3WzYBJDesVh+mf2uN+tgsTucf0ZGWPmZEQ=="],"@the-link/messagepack": ["@the-link/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" } }, "sha512-Ktnd6sBPZKLCYl6wnxZjxnCzCBWv33k5iUXAs3hVueejj7vQ5wK5KQVPqaQmfeBFuyOo68KqtVaMxl7A1c/atg=="],diff --git a/package.json b/package.jsonindex 0a615b6..94c517c 100644--- a/package.json+++ b/package.json@@ -41,7 +41,7 @@"@phreshos/react-ui": "^0.1.32","@the-link/core": "^0.3.1","@the-link/http": "^0.1.1",- "@the-link/ipc": "^0.2.1",+ "@the-link/ipc": "^0.2.2","@the-link/messagepack": "^0.1.0","@the-link/react": "^0.2.0","cfonts": "^3.3.1",diff --git a/source/server/core/server-runtime/command.ts b/source/server/core/server-runtime/command.tsindex 50b6470..45bb3b3 100644--- a/source/server/core/server-runtime/command.ts+++ b/source/server/core/server-runtime/command.ts@@ -1,63 +1,187 @@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, type ChildProcess } from "node:child_process"+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, { runtimeMessageBytes } from "./inbox"+import RuntimeInbox from "./inbox"type OutputListener = (stream: Stream, text: string) => void+const maximumFrameSize = 16 * 1024 * 1024+/** Runs one Server Endpoint as an operating-system process tree. */export default class CommandServerRuntime implements ServerRuntime {public readonly finished: Promise<ServerRuntimeEnding>- private readonly child: ChildProcess- private readonly tree: ProcessTree+private readonly inbox = new RuntimeInbox()+ private readonly output = new Set<OutputListener>()+ private readonly pendingMessages: Uint8Array[] = []+ private readonly address = commandAddress()+ private readonly token = randomUUID()+ private readonly server: Server+ private readonly sockets = new Set<Socket>()++ private tree: ProcessTree | null = null+ private socket: Socket | null = null+ private writes = Promise.resolve()+ private stopping = falsepublic constructor(command: string, directory: string) {- this.child = spawn(command, {+ let finish!: (ending: ServerRuntimeEnding) => void+ this.finished = new Promise(resolve => { finish = resolve })++ this.server = createServer(socket => this.accept(socket))+ this.server.on("error", error => {+ this.print("err", `${error.stack ?? error.message}\n`)+ if (this.tree) this.tree.stop()+ else {+ this.closeTransport().catch(() => undefined)+ finish({ code: 1, signal: null })+ }+ })+ this.server.once("listening", () => {+ // The token authenticates the Endpoint; POSIX permissions also keep+ // unrelated local users from opening the private transport.+ const protect = process.platform === "win32" ? Promise.resolve() : chmod(this.address, 0o600)+ protect.then(() => this.start(command, directory, finish)).catch(error => {+ this.print("err", `${error instanceof Error ? error.stack ?? error.message : String(error)}\n`)+ this.closeTransport().catch(() => undefined)+ finish({ code: 1, signal: null })+ })+ })+ this.server.listen({ path: this.address, readableAll: false, writableAll: false })+ }++ public send(event: string, ...values: unknown[]) {++ const message = messagepack.serialize([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 onOutput(listener: OutputListener) { this.output.add(listener) }++ public stop() {++ this.stopping = true+ this.tree?.stop()++ if (!this.tree) this.closeTransport().catch(() => undefined)+ }++ private start(command: string, directory: string, finish: (ending: ServerRuntimeEnding) => void) {++ if (this.stopping) return++ const child = spawn(command, {shell: true,detached: detachedProcessTree,cwd: directory,- stdio: ["ignore", "pipe", "pipe", "ipc"],- serialization: "advanced",- env: commandServerEnvironment(directory)+ stdio: ["ignore", "pipe", "pipe"],+ env: commandServerEnvironment(directory, process.env, this.address, this.token)})- if (typeof this.child.send !== "function") throw new Error("The server process has no IPC channel")+ this.tree = new ProcessTree(child, async (code, signal) => {+ await this.closeTransport()+ finish({ code, signal })+ })- let finish!: (ending: ServerRuntimeEnding) => void- this.finished = new Promise(resolve => { finish = resolve })- this.tree = new ProcessTree(this.child, (code, signal) => finish({ code, signal }))+ child.stdout?.on("data", chunk => this.print("out", String(chunk)))+ child.stderr?.on("data", chunk => this.print("err", String(chunk)))+ child.on("error", error => this.print("err", `${error.stack ?? error.message}\n`))- this.child.on("message", message => {+ if (this.stopping) this.tree.stop()+ }- const bytes = runtimeMessageBytes(message)+ private accept(candidate: Socket) {- if (bytes) this.inbox.receive(bytes)- })+ this.sockets.add(candidate)+ const reader = new FrameReader(maximumFrameSize)+ let authenticated = false++ candidate.on("data", chunk => {+ try {+ for (const frame of reader.read(typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk)) {+ if (!authenticated) {+ authenticated = new TextDecoder().decode(frame) === this.token+ if (!authenticated || this.socket) return candidate.destroy()- this.child.on("error", () => undefined)+ this.socket = candidate+ for (const message of this.pendingMessages.splice(0)) this.write(message)+ continue+ }++ this.inbox.receive(frame)+ }+ } catch { candidate.destroy() }+ })+ candidate.on("error", () => undefined)+ candidate.once("close", () => {+ this.sockets.delete(candidate)+ if (this.socket === candidate) this.socket = null+ })}- public send(event: string, ...values: unknown[]) { this.child.send!(messagepack.serialize([event, ...values])) }- public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }+ private write(message: Uint8Array) {- public onOutput(listener: OutputListener) {+ const socket = this.socket+ if (!socket) return- this.child.stdout?.on("data", chunk => listener("out", String(chunk)))- this.child.stderr?.on("data", chunk => listener("err", String(chunk)))+ this.writes = this.writes.then(() => writeFrame(socket, message, maximumFrameSize))+ this.writes.catch(() => undefined)}- public stop() { this.tree.stop() }+ private print(stream: Stream, text: string) {+ for (const listener of this.output) listener(stream, text)+ }++ private async closeTransport() {++ for (const socket of this.sockets) socket.destroy()+ this.sockets.clear()+ this.socket = null++ if (this.server.listening) {+ await new Promise<void>(resolve => this.server.close(() => resolve()))+ }++ if (process.platform !== "win32") await rm(this.address, { force: true }).catch(() => undefined)+ }}-export function commandServerEnvironment(directory: string, environment: NodeJS.ProcessEnv = process.env) {+export function commandServerEnvironment(+ directory: string,+ environment: NodeJS.ProcessEnv = process.env,+ address?: string,+ token?: string+): NodeJS.ProcessEnv {const key = Object.keys(environment).find(name => name.toLowerCase() === "path") ?? "PATH"const inherited = environment[key]- return { ...environment, [key]: [join(directory, "node_modules", ".bin"), inherited].filter(Boolean).join(delimiter) }+ return {+ ...environment,+ [key]: [join(directory, "node_modules", ".bin"), inherited].filter(Boolean).join(delimiter),+ ...(address ? { PHRESHOS_SERVER_ADDRESS: address } : {}),+ ...(token ? { PHRESHOS_SERVER_TOKEN: token } : {})+ }+}++function commandAddress() {++ // Unix socket addresses have a small platform limit; keep the basename+ // short enough even when the host's temporary directory is already long.+ const identity = `ps-${randomUUID().replaceAll("-", "")}`++ return process.platform === "win32" ? `\\\\.\\pipe\\${identity}` : join(tmpdir(), `${identity}.sock`)}diff --git a/tests/worker-runtime.test.ts b/tests/worker-runtime.test.tsindex 436ef21..232bf15 100644--- a/tests/worker-runtime.test.ts+++ b/tests/worker-runtime.test.ts@@ -29,6 +29,7 @@ test("server runtime contract", async () => {const codecDirectory = join(directory, "codec")const codecEntry = join(codecDirectory, "sandbox-codec.js")const codec = pathToFileURL(createRequire(import.meta.url).resolve("@the-link/messagepack")).href+ const framing = pathToFileURL(createRequire(import.meta.url).resolve("@the-link/ipc/framing")).hrefconst ready = [...messagepack.serialize(["boundary", "ready"])]const urlResult = [...messagepack.serialize(["url-result", "https://example.test/runtime"])]const bytesResult = [...messagepack.serialize(["bytes-result", [1, 2, 3]])]@@ -101,21 +102,22 @@ test("server runtime contract", async () => {await writeFile(commandEntry, `import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}+ import { FrameReader, writeFrame } from ${JSON.stringify(framing)}+ import { connect } from "node:net"console.log("command output")- process.send?.(encode(["boundary", "ready"]))- process.on("message", message => {- const [event, value] = decode(bytes(message))- if (event === "probe") process.send?.(encode(["probe-result", value]))+ const socket = connect(process.env.PHRESHOS_SERVER_ADDRESS)+ const reader = new FrameReader(16 * 1024 * 1024)+ socket.once("connect", async () => {+ await writeFrame(socket, new TextEncoder().encode(process.env.PHRESHOS_SERVER_TOKEN), 16 * 1024 * 1024)+ await writeFrame(socket, encode(["boundary", "ready"]), 16 * 1024 * 1024)+ })+ socket.on("data", async chunk => {+ for (const frame of reader.read(chunk)) {+ const [event, value] = decode(frame)+ if (event === "probe") await writeFrame(socket, encode(["probe-result", value]), 16 * 1024 * 1024)+ }})-- function bytes(value) {- if (value instanceof Uint8Array) return value- const record = value- const result = new Uint8Array(Object.keys(record).length)- for (let index = 0; index < result.length; index++) result[index] = record[index]- return result- }`)await build({@@ -171,7 +173,10 @@ test("server runtime contract", async () => {command.onMessage((event, ...values) => commandMessages.push([event, ...values]))command.onOutput((stream, text) => commandOutput.push([stream, text]))- await until(() => commandMessages.some(message => message[0] === "boundary" && message[1] === "ready"))+ await until(() => commandMessages.some(message => message[0] === "boundary" && message[1] === "ready")).catch(error => {+ const runtimeOutput = commandOutput.map(([stream, text]) => `${stream}: ${text}`).join("")+ throw new Error(`${error instanceof Error ? error.message : String(error)}${runtimeOutput ? `\n${runtimeOutput}` : ""}`)+ })command.send("probe", 42)