Skip to content

An open-source, self-hosted system for apps built with web technologies.

feat: own server worker execution

zohayrslileh2c8c679d0fee
diff --git a/README.md b/README.md
index b8f7faa..85820f0 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,8 @@ A Program is the stable unit installed or attached to the System. A Process is
one running incarnation of that Program. Its Endpoints are the places where its
code participates in the system:
-- A Server Endpoint runs Node.js code on the host.
+- A Server Endpoint runs JavaScript on the host, either in its own
+ operating-system process tree or in a Worker owned by the System.
- A Client Endpoint runs in a sandboxed iframe on the desktop and owns its
Window.
- Every Endpoint communicates through explicit Traffic.
@@ -36,6 +37,14 @@ Endpoints are silent by default. Data, events, permissions, and host state do
not enter an Endpoint merely because it exists; Program code must explicitly
request or subscribe to what it needs.
+A Program selects exactly one Server execution mode. `startCommand` preserves
+an arbitrary shell command and its independently supervised process tree.
+`entryFile` resolves a module inside the Program's Server files and runs it in a
+System-owned Worker, avoiding a separate Node.js process. Both modes expose the
+same Process and Server SDK contracts. A Worker has no independent working
+directory and is not a security boundary; a catastrophic Worker or native
+module failure can affect the System process.
+
## System boundaries
The server owns authoritative state and Process lifecycle. The desktop owns its
diff --git a/package.json b/package.json
index 210b504..cbf5786 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"build": "vite-node scripts/build.ts",
"start": "node --run build && node dist/server/main.js",
"pack": "node --run build && vite-node scripts/pack.ts",
- "verify:contracts": "vite-node scripts/verify-client-launch.mjs && vite-node scripts/verify-process-find-or-create.mjs && vite-node scripts/verify-client-surface.mjs && vite-node scripts/verify-window-geometry.mjs && vite-node scripts/verify-readiness.mjs && vite-node scripts/verify-storage.mjs && vite-node scripts/verify-uploads.mjs && vite-node scripts/verify-endpoint-services.mjs && vite-node scripts/verify-program-install.mjs && vite-node scripts/verify-host-traffic.mjs && vite-node scripts/verify-gateway-address.mjs && vite-node scripts/verify-gateway.mjs && vite-node scripts/verify-appearance.mjs",
+ "verify:contracts": "vite-node scripts/verify-client-launch.mjs && vite-node scripts/verify-process-find-or-create.mjs && vite-node scripts/verify-client-surface.mjs && vite-node scripts/verify-window-geometry.mjs && vite-node scripts/verify-readiness.mjs && vite-node scripts/verify-storage.mjs && vite-node scripts/verify-uploads.mjs && vite-node scripts/verify-endpoint-services.mjs && vite-node scripts/verify-program-install.mjs && vite-node scripts/verify-host-traffic.mjs && vite-node scripts/verify-gateway-address.mjs && vite-node scripts/verify-gateway.mjs && vite-node scripts/verify-appearance.mjs && vite-node scripts/verify-worker-runtime.mjs",
"verify:distribution": "node scripts/verify-distribution.mjs",
"verify": "node --run check && node --run verify:contracts && node --run verify:distribution"
},
diff --git a/scripts/verify-worker-runtime.mjs b/scripts/verify-worker-runtime.mjs
new file mode 100644
index 0000000..f987f4e
--- /dev/null
+++ b/scripts/verify-worker-runtime.mjs
@@ -0,0 +1,68 @@
+import assert from "node:assert/strict"
+import { mkdtemp, rm, writeFile } from "node:fs/promises"
+import { tmpdir } from "node:os"
+import { join, resolve } from "node:path"
+import { pathToFileURL } from "node:url"
+import { decode, encode } from "@msgpack/msgpack"
+import { WorkerServerRuntime } from "../source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts"
+import Program from "../source/server/core/link-manager/auth-manager/program-manager/program.ts"
+
+const directory = await mkdtemp(join(tmpdir(), "phresh-worker-runtime-"))
+const entry = join(directory, "server.mjs")
+const codec = pathToFileURL(resolve("node_modules/@msgpack/msgpack/dist.esm/index.mjs")).href
+
+await writeFile(entry, `
+import { parentPort } from "node:worker_threads"
+import { decode, encode } from ${JSON.stringify(codec)}
+
+console.log("worker output")
+parentPort.postMessage(encode(["boundary", "ready"]))
+parentPort.on("message", message => {
+ const [event, value] = decode(message)
+ if (event === "probe") parentPort.postMessage(encode(["probe-result", value]))
+})
+`)
+
+try {
+ const program = new Program({ identity: "worker-verification", server: { location: directory, entryFile: "server.mjs" } })
+
+ await program.validate()
+
+ assert.equal(program.serverEntryPath, entry)
+
+ assert.throws(() => new Program({ identity: "worker-conflict", server: { location: directory, startCommand: "node main.js", entryFile: "server.mjs" } }))
+ assert.throws(() => new Program({ identity: "worker-escape", server: { location: directory, entryFile: "../server.mjs" } }))
+
+ const runtime = new WorkerServerRuntime(entry)
+ const messages = []
+ const output = []
+
+ runtime.onMessage(message => messages.push(decode(message)))
+ runtime.onOutput((stream, text) => output.push([stream, text]))
+
+ await until(() => messages.some(message => message[0] === "boundary" && message[1] === "ready"))
+
+ runtime.send(encode(["probe", 42]))
+
+ await until(() => messages.some(message => message[0] === "probe-result"))
+ await until(() => output.some(([stream, text]) => stream === "out" && text.includes("worker output")))
+
+ assert.deepEqual(messages.find(message => message[0] === "probe-result"), ["probe-result", 42])
+
+ runtime.stop()
+
+ const ending = await runtime.finished
+
+ assert.equal(ending.signal, null)
+} finally {
+ await rm(directory, { recursive: true, force: true })
+}
+
+async function until(condition, timeout = 2_000) {
+ const began = Date.now()
+
+ while (!condition()) {
+ if (Date.now() - began >= timeout) throw new Error(`Worker verification timed out after ${timeout}ms`)
+ await new Promise(resolve => setTimeout(resolve, 10))
+ }
+}
diff --git a/source/libs/the-link/plugins/process-link/process-link.ts b/source/libs/the-link/plugins/process-link/process-link.ts
deleted file mode 100644
index 5974ca0..0000000
--- a/source/libs/the-link/plugins/process-link/process-link.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { ChildProcess } from "child_process"
-import TheLink from "../../the-link"
-import { defaultDeserialize, defaultSerialize, type Deserialize, type Serialize } from "../../codec"
-import { receiveBytes } from "./transport"
-
-/**
- * Process communication adapter using Node.js IPC.
- *
- * Provides bidirectional event routing between Node.js processes through an
- * active IPC channel. Incoming IPC messages are published through the inbound
- * tunnel, and outbound tunnel events are sent to the target process.
- *
- * Messages carry TheLink's `[event, ...values]` envelope as bytes.
- *
- * @example
- * ```typescript
- * // Child process
- * const childLink = new ProcessLink()
- * childLink.$inbound.subscribe("job:start", startJob)
- *
- * // Parent process
- * const parentLink = new ProcessLink(worker)
- * await parentLink.$outbound.publish("job:start", { id: 1 })
- * ```
- */
-export default class ProcessLink extends TheLink {
-
- /**
- * Target process used for IPC communication.
- *
- * Can be a ChildProcess instance in a parent process or the global process
- * object in a child process. The target must expose `send`.
- */
- private readonly target: NodeJS.Process | ChildProcess
-
- private readonly serialize: Serialize
-
- private readonly deserialize: Deserialize
-
- /**
- * Initialize a ProcessLink with a target IPC process.
- *
- * @param target Process to communicate with, defaults to the current process
- * @throws Error when the target does not have an active IPC channel
- */
- public constructor(target: NodeJS.Process | ChildProcess = process, serialize: Serialize = defaultSerialize, deserialize: Deserialize = defaultDeserialize) {
-
- super()
-
- // Store the IPC target for message delivery.
- this.target = target
-
- this.serialize = serialize
-
- this.deserialize = deserialize
-
- if (typeof this.target.send !== "function") throw new Error("IPC channel not available. Ensure the process was spawned with IPC support.")
-
- // Route IPC messages from the target into the local inbound tunnel.
- this.target.on("message", this.messageHandler.bind(this))
-
- // Send outbound tunnel events to the target process automatically.
- this.$outbound.forwardTo(this.publishHandler.bind(this))
- }
-
- /**
- * Process an incoming IPC message from the target process.
- *
- * Ignores messages that do not match TheLink's `[event, ...values]`
- * protocol shape.
- *
- * @param message Raw IPC message received from the process
- */
- private async messageHandler(message: unknown) {
-
- let decoded: unknown
-
- try { decoded = this.deserialize(receiveBytes(message)) }
-
- catch { return }
-
- if (Array.isArray(decoded) && typeof decoded[0] === "string") {
-
- // Decode the event envelope after validating its protocol shape.
- const [event, ...values] = decoded as [string, ...unknown[]]
-
- await this.$inbound.publish(event, ...values)
- }
- }
-
- /**
- * Publish an outbound tunnel event through the IPC channel.
- *
- * @param event Event identifier for the remote process
- * @param values Event payload values sent over IPC
- */
- private publishHandler(event: string, ...values: unknown[]) {
-
- // The non-null assertion is guarded by the constructor IPC check.
- this.target.send!(this.serialize([event, ...values]))
- }
-}
diff --git a/source/libs/the-link/plugins/process-link/transport.ts b/source/libs/the-link/plugins/process-link/transport.ts
deleted file mode 100644
index a0529ca..0000000
--- a/source/libs/the-link/plugins/process-link/transport.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import type { Bytes } from "../../codec"
-
-export const receiveBytes = (value: unknown): Bytes => {
-
- if (value instanceof Uint8Array) return Uint8Array.from(value)
-
- if (value instanceof ArrayBuffer) return new Uint8Array(value)
-
- if (ArrayBuffer.isView(value)) return Uint8Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))
-
- throw new TypeError("The process message is not binary")
-}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 44c1f24..55bd12a 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -1,6 +1,5 @@
import { Connect, Subscribe } from "@libs/the-link/decorators/escript"
import { uploadLimit } from "@server/core/upload-manager"
-import { ChildProcess } from "node:child_process"
import { type Launch, type LaunchClient, type Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import { Layer } from "../program-manager/config"
@@ -8,7 +7,6 @@ import Window, { Position, Size } from "./window"
import TheLink from "@libs/the-link/the-link"
import { Transmitted } from "@libs/messagepack"
import AuthManager from "../auth-manager"
-import { signalProcessTree } from "@libs/process-tree"
import Process, { type HostedProcess, type ProcessLaunch } from "./process"
import ServerProcessBoundary from "./server-process-boundary"
import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
@@ -20,6 +18,7 @@ import EndpointEvents from "./endpoint-events"
import EndpointServices from "./endpoint-services"
import OutsideQuestions from "./outside-questions"
import { isPermissionName, isServiceKey, type PermissionName, type WindowGeometry, type WindowLayer } from "@phreshos/core"
+import type { ServerRuntime } from "./server-runtime"
/**
* The core's processes: the wire and the collection. Each process owns
@@ -220,8 +219,7 @@ export default class ProcessManager extends TheLink {
))
}
- // A server runtime is a ProcessLink. Speaking through its outbound
- // tunnel keeps IPC as a transport detail and leaves a stopped child as
+ // The boundary owns its server runtime transport. A stopped child remains
// fire-and-forget: there is no receiver to promise once it has gone.
private say(server: ServerProcessBoundary | null | undefined, event: string, ...values: unknown[]) {
@@ -718,9 +716,9 @@ export default class ProcessManager extends TheLink {
else await this.transition(process, finish).catch(() => undefined)
}
- private activateServer(process: Process, child: ChildProcess) {
+ private activateServer(process: Process, runtime: ServerRuntime) {
- const server = process.startServer(child,
+ const server = process.startServer(runtime,
(boundary, code, signal) => this.serverEnded(process, boundary, code, signal),
@@ -741,18 +739,18 @@ export default class ProcessManager extends TheLink {
return new Window(shown, shape.position, shape.size, ++this.highest, shape.minimize)
}
- public async register(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, child: ChildProcess | null, client: boolean, shape: Shape | null, parent: Process | null, configure?: (process: Process) => void) {
+ public async register(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, runtime: ServerRuntime | null, client: boolean, shape: Shape | null, parent: Process | null, configure?: (process: Process) => void) {
if (this.processes.has(identity)) {
- if (child) signalProcessTree(child, "SIGKILL")
+ runtime?.stop()
throw new Error("The host already knows this process identity")
}
if (name !== null && [...this.processes.values()].some(process => process.program === program && process.name === name)) {
- if (child) signalProcessTree(child, "SIGKILL")
+ runtime?.stop()
throw new Error("This program already has a process with that name")
}
@@ -782,7 +780,7 @@ export default class ProcessManager extends TheLink {
if (client && window) process.startClient(window)
- if (child) this.activateServer(process, child)
+ if (runtime) this.activateServer(process, runtime)
// The subject first, which is what scopes a listener without
// anything being checked: a kit's `Events` refuses a value whose
@@ -894,13 +892,13 @@ export default class ProcessManager extends TheLink {
await process.program.validate()
- const child = this.authManager.programManager.spawnServer(process.program)
+ const runtime = this.authManager.programManager.serverRuntime(process.program)
- try { this.activateServer(process, child) }
+ try { this.activateServer(process, runtime) }
catch (error) {
- signalProcessTree(child, "SIGKILL")
+ runtime.stop()
throw error
}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index 1f3d528..926a399 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -1,7 +1,6 @@
import { Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import Window, { Position, Size } from "./window"
-import { ChildProcess } from "node:child_process"
import { Transmitted } from "@libs/messagepack"
import ServerProcessBoundary from "./server-process-boundary"
import HostTraffic from "./host-traffic"
@@ -9,6 +8,7 @@ import ClientState from "./client-state"
import { randomUUID } from "node:crypto"
import { type Layer, type PermissionName } from "@phreshos/core"
import Tunnel from "@libs/the-link/tunnel"
+import type { ServerRuntime } from "./server-runtime"
/**
* One live execution of a Program.
@@ -22,9 +22,9 @@ import Tunnel from "@libs/the-link/tunnel"
* owns. The Process remains the stable aggregate around those incarnations
* and must always have at least one live endpoint.
*
- * The child handle lives here beside the transmitted values and is left
- * out of toJSON: what crosses is declared, so a host-only handle needs no
- * second structure to hide in.
+ * The Server runtime boundary lives here beside the transmitted values and is
+ * left out of toJSON: what crosses is declared, so a host-only execution
+ * mechanism needs no second structure to hide in.
*/
export default class Process {
@@ -112,13 +112,13 @@ export default class Process {
this.hostTraffic = hostTraffic
}
- public startServer(child: ChildProcess, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel) {
+ public startServer(runtime: ServerRuntime, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel) {
if (this.server) return this.server
let boundary!: ServerProcessBoundary
- boundary = new ServerProcessBoundary(child, this.program.client !== null, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance)
+ boundary = new ServerProcessBoundary(runtime, this.program.client !== null, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance)
this.server = boundary
@@ -247,11 +247,11 @@ export default class Process {
}
}
- // Said once, however many ways it could be said: a child's exit
+ // Said once, however many ways it could be said: a Server runtime's exit
// removes the record, and removing the record is itself an ending.
// The result remains terminal state rather than becoming lost history:
// process creation announces externally before every internal owner has
- // finished attaching, and a fast child can exit during that announcement.
+ // finished attaching, and a fast runtime can exit during that announcement.
public ended(code: number | null, signal: NodeJS.Signals | null) {
if (this.ending) return
diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
index 2b80f22..01e166b 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/server-process-boundary.ts
@@ -1,6 +1,4 @@
-import ProcessLink from "@libs/the-link/plugins/process-link/process-link"
-import ProcessTree from "@libs/process-tree"
-import { type ChildProcess } from "node:child_process"
+import TheLink from "@libs/the-link/the-link"
import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
import HostTraffic from "./host-traffic"
import EndpointEvents from "./endpoint-events"
@@ -8,15 +6,16 @@ import EndpointServices, { type ServiceScope } from "./endpoint-services"
import type { ServiceKey } from "@phreshos/core"
import Tunnel from "@libs/the-link/tunnel"
import messagepack from "@libs/messagepack"
+import type { ServerRuntime, Stream } from "./server-runtime"
/**
* The boundary around one server execution endpoint.
*
- * The child speaks only here. Application events cross only when its SDK has
+ * The Server runtime speaks only here. Application events cross only when its SDK has
* registered an interest. Readiness travels out of the endpoint; the boundary
* never injects startup state into it.
*/
-export default class ServerProcessBoundary extends ProcessLink {
+export default class ServerProcessBoundary extends TheLink {
public ready = false
@@ -47,9 +46,7 @@ export default class ServerProcessBoundary extends ProcessLink {
private stopAppearance: (() => void) | null = null
- private readonly child: ChildProcess
-
- private readonly tree: ProcessTree
+ private readonly runtime: ServerRuntime
private readonly hostTraffic: HostTraffic
@@ -59,24 +56,31 @@ export default class ServerProcessBoundary extends ProcessLink {
public readonly finished: Promise<{ code: number | null, signal: NodeJS.Signals | null }>
- public constructor(child: ChildProcess, clientDeclared: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel) {
+ public constructor(runtime: ServerRuntime, clientDeclared: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel) {
- super(child, messagepack.serialize, messagepack.deserialize)
+ super()
this.clientDeclared = clientDeclared
- this.child = child
+ this.runtime = runtime
+
+ runtime.onMessage(message => { this.receive(message).catch(() => undefined) })
+
+ this.$outbound.forwardTo((event, ...values) => {
+
+ runtime.send(messagepack.serialize([event, ...values]))
+ })
let finish!: (ending: { code: number | null, signal: NodeJS.Signals | null }) => void
this.finished = new Promise(resolve => { finish = resolve })
- this.tree = new ProcessTree(child, async (code, signal) => {
+ runtime.finished.then(async ({ code, signal }) => {
try { await ended(code, signal) }
finally { finish({ code, signal }) }
- })
+ }).catch(() => undefined)
this.hostTraffic = hostTraffic
@@ -84,11 +88,25 @@ export default class ServerProcessBoundary extends ProcessLink {
this.unanswered = unanswered
- child.on("error", () => undefined)
-
this.$inbound.subscribe("boundary", (...values) => this.control(values))
}
+ /** Admit one binary envelope from this exact Server runtime. */
+ private async receive(message: unknown) {
+
+ let decoded: unknown
+
+ try { decoded = messagepack.deserialize(receiveBytes(message)) }
+
+ catch { return }
+
+ if (!Array.isArray(decoded) || typeof decoded[0] !== "string") return
+
+ const [event, ...values] = decoded as [string, ...unknown[]]
+
+ await this.$inbound.publish(event, ...values)
+ }
+
/** Deliver one routed envelope only when this endpoint requested it. */
public async deliver(route: string, ...values: unknown[]) {
@@ -287,14 +305,12 @@ export default class ServerProcessBoundary extends ProcessLink {
public stop() {
- this.tree.stop()
+ this.runtime.stop()
}
public onOutput(listener: (stream: Stream, text: string) => void) {
- this.child.stdout?.on("data", chunk => listener("out", String(chunk)))
-
- this.child.stderr?.on("data", chunk => listener("err", String(chunk)))
+ this.runtime.onOutput(listener)
}
private control(values: unknown[]) {
@@ -499,6 +515,17 @@ interface WaitingQuestion {
question: string
}
-export type Stream = "out" | "err"
+export type { Stream } from "./server-runtime"
export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
+
+function receiveBytes(value: unknown) {
+
+ if (value instanceof Uint8Array) return Uint8Array.from(value)
+
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
+
+ if (ArrayBuffer.isView(value)) return Uint8Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))
+
+ throw new TypeError("The server process message is not binary")
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts b/source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts
new file mode 100644
index 0000000..0594350
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts
@@ -0,0 +1,181 @@
+import ProcessTree from "@libs/process-tree"
+import { spawn, type ChildProcess } from "node:child_process"
+import { Worker } from "node:worker_threads"
+import { join } from "node:path"
+
+export interface ServerRuntime {
+
+ readonly finished: Promise<Ending>
+
+ send(message: Uint8Array): void
+
+ onMessage(listener: (message: unknown) => void): void
+
+ onOutput(listener: OutputListener): void
+
+ stop(): void
+}
+
+/** One Server running as an isolated operating-system process tree. */
+export class CommandServerRuntime implements ServerRuntime {
+
+ public readonly finished: Promise<Ending>
+
+ private readonly child: ChildProcess
+
+ private readonly tree: ProcessTree
+
+ private readonly inbox = new RuntimeInbox()
+
+ public constructor(command: string, directory: string) {
+
+ this.child = spawn(command, {
+
+ shell: true,
+
+ detached: true,
+
+ cwd: directory,
+
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
+
+ serialization: "advanced",
+
+ env: {
+
+ ...process.env,
+
+ PATH: `${join(process.cwd(), "node_modules", ".bin")}:${process.env.PATH}`
+ }
+ })
+
+ if (typeof this.child.send !== "function") throw new Error("The server process has no IPC channel")
+
+ let finish!: (ending: Ending) => void
+
+ this.finished = new Promise(resolve => { finish = resolve })
+
+ this.tree = new ProcessTree(this.child, (code, signal) => finish({ code, signal }))
+
+ this.child.on("message", message => this.inbox.receive(message))
+
+ this.child.on("error", () => undefined)
+ }
+
+ public send(message: Uint8Array) { this.child.send!(message) }
+
+ public onMessage(listener: (message: unknown) => void) { this.inbox.listen(listener) }
+
+ public onOutput(listener: OutputListener) {
+
+ this.child.stdout?.on("data", chunk => listener("out", String(chunk)))
+
+ this.child.stderr?.on("data", chunk => listener("err", String(chunk)))
+ }
+
+ public stop() { this.tree.stop() }
+}
+
+/** One JavaScript Server running as an isolate inside the System process. */
+export class WorkerServerRuntime implements ServerRuntime {
+
+ public readonly finished: Promise<Ending>
+
+ private readonly worker: Worker
+
+ private readonly output = new Set<OutputListener>()
+
+ private readonly pendingOutput: [Stream, string][] = []
+
+ private clearingPendingOutput = false
+
+ private readonly inbox = new RuntimeInbox()
+
+ public constructor(entry: string) {
+
+ this.worker = new Worker(entry, { stdout: true, stderr: true })
+
+ this.finished = new Promise(resolve => {
+
+ this.worker.once("exit", code => resolve({ code, signal: null }))
+ })
+
+ this.worker.on("message", message => this.inbox.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(message: Uint8Array) { this.worker.postMessage(message) }
+
+ public onMessage(listener: (message: unknown) => void) { this.inbox.listen(listener) }
+
+ public onOutput(listener: OutputListener) {
+
+ this.output.add(listener)
+
+ for (const [stream, text] of this.pendingOutput) listener(stream, text)
+
+ if (this.pendingOutput.length && !this.clearingPendingOutput) {
+
+ this.clearingPendingOutput = true
+
+ queueMicrotask(() => {
+
+ this.pendingOutput.splice(0)
+
+ this.clearingPendingOutput = false
+ })
+ }
+ }
+
+ public stop() { this.worker.terminate().catch(() => undefined) }
+
+ private print(stream: Stream, text: string) {
+
+ if (this.output.size === 0) {
+
+ if (this.pendingOutput.length < maximumPendingOutput) this.pendingOutput.push([stream, text])
+
+ return
+ }
+
+ for (const listener of this.output) listener(stream, text)
+ }
+}
+
+class RuntimeInbox {
+
+ private listener: ((message: unknown) => void) | null = null
+
+ private readonly pending: unknown[] = []
+
+ public receive(message: unknown) {
+
+ if (this.listener) this.listener(message)
+
+ else if (this.pending.length < maximumPendingMessages) this.pending.push(message)
+ }
+
+ public listen(listener: (message: unknown) => void) {
+
+ if (this.listener) throw new Error("The server runtime already has a message listener")
+
+ this.listener = listener
+
+ for (const message of this.pending.splice(0)) listener(message)
+ }
+}
+
+export type Stream = "out" | "err"
+
+type OutputListener = (stream: Stream, text: string) => void
+
+type Ending = { code: number | null, signal: NodeJS.Signals | null }
+
+const maximumPendingMessages = 256
+
+const maximumPendingOutput = 256
diff --git a/source/server/core/link-manager/auth-manager/program-manager/config.ts b/source/server/core/link-manager/auth-manager/program-manager/config.ts
index 677e1e4..6410ea1 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/config.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/config.ts
@@ -53,7 +53,7 @@ interface Described {
storage?: string
}
-export interface ServerConfig {
+interface ServerDescription {
// Where this half is. Empty names the program's own root.
location: string
@@ -67,10 +67,23 @@ export interface ServerConfig {
// Run while uninstalling, before the installed files are removed.
uninstallCommand?: string
- // Run to start a process, in that directory.
- startCommand: string
}
+export type ServerConfig = ServerDescription & ({
+
+ // Run an isolated operating-system process through the shell.
+ startCommand: string
+
+ entryFile?: never
+
+} | {
+
+ startCommand?: never
+
+ // Load this module as a worker owned by the System.
+ entryFile: string
+})
+
export interface ClientConfig {
// Where this half is: a directory holding index.html, or a URL.
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index 318f746..04b0ef1 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -1,6 +1,5 @@
import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
import { Connect } from "@libs/the-link/decorators/escript"
-import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import TheLink from "@libs/the-link/the-link"
import SqliteDatabase from "@libs/sqlite-database"
@@ -22,6 +21,7 @@ import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
import { readStartup, removeStartup, writeStartup } from "./startup"
import { readPermissions, writePermissions } from "./permissions"
+import { CommandServerRuntime, WorkerServerRuntime } from "../process-manager/server-runtime"
const maximumProcessesPerProgram = 20
@@ -1232,12 +1232,12 @@ export default class ProgramManager extends TheLink {
// server incarnation attaches to the same Process-level listeners.
const logs = this.logsOf(program)
- const child = server ? this.spawnServer(program) : null
+ const runtime = server ? this.serverRuntime(program) : null
// Lifecycle consumers are attached before either initial endpoint is
// activated, so even a server command that exits immediately has a
// complete output and exit record.
- await this.authManager.processManager.register(identity, launch.name ?? null, program, options, resolved.intent, child, client !== null, shape, parent, record => {
+ await this.authManager.processManager.register(identity, launch.name ?? null, program, options, resolved.intent, runtime, client !== null, shape, parent, record => {
record.onServerStart(server => server.onOutput((stream, text) => logs.printed(identity, stream === "err" ? "stderr" : "stdout", text)))
@@ -1256,55 +1256,18 @@ export default class ProgramManager extends TheLink {
return identity
}
- /** Starts one fresh server endpoint incarnation for a Process. */
- public spawnServer(program: Program) {
+ /** Creates one fresh execution runtime for a Server endpoint. */
+ public serverRuntime(program: Program) {
const server = program.server
if (!server) throw new Error("This program declared no server half")
- return spawn(server.startCommand, {
-
- shell: true,
-
- // One Process owns everything its server command starts.
- // A separate operating-system group makes that ownership real:
- // closing the Process can end the whole tree instead of only the
- // shell at its root.
- detached: true,
-
- cwd: program.serverPath!,
-
- // Always piped, because the system is always the audience.
- //
- // This was piped only when somebody was listening: a pipe
- // nobody reads fills at about 64 KB and the program stops
- // mid-write, and `stdio` is decided here and once, so an
- // audience arriving later heard nothing. Both halves of that
- // stopped being true when the core began keeping what a
- // program says — it reads, so the pipe drains, and a
- // listener no longer has to have been there at the start.
- //
- // Which also ends the difference between the two ways of
- // running one: an attached program's output is no longer a
- // road of its own, it is the same drain with somebody else
- // also watching.
- stdio: ["ignore", "pipe", "pipe", "ipc"],
-
- // MessagePack envelopes remain bytes across Node's IPC boundary.
- serialization: "advanced",
-
- // Only what the operating system needs to run a command.
- // No program data travels this way: options and places are
- // asked for over the channel, which is the one road a
- // client half can walk too.
- env: {
-
- ...process.env,
-
- PATH: `${join(process.cwd(), "node_modules", ".bin")}:${process.env.PATH}`
- }
- })
+ return server.startCommand !== undefined
+
+ ? new CommandServerRuntime(server.startCommand, program.serverPath!)
+
+ : new WorkerServerRuntime(program.serverEntryPath!)
}
/** Resolves and validates one client endpoint incarnation. */
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
index 0e886c5..7edf4ce 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -1,6 +1,6 @@
import { ClientConfig, isValue, kebab, layers, Position, ProgramConfig, ServerConfig, Size } from "./config"
-import { existsSync, readFileSync, statSync } from "node:fs"
-import { dirname, isAbsolute, resolve } from "node:path"
+import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
+import { dirname, isAbsolute, normalize, relative, resolve, sep } from "node:path"
import { spawn } from "node:child_process"
import { randomUUID } from "node:crypto"
import { validateIcon } from "./icon"
@@ -158,6 +158,13 @@ export default class Program {
return this.config.server ? this.place(this.config.server.location) : null
}
+ public get serverEntryPath() {
+
+ const entry = this.config.server?.entryFile
+
+ return entry && this.serverPath ? resolve(this.serverPath, entry) : null
+ }
+
public get clientPath() {
return this.config.client && !this.clientUrl ? this.place(this.config.client.location) : null
@@ -252,6 +259,12 @@ export default class Program {
if (server && !directory(server)) throw new Error(`The server directory is not there: ${server}`)
+ const entry = this.serverEntryPath
+
+ if (entry && !file(entry)) throw new Error(`The server worker entry file is not there: ${entry}`)
+
+ if (server && entry && !contained(server, entry)) throw new Error("The server worker entry file leaves its Server directory")
+
const client = this.clientPath
if (client && !directory(client)) throw new Error(`The client directory is not there: ${client}`)
@@ -359,7 +372,7 @@ function coherent(config: ProgramConfig) {
if (!(config.server && (config.server.start ?? true)) && !(config.client && (config.client.start ?? true))) throw new Error("A Program's default Process must start a server endpoint, a client endpoint, or both")
- if (config.server && (typeof config.server.startCommand !== "string" || config.server.startCommand.length === 0)) throw new Error("A server half must declare a start command")
+ if (config.server) execution(config.server)
if (config.server?.installCommand !== undefined && typeof config.server.installCommand !== "string") throw new Error("A server half's install command must be text")
@@ -388,8 +401,35 @@ function coherent(config: ProgramConfig) {
return config
}
-type Resolved<Half extends { start?: boolean }> = Omit<Half, "start"> & {
- start: boolean
+type Resolved<Half extends { start?: boolean }> = Half extends unknown ? Omit<Half, "start"> & { start: boolean } : never
+
+function execution(server: { startCommand?: unknown, entryFile?: unknown }) {
+
+ if ((server.startCommand === undefined) === (server.entryFile === undefined)) throw new Error("A server half must declare exactly one startCommand or entryFile")
+
+ if (server.startCommand !== undefined && (typeof server.startCommand !== "string" || server.startCommand.trim().length === 0)) throw new Error("A server half's startCommand must be non-empty text")
+
+ if (server.entryFile !== undefined && (typeof server.entryFile !== "string" || server.entryFile.trim().length === 0 || !containedEntry(server.entryFile))) throw new Error("A server half's entryFile must be a non-empty path inside its Server directory")
+}
+
+function containedEntry(entry: string) {
+
+ if (isAbsolute(entry)) return false
+
+ const path = normalize(entry)
+
+ return path !== ".." && !path.startsWith(`..${sep}`)
+}
+
+function contained(root: string, path: string) {
+
+ const from = realpathSync(root)
+
+ const to = realpathSync(path)
+
+ const relationship = relative(from, to)
+
+ return relationship !== ".." && !relationship.startsWith(`..${sep}`) && !isAbsolute(relationship)
}
function directory(path: string) {