Skip to content

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

Organize Server runtime View implementations

zohayrslileh84c8ff08161c
diff --git a/scripts/contracts/worker-runtime.ts b/scripts/contracts/worker-runtime.ts
index 65b1fcd..856eb0c 100644
--- a/scripts/contracts/worker-runtime.ts
+++ b/scripts/contracts/worker-runtime.ts
@@ -4,7 +4,8 @@ import { createRequire } from "node:module"
import { tmpdir } from "node:os"
import { delimiter, join } from "node:path"
import { pathToFileURL } from "node:url"
-import { CommandServerRuntime, commandServerEnvironment, WorkerServerRuntime } from "@server/view/server-runtime"
+import CommandServerRuntime, { commandServerEnvironment } from "@server/view/server-runtime/command"
+import WorkerServerRuntime from "@server/view/server-runtime/worker"
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
import type { ProgramConfig } from "@server/core/link-manager/auth-manager/program-manager/config"
diff --git a/source/server/view/server-runtime.ts b/source/server/view/server-runtime.ts
deleted file mode 100644
index 6e00299..0000000
--- a/source/server/view/server-runtime.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-import ProcessTree from "@libs/process-tree"
-import { spawn, type ChildProcess } from "node:child_process"
-import { Worker } from "node:worker_threads"
-import { delimiter, join } from "node:path"
-import messagepack from "@the-link/messagepack"
-import type { ServerRuntime, ServerRuntimeMessage, Stream } from "@server/core/server-runtime"
-import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
-
-/** Create the concrete host runtime selected by one Program declaration. */
-export default function serverRuntime(program: Program): ServerRuntime {
-
- const server = program.server
-
- if (!server) throw new Error("This program declared no server half")
-
- return server.startCommand !== undefined
-
- ? new CommandServerRuntime(server.startCommand, program.serverPath!)
-
- : new WorkerServerRuntime(program.serverEntryPath!)
-}
-
-/** 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: commandServerEnvironment(directory)
- })
-
- 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 => {
-
- const bytes = commandMessageBytes(message)
-
- if (bytes) this.inbox.receive(bytes)
- })
-
- this.child.on("error", () => undefined)
- }
-
- 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) }
-
- 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() }
-}
-
-/** Give a Server command the package-local tools belonging to its execution directory. */
-export function commandServerEnvironment(directory: string, environment: NodeJS.ProcessEnv = process.env) {
-
- 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)
- }
-}
-
-/** 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(event: string, ...values: unknown[]) { this.worker.postMessage(messagepack.serialize([event, ...values])) }
-
- public onMessage(listener: (event: string, ...values: 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: ((event: string, ...values: unknown[]) => void) | null = null
-
- private readonly pending: ServerRuntimeMessage[] = []
-
- public receive(message: unknown) {
-
- const bytes = commandMessageBytes(message)
-
- if (!bytes) return
-
- let decoded: unknown
-
- try { decoded = messagepack.deserialize(bytes) }
-
- catch { return }
-
- if (!Array.isArray(decoded) || typeof decoded[0] !== "string") return
-
- const envelope = decoded as ServerRuntimeMessage
-
- if (this.listener) this.listener(...envelope)
-
- else if (this.pending.length < maximumPendingMessages) this.pending.push(envelope)
- }
-
- public listen(listener: (event: string, ...values: 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)
- }
-}
-
-type OutputListener = (stream: Stream, text: string) => void
-
-type Ending = { code: number | null, signal: NodeJS.Signals | null }
-
-const maximumPendingMessages = 256
-
-const maximumPendingOutput = 256
-
-function commandMessageBytes(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))
-
- if (value === null || typeof value !== "object") return null
-
- const record = value as Record<string, unknown>
-
- const bytes = new Uint8Array(Object.keys(record).length)
-
- for (let index = 0; index < bytes.length; index++) {
-
- const byte = record[String(index)]
-
- if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) return null
-
- bytes[index] = byte
- }
-
- return bytes
-}
diff --git a/source/server/view/server-runtime/command.ts b/source/server/view/server-runtime/command.ts
new file mode 100644
index 0000000..f8fca23
--- /dev/null
+++ b/source/server/view/server-runtime/command.ts
@@ -0,0 +1,89 @@
+import ProcessTree from "@libs/process-tree"
+import type { ServerRuntime, ServerRuntimeEnding, Stream } from "@server/core/server-runtime"
+import messagepack from "@the-link/messagepack"
+import { spawn, type ChildProcess } from "node:child_process"
+import { delimiter, join } from "node:path"
+import RuntimeInbox, { runtimeMessageBytes } from "./inbox"
+
+type OutputListener = (stream: Stream, text: string) => void
+
+/** Represents one Server Endpoint as an isolated 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()
+
+ public constructor(command: string, directory: string) {
+
+ this.child = spawn(command, {
+
+ shell: true,
+
+ detached: true,
+
+ cwd: directory,
+
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
+
+ serialization: "advanced",
+
+ env: commandServerEnvironment(directory)
+ })
+
+ if (typeof this.child.send !== "function") throw new Error("The server process has no IPC channel")
+
+ let finish!: (ending: ServerRuntimeEnding) => void
+
+ this.finished = new Promise(resolve => { finish = resolve })
+
+ this.tree = new ProcessTree(this.child, (code, signal) => finish({ code, signal }))
+
+ this.child.on("message", message => {
+
+ const bytes = runtimeMessageBytes(message)
+
+ if (bytes) this.inbox.receive(bytes)
+ })
+
+ this.child.on("error", () => undefined)
+ }
+
+ 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)
+ }
+
+ 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() }
+}
+
+/** Gives a command the package-local executables belonging to its directory. */
+export function commandServerEnvironment(directory: string, environment: NodeJS.ProcessEnv = process.env) {
+
+ 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)
+ }
+}
diff --git a/source/server/view/server-runtime/inbox.ts b/source/server/view/server-runtime/inbox.ts
new file mode 100644
index 0000000..415f56b
--- /dev/null
+++ b/source/server/view/server-runtime/inbox.ts
@@ -0,0 +1,70 @@
+import type { ServerRuntimeMessage } from "@server/core/server-runtime"
+import messagepack from "@the-link/messagepack"
+
+type Listener = (event: string, ...values: unknown[]) => void
+
+const maximumPendingMessages = 256
+
+/** Preserves ordered runtime messages until the View installs their sole listener. */
+export default class RuntimeInbox {
+
+ private listener: Listener | null = null
+
+ private readonly pending: ServerRuntimeMessage[] = []
+
+ public receive(message: unknown) {
+
+ const bytes = runtimeMessageBytes(message)
+
+ if (!bytes) return
+
+ let decoded: unknown
+
+ try { decoded = messagepack.deserialize(bytes) }
+
+ catch { return }
+
+ if (!Array.isArray(decoded) || typeof decoded[0] !== "string") return
+
+ const envelope = decoded as ServerRuntimeMessage
+
+ if (this.listener) this.listener(...envelope)
+
+ else if (this.pending.length < maximumPendingMessages) this.pending.push(envelope)
+ }
+
+ public listen(listener: Listener) {
+
+ 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 function runtimeMessageBytes(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))
+
+ if (value === null || typeof value !== "object") return null
+
+ const record = value as Record<string, unknown>
+
+ const bytes = new Uint8Array(Object.keys(record).length)
+
+ for (let index = 0; index < bytes.length; index++) {
+
+ const byte = record[String(index)]
+
+ if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) return null
+
+ bytes[index] = byte
+ }
+
+ return bytes
+}
diff --git a/source/server/view/server-runtime/server-runtime.ts b/source/server/view/server-runtime/server-runtime.ts
new file mode 100644
index 0000000..fd6e1af
--- /dev/null
+++ b/source/server/view/server-runtime/server-runtime.ts
@@ -0,0 +1,18 @@
+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import type { ServerRuntime } from "@server/core/server-runtime"
+import CommandServerRuntime from "./command"
+import WorkerServerRuntime from "./worker"
+
+/** Creates the concrete View representation selected by a Program declaration. */
+export default function serverRuntime(program: Program): ServerRuntime {
+
+ const server = program.server
+
+ if (!server) throw new Error("This program declared no server half")
+
+ return server.startCommand !== undefined
+
+ ? new CommandServerRuntime(server.startCommand, program.serverPath!)
+
+ : new WorkerServerRuntime(program.serverEntryPath!)
+}
diff --git a/source/server/view/server-runtime/worker.ts b/source/server/view/server-runtime/worker.ts
new file mode 100644
index 0000000..b5d7758
--- /dev/null
+++ b/source/server/view/server-runtime/worker.ts
@@ -0,0 +1,85 @@
+import type { ServerRuntime, ServerRuntimeEnding, Stream } from "@server/core/server-runtime"
+import messagepack from "@the-link/messagepack"
+import { Worker } from "node:worker_threads"
+import RuntimeInbox from "./inbox"
+
+type OutputListener = (stream: Stream, text: string) => void
+
+const maximumPendingOutput = 256
+
+/** Represents one JavaScript Server Endpoint as an isolate inside the System process. */
+export default class WorkerServerRuntime implements ServerRuntime {
+
+ public readonly finished: Promise<ServerRuntimeEnding>
+
+ 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(event: string, ...values: unknown[]) {
+
+ this.worker.postMessage(messagepack.serialize([event, ...values]))
+ }
+
+ public onMessage(listener: (event: string, ...values: 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)
+ }
+}
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
index f0bccb5..16d52b6 100644
--- a/source/server/view/view.ts
+++ b/source/server/view/view.ts
@@ -15,7 +15,7 @@ import { Hono } from "hono"
import { resolve } from "node:path"
import { writeFile } from "node:fs/promises"
import { styleText } from "node:util"
-import serverRuntime from "./server-runtime"
+import serverRuntime from "./server-runtime/server-runtime"
import { listenOnPorts } from "./configuration"
export default async function (config: Config) {