Skip to content

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

Unify gateway with the system link manager

zohayrslileh263f6b248b36
diff --git a/bun.lock b/bun.lock
index 4e7333a..95775fa 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9,6 +9,7 @@
"@hono/node-server": "^2.1.1",
"@the-link/core": "^0.3.0",
"@the-link/http": "^0.1.1",
+ "@the-link/ipc": "^0.2.1",
"@the-link/messagepack": "^0.1.0",
"@the-link/react": "^0.2.0",
"cfonts": "^3.3.1",
@@ -308,6 +309,8 @@
"@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/messagepack": ["@the-link/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" } }, "sha512-Ktnd6sBPZKLCYl6wnxZjxnCzCBWv33k5iUXAs3hVueejj7vQ5wK5KQVPqaQmfeBFuyOo68KqtVaMxl7A1c/atg=="],
"@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.json
index 92e4931..9ff37b8 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"@hono/node-server": "^2.1.1",
"@the-link/core": "^0.3.0",
"@the-link/http": "^0.1.1",
+ "@the-link/ipc": "^0.2.1",
"@the-link/messagepack": "^0.1.0",
"@the-link/react": "^0.2.0",
"cfonts": "^3.3.1",
diff --git a/scripts/contracts/gateway-api.ts b/scripts/contracts/gateway-api.ts
deleted file mode 100644
index 96713bd..0000000
--- a/scripts/contracts/gateway-api.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-import assert from "node:assert/strict"
-import apiRequest from "@server/view/gateway/api-request"
-import type Application from "@server/core/application"
-
-const program = { identity: "example", reference: "example-reference" }
-const handle = { identity: "example", reference: "example-reference" }
-const processReference = { identity: "process-identity" }
-const processSnapshot = { identity: "process-identity", reference: "process-reference" }
-const calls: unknown[][] = []
-const system = {
- holdProgram(received: unknown) {
-
- assert.deepEqual(received, handle)
- return program
- },
- programStoragePath(owner: unknown, area: string) {
-
- assert.equal(owner, program)
- calls.push(["area", area])
- return "/system/programs/example/storage"
- },
- async programIcon(owner: unknown, size: string) {
-
- assert.equal(owner, program)
- calls.push(["icon", size])
- return Uint8Array.from([1, 2, 3])
- },
- programAgent(owner: unknown) {
-
- assert.equal(owner, program)
- calls.push(["agent"])
- return "Program agent"
- },
- async programStore(owner: unknown, operation: string, key: unknown, value: unknown, ttl: unknown) {
-
- assert.equal(owner, program)
- calls.push(["store", operation, key, value, ttl])
- return "stored"
- },
- programQuery(owner: unknown, database: string, statement: string, values: unknown[]) {
-
- assert.equal(owner, program)
- calls.push(["query", database])
- return [{ statement, values }]
- },
- listProcesses(owner: unknown) {
-
- assert.equal(owner, program)
- calls.push(["process", "list"])
- return [processReference]
- },
- processSnapshot(process: unknown) {
-
- assert.equal(process, processReference)
- return processSnapshot
- },
- processSnapshotFromReference(process: unknown) {
-
- assert.equal(process, processReference)
- return processSnapshot
- },
- observe(domain: string, event: string, subject: string, subscriber: (event: string, ...values: unknown[]) => void) {
-
- assert.equal(subject, program.reference)
- calls.push(["observe", domain, event])
- queueMicrotask(() => subscriber(
- event,
- ...(domain === "program"
- ? event === "uninstall" ? [true] : []
- : event === "exit" ? [processReference, 0, null] : [processReference])
- ))
- return () => undefined
- },
- requireProcess(identity: string) { return { identity } },
- observeTraffic(
- process: { identity: string },
- endpoint: string,
- kind: string,
- event: string | null,
- subscriber: (event: string, ...values: unknown[]) => void
- ) {
-
- calls.push(["traffic", process.identity, endpoint, kind, event])
- queueMicrotask(() => subscriber(event ?? "changed", { to: "destination", payload: 1 }))
- return () => undefined
- }
-}
-const application = {
- system
-} as unknown as Application
-
-const signal = new AbortController().signal
-
-assert.equal(await apiRequest(application, {
- capability: "program",
- operation: "storagePath",
- handle,
- area: "data"
-}, signal), "/system/programs/example/storage")
-
-assert.deepEqual(await apiRequest(application, {
- capability: "program",
- operation: "icon",
- handle,
- size: "medium"
-}, signal), [1, 2, 3])
-
-assert.equal(await apiRequest(application, {
- capability: "program",
- operation: "agent",
- handle
-}, signal), "Program agent")
-
-assert.equal(await apiRequest(application, {
- capability: "program",
- operation: "store",
- handle,
- storeOperation: "get",
- key: "state"
-}, signal), "stored")
-
-assert.deepEqual(await apiRequest(application, {
- capability: "program",
- operation: "query",
- handle,
- database: "logs",
- statement: "select ?",
- values: [1]
-}, signal), [{ statement: "select ?", values: [1] }])
-
-assert.equal(await apiRequest(application, {
- capability: "program",
- operation: "wait",
- handle,
- event: "uninstall"
-}, signal), true)
-
-assert.equal(await apiRequest(application, {
- capability: "program",
- operation: "wait",
- handle,
- event: "forget"
-}, signal), undefined)
-
-assert.deepEqual(await apiRequest(application, {
- capability: "programProcess",
- operation: "list",
- handle
-}, signal), [processSnapshot])
-
-assert.equal(await apiRequest(application, {
- capability: "programProcess",
- operation: "wait",
- handle,
- event: "create"
-}, signal), processSnapshot)
-
-assert.deepEqual(await apiRequest(application, {
- capability: "programProcess",
- operation: "wait",
- handle,
- event: "exit"
-}, signal), {
- process: processSnapshot,
- status: "exited",
- code: 0,
- signal: null
-})
-
-assert.deepEqual(await apiRequest(application, {
- capability: "traffic",
- operation: "wait",
- process: "process-identity",
- endpoint: "server",
- kind: "publish",
- event: "changed"
-}, signal), {
- event: "changed",
- values: [{ to: "destination", payload: 1 }]
-})
-
-assert.deepEqual(calls, [
- ["area", "data"],
- ["icon", "medium"],
- ["agent"],
- ["store", "get", "state", undefined, undefined],
- ["query", "logs"],
- ["observe", "program", "uninstall"],
- ["observe", "program", "forget"],
- ["process", "list"],
- ["observe", "process", "create"],
- ["observe", "process", "exit"],
- ["traffic", "process-identity", "server", "publish", "changed"]
-])
-
-await assert.rejects(apiRequest(application, {
- capability: "traffic",
- operation: "wait",
- process: "process-identity",
- endpoint: "client",
- kind: "answer",
- event: null
-}, signal), /Only Server traffic/)
diff --git a/scripts/contracts/gateway.ts b/scripts/contracts/gateway.ts
index f7ecc65..4fcd61f 100644
--- a/scripts/contracts/gateway.ts
+++ b/scripts/contracts/gateway.ts
@@ -1,165 +1,62 @@
import assert from "node:assert/strict"
import { mkdtemp, rm } from "node:fs/promises"
-import { connect } from "node:net"
import { resolve } from "node:path"
+import { SocketClient } from "@the-link/ipc/socket-client"
+import messagepack from "@the-link/messagepack"
import gatewayAddress from "@server/view/gateway/address"
import gateway from "@server/view/gateway/gateway"
-import type Application from "@server/core/application"
+import type LinkManager from "@server/core/link-manager/link-manager"
const directory = await mkdtemp(resolve(".verify-gateway-"))
const path = gatewayAddress(directory)
-const entry = {
- installed: false,
- program: { identity: "example" }
-}
-const forkedEntry = {
- installed: false,
- program: { identity: "forked" }
-}
-const programSnapshot = {
- reference: "example-reference",
- identity: "example",
- assetId: "00000000-0000-4000-8000-000000000000",
- name: "Example",
- version: "1.0.0",
- description: null,
- installed: false,
- hasAgent: false,
- server: null,
- client: { start: true }
-}
-const process = {
- reference: "process-reference",
- identity: "process-identity",
- program: { identity: entry.program.identity, client: {} },
- waitReady(endpoint: "server" | "client", notify: () => void) {
-
- assert.equal(endpoint, "client")
- notify()
-
- return () => undefined
- },
- onExit() { return () => undefined }
+const received: unknown[][] = []
+let removed = false
+const session = {
+ authorization: "owner",
+ linkManager: { appearance: { key: "appearance", value: {} } },
+ authManager: {
+ programManager: { programs: [] },
+ processManager: { processes: [] }
+ }
}
-const application = {
- system: {
- listPrograms() { return [] },
- async forceCreateProgram() { return entry.program },
- requireProgram(identity: string) { return identity === forkedEntry.program.identity ? forkedEntry : entry },
- programSnapshot(selected: typeof entry) { return { ...programSnapshot, identity: selected.program.identity } },
- holdProgram(handle: { identity?: string, reference?: string }) {
-
- assert.deepEqual(handle, { identity: "example", reference: "example-reference" })
- return entry.program
- },
- forkProgram(owner: unknown, identity: string) {
-
- assert.equal(owner, entry.program)
- assert.equal(identity, forkedEntry.program.identity)
-
- return forkedEntry.program
- },
- async *installProgram() {},
- findProcess() { return null },
- resolveProcess() { return process },
- endpointSnapshot(_process: unknown, endpoint: string) {
-
- return { process: process.identity, endpoint, running: true }
+const linkManager = {
+ addConnection() {
+ return {
+ async publish(event: string, ...values: unknown[]) {
+ received.push([event, ...values])
+ return [{ event, values }]
+ }
}
},
- linkManager: {
- authManager: {
- processManager: {
- processes: new Map(),
- async exit() {}
- },
- programManager: {}
- }
- }
+ async addSession(_connection: unknown, owner: boolean) {
+ assert.equal(owner, true)
+ return session
+ },
+ async removeConnection() { removed = true }
}
+const listener = await gateway(linkManager as unknown as LinkManager, path)
+const client = new SocketClient(path)
-const server = await gateway(application as unknown as Application, path)
-
-try {
- const system = await exchange(path, { target: "system", request: { capability: "program", operation: "list", input: {} } })
+client.setSerialize(messagepack.serialize)
+client.setDeserialize(messagepack.deserialize)
- assert.deepEqual(system, [{ success: true, result: { data: [], total: 0, truncated: false } }])
+const ready = client.$inbound.waitFirst("/gateway/ready")
- const ready = await exchange(path, {
- target: "system",
- request: {
- capability: "endpoint",
- operation: "waitReady",
- input: { process: process.identity, endpoint: "client" }
- }
- })
-
- assert.deepEqual(ready, [{
- success: true,
- result: { process: process.identity, endpoint: "client", running: true }
- }])
-
- const created = await exchange(path, {
- target: "program",
- request: { word: "force-create", program: { identity: "example", storage: "/tmp/example", client: { location: "/tmp/client" } } }
- })
-
- assert.deepEqual(created, [{
- event: "created",
- program: {
- reference: "example-reference",
- identity: "example",
- assetId: "00000000-0000-4000-8000-000000000000",
- name: "Example",
- version: "1.0.0",
- description: null,
- installed: false,
- hasAgent: false,
- server: null,
- client: { start: true }
- }
- }])
-
- const forked = await exchange(path, {
- target: "program",
- request: {
- word: "fork",
- handle: { identity: "example", reference: "example-reference" },
- identity: "forked"
- }
- })
-
- assert.deepEqual(forked, [{
- event: "created",
- program: { ...programSnapshot, identity: "forked" }
- }])
-
- const installed = await exchange(path, {
- target: "program",
- request: { word: "install-existing", handle: { identity: "example", reference: "example-reference" } }
- })
-
- assert.deepEqual(installed, [{
- event: "installed",
- identity: "example"
- }])
+try {
+ await client.connect()
+
+ assert.deepEqual(await ready, session)
+ assert.deepEqual(
+ await client.$outbound.publishFirst("/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }),
+ { event: "/auth/example", values: ["authorization", { binary: new Uint8Array([1, 2, 3]) }] }
+ )
+ assert.deepEqual(received, [["/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }]])
} finally {
- await server.close()
+ await client.disconnect()
+ await listener.close()
await rm(directory, { recursive: true, force: true })
}
-async function exchange(path: string, request: unknown): Promise<unknown[]> {
-
- return await new Promise<unknown[]>((resolve, reject) => {
-
- const socket = connect(path)
- let buffer = ""
-
- socket.on("connect", () => socket.write(`${JSON.stringify(request)}\n`))
- socket.on("data", chunk => { buffer += String(chunk) })
- socket.on("error", reject)
- socket.on("close", () => resolve(buffer.trim().split("\n").filter(Boolean).map(line => JSON.parse(line))))
- })
-}
+assert.equal(removed, true)
-console.log("shared gateway verified")
+console.log("gateway boundary verified")
diff --git a/scripts/contracts/ports.ts b/scripts/contracts/ports.ts
index bf70e07..13d3a9f 100644
--- a/scripts/contracts/ports.ts
+++ b/scripts/contracts/ports.ts
@@ -3,7 +3,7 @@ import { createServer } from "node:http"
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
-import { environmentPorts, listenOnPorts, parsePorts, portRange, requestedPorts } from "@server/view/view"
+import { environmentPorts, listenOnPorts, parsePorts, portRange, requestedPorts } from "@server/view/configuration"
assert.equal(environmentPorts("phreshos", {}), undefined)
assert.deepEqual(environmentPorts("phreshos", { PHRESHOS_PORT: "4305" }), [4305])
diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.ts
index 5428c01..8a22c6c 100644
--- a/scripts/contracts/process-lifecycle.ts
+++ b/scripts/contracts/process-lifecycle.ts
@@ -5,7 +5,7 @@ import Program from "@server/core/link-manager/auth-manager/program-manager/prog
import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"
-import type { ServerRuntime } from "@server/core/link-manager/auth-manager/process-manager/server-runtime"
+import type { ServerRuntime } from "@server/core/server-runtime"
const launch = { server: null, client: null, options: {} } as const
diff --git a/scripts/contracts/program-development.ts b/scripts/contracts/program-development.ts
index 1f441dc..3281516 100644
--- a/scripts/contracts/program-development.ts
+++ b/scripts/contracts/program-development.ts
@@ -1,6 +1,6 @@
import assert from "node:assert/strict"
import Program from "@server/core/link-manager/auth-manager/program-manager/program"
-import { developmentTarget } from "@server/view/program-development"
+import { developmentTarget } from "@server/view/http/program/development"
const development = new Program({
diff --git a/scripts/contracts/system-adapters.ts b/scripts/contracts/system-adapters.ts
deleted file mode 100644
index 6a8afb9..0000000
--- a/scripts/contracts/system-adapters.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import assert from "node:assert/strict"
-import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
-import systemRequest from "@server/view/gateway/system-request"
-import type Application from "@server/core/application"
-import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
-import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"
-
-const calls: unknown[][] = []
-const entry = {
- identity: "example",
- installed: true,
- program: {
- identity: "example",
- name: "Example",
- config: { description: null }
- }
-}
-const system = {
- listPrograms(onlyInstalled: boolean) {
-
- calls.push(["listPrograms", onlyInstalled])
- return [entry]
- },
- programSnapshot() {
-
- return { identity: "example" }
- }
-}
-const application = { system } as unknown as Application
-
-const gateway = await systemRequest(application, {
- capability: "program",
- operation: "list",
- input: { installedOnly: true }
-}, new AbortController().signal)
-
-const serverAdapter = {
- system,
- authManager: {
- programManager: {},
- linkManager: { application }
- }
-}
-const server = await (ProcessManager.prototype as unknown as {
- endHost(process: Process, boundary: ServerProcessBoundary, values: unknown[]): Promise<unknown[]>
-}).endHost.call(
- serverAdapter,
- {} as Process,
- {} as ServerProcessBoundary,
- ["host-program-list", true]
-)
-
-assert.deepEqual(gateway, { data: [{ identity: "example" }], total: 1, truncated: false })
-assert.deepEqual(server, [[entry]])
-assert.deepEqual(calls, [
- ["listPrograms", true],
- ["listPrograms", true]
-])
diff --git a/scripts/contracts/uploads.ts b/scripts/contracts/uploads.ts
index 4df0ddf..379e68a 100644
--- a/scripts/contracts/uploads.ts
+++ b/scripts/contracts/uploads.ts
@@ -3,7 +3,7 @@ import { mkdtemp, readFile, rm } from "node:fs/promises"
import { resolve } from "node:path"
import FileManager from "@libs/file-manager"
import UploadManager from "@server/core/upload-manager"
-import uploadView from "@server/view/uploads"
+import uploadView from "@server/view/http/uploads"
import type Application from "@server/core/application"
import { Hono } from "hono"
diff --git a/scripts/contracts/worker-runtime.ts b/scripts/contracts/worker-runtime.ts
index 2c6fbb2..65b1fcd 100644
--- a/scripts/contracts/worker-runtime.ts
+++ b/scripts/contracts/worker-runtime.ts
@@ -4,8 +4,7 @@ import { createRequire } from "node:module"
import { tmpdir } from "node:os"
import { delimiter, join } from "node:path"
import { pathToFileURL } from "node:url"
-import { deserialize as decode, serialize as encode } from "@the-link/messagepack"
-import { CommandServerRuntime, commandServerEnvironment, WorkerServerRuntime } from "@server/core/link-manager/auth-manager/process-manager/server-runtime"
+import { CommandServerRuntime, commandServerEnvironment, WorkerServerRuntime } from "@server/view/server-runtime"
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"
@@ -64,17 +63,12 @@ try {
const messages: unknown[][] = []
const output: ["out" | "err", string][] = []
- runtime.onMessage(message => {
- if (!(message instanceof Uint8Array)) throw new Error("The Worker response must be bytes")
- const decoded = decode(message)
- if (!Array.isArray(decoded)) throw new Error("The Worker response must be an array")
- messages.push(decoded)
- })
+ runtime.onMessage((event, ...values) => messages.push([event, ...values]))
runtime.onOutput((stream, text) => output.push([stream, text]))
await until(() => messages.some(message => message[0] === "boundary" && message[1] === "ready"))
- runtime.send(encode(["probe", 42]))
+ runtime.send("probe", 42)
await until(() => messages.some(message => message[0] === "probe-result"))
await until(() => output.some(([stream, text]) => stream === "out" && text.includes("worker output")))
@@ -91,17 +85,12 @@ try {
const commandMessages: unknown[][] = []
const commandOutput: ["out" | "err", string][] = []
- command.onMessage(message => {
- if (!(message instanceof Uint8Array)) throw new Error("The command response must be bytes")
- const decoded = decode(message)
- if (!Array.isArray(decoded)) throw new Error("The command response must be an array")
- commandMessages.push(decoded)
- })
+ 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"))
- command.send(encode(["probe", 42]))
+ command.send("probe", 42)
await until(() => commandMessages.some(message => message[0] === "probe-result"))
await until(() => commandOutput.some(([stream, text]) => stream === "out" && text.includes("command output")))
diff --git a/scripts/dev.ts b/scripts/dev.ts
index 1c5ab17..8618e18 100644
--- a/scripts/dev.ts
+++ b/scripts/dev.ts
@@ -1,6 +1,7 @@
import { displayName, name, version } from "@/package.json"
-import doors from "@server/view/doors"
-import view, { environmentHome } from "@server/view/view"
+import doors from "@server/view/http/doors"
+import view from "@server/view/view"
+import { environmentHome } from "@server/view/configuration"
import { createServer } from "vite"
import { fileURLToPath } from "node:url"
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
index 8bbc356..9be1a30 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -1,4 +1,4 @@
-import { TransmittedAuthManager } from "@server/core/link-manager/auth-manager/auth-manager"
+import { AuthManagerSnapshot } from "@server/core/link-manager/auth-manager/auth-manager"
import { Intercept } from "@the-link/core/decorators"
import ProcessManager from "./process-manager/process-manager"
import ProgramManager from "./program-manager/program-manager"
@@ -27,7 +27,7 @@ export default class AuthManager extends TheLink {
public readonly shellManager: ShellManager
- public constructor(linkManager: LinkManager, authorization: string, payload: TransmittedAuthManager) {
+ public constructor(linkManager: LinkManager, authorization: string, payload: AuthManagerSnapshot) {
super()
diff --git a/source/client/core/link-manager/auth-manager/dialog-manager.ts b/source/client/core/link-manager/auth-manager/dialog-manager.ts
index 6233993..b496ae9 100644
--- a/source/client/core/link-manager/auth-manager/dialog-manager.ts
+++ b/source/client/core/link-manager/auth-manager/dialog-manager.ts
@@ -1,4 +1,4 @@
-import { type PermissionChoice, type SystemDialog, type TransmittedDialogManager } from "@server/core/dialog-manager"
+import { type DialogManagerSnapshot, type PermissionChoice, type SystemDialog } from "@server/core/dialog-manager"
import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
import AuthManager from "./auth-manager"
@@ -10,7 +10,7 @@ export default class DialogManager extends TheLink {
public readonly dialogs: Map<string, SystemDialog>
- public constructor(authManager: AuthManager, payload: TransmittedDialogManager) {
+ public constructor(authManager: AuthManager, payload: DialogManagerSnapshot) {
super()
diff --git a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
index 84a0666..cbc22f9 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -1,4 +1,4 @@
-import { type TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"
+import { type ProcessSnapshot } from "@server/core/link-manager/auth-manager/process-manager/process"
import ProcessManager from "./process-manager"
import Window from "./window"
@@ -9,7 +9,7 @@ export default class ClientState {
public sameOrigin: boolean
- public constructor(processManager: ProcessManager, process: string, payload: NonNullable<TransmittedProcess["client"]>) {
+ public constructor(processManager: ProcessManager, process: string, payload: NonNullable<ProcessSnapshot["client"]>) {
this.window = new Window(processManager, process, payload.window)
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
index d74206a..d4b244a 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -1,6 +1,6 @@
-import { TransmittedProcessManager } from "@server/core/link-manager/auth-manager/process-manager/process-manager"
-import { TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"
-import { TransmittedWindow } from "@server/core/link-manager/auth-manager/process-manager/window"
+import { ProcessManagerSnapshot } from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+import { ProcessSnapshot } from "@server/core/link-manager/auth-manager/process-manager/process"
+import { WindowSnapshot } from "@server/core/link-manager/auth-manager/process-manager/window"
import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
import AuthManager from "../auth-manager"
@@ -26,7 +26,7 @@ export default class ProcessManager extends TheLink {
public readonly processes = new Map<string, Process>()
- public constructor(authManager: AuthManager, payload: TransmittedProcessManager) {
+ public constructor(authManager: AuthManager, payload: ProcessManagerSnapshot) {
super()
@@ -200,7 +200,7 @@ export default class ProcessManager extends TheLink {
// Any window change arrives in one shape: the process it belongs to,
// and the window whole.
- private followed(payload: { identity: string, window: TransmittedWindow } | null) {
+ private followed(payload: { identity: string, window: WindowSnapshot } | null) {
if (!payload) return
@@ -211,7 +211,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/created")
@Publish("/processes", "inbound")
- protected async createdHandle(payload: TransmittedProcess | null) {
+ protected async createdHandle(payload: ProcessSnapshot | null) {
if (!payload) return
@@ -240,7 +240,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/server-start")
@Publish("/processes", "inbound")
- protected async serverStartHandle(identity: string | null, payload: TransmittedProcess | null) {
+ protected async serverStartHandle(identity: string | null, payload: ProcessSnapshot | null) {
if (!identity || !payload) return
@@ -251,7 +251,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/server-stop")
@Publish("/processes", "inbound")
- protected async serverStopHandle(identity: string | null, _payload: TransmittedProcess | null) {
+ protected async serverStopHandle(identity: string | null, _payload: ProcessSnapshot | null) {
if (!identity) return
@@ -262,7 +262,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/client-start")
@Publish("/processes", "inbound")
- protected async clientStartHandle(identity: string | null, payload: TransmittedProcess | null) {
+ protected async clientStartHandle(identity: string | null, payload: ProcessSnapshot | null) {
if (!identity || !payload) return
@@ -273,7 +273,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/client-stop")
@Publish("/processes", "inbound")
- protected async clientStopHandle(identity: string | null, _payload: TransmittedProcess | null) {
+ protected async clientStopHandle(identity: string | null, _payload: ProcessSnapshot | null) {
if (!identity) return
@@ -284,7 +284,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/client-access")
@Publish("/processes", "inbound")
- protected async clientAccessHandle(identity: string | null, payload: TransmittedProcess | null) {
+ protected async clientAccessHandle(identity: string | null, payload: ProcessSnapshot | null) {
if (!identity || !payload) return
@@ -295,7 +295,7 @@ export default class ProcessManager extends TheLink {
@Subscribe("/exited")
@Publish("/processes", "inbound")
- protected async exitedHandle(payload: TransmittedProcess | null) {
+ protected async exitedHandle(payload: ProcessSnapshot | null) {
if (!payload) return
@@ -306,42 +306,42 @@ export default class ProcessManager extends TheLink {
@Subscribe("/move")
@Publish("/processes", "inbound")
- protected async moveHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+ protected async moveHandle(payload: { identity: string, window: WindowSnapshot } | null) {
return this.followed(payload)
}
@Subscribe("/resize")
@Publish("/processes", "inbound")
- protected async resizeHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+ protected async resizeHandle(payload: { identity: string, window: WindowSnapshot } | null) {
return this.followed(payload)
}
@Subscribe("/geometry")
@Publish("/processes", "inbound")
- protected async geometryHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+ protected async geometryHandle(payload: { identity: string, window: WindowSnapshot } | null) {
return this.followed(payload)
}
@Subscribe("/raise")
@Publish("/processes", "inbound")
- protected async raiseHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+ protected async raiseHandle(payload: { identity: string, window: WindowSnapshot } | null) {
return this.followed(payload)
}
@Subscribe("/change-title")
@Publish("/processes", "inbound")
- protected async changeTitleHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+ protected async changeTitleHandle(payload: { identity: string, window: WindowSnapshot } | null) {
return this.followed(payload)
}
@Subscribe("/minimize")
@Publish("/processes", "inbound")
- protected async minimizeHandle(payload: { identity: string, window: TransmittedWindow } | null) {
+ protected async minimizeHandle(payload: { identity: string, window: WindowSnapshot } | null) {
return this.followed(payload)
}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/process.ts b/source/client/core/link-manager/auth-manager/process-manager/process.ts
index 56161f0..6ca853a 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/process.ts
@@ -1,4 +1,4 @@
-import { TransmittedProcess } from "@server/core/link-manager/auth-manager/process-manager/process"
+import { ProcessSnapshot } from "@server/core/link-manager/auth-manager/process-manager/process"
import ProcessManager from "./process-manager"
import ClientState from "./client-state"
@@ -36,7 +36,7 @@ export default class Process {
// What its launch said, carried for its whole life.
public readonly options: Record<string, string>
- public constructor(processManager: ProcessManager, payload: TransmittedProcess) {
+ public constructor(processManager: ProcessManager, payload: ProcessSnapshot) {
this.processManager = processManager
@@ -72,7 +72,7 @@ export default class Process {
await this.processManager.$outbound.publish("/frame/end-end", this.identity, args)
}
- public serverStarted(payload: TransmittedProcess) {
+ public serverStarted(payload: ProcessSnapshot) {
if (payload.server) this.server = payload.server
}
@@ -82,7 +82,7 @@ export default class Process {
this.server = null
}
- public clientStarted(payload: TransmittedProcess) {
+ public clientStarted(payload: ProcessSnapshot) {
if (!payload.client) return
@@ -107,7 +107,7 @@ export default class Process {
this.client = null
}
- public clientAccessChanged(payload: TransmittedProcess) {
+ public clientAccessChanged(payload: ProcessSnapshot) {
if (this.client && payload.client) this.client.sameOrigin = payload.client.sameOrigin
}
diff --git a/source/client/core/link-manager/auth-manager/process-manager/window.ts b/source/client/core/link-manager/auth-manager/process-manager/window.ts
index d3ad9ac..7c3bca8 100644
--- a/source/client/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/client/core/link-manager/auth-manager/process-manager/window.ts
@@ -1,4 +1,4 @@
-import { type TransmittedWindow, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
+import { type WindowSnapshot, type Position, type Size } from "@server/core/link-manager/auth-manager/process-manager/window"
import { type WindowGeometry, type WindowLayer } from "@phreshos/core"
import ProcessManager from "./process-manager"
@@ -37,7 +37,7 @@ export default class Window {
// Which of the half's own pages the frame opens on.
public location: string
- public constructor(processManager: ProcessManager, process: string, payload: TransmittedWindow) {
+ public constructor(processManager: ProcessManager, process: string, payload: WindowSnapshot) {
this.title = payload.title
@@ -60,7 +60,7 @@ export default class Window {
}
// What the echo carries, applied whole: one shape for any change.
- public follow(payload: TransmittedWindow) {
+ public follow(payload: WindowSnapshot) {
this.title = payload.title
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
index 131e10f..ce7c196 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -1,4 +1,4 @@
-import { TransmittedProgramManager } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { ProgramManagerSnapshot } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
import { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { Publish, Subscribe } from "@the-link/core/decorators"
import { TheLink } from "@the-link/core"
@@ -33,7 +33,7 @@ export default class ProgramManager extends TheLink {
private readonly commands = new StreamRelay("Program command output", programCommandChunk)
- public constructor(authManager: AuthManager, payload: TransmittedProgramManager) {
+ public constructor(authManager: AuthManager, payload: ProgramManagerSnapshot) {
super()
@@ -100,8 +100,8 @@ export default class ProgramManager extends TheLink {
public command(subject: unknown, operation: "install" | "uninstall" | "run", value: unknown, asker: string) {
return this.commands.open(
- stream => this.$outbound.publishFirst("/client-command", stream, operation, subject, value, asker),
- stream => this.$outbound.publish("/client-command-cancel", stream)
+ stream => this.$outbound.publishFirst("/command", stream, operation, subject, value, asker),
+ stream => this.$outbound.publish("/command-cancel", stream)
)
}
@@ -172,7 +172,7 @@ export default class ProgramManager extends TheLink {
return this.arrived(payload)
}
- @Subscribe("/client-command-output")
+ @Subscribe("/command-output")
protected commandOutput(stream: string, value: unknown) {
this.commands.receive(stream, value)
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program.ts b/source/client/core/link-manager/auth-manager/program-manager/program.ts
index bcb654b..c796795 100644
--- a/source/client/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/client/core/link-manager/auth-manager/program-manager/program.ts
@@ -1,11 +1,10 @@
import { ProgramRecord } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { type Launch } from "@phreshos/core"
import ProgramManager from "./program-manager"
-import type { Transmitted } from "@the-link/messagepack"
/**
* A program this session knows about, rebuilt from what the core
- * transmitted. What it holds is what a program says of itself and what
+ * represented. What it holds is what a program says of itself and what
* is needed to draw it — never a path, because this side has no disk
* and where the machine put things is not a program's own word.
*
@@ -32,11 +31,11 @@ export default class Program {
public readonly hasAgent: boolean
- public readonly server: Transmitted<ProgramRecord>["server"]
+ public readonly server: ProgramRecord["server"]
- public readonly client: Transmitted<ProgramRecord>["client"]
+ public readonly client: ProgramRecord["client"]
- public constructor(programManager: ProgramManager, payload: Transmitted<ProgramRecord>) {
+ public constructor(programManager: ProgramManager, payload: ProgramRecord) {
this.programManager = programManager
diff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.ts
index 545a45a..1a84c95 100644
--- a/source/client/core/link-manager/link-manager.ts
+++ b/source/client/core/link-manager/link-manager.ts
@@ -1,5 +1,5 @@
-import { TransmittedAuthManager } from "@server/core/link-manager/auth-manager/auth-manager"
-import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"
+import { AuthManagerSnapshot } from "@server/core/link-manager/auth-manager/auth-manager"
+import { LinkManagerSnapshot } from "@server/core/link-manager/link-manager"
import { type AuthenticationState } from "@server/core/authentication/authentication"
import { type RegistrationResponse } from "@server/core/link-manager/link-manager"
import { type Appearance, type DesktopPreferences, type DesktopPreferencesUpdate } from "@phreshos/core"
@@ -22,7 +22,7 @@ export default class LinkManager extends TheLink {
/** Complete effective local Desktop preferences and future updates. */
public readonly desktopPreferences: Property<DesktopPreferences>
- public constructor(application: Application, sourceLink: TheLink, payload: TransmittedLinkManager, desktopPreferences: DesktopPreferences) {
+ public constructor(application: Application, sourceLink: TheLink, payload: LinkManagerSnapshot, desktopPreferences: DesktopPreferences) {
super()
@@ -81,6 +81,6 @@ export default class LinkManager extends TheLink {
public async sessionAuthenticate(authorization: string | null) {
- return await this.$outbound.publishFirst<[string, TransmittedAuthManager] | false>("/session-authenticate", authorization)
+ return await this.$outbound.publishFirst<[string, AuthManagerSnapshot] | false>("/session-authenticate", authorization)
}
}
diff --git a/source/client/main.ts b/source/client/main.ts
index 79c73c7..f0e6984 100644
--- a/source/client/main.ts
+++ b/source/client/main.ts
@@ -1,5 +1,5 @@
import { displayName, name, version } from "@/package.json"
-import doors from "@server/view/doors"
+import doors from "@server/view/http/doors"
import view from "./view/view"
view({ name, displayName, version, doors, document })
diff --git a/source/client/view/structure/structure.tsx b/source/client/view/structure/structure.tsx
index be90804..8e8c5e7 100644
--- a/source/client/view/structure/structure.tsx
+++ b/source/client/view/structure/structure.tsx
@@ -1,6 +1,6 @@
import { ReactTunnel } from "@the-link/react"
import { useProperty } from "@the-link/react"
-import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"
+import { LinkManagerSnapshot } from "@server/core/link-manager/link-manager"
import LinkManager from "@client/core/link-manager/link-manager"
import { AppearanceProvider, useResolveTheme } from "@phreshos/react-ui"
import Loading from "../components/loading"
@@ -49,7 +49,7 @@ function Desktop() {
const subscribe = useCallback(function () {
- return application.httpClient.onSubscribe<TransmittedLinkManager>(function (link) {
+ return application.httpClient.onSubscribe<LinkManagerSnapshot>(function (link) {
const manager = new LinkManager(application, link, link.payload, preferences)
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
index e689a1c..436a98d 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -10,6 +10,8 @@ import Keyv from "keyv"
import FileArea, { FileSystem } from "@libs/file-area"
import { homedir } from "node:os"
import System from "./system"
+import type Program from "./link-manager/auth-manager/program-manager/program"
+import type { ServerRuntimeFactory } from "./server-runtime"
export default class Application {
@@ -45,6 +47,9 @@ export default class Application {
/** One authoritative System domain shared by every trusted adapter. */
public readonly system: System
+ /** Runtime creation supplied by the host boundary. */
+ public readonly createServerRuntime: ServerRuntimeFactory<Program>
+
private constructor(payload: ApplicationPayload) {
this.name = payload.name
@@ -69,6 +74,8 @@ export default class Application {
this.appearanceManager = payload.appearanceManager
+ this.createServerRuntime = payload.createServerRuntime
+
this.dialogManager = new DialogManager()
this.linkManager = new LinkManager(this)
@@ -76,7 +83,7 @@ export default class Application {
this.system = new System(this)
}
- public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string) {
+ public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string, createServerRuntime: ServerRuntimeFactory<Program>) {
const storage = new FileManager(homePath)
@@ -92,7 +99,7 @@ export default class Application {
const appearanceManager = await AppearanceManager.open(store, uploads)
- const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, encryptor, authentication, appearanceManager, uploads })
+ const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, encryptor, authentication, appearanceManager, uploads, createServerRuntime })
await application.linkManager.authManager.programManager.initialize()
@@ -123,4 +130,6 @@ interface ApplicationPayload {
appearanceManager: AppearanceManager
uploads: UploadManager
+
+ createServerRuntime: ServerRuntimeFactory<Program>
}
diff --git a/source/server/core/authentication/authentication.ts b/source/server/core/authentication/authentication.ts
index e50b38a..6218360 100644
--- a/source/server/core/authentication/authentication.ts
+++ b/source/server/core/authentication/authentication.ts
@@ -146,10 +146,16 @@ export default class Authentication {
&& timingSafeEqual(candidate, expected)
}
- /** Creates a durable session after the owner has authenticated. */
- public createSession() {
+ /** Creates a session with the authority assigned by its trusted boundary. */
+ public createSession(owner = false) {
- return this.sessions.create()
+ return this.sessions.create(owner)
+ }
+
+ /** Whether a valid session belongs to a trusted owner-local connection. */
+ public sessionOwner(identity: string) {
+
+ return this.sessions.owner(identity)
}
/** Whether a session is still within its connection-bound lifetime. */
diff --git a/source/server/core/authentication/sessions.ts b/source/server/core/authentication/sessions.ts
index b8af142..0a9c23a 100644
--- a/source/server/core/authentication/sessions.ts
+++ b/source/server/core/authentication/sessions.ts
@@ -9,9 +9,10 @@ export const disconnectedSessionLifetime = 24 * 60 * 60 * 1_000
/**
* Durable authentication sessions, independent of transient desktop links.
*
- * A session remains valid while at least one connection holds it. The link
- * manager records the final connection loss here; reconnecting clears that
- * timestamp, while a full disconnected day makes the session unreachable.
+ * A session remains valid while at least one connection holds it. Ordinary
+ * sessions receive a reconnecting grace period; owner-local sessions are
+ * removed with their final connection because no reusable token leaves that
+ * boundary.
*/
export default class Sessions {
@@ -53,7 +54,11 @@ export default class Sessions {
continue
}
- sessions.set(record.identity, { identity: record.identity, disconnectedAt })
+ const owner = record.owner === true
+
+ if (record.owner === undefined) changed = true
+
+ sessions.set(record.identity, { identity: record.identity, owner, disconnectedAt })
}
const opened = new Sessions(store, sessions)
@@ -63,14 +68,14 @@ export default class Sessions {
return opened
}
- /** Creates a resumable session which has not yet acquired a connection. */
- public async create() {
+ /** Creates a session which has not yet acquired a connection. */
+ public async create(owner = false) {
this.prune(Date.now())
const identity = randomUUID()
- this.sessions.set(identity, { identity, disconnectedAt: Date.now() })
+ this.sessions.set(identity, { identity, owner, disconnectedAt: Date.now() })
await this.persist()
@@ -93,6 +98,12 @@ export default class Sessions {
return false
}
+ /** Whether this session represents a trusted owner-local connection. */
+ public owner(identity: string) {
+
+ return this.valid(identity) && this.sessions.get(identity)!.owner
+ }
+
/** Resumes a valid session and removes its disconnected deadline. */
public async connect(identity: string) {
@@ -149,7 +160,7 @@ export default class Sessions {
}
}
-function parse(value: unknown): StoredSession[] {
+function parse(value: unknown): StoredSessionInput[] {
if (value === undefined) return []
@@ -158,18 +169,24 @@ function parse(value: unknown): StoredSession[] {
return value
}
-function isStoredSession(value: unknown): value is StoredSession {
+function isStoredSession(value: unknown): value is StoredSessionInput {
if (!value || typeof value !== "object") return false
- const record = value as Partial<StoredSession>
+ const record = value as Partial<StoredSessionInput>
- return typeof record.identity === "string" && (record.disconnectedAt === null || typeof record.disconnectedAt === "number" && Number.isFinite(record.disconnectedAt))
+ return typeof record.identity === "string"
+ && (record.owner === undefined || typeof record.owner === "boolean")
+ && (record.disconnectedAt === null || typeof record.disconnectedAt === "number" && Number.isFinite(record.disconnectedAt))
}
interface StoredSession {
identity: string
+ owner: boolean
+
disconnectedAt: number | null
}
+
+type StoredSessionInput = Omit<StoredSession, "owner"> & { owner?: boolean }
diff --git a/source/server/core/dialog-manager.ts b/source/server/core/dialog-manager.ts
index 102c16e..2d63b06 100644
--- a/source/server/core/dialog-manager.ts
+++ b/source/server/core/dialog-manager.ts
@@ -1,5 +1,4 @@
import { Subscribe } from "@the-link/core/decorators"
-import { Transmitted } from "@the-link/messagepack"
import { TheLink } from "@the-link/core"
import { randomUUID } from "node:crypto"
import { type default as Process } from "./link-manager/auth-manager/process-manager/process"
@@ -200,4 +199,4 @@ function isPermissionChoice(value: unknown): value is PermissionChoice {
return value === "process" || value === "always" || value === false || value === null
}
-export type TransmittedDialogManager = Transmitted<DialogManager>
+export type DialogManagerSnapshot = ReturnType<DialogManager["toJSON"]>
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index 98bef68..a2adde4 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -1,9 +1,8 @@
import { Connect, Forward, Intercept, Subscribe } from "@the-link/core/decorators"
-import UploadManager from "@server/core/upload-manager"
+import UploadManager, { uploadLimit } from "@server/core/upload-manager"
import DialogManager from "@server/core/dialog-manager"
import ProcessManager from "./process-manager/process-manager"
import ProgramManager from "./program-manager/program-manager"
-import { Transmitted } from "@the-link/messagepack"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
import { parsePermissionName, type PermissionRequest } from "@phreshos/core"
@@ -62,6 +61,12 @@ export default class AuthManager extends TheLink {
return this.linkManager.connection().identity
}
+ /** Lifetime of the connection currently invoking an authenticated operation. */
+ public connectionSignal() {
+
+ return this.linkManager.connection().signal
+ }
+
@Intercept("inbound")
protected authenticate(authorization: string, ...values: unknown[]) {
@@ -119,6 +124,18 @@ export default class AuthManager extends TheLink {
return this.uploads.fileManager.path
}
+ @Connect("/uploads/access")
+ protected async uploadsAccess() {
+
+ return { path: this.uploads.fileManager.path, limit: uploadLimit }
+ }
+
+ @Connect("/uploads/stat")
+ protected async uploadStat(file: unknown) {
+
+ return this.uploads.stat(String(file))
+ }
+
@Connect("/appearance/update")
protected async changeAppearance(value: unknown) {
@@ -213,4 +230,11 @@ export default class AuthManager extends TheLink {
}
}
-export type TransmittedAuthManager = Transmitted<AuthManager>
+export interface AuthManagerSnapshot {
+
+ programManager: ReturnType<ProgramManager["toJSON"]>
+
+ processManager: import("./process-manager/process-manager").ProcessManagerSnapshot
+
+ dialogManager: ReturnType<DialogManager["toJSON"]>
+}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
index 6a873f8..0ca4ad6 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
@@ -16,7 +16,7 @@ export default class EndpointServices extends TheLink {
return this.target(key) !== null
}
- public async waitReady(key: unknown, timeout: unknown = 10_000) {
+ public async waitReady(key: unknown, timeout: unknown = 10_000, signal?: AbortSignal) {
const resolved = this.key(key)
@@ -26,18 +26,23 @@ export default class EndpointServices extends TheLink {
let settled = false
let stopReady: () => void = () => undefined
+ let stopStart: () => void = () => undefined
+ let timer: ReturnType<typeof setTimeout> | undefined
const finish = (complete: () => void) => {
if (settled) return
settled = true
- clearTimeout(timer)
+ if (timer) clearTimeout(timer)
stopStart()
stopReady()
+ signal?.removeEventListener("abort", abort)
complete()
}
+ const abort = () => finish(() => reject(signal?.reason instanceof Error ? signal.reason : new Error("Waiting for the service was cancelled")))
+
const inspect = () => {
stopReady()
@@ -50,10 +55,13 @@ export default class EndpointServices extends TheLink {
stopReady = target.process.waitReady(resolved.endpoint, () => finish(resolve))
}
- const stopStart = this.$inbound.subscribe(this.event(resolved, "lifecycle", "start"), inspect)
- const timer = setTimeout(() => finish(() => reject(new Error("The service did not become ready before the timeout"))), milliseconds)
+ stopStart = this.$inbound.subscribe(this.event(resolved, "lifecycle", "start"), inspect)
+ timer = setTimeout(() => finish(() => reject(new Error("The service did not become ready before the timeout"))), milliseconds)
+
+ signal?.addEventListener("abort", abort, { once: true })
- inspect()
+ if (signal?.aborted) abort()
+ else inspect()
})
}
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 345bb2e..5c1e078 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
@@ -5,9 +5,8 @@ import Program from "../program-manager/program"
import { Layer } from "../program-manager/config"
import Window, { Position, Size } from "./window"
import { TheLink } from "@the-link/core"
-import { Transmitted } from "@the-link/messagepack"
import AuthManager from "../auth-manager"
-import Process, { type HostedProcess, type ProcessLaunch } from "./process"
+import Process, { type HostedProcess, type ProcessLaunch, type ProcessSnapshot } from "./process"
import ServerProcessBoundary from "./server-process-boundary"
import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
import ClientProcessForwarder from "./client-process-forwarder"
@@ -15,7 +14,7 @@ import HostTraffic from "./host-traffic"
import { failed, succeeded, type RequestOutcome } from "@libs/request-outcome"
import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
-import EndpointServices from "./endpoint-services"
+import EndpointServices, { serviceTimeout } from "./endpoint-services"
import OutsideQuestions from "./outside-questions"
import {
isServiceKey,
@@ -33,7 +32,7 @@ import {
type WindowGeometry,
type WindowLayer
} from "@phreshos/core"
-import type { ServerRuntime } from "./server-runtime"
+import type { ServerRuntime } from "@server/core/server-runtime"
import { permissionCatalog } from "@server/core/permissions"
/**
@@ -74,6 +73,9 @@ export default class ProcessManager extends TheLink {
// document's forwarding interests and disappears with the lease.
private readonly clientForwarders = new Map<string, ClientProcessForwarder>()
+ /** Live observations owned by an authenticated System representation. */
+ private readonly connectionObservations = new Map<string, Map<string, () => void>>()
+
// Endpoint transitions for one Process are serialized. State is changed in
// one place, so two simultaneous stop requests cannot both believe the
// other endpoint will preserve the Process lifetime.
@@ -269,6 +271,46 @@ export default class ProcessManager extends TheLink {
return this.services.follow(key, scope, event, subscriber)
}
+ /** Publish to an Endpoint from the invoking System representation. */
+ @Subscribe("/endpoint/publish")
+ protected async publishForConnection(target: unknown, endpoint: unknown, event: unknown, payload: unknown) {
+
+ if (typeof event !== "string") throw new Error("An Endpoint event must be text")
+
+ const process = this.find(String(target))
+
+ await this.publishFromOutside(process.identity, half(endpoint), event, payload)
+ }
+
+ /** Ask a Server Endpoint from the invoking System representation. */
+ @Subscribe("/endpoint/ask")
+ protected askForConnection(target: unknown, event: unknown, payload: unknown, timeout: unknown) {
+
+ if (typeof event !== "string") throw new Error("An Endpoint event must be text")
+
+ const process = this.find(String(target))
+
+ return this.askFromOutside(process.identity, event, payload, serviceTimeout(timeout), this.authManager.connectionSignal())
+ }
+
+ /** Publish through a Service from the invoking System representation. */
+ @Subscribe("/service/publish")
+ protected async publishServiceForConnection(key: unknown, event: unknown, payload: unknown) {
+
+ if (typeof event !== "string") throw new Error("A Service event must be text")
+
+ await this.publishServiceFromOutside(key, event, payload)
+ }
+
+ /** Ask a Server Service from the invoking System representation. */
+ @Subscribe("/service/ask")
+ protected askServiceForConnection(key: unknown, event: unknown, payload: unknown, timeout: unknown) {
+
+ if (typeof event !== "string") throw new Error("A Service event must be text")
+
+ return this.askServiceFromOutside(key, event, payload, serviceTimeout(timeout), this.authManager.connectionSignal())
+ }
+
// 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[]) {
@@ -503,6 +545,82 @@ export default class ProcessManager extends TheLink {
this.clientForwarders.delete(key)
}
+
+ const observations = this.connectionObservations.get(connection)
+
+ if (observations) for (const stop of observations.values()) stop()
+
+ this.connectionObservations.delete(connection)
+ }
+
+ /** Attach one live domain observation to the invoking connection. */
+ @Subscribe("/follow")
+ protected followConnection(subscription: unknown, value: unknown) {
+
+ if (typeof subscription !== "string" || !subscription) throw new Error("A System observation identity is required")
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A System observation is required")
+
+ const connection = this.authManager.connection()
+ const observations = this.connectionObservations.get(connection) ?? new Map<string, () => void>()
+
+ observations.get(subscription)?.()
+ this.connectionObservations.set(connection, observations)
+
+ const observation = value as Record<string, unknown>
+ const event = observation.event === null || typeof observation.event === "string" ? observation.event : invalid("A System observation event must be text or null")
+ const followed = (received: string, payload: unknown) => this.authManager.publishToConnection(connection, "/process/followed", subscription, received, payload).catch(() => undefined)
+ const impossible = (reason: string) => {
+
+ this.removeConnectionObservation(connection, subscription)
+ this.authManager.publishToConnection(connection, "/process/impossible", subscription, reason).catch(() => undefined)
+ }
+
+ let stop: () => void
+
+ if (observation.scope === "endpoint") {
+
+ const endpoint = half(observation.endpoint)
+ const process = this.find(String(observation.process))
+
+ stop = this.observeEndpoint(process.identity, endpoint, event, (payload, received) => followed(received, payload), impossible)
+ }
+
+ else if (observation.scope === "traffic") {
+
+ const endpoint = half(observation.endpoint)
+ const kind = trafficKind(observation.kind)
+ const process = this.find(String(observation.process))
+
+ stop = this.observeTrafficFromOutside(process.identity, endpoint, kind, event, (received, ...values) => followed(received, values), impossible)
+ }
+
+ else if (observation.scope === "service") {
+
+ if (observation.kind !== "events" && observation.kind !== "lifecycle") throw new Error("A Service observation kind is events or lifecycle")
+
+ stop = this.observeServiceFromOutside(observation.key, observation.kind, event, followed)
+ }
+
+ else throw new Error("A System observation scope is endpoint, traffic, or service")
+
+ observations.set(subscription, stop)
+ }
+
+ /** Release one observation without affecting its connection or siblings. */
+ @Subscribe("/unfollow")
+ protected unfollowConnection(subscription: unknown) {
+
+ if (typeof subscription === "string") this.removeConnectionObservation(this.authManager.connection(), subscription)
+ }
+
+ private removeConnectionObservation(connection: string, subscription: string) {
+
+ const observations = this.connectionObservations.get(connection)
+
+ observations?.get(subscription)?.()
+ observations?.delete(subscription)
+
+ if (!observations?.size) this.connectionObservations.delete(connection)
}
public retainClientOperation(connection: string, pane: string, operation: string, cancel: () => void) {
@@ -1274,7 +1392,7 @@ export default class ProcessManager extends TheLink {
@Connect("/service/wait-ready")
protected async waitServiceReady(key: unknown, timeout: unknown) {
- await this.services.waitReady(key, timeout)
+ await this.services.waitReady(key, timeout, this.authManager.connectionSignal())
}
@Subscribe("/service/send")
@@ -2690,6 +2808,25 @@ function isTrafficKind(value: unknown): value is TrafficKind {
return value === "publish" || value === "ask" || value === "answer"
}
+function half(value: unknown): Half {
+
+ if (value === "server" || value === "client") return value
+
+ throw new Error("An Endpoint observation targets server or client")
+}
+
+function trafficKind(value: unknown): TrafficKind {
+
+ if (isTrafficKind(value)) return value
+
+ throw new Error("A traffic observation kind is publish, ask, or answer")
+}
+
+function invalid(message: string): never {
+
+ throw new Error(message)
+}
+
interface HandleAddress {
identity: string
@@ -2760,7 +2897,10 @@ export type Shape = StandardShape
type EndpointEvent = "endpointStart" | "endpointStop"
-export type TransmittedProcessManager = Transmitted<ProcessManager>
+export type ProcessManagerSnapshot = {
+
+ processes: [string, ProcessSnapshot][]
+}
// Inside, or not at all. A program joining its own paths from the root
// gives that up knowingly; a join asked of the host does not.
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 e55a561..9baeb4b 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,14 +1,13 @@
import { Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import Window, { Position, Size } from "./window"
-import { Transmitted } from "@the-link/messagepack"
import ServerProcessBoundary from "./server-process-boundary"
import HostTraffic from "./host-traffic"
import ClientState from "./client-state"
import { randomUUID } from "node:crypto"
import { type Layer } from "@phreshos/core"
import { Tunnel } from "@the-link/core"
-import type { ServerRuntime } from "./server-runtime"
+import type { ServerRuntime } from "@server/core/server-runtime"
import type { PermissionName, PermissionValue } from "@phreshos/core"
/**
@@ -54,13 +53,8 @@ export default class Process {
// When this instance began. A process's birth is its construction,
// so nothing hands this over — there is no earlier moment to mean.
//
- // A `Date`, and the link keeps it one: MessagePack carries dates, and
- // `libs/messagepack` leaves them alone rather than letting `toJSON`
- // degrade them to strings. The other two roads out of here speak
- // plain JSON — a program's channel and this machine's door — so on
- // those it arrives as the ISO string a date serialises to. That is
- // harmless while nothing reads it there, and would stop being
- // harmless the moment a kit declared it a `Date`.
+ // A `Date` in the public representation contract. Every boundary adapter
+ // must preserve that value without changing the domain shape.
public readonly startedAt = new Date()
// The current server incarnation. Null is current live state, not a
@@ -353,7 +347,18 @@ export type HostedProcess = ReturnType<Process["hosted"]>
/** Public Process data from which an endpoint SDK reconstructs a handle. */
export type ProcessRecord = ReturnType<Process["record"]>
-export type TransmittedProcess = Transmitted<HostedProcess>
+export type ProcessSnapshot = Omit<HostedProcess, "client"> & {
+
+ client: HostedProcess["client"] extends infer Client
+
+ ? Client extends { window: Window }
+
+ ? Omit<Client, "window"> & { window: ReturnType<Window["toJSON"]> }
+
+ : Client
+
+ : never
+}
export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void
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 6779754..2747ccd 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
@@ -5,8 +5,7 @@ import EndpointEvents from "./endpoint-events"
import EndpointServices, { type ServiceScope } from "./endpoint-services"
import type { ServiceKey } from "@phreshos/core"
import { Tunnel } from "@the-link/core"
-import messagepack from "@the-link/messagepack"
-import type { ServerRuntime, Stream } from "./server-runtime"
+import type { ServerRuntime, Stream } from "@server/core/server-runtime"
/**
* The boundary around one server execution endpoint.
@@ -68,11 +67,11 @@ export default class ServerProcessBoundary extends TheLink {
this.runtime = runtime
- runtime.onMessage(message => { this.receive(message).catch(() => undefined) })
+ runtime.onMessage((event, ...values) => { this.$inbound.publish(event, ...values).catch(() => undefined) })
this.$outbound.forwardTo((event, ...values) => {
- runtime.send(messagepack.serialize([event, ...values]))
+ runtime.send(event, ...values)
})
let finish!: (ending: { code: number | null, signal: NodeJS.Signals | null }) => void
@@ -95,22 +94,6 @@ export default class ServerProcessBoundary extends TheLink {
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[]) {
@@ -519,17 +502,6 @@ interface WaitingQuestion {
question: string
}
-export type { Stream } from "./server-runtime"
+export type { Stream } from "@server/core/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/window.ts b/source/server/core/link-manager/auth-manager/process-manager/window.ts
index e7873b1..18023f3 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/window.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/window.ts
@@ -1,5 +1,4 @@
import { isRelativeValue, type Position, type Size, type Value, type WindowGeometry, type WindowLayer } from "@phreshos/core"
-import { Transmitted } from "@the-link/messagepack"
/**
* How a process is shown. Every value is either a number of pixels or a
@@ -191,6 +190,6 @@ function validate(value: Value, name: string) {
throw new Error(`${name} must be a finite pixel number or a relative expression such as "50% + 10"`)
}
-export type TransmittedWindow = Transmitted<Window>
+export type WindowSnapshot = ReturnType<Window["toJSON"]>
export type { Position, Size, Value } from "@phreshos/core"
diff --git a/source/server/core/link-manager/auth-manager/program-manager/entry.ts b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
index 62b689a..7cb203f 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/entry.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
@@ -1,4 +1,3 @@
-import { Transmitted } from "@the-link/messagepack"
import Program from "./program"
/**
@@ -48,5 +47,3 @@ export default class Entry {
}
export type ProgramRecord = ReturnType<Entry["record"]>
-
-export type TransmittedEntry = Transmitted<ProgramRecord>
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 7a409a8..2c08a97 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
@@ -3,7 +3,6 @@ import { Connect, Subscribe } from "@the-link/core/decorators"
import { randomUUID } from "node:crypto"
import { TheLink } from "@the-link/core"
import SqliteDatabase from "@libs/sqlite-database"
-import { Transmitted } from "@the-link/messagepack"
import FileManager from "@libs/file-manager"
import FileArea from "@libs/file-area"
import openStore from "@server/core/open-store"
@@ -20,7 +19,6 @@ import Entry, { type ProgramRecord } from "./entry"
import Keyv from "keyv"
import { isIconSize, ProgramIcons } from "./icon"
import { readStartup, removeStartup, writeStartup } from "./startup"
-import { CommandServerRuntime, WorkerServerRuntime } from "../process-manager/server-runtime"
import { permissionCatalog } from "@server/core/permissions"
import { readPermissions, writePermissions } from "./permissions"
import {
@@ -68,7 +66,7 @@ export default class ProgramManager extends TheLink {
// This keeps find-or-create atomic even when another caller uses create.
private readonly creating = new Map<string, Promise<void>>()
- private readonly clientCommands = new Map<string, () => void>()
+ private readonly commands = new Map<string, () => void>()
// What each program remembers about itself, opened on first use and
// kept by the identity of the program that asked.
@@ -712,12 +710,13 @@ export default class ProgramManager extends TheLink {
return await this.forget(this.held(subject), asker)
}
- @Connect("/client-command")
- protected async clientCommand(stream: string, operation: string, subject: unknown, value: unknown, asker: string) {
+ @Connect("/command")
+ protected async command(stream: string, operation: string, subject: unknown, value: unknown, asker: string) {
- if (!stream || this.clientCommands.has(stream)) throw new Error("A Client Program command needs a unique stream")
+ if (!stream || this.commands.has(stream)) throw new Error("A Program command needs a unique stream")
const program = this.held(subject)
+ const connection = this.authManager.connectionSignal()
let active = true
let running: Process | null = null
const cancel = () => {
@@ -726,7 +725,8 @@ export default class ProgramManager extends TheLink {
if (running) this.authManager.linkManager.application.system.exitProcess(running).catch(() => undefined)
}
- this.clientCommands.set(stream, cancel)
+ this.commands.set(stream, cancel)
+ connection.addEventListener("abort", cancel, { once: true })
try {
@@ -738,7 +738,7 @@ export default class ProgramManager extends TheLink {
const emit = (event: unknown) => {
if (!active) return
- sending = sending.then(async () => { await this.$outbound.publish("/client-command-output", stream, event) })
+ sending = sending.then(async () => { await this.$outbound.publish("/command-output", stream, event) })
}
await this.runProcess(program, value as Launch ?? {}, {
@@ -775,19 +775,20 @@ export default class ProgramManager extends TheLink {
for await (const chunk of command) {
if (!active) return
- await this.$outbound.publish("/client-command-output", stream, chunk)
+ await this.$outbound.publish("/command-output", stream, chunk)
}
}
finally {
- this.clientCommands.delete(stream)
+ connection.removeEventListener("abort", cancel)
+ this.commands.delete(stream)
}
}
- @Subscribe("/client-command-cancel")
- protected cancelClientCommand(stream: unknown) {
+ @Subscribe("/command-cancel")
+ protected cancelCommand(stream: unknown) {
- if (typeof stream === "string") this.clientCommands.get(stream)?.()
+ if (typeof stream === "string") this.commands.get(stream)?.()
}
/** Install while exposing command output with consumer-driven backpressure. */
@@ -1315,11 +1316,7 @@ export default class ProgramManager extends TheLink {
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!)
+ return this.authManager.linkManager.application.createServerRuntime(program)
}
/** Resolves and validates one client endpoint incarnation. */
@@ -1379,7 +1376,7 @@ export default class ProgramManager extends TheLink {
}
}
-export type TransmittedProgramManager = Transmitted<ProgramManager>
+export type ProgramManagerSnapshot = ReturnType<ProgramManager["toJSON"]>
// Which of a half's own pages a launch asked for.
//
diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.ts
index f4a5b2f..3f1ff9f 100644
--- a/source/server/core/link-manager/link-manager.ts
+++ b/source/server/core/link-manager/link-manager.ts
@@ -2,7 +2,6 @@ import { Forward, Subscribe } from "@the-link/core/decorators"
import AuthManager from "./auth-manager/auth-manager"
import { TheLink } from "@the-link/core"
import { Property } from "@the-link/core"
-import { Transmitted } from "@the-link/messagepack"
import Application from "../application"
import { type Appearance } from "@phreshos/core"
import { type AuthenticationState, type RegistrationError } from "../authentication/authentication"
@@ -12,7 +11,7 @@ export default class LinkManager extends TheLink {
public readonly application: Application
- /** Live desktop connections. Authentication sessions outlive these links. */
+ /** Live boundary connections. Ordinary authentication sessions outlive them. */
public readonly connections = new Map<string, Connection>()
private readonly connectionContext = new AsyncLocalStorage<Connection>()
@@ -44,15 +43,39 @@ export default class LinkManager extends TheLink {
return connection
}
+ /** Create and bind a new authenticated session to a live connection. */
+ public async addSession(connection: Connection, owner = false) {
+
+ if (this.connections.get(connection.identity) !== connection) throw new Error("Connection not found")
+ if (connection.session) throw new Error("The connection already has a session")
+
+ const session = await this.application.authentication.createSession(owner)
+
+ if (!await this.application.authentication.connectSession(session)) throw new Error("The created session is unavailable")
+
+ connection.session = session
+
+ return {
+
+ authorization: this.application.encryptor.createToken({ version: 1, session }),
+
+ linkManager: this,
+
+ authManager: this.authManager
+ }
+ }
+
public async removeConnection(connection: Connection) {
if (this.connections.get(connection.identity) !== connection) return
+ connection.close()
+
this.authManager.processManager.releaseConnection(connection.identity)
this.connections.delete(connection.identity)
- if (connection.session && !this.connected(connection.session)) await this.application.authentication.disconnectSession(connection.session)
+ if (connection.session && !this.connected(connection.session)) await this.releaseSession(connection.session)
}
public receive(connection: Connection, event: string, ...values: unknown[]) {
@@ -186,7 +209,16 @@ export default class LinkManager extends TheLink {
return
}
- if (!this.connected(session)) await this.application.authentication.disconnectSession(session)
+ if (!this.connected(session)) await this.releaseSession(session)
+ }
+
+ private releaseSession(session: string) {
+
+ return this.application.authentication.sessionOwner(session)
+
+ ? this.application.authentication.removeSession(session)
+
+ : this.application.authentication.disconnectSession(session)
}
/** Persist and publish one authorized Appearance replacement in call order. */
@@ -218,7 +250,10 @@ export default class LinkManager extends TheLink {
}
}
-export type TransmittedLinkManager = Transmitted<LinkManager>
+export interface LinkManagerSnapshot {
+
+ appearance: ReturnType<Property<Appearance>["toJSON"]>
+}
export type RegistrationResponse = { authorization: string } | { error: RegistrationError }
@@ -228,12 +263,21 @@ export class Connection {
public session: string | null = null
+ private readonly lifetime = new AbortController()
+
+ public readonly signal = this.lifetime.signal
+
public constructor(private readonly manager: LinkManager, public readonly link: TheLink) {}
public publish(event: string, ...values: unknown[]) {
return this.manager.receive(this, event, ...values)
}
+
+ public close() {
+
+ this.lifetime.abort(new Error("The System representation disconnected"))
+ }
}
function isAuthorization(value: unknown): value is { version: 1, session: string } {
diff --git a/source/server/core/server-runtime.ts b/source/server/core/server-runtime.ts
new file mode 100644
index 0000000..7790da6
--- /dev/null
+++ b/source/server/core/server-runtime.ts
@@ -0,0 +1,21 @@
+/** Execution boundary presented to the System domain by any Server runtime adapter. */
+export interface ServerRuntime {
+
+ readonly finished: Promise<ServerRuntimeEnding>
+
+ send(event: string, ...values: unknown[]): void
+
+ onMessage(listener: (event: string, ...values: unknown[]) => void): void
+
+ onOutput(listener: (stream: Stream, text: string) => void): void
+
+ stop(): void
+}
+
+export type ServerRuntimeFactory<Program> = (program: Program) => ServerRuntime
+
+export type ServerRuntimeMessage = [event: string, ...values: unknown[]]
+
+export type ServerRuntimeEnding = { code: number | null, signal: NodeJS.Signals | null }
+
+export type Stream = "out" | "err"
diff --git a/source/server/main.ts b/source/server/main.ts
index 952196d..09db2f1 100644
--- a/source/server/main.ts
+++ b/source/server/main.ts
@@ -1,5 +1,6 @@
import { displayName, name, version } from "@/package.json"
-import view, { defaultHome, environmentHome, environmentPorts, portRange, requestedHome, requestedPorts } from "./view/view"
+import view from "./view/view"
+import { defaultHome, environmentHome, environmentPorts, portRange, requestedHome, requestedPorts } from "./view/configuration"
import { fileURLToPath } from "node:url"
const requested = await requestedHome(process.argv)
diff --git a/source/server/view/configuration.ts b/source/server/view/configuration.ts
new file mode 100644
index 0000000..5a75513
--- /dev/null
+++ b/source/server/view/configuration.ts
@@ -0,0 +1,179 @@
+import environment from "@libs/environment"
+import type { ServerType } from "@hono/node-server"
+import { readFile, rm } from "node:fs/promises"
+import { isAbsolute, normalize, resolve } from "node:path"
+
+/** Expand one inclusive TCP port range. */
+export function portRange(from: number, to: number) {
+
+ return Array.from({ length: to - from + 1 }, (_, index) => from + index)
+}
+
+/** Read the optional ordered production port selection. */
+export function environmentPorts(name: string, variables: NodeJS.ProcessEnv) {
+
+ const selected = environment(name, "PORT", variables)
+
+ if (selected.value === undefined) return undefined
+
+ return parsePorts(selected.value, selected.key)
+}
+
+/** Parse comma-separated TCP ports and inclusive ranges in declared order. */
+export function parsePorts(value: string, name = "Port selection") {
+
+ const ports: number[] = []
+ const included = new Set<number>()
+
+ for (const part of value.split(",")) {
+
+ const match = /^(\d+)(?:-(\d+))?$/.exec(part)
+
+ if (!match) throw portSelectionError(name)
+
+ const from = Number(match[1])
+ const to = Number(match[2] ?? match[1])
+
+ if (!validPort(from) || !validPort(to) || from > to) throw portSelectionError(name)
+
+ for (let port = from; port <= to; port++) {
+
+ if (included.has(port)) continue
+
+ included.add(port)
+ ports.push(port)
+ }
+ }
+
+ return Object.freeze(ports)
+}
+
+/** Consume the optional one-time port selection supplied through the native service boundary. */
+export async function requestedPorts(arguments_: string[]) {
+
+ const positions = arguments_.flatMap((value, index) => value === "--port-request" ? [index] : [])
+
+ if (positions.length === 0) return undefined
+ if (positions.length !== 1) throw new Error("--port-request can be supplied only once")
+
+ const path = arguments_[positions[0]! + 1]
+
+ if (!path || !isAbsolute(path)) throw new Error("--port-request must be followed by an absolute filesystem path")
+
+ let value: string
+
+ try { value = (await readFile(path, "utf8")).trim() }
+ catch (error) {
+
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
+ throw error
+ }
+
+ await rm(path, { force: true })
+
+ return parsePorts(value, "The requested PhreshOS port selection")
+}
+
+/** Bind one server to the first available candidate or an assigned port. */
+export async function listenOnPorts(server: ServerType, hostname: string, ports?: readonly number[]) {
+
+ for (const port of ports ?? [0]) {
+
+ const address = await tryListen(server, hostname, port)
+
+ if (address !== null) return address
+ }
+
+ throw new Error("No configured System port is available")
+}
+
+/** Read the stable fallback home supplied by the native service definition. */
+export function defaultHome(arguments_: string[]) {
+
+ const positions = arguments_.flatMap((value, index) => value === "--default-home" ? [index] : [])
+
+ if (positions.length === 0) return undefined
+ if (positions.length !== 1) throw new Error("--default-home can be supplied only once")
+
+ const value = arguments_[positions[0]! + 1]
+
+ if (!value || !isAbsolute(value)) throw new Error("--default-home must be followed by an absolute filesystem path")
+
+ return normalize(value)
+}
+
+/** Consume the optional one-time home request supplied through the native service boundary. */
+export async function requestedHome(arguments_: string[]) {
+
+ const positions = arguments_.flatMap((value, index) => value === "--home-request" ? [index] : [])
+
+ if (positions.length === 0) return undefined
+ if (positions.length !== 1) throw new Error("--home-request can be supplied only once")
+
+ const path = arguments_[positions[0]! + 1]
+
+ if (!path || !isAbsolute(path)) throw new Error("--home-request must be followed by an absolute filesystem path")
+
+ let value: string
+
+ try { value = (await readFile(path, "utf8")).trim() }
+ catch (error) {
+
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
+ throw error
+ }
+
+ await rm(path, { force: true })
+
+ if (!isAbsolute(value)) throw new Error("The requested PhreshOS home must be an absolute filesystem path")
+
+ return normalize(value)
+}
+
+/** Read the optional absolute authoritative home selected by Main's environment. */
+export function environmentHome(name: string, variables: NodeJS.ProcessEnv) {
+
+ const selected = environment(name, "HOME", variables)
+ const value = selected.value
+
+ if (value === undefined) return undefined
+ if (!isAbsolute(value)) throw new Error(`${selected.key} must be an absolute filesystem path`)
+
+ return resolve(value)
+}
+
+function tryListen(server: ServerType, hostname: string, port: number) {
+
+ return new Promise<number | null>((resolve, reject) => {
+
+ const failed = (error: NodeJS.ErrnoException) => {
+
+ server.off("error", failed)
+
+ if (error.code === "EADDRINUSE" || error.code === "EACCES") resolve(null)
+ else reject(error)
+ }
+
+ server.once("error", failed)
+
+ server.listen(port, hostname, () => {
+
+ server.off("error", failed)
+
+ const address = server.address()
+
+ if (!address || typeof address === "string") reject(new Error("The System listener has no TCP address"))
+ else resolve(address.port)
+ })
+ })
+}
+
+function validPort(value: number) {
+
+ return Number.isInteger(value) && value >= 1 && value <= 65_535
+}
+
+function portSelectionError(name: string) {
+
+ return new Error(`${name} must contain ports or inclusive ranges from 1 to 65535`)
+}
diff --git a/source/server/view/gateway/api-request.ts b/source/server/view/gateway/api-request.ts
deleted file mode 100644
index e047708..0000000
--- a/source/server/view/gateway/api-request.ts
+++ /dev/null
@@ -1,340 +0,0 @@
-import type Application from "@server/core/application"
-import { uploadLimit } from "@server/core/upload-manager"
-import { parsePermissionName, type PermissionInput } from "@phreshos/core"
-
-/** Execute one operation belonging to the shared System SDK contract. */
-export default async function apiRequest(application: Application, value: unknown, signal: AbortSignal) {
-
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The System API request must be an object")
-
- const request = value as Record<string, unknown>
- const system = application.system
-
- if (request.capability === "appearance") {
-
- if (request.operation === "snapshot") return system.appearance
- if (request.operation === "update") return await system.updateAppearance(request.value)
- if (request.operation === "wait") return await waitForAppearance(system, signal)
-
- throw new Error(`The Appearance API does not know "${String(request.operation)}"`)
- }
-
- if (request.capability === "uploads") {
-
- if (request.operation === "access") return { path: system.uploads.fileManager.path, limit: uploadLimit }
- if (request.operation === "stat") return system.uploads.stat(String(request.file))
-
- throw new Error(`The Uploads API does not know "${String(request.operation)}"`)
- }
-
- if (request.capability === "program") {
-
- const program = system.holdProgram(request.handle)
-
- if (request.operation === "storagePath") {
-
- if (request.area !== "data" && request.area !== "cache") throw new Error("A Program storage area is data or cache")
- return system.programStoragePath(program, request.area)
- }
-
- if (request.operation === "icon") {
-
- if (request.size !== "small" && request.size !== "medium" && request.size !== "large") throw new Error("A Program icon size is small, medium, or large")
- return Array.from(await system.programIcon(program, request.size))
- }
-
- if (request.operation === "agent") return system.programAgent(program)
-
- if (request.operation === "permissions") {
-
- if (request.permissionOperation === "all") return system.programPermissions(program)
- if (request.permissionOperation === "get") return system.programPermission(program, parsePermissionName(request.name))
- if (request.permissionOperation === "set") {
-
- const permission = parsePermissionName(request.name)
-
- return system.setProgramPermission(program, permission, request.permission as Exclude<PermissionInput<typeof permission>, null>)
- }
- if (request.permissionOperation === "delete") return system.deleteProgramPermission(program, parsePermissionName(request.name))
-
- throw new Error(`The Program permissions API does not know "${String(request.permissionOperation)}"`)
- }
-
- if (request.operation === "store") {
-
- if (typeof request.storeOperation !== "string") throw new Error("A Program store operation is required")
- return await system.programStore(program, request.storeOperation, request.key as string, request.value, number(request.ttl))
- }
-
- if (request.operation === "query") {
-
- if (request.database !== "logs" && request.database !== "database") throw new Error("A Program query targets logs or database")
- if (typeof request.statement !== "string" || !Array.isArray(request.values)) throw new Error("A Program query needs a statement and values")
- return system.programQuery(program, request.database, request.statement, request.values)
- }
-
- if (request.operation === "wait") {
-
- if (request.event !== "forget" && request.event !== "uninstall") throw new Error("A Program event is forget or uninstall")
-
- const values = await waitForHost(system, "program", request.event, program.reference, timed(signal, request.timeout))
-
- return request.event === "uninstall" ? values[0] === true : undefined
- }
-
- throw new Error(`The Program API does not know "${String(request.operation)}"`)
- }
-
- if (request.capability === "programProcess") {
-
- const program = system.holdProgram(request.handle)
-
- if (request.operation === "list") return system.listProcesses(program).map(process => system.processSnapshot(process))
-
- if (request.operation === "wait") {
-
- if (request.event !== "create" && request.event !== "exit") throw new Error("A Program Process event is create or exit")
-
- const values = await waitForHost(system, "process", request.event, program.reference, timed(signal, request.timeout))
- const process = system.processSnapshotFromReference(values[0] as Parameters<typeof system.processSnapshotFromReference>[0])
-
- if (request.event === "create") return process
-
- const namedSignal = typeof values[2] === "string" ? values[2] : null
-
- return Object.freeze({
- process,
- status: namedSignal === null ? "exited" : "signaled",
- code: typeof values[1] === "number" ? values[1] : null,
- signal: namedSignal
- })
- }
-
- throw new Error(`The Program Process API does not know "${String(request.operation)}"`)
- }
-
- if (request.capability === "endpoint" && request.operation === "isService") {
-
- if (typeof request.process !== "string" || request.endpoint !== "server" && request.endpoint !== "client") {
-
- throw new Error("Reading an Endpoint service role needs a Process and Endpoint")
- }
-
- return system.endpointIsService(system.requireProcess(request.process), request.endpoint)
- }
-
- if (request.capability === "endpoint" && request.operation === "wait") {
-
- if (typeof request.process !== "string" || request.endpoint !== "server" && request.endpoint !== "client") {
-
- throw new Error("Waiting for an Endpoint needs a Process and Endpoint")
- }
- if (request.event !== null && typeof request.event !== "string") throw new Error("An Endpoint event must be text or null")
-
- return await waitForEndpoint(system, system.requireProcess(request.process), request.endpoint, request.event, timed(signal, request.timeout))
- }
-
- if (request.capability === "traffic" && request.operation === "wait") {
-
- if (typeof request.process !== "string" || request.endpoint !== "server" && request.endpoint !== "client") {
-
- throw new Error("Waiting for Endpoint traffic needs a Process and Endpoint")
- }
- if (request.kind !== "publish" && request.kind !== "ask" && request.kind !== "answer") throw new Error("Endpoint traffic is publish, ask, or answer")
- if (request.kind === "answer" && request.endpoint !== "server") throw new Error("Only Server traffic contains answers")
- if (request.event !== null && typeof request.event !== "string") throw new Error("A traffic event must be text or null")
-
- return await waitForTraffic(
- system,
- system.requireProcess(request.process),
- request.endpoint,
- request.kind,
- request.event,
- timed(signal, request.timeout)
- )
- }
-
- if (request.capability === "service") {
-
- const key = request.key
-
- if (request.operation === "exists") return system.serviceExists(key)
- if (request.operation === "waitReady") return await system.waitServiceReady(key, number(request.timeout))
-
- if (request.operation === "publish" || request.operation === "ask") {
-
- if (typeof request.event !== "string") throw new Error("A Service event must be text")
- if (request.operation === "publish") return await system.publishService(key, request.event, request.payload)
- return await system.askService(key, request.event, request.payload, number(request.timeout) ?? 10_000, signal)
- }
- if (request.operation === "wait") {
-
- if (request.event !== null && typeof request.event !== "string") throw new Error("A Service event must be text or null")
- return await waitForService(system, key, String(request.scope), request.event, timed(signal, request.timeout))
- }
-
- throw new Error(`The Service API does not know "${String(request.operation)}"`)
- }
-
- throw new Error(`Unknown System API capability "${String(request.capability)}"`)
-}
-
-function number(value: unknown) {
-
- if (value === undefined) return undefined
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("A timeout must be a non-negative finite number")
- return value
-}
-
-function waitForService(system: Application["system"], key: unknown, scope: string, event: string | null, signal: AbortSignal) {
-
- if (scope !== "lifecycle" && scope !== "events") throw new Error("A Service wait scope must be lifecycle or events")
-
- return new Promise((resolve, reject) => {
-
- const stop = system.observeService(key, scope, event, (received, payload) => {
-
- cleanup()
- resolve(event === null ? { event: received, payload } : payload)
- })
- const abort = () => {
-
- cleanup()
- reject(signal.reason instanceof Error ? signal.reason : new Error("The Service wait was cancelled"))
- }
- const cleanup = () => {
-
- stop()
- signal.removeEventListener("abort", abort)
- }
-
- if (signal.aborted) abort()
- else signal.addEventListener("abort", abort, { once: true })
- })
-}
-
-function timed(signal: AbortSignal, value: unknown) {
-
- return AbortSignal.any([signal, AbortSignal.timeout(number(value) ?? 10_000)])
-}
-
-function waitForHost(
- system: Application["system"],
- domain: "program" | "process",
- event: string,
- subject: string,
- signal: AbortSignal
-) {
-
- return new Promise<unknown[]>((resolve, reject) => {
-
- const stop = system.observe(domain, event, subject, (_event, ...values) => {
-
- cleanup()
- resolve(values)
- })
- const abort = () => {
-
- cleanup()
- reject(signal.reason instanceof Error ? signal.reason : new Error("The System wait was cancelled"))
- }
- const cleanup = () => {
-
- stop()
- signal.removeEventListener("abort", abort)
- }
-
- if (signal.aborted) abort()
- else signal.addEventListener("abort", abort, { once: true })
- })
-}
-
-function waitForEndpoint(system: Application["system"], process: Parameters<Application["system"]["observeEndpoint"]>[0], endpoint: "server" | "client", event: string | null, signal: AbortSignal) {
-
- return new Promise((resolve, reject) => {
-
- const stop = system.observeEndpoint(process, endpoint, event, (payload, received) => {
-
- cleanup()
- resolve({ event: received, payload })
- }, reason => {
-
- cleanup()
- reject(new Error(reason))
- })
- const abort = () => {
-
- cleanup()
- reject(signal.reason instanceof Error ? signal.reason : new Error("The Endpoint wait was cancelled"))
- }
- const cleanup = () => {
-
- stop()
- signal.removeEventListener("abort", abort)
- }
-
- if (signal.aborted) abort()
- else signal.addEventListener("abort", abort, { once: true })
- })
-}
-
-function waitForTraffic(
- system: Application["system"],
- process: Parameters<Application["system"]["observeTraffic"]>[0],
- endpoint: "server" | "client",
- kind: "publish" | "ask" | "answer",
- event: string | null,
- signal: AbortSignal
-) {
-
- return new Promise((resolve, reject) => {
-
- const stop = system.observeTraffic(process, endpoint, kind, event, (received, ...values) => {
-
- cleanup()
- resolve({ event: received, values })
- }, reason => {
-
- cleanup()
- reject(new Error(reason))
- })
- const abort = () => {
-
- cleanup()
- reject(signal.reason instanceof Error ? signal.reason : new Error("The traffic wait was cancelled"))
- }
- const cleanup = () => {
-
- stop()
- signal.removeEventListener("abort", abort)
- }
-
- if (signal.aborted) abort()
- else signal.addEventListener("abort", abort, { once: true })
- })
-}
-
-function waitForAppearance(system: Application["system"], signal: AbortSignal) {
-
- return new Promise((resolve, reject) => {
-
- const stop = system.observeAppearance((value: unknown) => {
-
- cleanup()
- resolve(value)
- })
- const abort = () => {
-
- cleanup()
- reject(signal.reason instanceof Error ? signal.reason : new Error("The Appearance wait was cancelled"))
- }
- const cleanup = () => {
-
- stop()
- signal.removeEventListener("abort", abort)
- }
-
- if (signal.aborted) abort()
- else signal.addEventListener("abort", abort, { once: true })
- })
-}
diff --git a/source/server/view/gateway/gateway.ts b/source/server/view/gateway/gateway.ts
index 1af4140..e478fd5 100644
--- a/source/server/view/gateway/gateway.ts
+++ b/source/server/view/gateway/gateway.ts
@@ -1,105 +1,51 @@
-import type Application from "@server/core/application"
+import type LinkManager from "@server/core/link-manager/link-manager"
import localServer from "./local-server"
-import apiRequest from "./api-request"
-import programRequest from "./program-request"
-import systemRequest from "./system-request"
+import messagepack from "@the-link/messagepack"
+import type { SocketServer } from "@the-link/ipc/socket-server"
-const maximumRequestSize = 16 * 1024 * 1024
+/** Open the owner-local IPC adapter for the System Link Manager. */
+export default function gateway(linkManager: LinkManager, path: string) {
-/** Open the one owner-local gateway and route each connection internally. */
-export default function gateway(application: Application, path: string) {
+ return localServer(path, function (server) {
- return localServer(path, function (socket) {
-
- const controller = new AbortController()
- let buffer = ""
- let handled = false
-
- socket.on("data", function (chunk) {
-
- if (handled) return
-
- buffer += String(chunk)
-
- if (buffer.length > maximumRequestSize) {
-
- handled = true
- return fail(socket, new Error("The gateway request is too large"))
- }
-
- const boundary = buffer.indexOf("\n")
-
- if (boundary < 0) return
-
- handled = true
-
- let envelope: GatewayEnvelope
-
- try { envelope = parseEnvelope(buffer.slice(0, boundary)) }
- catch (error) { return fail(socket, error) }
-
- if (envelope.target === "program") {
-
- programRequest(application, socket, envelope.request).catch(error => fail(socket, error))
- return
- }
-
- if (envelope.target === "api") {
-
- apiRequest(application, envelope.request, controller.signal).then(
- result => finish(socket, { success: true, result }),
- error => finish(socket, { success: false, error: reason(error) })
- )
- return
- }
-
- systemRequest(application, envelope.request, controller.signal).then(
- result => finish(socket, { success: true, result }),
- error => finish(socket, { success: false, error: reason(error) })
- )
- })
-
- socket.on("close", () => controller.abort(new Error("The requester disconnected")))
- socket.on("error", () => undefined)
+ server.setSerialize(messagepack.serialize)
+ server.setDeserialize(messagepack.deserialize)
+ server.onConnection(peer => connect(linkManager, peer))
})
}
-function parseEnvelope(line: string): GatewayEnvelope {
+async function connect(linkManager: LinkManager, peer: GatewayPeer) {
- let value: unknown
+ const connection = linkManager.addConnection(peer)
+ let closed = false
+ const close = async () => {
- try { value = JSON.parse(line) }
- catch { throw new Error("What arrived is not JSON") }
+ if (closed) return
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The gateway request must be an object")
+ closed = true
- const envelope = value as Record<string, unknown>
+ stopForwarding()
- if (Object.keys(envelope).some(key => key !== "target" && key !== "request")) throw new Error("The gateway request contains an unknown field")
+ await linkManager.removeConnection(connection)
+ }
+ const stopForwarding = peer.$inbound.forwardTo((event, ...values: unknown[]) => connection.publish(event, ...values))
- if (envelope.target !== "api" && envelope.target !== "program" && envelope.target !== "system") throw new Error("The Gateway target must be api, program, or system")
- if (!("request" in envelope)) throw new Error("The gateway request is missing")
+ peer.$internal.subscribeOnce("disconnect", close)
- return { target: envelope.target, request: envelope.request }
-}
+ try {
-function fail(socket: import("node:net").Socket, error: unknown) {
+ const session = await linkManager.addSession(connection, true)
- if (socket.writable) socket.end(`${JSON.stringify({ event: "error", message: reason(error) })}\n`)
-}
-
-function finish(socket: import("node:net").Socket, outcome: object) {
+ await peer.$outbound.publish("/gateway/ready", session)
+ }
- if (socket.writable) socket.end(`${JSON.stringify(outcome)}\n`)
-}
+ catch (error) {
-function reason(error: unknown) {
+ await close()
+ await peer.disconnect()
- return error instanceof Error ? error.message : String(error)
+ throw error
+ }
}
-interface GatewayEnvelope {
-
- target: "api" | "program" | "system"
- request: unknown
-}
+type GatewayPeer = Parameters<Parameters<SocketServer["onConnection"]>[0]>[0]
diff --git a/source/server/view/gateway/local-server.ts b/source/server/view/gateway/local-server.ts
index 1e86048..4fd6b94 100644
--- a/source/server/view/gateway/local-server.ts
+++ b/source/server/view/gateway/local-server.ts
@@ -1,55 +1,44 @@
-import { chmodSync, mkdirSync, rmSync } from "node:fs"
-import { connect, createServer, type Socket } from "node:net"
+import { mkdirSync, rmSync } from "node:fs"
+import { connect } from "node:net"
import { dirname } from "node:path"
+import { SocketServer } from "@the-link/ipc/socket-server"
-/** Open Gateway's owner-only local socket and safely recover a stale POSIX address. */
-export default function localServer(path: string, receive: (socket: Socket) => void) {
+/** Open the owner-only IPC listener and safely recover a stale POSIX address. */
+export default async function localServer(path: string, prepare: (server: SocketServer) => void) {
const namedPipe = process.platform === "win32"
- const server = createServer(receive)
if (!namedPipe) mkdirSync(dirname(path), { recursive: true })
- return new Promise<LocalServer>(function (resolve, reject) {
+ for (let recovered = false; ; recovered = true) {
- const listen = (recovered: boolean) => {
+ const server = new SocketServer(path, { mode: 0o600 })
- server.once("error", function (error: NodeJS.ErrnoException) {
+ prepare(server)
- if (error.code !== "EADDRINUSE" || recovered) return reject(error)
+ try {
- alive(path).then(function (running) {
+ await server.listen()
- if (running) return reject(new Error(`A system is already running here — ${dirname(path)} holds one system, and two would share its programs and persistent state`))
-
- if (namedPipe) return reject(error)
-
- rmSync(path, { force: true })
- listen(true)
- }, reject)
- })
-
- server.listen({ path, readableAll: false, writableAll: false }, () => resolve({
- path: secured(path, namedPipe),
- close: () => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
- }))
+ return { path, server, close: () => server.close() }
}
- listen(false)
- })
-}
+ catch (error) {
-export interface LocalServer {
+ const failure = error as NodeJS.ErrnoException
- path: string
- close(): Promise<void>
-}
+ if (failure.code !== "EADDRINUSE" || recovered) throw error
-function secured(path: string, namedPipe: boolean) {
+ if (await alive(path)) {
- if (!namedPipe) chmodSync(path, 0o600)
+ throw new Error(`A system is already running here — ${dirname(path)} holds one system, and two would share its programs and persistent state`)
+ }
- return path
+ if (namedPipe) throw error
+
+ rmSync(path, { force: true })
+ }
+ }
}
function alive(path: string) {
diff --git a/source/server/view/gateway/program-request.ts b/source/server/view/gateway/program-request.ts
deleted file mode 100644
index 1247d3d..0000000
--- a/source/server/view/gateway/program-request.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import type Application from "@server/core/application"
-import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
-import type { Socket } from "node:net"
-
-/** Execute a streamed owner-local Program lifecycle request. */
-export default async function programRequest(application: Application, socket: Socket, value: unknown) {
-
- if (!record(value)) throw new Error("The Program request must be an object")
-
- const asked = value as Asked
- const attached = new Set<string>()
- const say = (event: Record<string, unknown>) => {
-
- if (socket.writable) socket.write(`${JSON.stringify(event)}\n`)
- }
- const done = () => socket.end()
-
- socket.on("close", function () {
-
- for (const identity of attached) {
-
- const process = application.system.findProcess(identity)
-
- if (process) application.system.exitProcess(process).catch(() => undefined)
- }
-
- attached.clear()
- })
-
- const system = application.system
-
- if (asked.word === "create") {
-
- if (!asked.program) throw new Error("Creating needs a Program definition")
-
- const program = await system.createProgram(asked.program)
- const entry = system.requireProgram(program.identity)
-
- say({ event: "created", program: system.programSnapshot(entry) })
- return done()
- }
-
- if (asked.word === "force-create") {
-
- if (!asked.program) throw new Error("Creating needs a Program definition")
-
- const program = await system.forceCreateProgram(asked.program)
- const entry = system.requireProgram(program.identity)
-
- say({ event: "created", program: system.programSnapshot(entry) })
- return done()
- }
-
- if (asked.word === "fork") {
-
- const program = system.holdProgram(asked.handle)
-
- if (typeof asked.identity !== "string") throw new Error("Forking needs a Program identity")
-
- const forked = await system.forkProgram(program, asked.identity)
- const entry = system.requireProgram(forked.identity)
-
- say({ event: "created", program: system.programSnapshot(entry) })
- return done()
- }
-
- if (asked.word === "run-process") {
-
- const program = system.holdProgram(asked.handle)
- let identity: string | null = null
- let ended = false
- let processRecord: ReturnType<Process["record"]> | null = null
-
- identity = await system.runProcess(program, asked.launch ?? {}, {
- started: process => {
-
- processRecord = process.record()
- attached.add(process.identity)
- say({ event: "started", process: system.processSnapshot(process) })
- },
- output: (stream, text) => say({ event: "output", stream: stream === "err" ? "stderr" : "stdout", text }),
- exited: function (code, signal) {
-
- ended = true
- if (identity) attached.delete(identity)
- say({
- event: "exited",
- process: processRecord,
- exit: { status: signal ? "signaled" : "exited", code, signal }
- })
- done()
- }
- })
-
- if (ended) return
-
- if (socket.destroyed) {
-
- const process = system.findProcess(identity)
-
- if (process) await system.exitProcess(process)
-
- return
- }
- return
- }
-
- if (asked.word === "installed") {
-
- const program = system.holdProgram(asked.handle)
- const entry = system.findProgram(program.identity)
-
- say({ event: "installedState", installed: entry?.installed === true })
- return done()
- }
-
- if (asked.word === "startup") {
-
- const program = system.holdProgram(asked.handle)
- const operation = asked.operation
-
- if (operation !== "get" && operation !== "enable" && operation !== "disable") throw new Error("Startup must be read, enabled, or disabled")
-
- const launch = await system.programStartup(program, operation, asked.launch)
-
- say({ event: "startup", launch })
- return done()
- }
-
- if (asked.word === "create-process") {
-
- const program = system.holdProgram(asked.handle)
- const identity = await system.createProcess(program, asked.launch ?? {})
- const process = system.findProcess(identity)
-
- if (!process) throw new Error("The created Process no longer exists")
-
- say({ event: "createdProcess", process: system.processSnapshot(process) })
- return done()
- }
-
- if (asked.word === "find-or-create-process") {
-
- const program = system.holdProgram(asked.handle)
- const identity = await system.findOrCreateProcess(program, asked.launch as NonNullable<Asked["launch"]> & { name: string })
- const process = system.findProcess(identity)
-
- if (!process) throw new Error("The created Process no longer exists")
-
- say({ event: "createdProcess", process: system.processSnapshot(process) })
- return done()
- }
-
- if (asked.word === "forget") {
-
- const program = system.holdProgram(asked.handle)
-
- await system.forgetProgram(program)
-
- say({ event: "forgotten", identity: program.identity })
- return done()
- }
-
- if (asked.word === "install-existing") {
-
- const program = system.holdProgram(asked.handle)
-
- for await (const chunk of system.installProgram(program)) say({ event: "output", ...chunk })
-
- say({ event: "installed", identity: program.identity })
- return done()
- }
-
- if (asked.word === "uninstall-existing") {
-
- const program = system.holdProgram(asked.handle)
-
- for await (const chunk of system.uninstallProgram(program, asked.everything === true)) say({ event: "output", ...chunk })
-
- say({ event: "uninstalled", identity: program.identity, everything: asked.everything === true })
- return done()
- }
-
- throw new Error(`The Program transport does not know the word "${String(asked.word)}"`)
-}
-
-function record(value: unknown): value is Record<string, unknown> {
-
- return typeof value === "object" && value !== null && !Array.isArray(value)
-}
-
-interface Asked {
-
- word?: string
- everything?: boolean
- handle?: unknown
- identity?: string
- operation?: string
- launch?: Parameters<Application["system"]["runProcess"]>[1]
- program?: Parameters<Application["system"]["forceCreateProgram"]>[0]
-}
diff --git a/source/server/view/gateway/system-control.ts b/source/server/view/gateway/system-control.ts
deleted file mode 100644
index db32c5c..0000000
--- a/source/server/view/gateway/system-control.ts
+++ /dev/null
@@ -1,397 +0,0 @@
-import {
- systemControlInputIssue,
- systemControlOperation,
- type EndpointAskInput,
- type EndpointInput,
- type EndpointWaitLifecycleInput,
- type EndpointPublishInput,
- type EndpointStartInput,
- type EndpointWaitInput,
- type EndpointWaitReadyInput,
- type ProcessCreateInput,
- type ProcessFindOrCreateInput,
- type ProcessInput,
- type ProcessListInput,
- type ProcessWaitInput,
- type ProgramInput,
- type ProgramListInput,
- type ProgramWaitInput,
- type SystemControlRequest,
- type SystemControlOperation,
- type WindowInput,
- type WindowWaitInput
-} from "@phreshos/core"
-import { z } from "zod"
-import type System from "@server/core/system"
-import type Entry from "@server/core/link-manager/auth-manager/program-manager/entry"
-import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
-
-const envelope = z.object({
- capability: z.string(),
- operation: z.string(),
- input: z.unknown()
-}).strict()
-
-const inputs = new WeakMap<SystemControlOperation, z.ZodType>()
-
-/** Owner-Gateway adapter for the neutral serialized System operation contract. */
-export default class SystemControl {
-
- public constructor(private readonly system: System) {}
-
- public async execute(value: unknown, signal?: AbortSignal) {
-
- const request = envelope.parse(value)
- const operation = systemControlOperation(request.capability, request.operation)
-
- if (!operation) throw new Error(`Unknown System control operation "${request.capability}.${request.operation}"`)
-
- let validator = inputs.get(operation)
-
- if (!validator) {
-
- validator = z.fromJSONSchema(operation.input as Parameters<typeof z.fromJSONSchema>[0])
- inputs.set(operation, validator)
- }
-
- const input = validator.parse(request.input)
- const issue = systemControlInputIssue(request.capability, request.operation, input)
-
- if (issue) throw new Error(issue)
-
- const normalized = { capability: request.capability, operation: request.operation, input } as SystemControlRequest
-
- if (normalized.capability === "program") return this.program(normalized.operation, normalized.input, signal)
- if (normalized.capability === "process") return this.process(normalized.operation, normalized.input, signal)
- if (normalized.capability === "endpoint") return this.endpoint(normalized.operation, normalized.input, signal)
- return this.window(normalized.operation, normalized.input, signal)
- }
-
- private async program(operation: string, input: ProgramListInput | ProgramInput | ProgramWaitInput, signal?: AbortSignal) {
-
- if (operation === "list") {
-
- const request = input as ProgramListInput
- const installedOnly = request.installedOnly ?? true
- const query = request.search?.toLocaleLowerCase()
- const found = this.system.listPrograms(installedOnly).filter(entry => (
- !query || [entry.identity, entry.program.name, entry.program.config.description]
- .some(value => value?.toLocaleLowerCase().includes(query)))
- )
- const selected = found
- .sort((left, right) => left.identity.localeCompare(right.identity))
- .slice(request.offset ?? 0, (request.offset ?? 0) + (request.limit ?? 30))
-
- return Object.freeze({
- data: Object.freeze(selected.map(entry => this.system.programSnapshot(entry))),
- total: found.length,
- truncated: (request.offset ?? 0) + selected.length < found.length
- })
- }
-
- if (operation === "wait") return this.waitProgram(input as ProgramWaitInput, signal)
-
- const entry = this.system.requireProgram((input as ProgramInput).program)
-
- if (operation === "inspect") return this.system.programSnapshot(entry)
-
- const content = await this.system.programAgent(entry.program)
-
- if (content === null) throw new Error(`Program "${entry.identity}" has no agent documentation`)
-
- return Object.freeze({ program: entry.identity, content })
- }
-
- private async process(operation: string, input: ProcessListInput | ProcessInput | ProcessCreateInput | ProcessFindOrCreateInput | ProcessWaitInput, signal?: AbortSignal) {
-
- if (operation === "list") {
-
- const request = input as ProcessListInput
- const owner = request.program ? this.system.requireProgram(request.program).program : null
- const query = request.search?.toLocaleLowerCase()
- const found = this.system.listProcesses(owner ?? undefined).filter(process => (
- !query || [process.identity, process.name, process.program.identity]
- .some(value => value?.toLocaleLowerCase().includes(query)))
- )
- const selected = found
- .sort((left, right) => right.startedAt.getTime() - left.startedAt.getTime())
- .slice(request.offset ?? 0, (request.offset ?? 0) + (request.limit ?? 30))
-
- return Object.freeze({
- data: Object.freeze(selected.map(process => this.system.processSnapshot(process))),
- total: found.length,
- truncated: (request.offset ?? 0) + selected.length < found.length
- })
- }
-
- if (operation === "wait") return this.waitProcess(input as ProcessWaitInput, signal)
-
- if (operation === "create" || operation === "findOrCreate") {
-
- const request = input as ProcessCreateInput | ProcessFindOrCreateInput
- const identity = operation === "create"
- ? await this.system.createProcess(request.program, request.launch)
- : await this.system.findOrCreateProcess(
- request.program,
- (request as ProcessFindOrCreateInput).launch
- )
-
- return this.system.processSnapshot(this.system.requireProcess(identity))
- }
-
- const request = input as ProcessInput
- const process = this.system.resolveProcess(request)
- const snapshot = this.system.processSnapshot(process)
-
- if (operation === "exit") {
-
- await this.system.exitProcess(process)
-
- return Object.freeze({ ...snapshot, exited: true })
- }
-
- return snapshot
- }
-
- private async endpoint(operation: string, input: EndpointInput | EndpointStartInput | EndpointWaitReadyInput | EndpointWaitLifecycleInput | EndpointAskInput | EndpointPublishInput | EndpointWaitInput, signal?: AbortSignal) {
-
- const process = this.system.resolveProcess(input)
- const declaration = process.program[input.endpoint]
-
- if (!declaration) throw new Error(`Program "${process.program.identity}" does not declare a ${input.endpoint} Endpoint`)
-
- if (operation === "inspect") return this.system.endpointSnapshot(process, input.endpoint)
-
- if (operation === "start" || operation === "stop") {
-
- if (operation === "start") {
-
- const request = input as EndpointStartInput
-
- if (request.endpoint === "server") await this.system.startEndpoint(process, "server", request.launch)
- else await this.system.startEndpoint(process, "client", request.launch)
- } else {
- await this.system.stopEndpoint(process, input.endpoint)
- }
-
- return this.system.endpointSnapshot(process, input.endpoint)
- }
-
- if (operation === "waitReady") {
-
- const request = input as EndpointWaitReadyInput
-
- await waitReady(process, request.endpoint, request.timeout, signal)
-
- return this.system.endpointSnapshot(process, request.endpoint)
- }
-
- if (operation === "waitLifecycle") {
-
- const request = input as EndpointWaitLifecycleInput
- const internalEvent = request.event === "start" ? "endpointStart" : "endpointStop"
-
- await waitFor<void>(resolve => this.system.observe(
- "process",
- internalEvent,
- process.reference,
- (_event, _record, endpoint) => { if (endpoint === request.endpoint) resolve() }
- ), request.timeout, signal)
-
- return Object.freeze({
- scope: "endpoint.lifecycle",
- process: process.identity,
- endpoint: request.endpoint,
- event: request.event,
- payload: undefined
- })
- }
-
- if (operation === "ask") {
-
- const request = input as EndpointAskInput
-
- return this.system.askEndpoint(
- process,
- request.event,
- request.payload,
- request.timeout,
- signal
- )
- }
-
- if (operation === "publish") {
-
- const request = input as EndpointPublishInput
-
- await this.system.publishEndpoint(process, request.endpoint, request.event, request.payload)
-
- return Object.freeze({ ...this.system.endpointSnapshot(process, request.endpoint), event: request.event, published: true })
- }
-
- const request = input as EndpointWaitInput
- const payload = await waitFor(
- (resolve, reject) => this.system.observeEndpoint(
- process,
- request.endpoint,
- request.event,
- resolve,
- reason => reject(new Error(reason))
- ),
- request.timeout,
- signal
- )
-
- return Object.freeze({
- scope: "endpoint",
- process: process.identity,
- endpoint: request.endpoint,
- event: request.event,
- payload
- })
- }
-
- private async window(operation: string, input: WindowInput | WindowWaitInput | (WindowInput & Record<string, unknown>), signal?: AbortSignal) {
-
- const process = this.system.resolveProcess(input)
- const request = input as WindowInput & Record<string, unknown>
-
- if (!process.client) throw new Error(`Process "${process.identity}" has no running Client Endpoint`)
-
- if (operation === "wait") {
-
- const waiting = input as WindowWaitInput
- const payload = await waitFor(
- (resolve, reject) => {
-
- const stopObservation = this.system.observe("window", waiting.event, process.reference, (_event, _subject, value) => resolve(value))
- const stopProcess = process.onExit(() => reject(new Error(`Process "${process.identity}" exited while waiting for its Window`)))
- const stopClient = process.onClientStop(() => reject(new Error(`The Client Endpoint stopped while waiting for Process "${process.identity}" Window`)))
-
- return () => { stopObservation(); stopProcess(); stopClient() }
- },
- waiting.timeout,
- signal
- )
-
- return Object.freeze({ scope: "window", process: process.identity, event: waiting.event, payload })
- }
-
- if (operation === "move") await this.system.moveWindow(process, request.position as never)
- else if (operation === "resize") await this.system.resizeWindow(process, request.size as never)
- else if (operation === "setGeometry") await this.system.setWindowGeometry(process, {
- position: request.position as never,
- size: request.size as never
- })
- else if (operation === "minimize") await this.system.minimizeWindow(process, request.minimized !== false)
- else if (operation === "changeTitle") await this.system.changeWindowTitle(process, String(request.title))
- else if (operation === "raise") await this.system.raiseWindow(process)
-
- return Object.freeze({ process: process.identity, ...this.system.windowSnapshot(process) })
- }
-
- private async waitProgram(request: ProgramWaitInput, signal?: AbortSignal) {
-
- const entry = request.program ? this.system.requireProgram(request.program) : null
- const subject = entry?.program.reference ?? null
- const values = await waitFor<unknown[]>(
- resolve => this.system.observe("program", request.event, subject, (_event, ...payload) => resolve(payload)),
- request.timeout,
- signal
- )
-
- const affected = entry ?? values.find(value => value && typeof value === "object" && "program" in value) as Entry | undefined
- ?? values.find(value => value && typeof value === "object" && "installed" in value) as Entry | undefined
-
- return Object.freeze({
- scope: entry ? "program" : "host",
- ...(entry ? { program: this.system.programSnapshot(entry) } : {}),
- event: request.event,
- payload: request.event === "uninstall"
- ? Object.freeze({
- ...(affected ? { program: this.system.programSnapshot(affected) } : {}),
- everything: values.at(-1) === true
- })
- : affected ? this.system.programSnapshot(affected) : values
- })
- }
-
- private async waitProcess(request: ProcessWaitInput, signal?: AbortSignal) {
-
- const process = request.process
- ? this.system.resolveProcess(request as ProcessInput)
- : null
- const program = !process && request.program
- ? this.system.requireProgram(request.program)
- : null
- const subject = process?.reference ?? program?.program.reference ?? null
- const values = await waitFor<unknown[]>(
- resolve => this.system.observe("process", request.event, subject, (_event, ...payload) => resolve(payload)),
- request.timeout,
- signal
- )
- const record = values.find(value => value && typeof value === "object" && "identity" in value) as Parameters<System["processSnapshotFromReference"]>[0] | undefined
-
- return Object.freeze({
- scope: process ? "process" : program ? "program" : "host",
- ...(process ? { process: process.identity } : {}),
- ...(program ? { program: program.identity } : {}),
- event: request.event,
- payload: request.event === "exit"
- ? Object.freeze({
- process: record?.identity ?? process?.identity ?? null,
- ...(record ? { processSnapshot: this.system.processSnapshotFromReference(record) } : {}),
- status: values.at(-1) ? "signaled" : "exited",
- code: values.at(-2) ?? null,
- signal: values.at(-1) ?? null
- })
- : record ? this.system.processSnapshotFromReference(record) : values
- })
- }
-
-}
-
-
-function waitReady(process: Process, endpoint: "server" | "client", timeout = 10_000, signal?: AbortSignal) {
-
- return waitFor<void>((resolve, reject) => {
-
- const stopReady = process.waitReady(endpoint, resolve)
- const stopExit = process.onExit(() => reject(new Error(`Process "${process.identity}" exited before its ${endpoint} Endpoint became ready`)))
-
- return () => { stopReady(); stopExit() }
- }, timeout, signal)
-}
-
-function waitFor<Value>(subscribe: (resolve: (value: Value) => void, reject: (error: Error) => void) => () => void, timeout = 10_000, signal?: AbortSignal) {
-
- return new Promise<Value>((resolve, reject) => {
-
- let done = false
- let cleanup: () => void = () => undefined
- const finish = (work: () => void) => {
-
- if (done) return
-
- done = true
- clearTimeout(timer)
- signal?.removeEventListener("abort", cancel)
- cleanup()
- work()
- }
- const cancel = () => finish(() => reject(signal?.reason instanceof Error ? signal.reason : new Error("The wait was cancelled")))
- const timer = setTimeout(() => finish(() => reject(new Error(`Event promise timeout ${timeout}ms`))), timeout)
-
- const subscribed = subscribe(
- value => finish(() => resolve(value)),
- error => finish(() => reject(error))
- )
-
- cleanup = subscribed
-
- if (done) cleanup()
-
- if (signal?.aborted) cancel()
- else signal?.addEventListener("abort", cancel, { once: true })
- })
-}
diff --git a/source/server/view/gateway/system-request.ts b/source/server/view/gateway/system-request.ts
deleted file mode 100644
index f82161a..0000000
--- a/source/server/view/gateway/system-request.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import type Application from "@server/core/application"
-import SystemControl from "./system-control"
-
-const adapters = new WeakMap<Application, SystemControl>()
-
-/** Execute a short owner-local System request. */
-export default async function systemRequest(application: Application, request: unknown, signal: AbortSignal) {
-
- let adapter = adapters.get(application)
-
- if (!adapter) {
-
- adapter = new SystemControl(application.system)
- adapters.set(application, adapter)
- }
-
- return adapter.execute(request, signal)
-}
diff --git a/source/server/view/doors.ts b/source/server/view/http/doors.ts
similarity index 100%
rename from source/server/view/doors.ts
rename to source/server/view/http/doors.ts
diff --git a/source/server/view/link.ts b/source/server/view/http/link.ts
similarity index 100%
rename from source/server/view/link.ts
rename to source/server/view/http/link.ts
diff --git a/source/server/view/program-development.ts b/source/server/view/http/program/development.ts
similarity index 100%
rename from source/server/view/program-development.ts
rename to source/server/view/http/program/development.ts
diff --git a/source/server/view/program.ts b/source/server/view/http/program/program.ts
similarity index 98%
rename from source/server/view/program.ts
rename to source/server/view/http/program/program.ts
index 073abd7..e9534fb 100644
--- a/source/server/view/program.ts
+++ b/source/server/view/http/program/program.ts
@@ -3,8 +3,8 @@ import Application from "@server/core/application"
import { isIconSize } from "@server/core/link-manager/auth-manager/program-manager/icon"
import { existsSync } from "node:fs"
import { Hono } from "hono"
-import doors from "./doors"
-import { developmentResponse, developmentSocket, developmentTarget } from "./program-development"
+import doors from "../doors"
+import { developmentResponse, developmentSocket, developmentTarget } from "./development"
/**
* The browser representation of one Program domain.
diff --git a/source/server/view/proxy.ts b/source/server/view/http/proxy.ts
similarity index 100%
rename from source/server/view/proxy.ts
rename to source/server/view/http/proxy.ts
diff --git a/source/server/view/storage.ts b/source/server/view/http/storage.ts
similarity index 100%
rename from source/server/view/storage.ts
rename to source/server/view/http/storage.ts
diff --git a/source/server/view/uploads.ts b/source/server/view/http/uploads.ts
similarity index 100%
rename from source/server/view/uploads.ts
rename to source/server/view/http/uploads.ts
diff --git a/source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts b/source/server/view/server-runtime.ts
similarity index 74%
rename from source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts
rename to source/server/view/server-runtime.ts
index 37c4936..6e00299 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/server-runtime.ts
+++ b/source/server/view/server-runtime.ts
@@ -2,18 +2,22 @@ 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"
-export interface ServerRuntime {
+/** Create the concrete host runtime selected by one Program declaration. */
+export default function serverRuntime(program: Program): ServerRuntime {
- readonly finished: Promise<Ending>
+ const server = program.server
- send(message: Uint8Array): void
+ if (!server) throw new Error("This program declared no server half")
- onMessage(listener: (message: unknown) => void): void
+ return server.startCommand !== undefined
- onOutput(listener: OutputListener): void
+ ? new CommandServerRuntime(server.startCommand, program.serverPath!)
- stop(): void
+ : new WorkerServerRuntime(program.serverEntryPath!)
}
/** One Server running as an isolated operating-system process tree. */
@@ -62,9 +66,9 @@ export class CommandServerRuntime implements ServerRuntime {
this.child.on("error", () => undefined)
}
- public send(message: Uint8Array) { this.child.send!(message) }
+ public send(event: string, ...values: unknown[]) { this.child.send!(messagepack.serialize([event, ...values])) }
- public onMessage(listener: (message: unknown) => void) { this.inbox.listen(listener) }
+ public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }
public onOutput(listener: OutputListener) {
@@ -124,9 +128,9 @@ export class WorkerServerRuntime implements ServerRuntime {
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 send(event: string, ...values: unknown[]) { this.worker.postMessage(messagepack.serialize([event, ...values])) }
- public onMessage(listener: (message: unknown) => void) { this.inbox.listen(listener) }
+ public onMessage(listener: (event: string, ...values: unknown[]) => void) { this.inbox.listen(listener) }
public onOutput(listener: OutputListener) {
@@ -164,29 +168,41 @@ export class WorkerServerRuntime implements ServerRuntime {
class RuntimeInbox {
- private listener: ((message: unknown) => void) | null = null
+ private listener: ((event: string, ...values: unknown[]) => void) | null = null
- private readonly pending: unknown[] = []
+ private readonly pending: ServerRuntimeMessage[] = []
public receive(message: unknown) {
- if (this.listener) this.listener(message)
+ const bytes = commandMessageBytes(message)
- else if (this.pending.length < maximumPendingMessages) this.pending.push(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: (message: unknown) => void) {
+ 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)
+ 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 }
diff --git a/source/server/view/view.ts b/source/server/view/view.ts
index 596c07b..f0bccb5 100644
--- a/source/server/view/view.ts
+++ b/source/server/view/view.ts
@@ -1,21 +1,22 @@
import Application from "@server/core/application"
import { serveStatic } from "@hono/node-server/serve-static"
-import { createAdaptorServer, type ServerType } from "@hono/node-server"
+import { createAdaptorServer } from "@hono/node-server"
import { WebSocketServer } from "ws"
-import doors from "./doors"
+import doors from "./http/doors"
import gateway from "./gateway/gateway"
import gatewayAddress from "./gateway/address"
-import program from "./program"
-import proxy from "./proxy"
-import storage from "./storage"
-import uploads from "./uploads"
-import link from "./link"
+import program from "./http/program/program"
+import proxy from "./http/proxy"
+import storage from "./http/storage"
+import uploads from "./http/uploads"
+import link from "./http/link"
import cfonts from "cfonts"
import { Hono } from "hono"
-import { isAbsolute, normalize, resolve } from "node:path"
-import { readFile, rm, writeFile } from "node:fs/promises"
+import { resolve } from "node:path"
+import { writeFile } from "node:fs/promises"
import { styleText } from "node:util"
-import environment from "@libs/environment"
+import serverRuntime from "./server-runtime"
+import { listenOnPorts } from "./configuration"
export default async function (config: Config) {
@@ -28,7 +29,7 @@ export default async function (config: Config) {
font: "simple"
})
- const application = await Application.initialize(config.name, config.displayName, config.version, config.home, resolve("assets/default-icon.png"))
+ const application = await Application.initialize(config.name, config.displayName, config.version, config.home, resolve("assets/default-icon.png"), serverRuntime)
// One server, five doors, each at its own name. A program's client
// is still not the API — it is files a browser reads, with no link,
@@ -66,7 +67,7 @@ export default async function (config: Config) {
await writeFile(resolve(application.storage.path, "desktop"), `${origin}\n`, { mode: 0o600 })
- const localGateway = await gateway(application, gatewayAddress(application.storage.path))
+ const localGateway = await gateway(application.linkManager, gatewayAddress(application.storage.path))
if (config.assets) console.log(` ➜ ${styleText("bold", "Desktop:")} ${origin}`)
@@ -95,189 +96,3 @@ export interface Config {
/** Ordered public port candidates. Omit to let the operating system assign one. */
ports?: readonly number[]
}
-
-/** Expand one inclusive TCP port range. */
-export function portRange(from: number, to: number) {
-
- return Array.from({ length: to - from + 1 }, (_, index) => from + index)
-}
-
-/** Read the optional ordered production port selection. */
-export function environmentPorts(name: string, variables: NodeJS.ProcessEnv) {
-
- const selected = environment(name, "PORT", variables)
-
- if (selected.value === undefined) return undefined
-
- return parsePorts(selected.value, selected.key)
-}
-
-/** Parse comma-separated TCP ports and inclusive ranges in declared order. */
-export function parsePorts(value: string, name = "Port selection") {
-
- const ports: number[] = []
-
- const included = new Set<number>()
-
- for (const part of value.split(",")) {
-
- const match = /^(\d+)(?:-(\d+))?$/.exec(part)
-
- if (!match) throw portSelectionError(name)
-
- const from = Number(match[1])
-
- const to = Number(match[2] ?? match[1])
-
- if (!validPort(from) || !validPort(to) || from > to) throw portSelectionError(name)
-
- for (let port = from; port <= to; port++) {
-
- if (included.has(port)) continue
-
- included.add(port)
-
- ports.push(port)
- }
- }
-
- return Object.freeze(ports)
-}
-
-/** Consume the optional one-time port selection supplied through the native service boundary. */
-export async function requestedPorts(arguments_: string[]) {
-
- const positions = arguments_.flatMap((value, index) => value === "--port-request" ? [index] : [])
-
- if (positions.length === 0) return undefined
-
- if (positions.length !== 1) throw new Error("--port-request can be supplied only once")
-
- const path = arguments_[positions[0]! + 1]
-
- if (!path || !isAbsolute(path)) throw new Error("--port-request must be followed by an absolute filesystem path")
-
- let value: string
-
- try { value = (await readFile(path, "utf8")).trim() }
-
- catch (error) {
-
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
-
- throw error
- }
-
- await rm(path, { force: true })
-
- return parsePorts(value, "The requested PhreshOS port selection")
-}
-
-/** Bind one server to the first available candidate or an assigned port. */
-export async function listenOnPorts(server: ServerType, hostname: string, ports?: readonly number[]) {
-
- for (const port of ports ?? [0]) {
-
- const address = await tryListen(server, hostname, port)
-
- if (address !== null) return address
- }
-
- throw new Error("No configured System port is available")
-}
-
-function tryListen(server: ServerType, hostname: string, port: number) {
-
- return new Promise<number | null>((resolve, reject) => {
-
- const failed = (error: NodeJS.ErrnoException) => {
-
- server.off("error", failed)
-
- if (error.code === "EADDRINUSE" || error.code === "EACCES") resolve(null)
-
- else reject(error)
- }
-
- server.once("error", failed)
-
- server.listen(port, hostname, () => {
-
- server.off("error", failed)
-
- const address = server.address()
-
- if (!address || typeof address === "string") reject(new Error("The System listener has no TCP address"))
-
- else resolve(address.port)
- })
- })
-}
-
-function validPort(value: number) {
-
- return Number.isInteger(value) && value >= 1 && value <= 65_535
-}
-
-function portSelectionError(name: string) {
-
- return new Error(`${name} must contain ports or inclusive ranges from 1 to 65535`)
-}
-
-/** Read the stable fallback home supplied by the native service definition. */
-export function defaultHome(arguments_: string[]) {
-
- const positions = arguments_.flatMap((value, index) => value === "--default-home" ? [index] : [])
-
- if (positions.length === 0) return undefined
- if (positions.length !== 1) throw new Error("--default-home can be supplied only once")
-
- const value = arguments_[positions[0]! + 1]
-
- if (!value || !isAbsolute(value)) throw new Error("--default-home must be followed by an absolute filesystem path")
-
- return normalize(value)
-}
-
-/** Consume the optional one-time home request supplied through the native service boundary. */
-export async function requestedHome(arguments_: string[]) {
-
- const positions = arguments_.flatMap((value, index) => value === "--home-request" ? [index] : [])
-
- if (positions.length === 0) return undefined
- if (positions.length !== 1) throw new Error("--home-request can be supplied only once")
-
- const path = arguments_[positions[0]! + 1]
-
- if (!path || !isAbsolute(path)) throw new Error("--home-request must be followed by an absolute filesystem path")
-
- let value: string
-
- try { value = (await readFile(path, "utf8")).trim() }
- catch (error) {
-
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined
- throw error
- }
-
- await rm(path, { force: true })
-
- if (!isAbsolute(value)) throw new Error("The requested PhreshOS home must be an absolute filesystem path")
-
- return normalize(value)
-}
-
-/** Read the optional public port override named from the application identity. */
-/** Read the optional absolute authoritative home selected by Main's environment. */
-export function environmentHome(name: string, variables: NodeJS.ProcessEnv) {
-
- const selected = environment(name, "HOME", variables)
-
- const value = selected.value
-
- if (value === undefined) return undefined
-
- if (!isAbsolute(value)) throw new Error(`${selected.key} must be an absolute filesystem path`)
-
- return resolve(value)
-}