Skip to content

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

Release System 0.1.51

zohayrslileh582a2e8ad374
diff --git a/bun.lock b/bun.lock
index 7c5887b..f18246d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9,7 +9,7 @@
"@hono/node-server": "^2.1.1",
"@msgpack/msgpack": "^3.1.3",
"@phreshos/client": "^0.1.28",
- "@phreshos/server": "^0.1.29",
+ "@phreshos/server": "^0.1.31",
"cfonts": "^3.3.1",
"get-port": "^7.2.0",
"gsap": "^3.15.0",
@@ -26,7 +26,7 @@
"devDependencies": {
"@babel/core": "^7.29.7",
"@babel/plugin-proposal-decorators": "^7.29.7",
- "@phreshos/core": "^0.1.29",
+ "@phreshos/core": "^0.1.30",
"@phreshos/react-ui": "^0.1.13",
"@rolldown/plugin-babel": "^0.2.3",
"@tailwindcss/vite": "^4.3.3",
@@ -236,11 +236,11 @@
"@phreshos/client": ["@phreshos/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" }, "peerDependencies": { "@phreshos/core": "^0.1.29" } }, "sha512-bwVc3hC24o5fqGifCrXPLq9aCEnIpJ8rqGx6cScsA1sJXKGnuShhfa8Mcj4wYuEEE1GG4dmKxsVmwkFe14Vjqw=="],
- "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-zDzxkf+ETuesTjuNC2f/+kKiFkiPhhShFa2OROsPHRDRLC0PZybmAwdu35AmwEpvmORxOvtkXYImEa66bdTJ4A=="],
+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-l7/jDMZqcYVdpl4RjM6zF4tQVreWVhiNlWJL4ijhsLQbF6Waal7rwoQBaS3eJKY5s/ULQlmlQ17LQCxeYjoP4w=="],
"@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "react-aria-components": "^1.20.0" }, "peerDependencies": { "@phreshos/core": "^0.1.22", "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-0UnyNPWnP+9vCUCC9gi+Km+bW78hFErSQkmTlCuU1rNVRFuuVaNlZ0kmEuAxx7Ns1thMZ3bApzOjsMbMtmPzCA=="],
- "@phreshos/server": ["@phreshos/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" }, "peerDependencies": { "@phreshos/core": "^0.1.29" } }, "sha512-cpLsqYREZCsxJR5g+BVawbZJKHggd1+8Qo6/ad/YHSoP7fWCHa1Gx97Yuz44Jx7DUfnJS+uZLKEbKV1Auol4PA=="],
+ "@phreshos/server": ["@phreshos/[email protected]", "", { "dependencies": { "@msgpack/msgpack": "^3.1.3" }, "peerDependencies": { "@phreshos/core": "^0.1.30" } }, "sha512-NMxPhmSMTozAsYm1kaL0Lgj3BIzVpmGsbRTrokTuJ9CCH6tVA0BsOjUWY8Mi1GmBTetIhTJgoPoTRLd2a60G2g=="],
"@react-types/shared": ["@react-types/[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AzsuD9OfxTOZMMvTRhlN3oHBwOmFN7tDh27LzqmHt4+uOgPhJT7ZM7/kVs/8/o0WxayMUIk3hBmCFRHv1FUoag=="],
diff --git a/package.json b/package.json
index 6554a58..ccd27f2 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "phreshos",
"displayName": "PhreshOS",
- "version": "0.1.50",
+ "version": "0.1.51",
"description": "The PhreshOS server, desktop, and authoritative system runtime.",
"type": "module",
"private": true,
@@ -38,8 +38,8 @@
"@fontsource/roboto": "^5.3.0",
"@hono/node-server": "^2.1.1",
"@msgpack/msgpack": "^3.1.3",
- "@phreshos/client": "^0.1.28",
- "@phreshos/server": "^0.1.29",
+ "@phreshos/client": "^0.1.28",
+ "@phreshos/server": "^0.1.31",
"cfonts": "^3.3.1",
"get-port": "^7.2.0",
"gsap": "^3.15.0",
@@ -56,8 +56,8 @@
"devDependencies": {
"@babel/core": "^7.29.7",
"@babel/plugin-proposal-decorators": "^7.29.7",
- "@phreshos/core": "^0.1.29",
- "@phreshos/react-ui": "^0.1.13",
+ "@phreshos/core": "^0.1.30",
+ "@phreshos/react-ui": "^0.1.13",
"@rolldown/plugin-babel": "^0.2.3",
"@tailwindcss/vite": "^4.3.3",
"@types/adm-zip": "^0.5.8",
diff --git a/scripts/contracts/gateway-api.ts b/scripts/contracts/gateway-api.ts
new file mode 100644
index 0000000..d58ae4a
--- /dev/null
+++ b/scripts/contracts/gateway-api.ts
@@ -0,0 +1,115 @@
+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" }
+const calls: unknown[][] = []
+const system = {
+ requireProgram(identity: string) {
+
+ assert.equal(identity, program.identity)
+ 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])
+ },
+ 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 }]
+ },
+ 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",
+ program: "example",
+ area: "data"
+}, signal), "/system/programs/example/storage")
+
+assert.deepEqual(await apiRequest(application, {
+ capability: "program",
+ operation: "icon",
+ program: "example",
+ size: "medium"
+}, signal), [1, 2, 3])
+
+assert.equal(await apiRequest(application, {
+ capability: "program",
+ operation: "store",
+ program: "example",
+ storeOperation: "get",
+ key: "state"
+}, signal), "stored")
+
+assert.deepEqual(await apiRequest(application, {
+ capability: "program",
+ operation: "query",
+ program: "example",
+ database: "logs",
+ statement: "select ?",
+ values: [1]
+}, signal), [{ statement: "select ?", values: [1] }])
+
+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"],
+ ["store", "get", "state", undefined, undefined],
+ ["query", "logs"],
+ ["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 7c0a5b9..e5375be 100644
--- a/scripts/contracts/gateway.ts
+++ b/scripts/contracts/gateway.ts
@@ -8,9 +8,34 @@ import type Application from "@server/core/application"
const directory = await mkdtemp(resolve(".verify-gateway-"))
const path = gatewayAddress(directory)
+const entry = {
+ installed: false,
+ program: { identity: "example" }
+}
+const programSnapshot = {
+ reference: "example-reference",
+ identity: "example",
+ name: "Example",
+ version: "1.0.0",
+ description: null,
+ installed: false,
+ hasAgent: false,
+ server: null,
+ client: { start: true }
+}
const application = {
- systemControl: {
- async execute(request: unknown) { return { received: request } }
+ system: {
+ listPrograms() { return [] },
+ async forceCreateProgram() { return entry.program },
+ requireProgram() { return entry },
+ programSnapshot() { return programSnapshot },
+ holdProgram(handle: { identity?: string, reference?: string }) {
+
+ assert.deepEqual(handle, { identity: "example", reference: "example-reference" })
+ return entry.program
+ },
+ async *installProgram() {},
+ findProcess() { return null }
},
linkManager: {
authManager: {
@@ -18,30 +43,7 @@ const application = {
processes: new Map(),
async exit() {}
},
- programManager: {
- async forceCreate() { return { identity: "example" } },
- find() {
- return {
- record() {
- return {
- reference: "example-reference",
- identity: "example",
- name: "Example",
- version: "1.0.0",
- description: null,
- hasAgent: false,
- server: null,
- client: { start: true }
- }
- }
- }
- },
- held(handle: { identity?: string, reference?: string }) {
- assert.deepEqual(handle, { identity: "example", reference: "example-reference" })
- return { identity: "example" }
- },
- async *installStreaming() {}
- }
+ programManager: {}
}
}
}
@@ -51,7 +53,7 @@ const server = await gateway(application as unknown as Application, path)
try {
const system = await exchange(path, { target: "system", request: { capability: "program", operation: "list", input: {} } })
- assert.deepEqual(system, [{ success: true, result: { received: { capability: "program", operation: "list", input: {} } } }])
+ assert.deepEqual(system, [{ success: true, result: { data: [], total: 0, truncated: false } }])
const created = await exchange(path, {
target: "program",
@@ -66,6 +68,7 @@ try {
name: "Example",
version: "1.0.0",
description: null,
+ installed: false,
hasAgent: false,
server: null,
client: { start: true }
@@ -87,7 +90,9 @@ try {
}
async function exchange(path: string, request: unknown): Promise<unknown[]> {
+
return await new Promise<unknown[]>((resolve, reject) => {
+
const socket = connect(path)
let buffer = ""
diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.ts
index 3645440..1533113 100644
--- a/scripts/contracts/process-lifecycle.ts
+++ b/scripts/contracts/process-lifecycle.ts
@@ -11,7 +11,31 @@ const launch = { server: null, client: null, options: {} } as const
function processManager() {
- return new ProcessManager(new TheLink() as unknown as AuthManager)
+ const authManager = new TheLink() as unknown as AuthManager
+ const manager = new ProcessManager(authManager)
+
+ Object.assign(authManager, {
+ linkManager: {
+ application: {
+ system: {
+ holdProcess(value: unknown, fallback?: Process) {
+
+ if (value === undefined || value === null) return fallback
+ if (typeof value !== "object" || value === null) throw new Error("Invalid Process handle")
+
+ const handle = value as { identity?: string, reference?: string }
+ const process = handle.identity ? manager.processes.get(handle.identity) : null
+
+ if (!process || process.reference !== handle.reference) throw new Error("The Process represented by this handle does not exist")
+
+ return process
+ }
+ }
+ }
+ }
+ })
+
+ return manager
}
function program(identity: string) {
diff --git a/scripts/contracts/system-adapters.ts b/scripts/contracts/system-adapters.ts
new file mode 100644
index 0000000..6a8afb9
--- /dev/null
+++ b/scripts/contracts/system-adapters.ts
@@ -0,0 +1,58 @@
+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/source/server/core/application.ts b/source/server/core/application.ts
index 800a1ca..38dbcfe 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -9,7 +9,7 @@ import openStore from "./open-store"
import Keyv from "keyv"
import FileArea from "@libs/file-area"
import { homedir } from "node:os"
-import SystemControl from "./system-control/system-control"
+import System from "./system"
export default class Application {
@@ -42,7 +42,8 @@ export default class Application {
public readonly linkManager: LinkManager
- public readonly systemControl: SystemControl
+ /** One authoritative System domain shared by every trusted adapter. */
+ public readonly system: System
private constructor(payload: ApplicationPayload) {
@@ -72,7 +73,7 @@ export default class Application {
this.linkManager = new LinkManager(this)
- this.systemControl = new SystemControl(this)
+ this.system = new System(this)
}
public static async initialize(name: string, displayName: string, version: string, homePath: string, defaultProgramIcon: string) {
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 909b780..1a46291 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
@@ -110,47 +110,9 @@ export default class ProcessManager extends TheLink {
return process && service === true ? { process, endpoint: key.endpoint } : null
}
- /** Resolve an SDK handle without ever letting an old handle retarget a replacement. */
- private heldProcess(value: unknown, fallback?: Process) {
-
- if (value === undefined || value === null) {
-
- if (fallback) return fallback
-
- throw new Error("A Process handle is required")
- }
-
- if (!isHandleAddress(value)) throw new Error("The boundary returned an invalid Process handle")
-
- const process = this.processes.get(value.identity)
-
- if (!process || process.reference !== value.reference) throw new Error("The Process represented by this handle does not exist")
-
- return process
- }
-
- /** Resolve the exact runtime Program entity addressed by an SDK handle. */
- private heldProgram(value: unknown, fallback?: Program) {
-
- if (value === undefined || value === null) {
-
- if (fallback) return fallback
-
- throw new Error("A Program handle is required")
- }
-
- if (!isHandleAddress(value)) throw new Error("The boundary returned an invalid Program handle")
-
- const program = this.authManager.programManager.reach(value.identity)
-
- if (!program || program.reference !== value.reference) throw new Error("The Program represented by this handle does not exist")
-
- return program
- }
-
private heldWindow(value: unknown, fallback: Process) {
- const process = this.heldProcess(value, fallback)
+ const process = this.system.holdProcess(value, fallback)
const window = process.client?.window
@@ -175,6 +137,8 @@ export default class ProcessManager extends TheLink {
return window
}
+ private get system() { return this.authManager.linkManager.application.system }
+
/** Complete public Window state, shared by every representation. */
public windowSnapshot(identity: string) {
@@ -208,6 +172,16 @@ export default class ProcessManager extends TheLink {
return this.endpointEvents.follow(process.reference, half, event, (word, payload) => subscriber(payload, word), impossible)
}
+ /** Observe directed application traffic originating from one Endpoint. */
+ public observeTrafficFromOutside(identity: string, half: Half, kind: TrafficKind, event: string | null, subscriber: (event: string, ...values: unknown[]) => void, impossible?: (reason: string) => void) {
+
+ const process = this.find(identity)
+
+ if (!process.program[half]) throw new Error(`This program declared no ${half} endpoint`)
+
+ return this.traffic.observe(process.reference, half, kind, event, subscriber, impossible)
+ }
+
/** Publish from a trusted execution boundary whose identity is not a Program Endpoint. */
public async publishFromOutside(identity: string, half: Half, event: string, payload: unknown) {
@@ -380,7 +354,7 @@ export default class ProcessManager extends TheLink {
try {
- observed = this.heldProcess(target)
+ observed = this.system.holdProcess(target)
if (observed.program !== this.find(pane).program) throw new Error("The desktop does not know this process")
}
@@ -447,7 +421,7 @@ export default class ProcessManager extends TheLink {
try {
- observed = this.heldProcess(target)
+ observed = this.system.holdProcess(target)
if (observed.program !== this.find(pane).program) throw new Error("The desktop does not know this process")
}
@@ -1260,7 +1234,7 @@ export default class ProcessManager extends TheLink {
if (endpoint !== "server" && endpoint !== "client") throw new Error("A service Endpoint must be server or client")
- const held = this.heldProcess(target)
+ const held = this.system.holdProcess(target)
if (held.program !== process.program) throw new Error("The desktop does not know this process")
@@ -1495,64 +1469,62 @@ export default class ProcessManager extends TheLink {
const [word, ...rest] = args
- const programManager = this.authManager.programManager
-
- if (word === "host-program-list") return [[...programManager.programs.values()].filter(entry => rest[0] !== true || entry.installed)]
+ if (word === "host-program-list") return [this.system.listPrograms(rest[0] === true)]
if (word === "host-program-find") {
const identity = String(rest[0])
- return [programManager.programs.get(identity) ?? null]
+ return [this.system.findProgram(identity)]
}
- if (word === "current-program") return [programManager.find(process.program.identity)]
+ if (word === "current-program") return [this.system.requireProgram(process.program.identity)]
if (word === "program-agent") {
- const program = this.heldProgram(rest[0], process.program)
+ const program = this.system.holdProgram(rest[0], process.program)
- return [await programManager.agent(program.identity)]
+ return [await this.system.programAgent(program)]
}
if (word === "current-process") return [processReference(process)]
if (word === "icon") {
- return [await programManager.icon(this.heldProgram(rest[0], process.program).identity, rest[1])]
+ return [await this.system.programIcon(this.system.holdProgram(rest[0], process.program), rest[1])]
}
if (word === "startup") {
- const program = this.heldProgram(rest[0], process.program)
+ const program = this.system.holdProgram(rest[0], process.program)
- return [await programManager.startup(program, String(rest[1]), rest[2])]
+ return [await this.system.programStartup(program, String(rest[1]), rest[2])]
}
if (word === "program-permission") {
- const program = this.heldProgram(rest[0], process.program)
+ const program = this.system.holdProgram(rest[0], process.program)
const operation = rest[1]
const name = rest[2]
- if (operation === "getAll") return [programManager.permissions(program)]
+ if (operation === "getAll") return [this.system.programPermissions(program)]
if (!isPermissionName(name)) throw new Error(`The system does not know the permission "${String(name)}"`)
- if (operation === "get") return [programManager.permission(program, name)]
+ if (operation === "get") return [this.system.programPermission(program, name)]
if (operation === "set") {
if (typeof rest[3] !== "boolean") throw new Error("A permission decision must be boolean")
- programManager.setPermission(program, name, rest[3])
+ this.system.setProgramPermission(program, name, rest[3])
return []
}
if (operation === "delete") {
- programManager.deletePermission(program, name)
+ this.system.deleteProgramPermission(program, name)
return []
}
@@ -1565,7 +1537,7 @@ export default class ProcessManager extends TheLink {
// once the parent disappears that retained handle no longer resolves.
if (word === "parent") {
- const target = this.heldProcess(rest[0], process)
+ const target = this.system.holdProcess(rest[0], process)
if (!target.parent) return [null]
@@ -1583,9 +1555,9 @@ export default class ProcessManager extends TheLink {
if (typeof source !== "string" && (typeof source !== "object" || source === null)) throw new Error("A program is created from a config or a path")
- const created = await programManager.create(source as Parameters<typeof programManager.create>[0])
+ const created = await this.system.createProgram(source as Parameters<(typeof this.system)["createProgram"]>[0])
- return [programManager.find(created.identity)]
+ return [this.system.requireProgram(created.identity)]
}
if (word === "host-program-force-create") {
@@ -1594,64 +1566,64 @@ export default class ProcessManager extends TheLink {
if (typeof source !== "string" && (typeof source !== "object" || source === null)) throw new Error("A program is created from a config or a path")
- const created = await programManager.forceCreate(source as Parameters<typeof programManager.forceCreate>[0], process.identity)
+ const created = await this.system.forceCreateProgram(source as Parameters<(typeof this.system)["forceCreateProgram"]>[0], process.identity)
- return [programManager.find(created.identity)]
+ return [this.system.requireProgram(created.identity)]
}
- if (word === "appearance") return [this.authManager.linkManager.appearance.value]
+ if (word === "appearance") return [this.system.appearance]
if (word === "update-appearance") {
- await this.authManager.updateAppearance(rest[0])
+ await this.system.updateAppearance(rest[0])
return []
}
if (word === "fork") {
- const program = this.heldProgram(rest[0])
+ const program = this.system.holdProgram(rest[0])
- const forked = await programManager.fork(program, String(rest[1]))
+ const forked = await this.system.forkProgram(program, String(rest[1]))
- return [programManager.find(forked.identity)]
+ return [this.system.requireProgram(forked.identity)]
}
if (word === "installed") {
- return [programManager.installed(this.heldProgram(rest[0]))]
+ return [this.system.programInstalled(this.system.holdProgram(rest[0]))]
}
if (word === "forget") {
- const program = this.heldProgram(rest[0])
+ const program = this.system.holdProgram(rest[0])
- return [await programManager.forget(program, process.identity)]
+ return [await this.system.forgetProgram(program, process.identity)]
}
if (word === "program-process-create") {
- const program = this.heldProgram(rest[0])
+ const program = this.system.holdProgram(rest[0])
// The whole record, not the identity alone: the kit builds a
// Process from this answer, and a record invented at the
// other end — identity and program, nothing else — was how every
// process held by its launcher had no startedAt while every
// other road's did.
- return [processReference(this.find(await programManager.createProcess(program.identity, rest[1] as Launch, process)))]
+ return [processReference(this.system.requireProcess(await this.system.createProcess(program, rest[1] as Launch, process)))]
}
if (word === "program-process-find-or-create") {
- const program = this.heldProgram(rest[0])
+ const program = this.system.holdProgram(rest[0])
- return [processReference(this.find(await programManager.findOrCreateProcess(program.identity, rest[1] as Launch & { name: string }, process)))]
+ return [processReference(this.system.requireProcess(await this.system.findOrCreateProcess(program, rest[1] as Launch & { name: string }, process)))]
}
// Named, only that program's instances; unnamed, every one.
if (word === "host-process-list" || word === "program-process-list") {
- const living = [...this.processes.values()]
+ const living = this.system.listProcesses()
if (word === "host-process-list") return [living.map(processReference)]
@@ -1661,22 +1633,18 @@ export default class ProcessManager extends TheLink {
// from *there is no such program* — every other act on one
// refuses, and a word that answers falsely where its
// neighbours refuse is worse than either.
- const program = this.heldProgram(rest[0])
+ const program = this.system.holdProgram(rest[0])
- return [living.filter(entry => entry.program === program).map(processReference)]
+ return [this.system.listProcesses(program).map(processReference)]
}
if (word === "program-process-find") {
- const program = this.heldProgram(rest[0])
+ const program = this.system.holdProgram(rest[0])
const wanted = String(rest[1])
- const identified = this.processes.get(wanted)
-
- if (identified?.program === program) return [processReference(identified)]
-
- const found = [...this.processes.values()].find(entry => entry.program === program && entry.name === wanted)
+ const found = this.system.findProcess(wanted, program)
return [found ? processReference(found) : null]
}
@@ -1685,7 +1653,7 @@ export default class ProcessManager extends TheLink {
if (typeof rest[0] === "string") {
- const target = this.processes.get(rest[0])
+ const target = this.system.findProcess(rest[0])
return [target ? processReference(target) : null]
}
@@ -1695,7 +1663,7 @@ export default class ProcessManager extends TheLink {
if (word === "exists") {
- const target = this.heldProcess(rest[1], process)
+ const target = this.system.holdProcess(rest[1], process)
if (rest[0] === "server") return [target.server !== null]
@@ -1706,7 +1674,7 @@ export default class ProcessManager extends TheLink {
if (word === "is-service") {
- const target = this.heldProcess(rest[1], process)
+ const target = this.system.holdProcess(rest[1], process)
const endpoint = rest[0] ?? "server"
if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")
@@ -1716,27 +1684,27 @@ export default class ProcessManager extends TheLink {
if (word === "start-endpoint") {
- const target = this.heldProcess(rest[0], process)
+ const target = this.system.holdProcess(rest[0], process)
- if (rest[1] === "server") return [await this.startServer(target.identity, rest[2] as ServerLaunch | undefined)]
+ if (rest[1] === "server") return [await this.system.startEndpoint(target, "server", rest[2] as ServerLaunch | undefined)]
- if (rest[1] === "client") return [await this.startClient(target.identity, rest[2] as ClientLaunch | undefined)]
+ if (rest[1] === "client") return [await this.system.startEndpoint(target, "client", rest[2] as ClientLaunch | undefined)]
throw new Error("A Process endpoint is server or client")
}
if (word === "stop-endpoint") {
- const target = this.heldProcess(rest[0], process)
+ const target = this.system.holdProcess(rest[0], process)
- if (rest[1] === "server") return [await this.stopServer(target.identity)]
+ if (rest[1] === "server") return [await this.system.stopEndpoint(target, "server")]
- if (rest[1] === "client") return [await this.stopClient(target.identity)]
+ if (rest[1] === "client") return [await this.system.stopEndpoint(target, "client")]
throw new Error("A Process endpoint is server or client")
}
- if (word === "stop-current") return [await this.stopServer(process.identity)]
+ if (word === "stop-current") return [await this.system.stopEndpoint(process, "server")]
if (word === "service-exists") return [this.services.exists(rest[0])]
@@ -1828,73 +1796,73 @@ export default class ProcessManager extends TheLink {
const target = this.heldWindow(rest[0], process).process
- return [this.windowSnapshot(target.identity)]
+ return [this.system.windowSnapshot(target)]
}
if (word === "move") {
- const target = this.heldWindow(rest[0], process).process.identity
+ const target = this.heldWindow(rest[0], process).process
- await this.move(target, rest[1] as Position)
+ await this.system.moveWindow(target, rest[1] as Position)
- return [target]
+ return [target.identity]
}
if (word === "resize") {
- const target = this.heldWindow(rest[0], process).process.identity
+ const target = this.heldWindow(rest[0], process).process
- await this.resize(target, rest[1] as Size)
+ await this.system.resizeWindow(target, rest[1] as Size)
- return [target]
+ return [target.identity]
}
if (word === "setGeometry") {
- const target = this.heldWindow(rest[0], process).process.identity
+ const target = this.heldWindow(rest[0], process).process
- await this.setGeometry(target, rest[1] as WindowGeometry)
+ await this.system.setWindowGeometry(target, rest[1] as WindowGeometry)
- return [target]
+ return [target.identity]
}
if (word === "changeTitle") {
- const target = this.heldWindow(rest[0], process).process.identity
+ const target = this.heldWindow(rest[0], process).process
- await this.changeTitle(target, String(rest[1] ?? ""))
+ await this.system.changeWindowTitle(target, String(rest[1] ?? ""))
- return [target]
+ return [target.identity]
}
if (word === "raise") {
- const target = this.heldWindow(rest[0], process).process.identity
+ const target = this.heldWindow(rest[0], process).process
- await this.raise(target)
+ await this.system.raiseWindow(target)
- return [target]
+ return [target.identity]
}
if (word === "minimize") {
- const target = this.heldWindow(rest[0], process).process.identity
+ const target = this.heldWindow(rest[0], process).process
- await this.minimize(target, rest[1] !== false)
+ await this.system.minimizeWindow(target, rest[1] !== false)
- return [target]
+ return [target.identity]
}
if (word === "exit") {
- const target = this.heldProcess(rest[0], process)
+ const target = this.system.holdProcess(rest[0], process)
- await this.exit(target.identity)
+ await this.system.exitProcess(target)
return [target.identity]
}
- if (word === "program-process-exit-all") return [await this.exitAll(this.heldProgram(rest[0]).identity, process.identity)]
+ if (word === "program-process-exit-all") return [await this.system.exitProgramProcesses(this.system.holdProgram(rest[0]), process.identity)]
if (word === "observe") {
@@ -1908,7 +1876,7 @@ export default class ProcessManager extends TheLink {
if (event !== null && typeof event !== "string") return []
- const target = this.heldProcess(rest[1], process)
+ const target = this.system.holdProcess(rest[1], process)
this.observeServer(process, String(rest[0]), target, String(rest[2]), kind, event, reportImpossible)
@@ -1928,7 +1896,7 @@ export default class ProcessManager extends TheLink {
if (event !== null && typeof event !== "string") return []
- const target = this.heldProcess(rest[1], process)
+ const target = this.system.holdProcess(rest[1], process)
this.followServer(process, String(rest[0]), target, String(rest[2]), event, rest[4] === true)
@@ -1972,7 +1940,7 @@ export default class ProcessManager extends TheLink {
if (half !== "server" && half !== "client") throw new Error(`A process has no "${String(half)}" end`)
- const target = this.heldProcess(rest[0])
+ const target = this.system.holdProcess(rest[0])
await this.publish(process.identity, "server", target.identity, half, rest.slice(2))
@@ -1997,7 +1965,7 @@ export default class ProcessManager extends TheLink {
if (typeof rest[3] !== "string" || typeof rest[4] !== "string") throw new Error("A question needs a public id and an event name")
- const targetProcess = this.heldProcess(rest[0])
+ const targetProcess = this.system.holdProcess(rest[0])
const target = targetProcess.server
@@ -2018,7 +1986,7 @@ export default class ProcessManager extends TheLink {
// What a launch said, carried by the process it launched.
if (word === "option") {
- const asked = this.heldProcess(rest[0], process)
+ const asked = this.system.holdProcess(rest[0], process)
return [asked.options[String(rest[1])]]
}
@@ -2032,11 +2000,11 @@ export default class ProcessManager extends TheLink {
// The one registry is the authority for every program,
// installed or not. Naming the current program explicitly
// must therefore be equivalent to leaving the subject empty.
- const program = this.heldProgram(rest[0], process.program)
+ const program = this.system.holdProgram(rest[0], process.program)
if (rest[1] !== "path") throw new Error("A server half asks the host only for an area path")
- return [programManager.operate(program, word, "path", [])]
+ return [this.system.programArea(program, word, "path", [])]
}
// Native filesystem work remains local to the Server SDK. The System
@@ -2046,7 +2014,7 @@ export default class ProcessManager extends TheLink {
if (rest[0] !== "path") throw new Error("A server half asks the host only for its Storage path")
- return [this.authManager.linkManager.application.home.path]
+ return [this.system.storagePath]
}
// What a program has said, asked for and never told. The
@@ -2055,9 +2023,9 @@ export default class ProcessManager extends TheLink {
// anything here deciding what a query means.
if (word === "logs") {
- const program = this.heldProgram(rest[0], process.program)
+ const program = this.system.holdProgram(rest[0], process.program)
- return [programManager.logsOf(program).query(String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
+ return [this.system.programQuery(program, "logs", String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
}
// A program's own database. Written as well as read, unlike the
@@ -2065,9 +2033,9 @@ export default class ProcessManager extends TheLink {
// is the program's own, which is why they are two files.
if (word === "database") {
- const program = this.heldProgram(rest[0], process.program)
+ const program = this.system.holdProgram(rest[0], process.program)
- return [programManager.databaseOf(program).query(String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
+ return [this.system.programQuery(program, "database", String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
}
// A Server Endpoint performs upload byte I/O locally. The SDK receives
@@ -2075,7 +2043,7 @@ export default class ProcessManager extends TheLink {
// remain flat and validated by both sides.
if (word === "uploads") {
- const { uploads } = this.authManager.linkManager.application
+ const { uploads } = this.system
if (rest[0] === "access") return [uploads.fileManager.path, uploadLimit]
if (rest[0] === "stat") return [uploads.stat(String(rest[1]))]
@@ -2091,9 +2059,9 @@ export default class ProcessManager extends TheLink {
const [operation, key, value, ttl] = rest.slice(1) as [string, string, unknown, number | undefined]
- const whose = this.heldProgram(rest[0], process.program).identity
+ const whose = this.system.holdProgram(rest[0], process.program)
- return [await programManager.store(whose, operation, key, value, ttl)]
+ return [await this.system.programStore(whose, operation, key, value, ttl)]
}
throw new Error(`The host does not know the word "${String(word)}"`)
@@ -2105,7 +2073,7 @@ export default class ProcessManager extends TheLink {
if (args[0] === "wait-ready") {
- const target = this.heldProcess(args[1], process)
+ const target = this.system.holdProcess(args[1], process)
const requireCurrentIncarnation = args[2] === true
@@ -2189,8 +2157,6 @@ export default class ProcessManager extends TheLink {
let active = true
let cancel = () => { active = false }
- const programManager = this.authManager.programManager
-
server.retain(question, () => cancel())
await this.say(server, "host-end", "stream", question, "open")
@@ -2198,7 +2164,7 @@ export default class ProcessManager extends TheLink {
try {
const operation = args[0]
- const program = this.heldProgram(args[1])
+ const program = this.system.holdProgram(args[1])
if (operation === "run") {
@@ -2218,10 +2184,10 @@ export default class ProcessManager extends TheLink {
active = false
- if (running) this.exit(running.identity).catch(() => undefined)
+ if (running) this.system.exitProcess(running).catch(() => undefined)
}
- const identity = await programManager.runProcess(program, args[2] as Launch ?? {}, {
+ const identity = await this.system.runProcess(program, args[2] as Launch ?? {}, {
started: created => {
running = created
@@ -2242,7 +2208,7 @@ export default class ProcessManager extends TheLink {
}
}, process)
- if (!active) await this.exit(identity)
+ if (!active) await this.system.exitProcess(this.system.requireProcess(identity))
await completion
await sending
@@ -2253,9 +2219,9 @@ export default class ProcessManager extends TheLink {
}
const stream = operation === "install"
- ? this.authManager.programManager.installStreaming(program, process.identity)
+ ? this.system.installProgram(program, process.identity)
: operation === "uninstall"
- ? this.authManager.programManager.uninstallStreaming(program, args[2] === true, process.identity)
+ ? this.system.uninstallProgram(program, args[2] === true, process.identity)
: null
if (!stream) throw new Error(`The host does not know the stream operation "${String(operation)}"`)
diff --git a/source/server/core/system.ts b/source/server/core/system.ts
new file mode 100644
index 0000000..b3c673e
--- /dev/null
+++ b/source/server/core/system.ts
@@ -0,0 +1,434 @@
+import type Application from "./application"
+import type Entry from "./link-manager/auth-manager/program-manager/entry"
+import type Program from "./link-manager/auth-manager/program-manager/program"
+import type Process from "./link-manager/auth-manager/process-manager/process"
+import type { ClientLaunch, Launch, PermissionName, Position, ServerLaunch, Size, WindowGeometry } from "@phreshos/core"
+import type { Half, TrafficKind } from "./link-manager/auth-manager/process-manager/process-traffic"
+import type { Area, Watching } from "./link-manager/auth-manager/program-manager/program-manager"
+
+type Endpoint = "server" | "client"
+type ProgramSource = Parameters<Application["linkManager"]["authManager"]["programManager"]["create"]>[0]
+
+/**
+ * The authoritative System domain shared by every trusted boundary.
+ *
+ * A transport may validate, authenticate, serialize, or stream an operation,
+ * but it does not implement System behavior. Both the in-process Server
+ * boundary and the owner Gateway resolve and mutate entities through here.
+ */
+export default class System {
+
+ public constructor(private readonly application: Application) {}
+
+ public listPrograms(onlyInstalled = false) {
+
+ return [...this.programManager.programs.values()].filter(entry => !onlyInstalled || entry.installed)
+ }
+
+ public findProgram(identity: string) {
+
+ return this.programManager.programs.get(identity) ?? null
+ }
+
+ public requireProgram(identity: string) {
+
+ const entry = this.findProgram(identity)
+
+ if (!entry) throw new Error(`Unknown Program "${identity}"`)
+
+ return entry
+ }
+
+ /** Resolve an exact Program handle without retargeting a replacement. */
+ public holdProgram(value: unknown, fallback?: Program) {
+
+ if (value === undefined || value === null) {
+
+ if (fallback) return fallback
+
+ throw new Error("A Program handle is required")
+ }
+
+ if (!isHandleAddress(value)) throw new Error("The boundary returned an invalid Program handle")
+
+ const program = this.programManager.reach(value.identity)
+
+ if (!program || program.reference !== value.reference) throw new Error("The Program represented by this handle does not exist")
+
+ return program
+ }
+
+ public async createProgram(source: ProgramSource) {
+
+ return this.programManager.create(source)
+ }
+
+ public async forceCreateProgram(source: ProgramSource, asker: string | null = null) {
+
+ return this.programManager.forceCreate(source, asker)
+ }
+
+ public forkProgram(program: Program, identity: string) {
+
+ return this.programManager.fork(program, identity)
+ }
+
+ public programPermissions(program: Program) {
+
+ return this.programManager.permissions(program)
+ }
+
+ public programPermission(program: Program, permission: PermissionName) {
+
+ return this.programManager.permission(program, permission)
+ }
+
+ public setProgramPermission(program: Program, permission: PermissionName, value: boolean) {
+
+ this.programManager.setPermission(program, permission, value)
+ }
+
+ public deleteProgramPermission(program: Program, permission: PermissionName) {
+
+ this.programManager.deletePermission(program, permission)
+ }
+
+ public listProcesses(program?: Program) {
+
+ return [...this.processManager.processes.values()].filter(process => !program || process.program === program)
+ }
+
+ public findProcess(identity: string, program?: Program) {
+
+ const exact = this.processManager.processes.get(identity)
+
+ if (!program) return exact ?? null
+ if (exact?.program === program) return exact
+
+ return this.listProcesses(program).find(process => process.name === identity) ?? null
+ }
+
+ public requireProcess(identity: string, program?: Program) {
+
+ const process = this.findProcess(identity, program)
+
+ if (!process) {
+
+ const scope = program ? ` in Program "${program.identity}"` : ""
+
+ throw new Error(`Unknown Process "${identity}"${scope}`)
+ }
+
+ return process
+ }
+
+ /** Resolve an exact Process handle without retargeting a replacement. */
+ public holdProcess(value: unknown, fallback?: Process) {
+
+ if (value === undefined || value === null) {
+
+ if (fallback) return fallback
+
+ throw new Error("A Process handle is required")
+ }
+
+ if (!isHandleAddress(value)) throw new Error("The boundary returned an invalid Process handle")
+
+ const process = this.processManager.processes.get(value.identity)
+
+ if (!process || process.reference !== value.reference) throw new Error("The Process represented by this handle does not exist")
+
+ return process
+ }
+
+ public resolveProcess(input: { process: string, program?: string }) {
+
+ const program = input.program ? this.requireProgram(input.program).program : undefined
+
+ return this.requireProcess(input.process, program)
+ }
+
+ public async createProcess(program: string | Program, launch: Launch = {}, parent: Process | string | null = null) {
+
+ return this.programManager.createProcess(typeof program === "string" ? program : program.identity, launch, parent)
+ }
+
+ public async findOrCreateProcess(program: string | Program, launch: Launch & { name: string }, parent: Process | string | null = null) {
+
+ return this.programManager.findOrCreateProcess(program, launch, parent)
+ }
+
+ public runProcess(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null) {
+
+ return this.programManager.runProcess(program, launch, watching, parent)
+ }
+
+ public exitProgramProcesses(program: Program, asker: string | null = null) {
+
+ return this.processManager.exitAll(program.identity, asker)
+ }
+
+ public async exitProcess(process: Process) {
+
+ return this.processManager.exit(process.identity)
+ }
+
+ public async startEndpoint(process: Process, endpoint: "server", launch?: ServerLaunch): Promise<void>
+ public async startEndpoint(process: Process, endpoint: "client", launch?: ClientLaunch): Promise<void>
+ public async startEndpoint(process: Process, endpoint: Endpoint, launch?: ServerLaunch | ClientLaunch) {
+
+ if (endpoint === "server") await this.processManager.startServer(process.identity, launch as ServerLaunch)
+ else await this.processManager.startClient(process.identity, launch as ClientLaunch)
+ }
+
+ public async stopEndpoint(process: Process, endpoint: Endpoint) {
+
+ if (endpoint === "server") await this.processManager.stopServer(process.identity)
+ else await this.processManager.stopClient(process.identity)
+ }
+
+ public endpointSnapshot(process: Process, endpoint: Endpoint) {
+
+ return Object.freeze({
+ process: process.identity,
+ program: process.program.identity,
+ endpoint,
+ declared: process.program[endpoint] !== null,
+ running: process[endpoint] !== null,
+ service: process[endpoint]?.service ?? false
+ })
+ }
+
+ public observe(domain: "program" | "process" | "window", event: string, subject: string | null, subscriber: (event: string, ...values: unknown[]) => void) {
+
+ return this.processManager.observeHost(domain, event, subject, subscriber)
+ }
+
+ public observeEndpoint(process: Process, endpoint: Half, event: string | null, subscriber: (payload: unknown, event: string) => void, impossible?: (reason: string) => void) {
+
+ return this.processManager.observeEndpoint(process.identity, endpoint, event, subscriber, impossible)
+ }
+
+ public observeTraffic(process: Process, endpoint: Half, kind: TrafficKind, event: string | null, subscriber: (event: string, ...values: unknown[]) => void, impossible?: (reason: string) => void) {
+
+ return this.processManager.observeTrafficFromOutside(process.identity, endpoint, kind, event, subscriber, impossible)
+ }
+
+ public publishEndpoint(process: Process, endpoint: Half, event: string, payload: unknown) {
+
+ return this.processManager.publishFromOutside(process.identity, endpoint, event, payload)
+ }
+
+ public askEndpoint(process: Process, event: string, payload: unknown, timeout = 10_000, signal?: AbortSignal) {
+
+ return this.processManager.askFromOutside(process.identity, event, payload, timeout, signal)
+ }
+
+ public windowSnapshot(process: Process) {
+
+ return this.processManager.windowSnapshot(process.identity)
+ }
+
+ public async moveWindow(process: Process, position: Position) {
+
+ await this.processManager.move(process.identity, position)
+ }
+
+ public async resizeWindow(process: Process, size: Size) {
+
+ await this.processManager.resize(process.identity, size)
+ }
+
+ public async setWindowGeometry(process: Process, geometry: WindowGeometry) {
+
+ await this.processManager.setGeometry(process.identity, geometry)
+ }
+
+ public async minimizeWindow(process: Process, minimized: boolean) {
+
+ await this.processManager.minimize(process.identity, minimized)
+ }
+
+ public async changeWindowTitle(process: Process, title: string) {
+
+ await this.processManager.changeTitle(process.identity, title)
+ }
+
+ public async raiseWindow(process: Process) {
+
+ await this.processManager.raise(process.identity)
+ }
+
+ public programSnapshot(entry: Entry) {
+
+ const program = entry.program
+
+ return Object.freeze({
+ reference: program.reference,
+ identity: program.identity,
+ name: program.name,
+ version: program.config.version ?? null,
+ description: program.config.description ?? null,
+ installed: entry.installed,
+ hasAgent: program.agentPath !== null,
+ server: program.server ? Object.freeze({ start: program.server.start, service: program.server.service }) : null,
+ client: program.client ? Object.freeze({
+ start: program.client.start,
+ service: program.client.service,
+ title: program.client.title ?? null,
+ size: program.client.size ?? null,
+ position: program.client.position ?? null,
+ layer: program.client.layer ?? null,
+ minimize: program.client.minimize ?? null
+ }) : null
+ })
+ }
+
+ public processSnapshot(process: Process) {
+
+ const owner = process.program.record()
+
+ return Object.freeze({
+ reference: process.reference,
+ identity: process.identity,
+ name: process.name,
+ program: process.program.identity,
+ programSnapshot: Object.freeze({
+ reference: owner.reference,
+ identity: owner.identity,
+ name: owner.name,
+ version: owner.version,
+ description: owner.description,
+ hasAgent: owner.hasAgent,
+ server: owner.server,
+ client: owner.client
+ }),
+ parent: process.parent?.identity ?? null,
+ options: Object.freeze({ ...process.options }),
+ startedAt: process.startedAt.toISOString(),
+ server: Object.freeze({ declared: process.program.server !== null, running: process.server !== null, service: process.server?.service ?? false }),
+ client: Object.freeze({ declared: process.program.client !== null, running: process.client !== null, service: process.client?.service ?? false })
+ })
+ }
+
+ public get appearance() {
+
+ return this.application.appearanceManager.value
+ }
+
+ public updateAppearance(value: unknown) {
+
+ return this.application.linkManager.updateAppearance(value)
+ }
+
+ public observeAppearance(subscriber: (value: unknown) => void) {
+
+ return this.application.linkManager.appearance.tunnel.subscribe("change", subscriber)
+ }
+
+ public programIcon(program: Program, size: unknown) {
+
+ return this.programManager.icon(program.identity, size)
+ }
+
+ public programAgent(program: Program) {
+
+ return this.programManager.agent(program.identity)
+ }
+
+ public programStartup(program: Program, operation: string, value?: unknown) {
+
+ return this.programManager.startup(program, operation, value)
+ }
+
+ public programInstalled(program: Program) {
+
+ return this.programManager.installed(program)
+ }
+
+ public forgetProgram(program: Program, asker: string | null = null) {
+
+ return this.programManager.forget(program, asker)
+ }
+
+ public installProgram(program: Program, asker: string | null = null) {
+
+ return this.programManager.installStreaming(program, asker)
+ }
+
+ public uninstallProgram(program: Program, everything = false, asker: string | null = null) {
+
+ return this.programManager.uninstallStreaming(program, everything, asker)
+ }
+
+ public programArea(program: Program, area: Area, operation: string, args: unknown[]) {
+
+ return this.programManager.operate(program, area, operation, args)
+ }
+
+ public programStoragePath(program: Program, area: Area) {
+
+ return this.programManager.area(program.identity, area, "path", [])
+ }
+
+ public programStore(program: Program, operation: string, key: string, value?: unknown, ttl?: number) {
+
+ return this.programManager.store(program.identity, operation, key, value, ttl)
+ }
+
+ public programQuery(program: Program, database: "logs" | "database", statement: string, values: unknown[]) {
+
+ return (database === "logs" ? this.programManager.logsOf(program) : this.programManager.databaseOf(program)).query(statement, values)
+ }
+
+ public endpointIsService(process: Process, endpoint: Half) {
+
+ return this.processManager.endpointIsServiceFromOutside(process.identity, endpoint)
+ }
+
+ public serviceExists(key: unknown) {
+
+ return this.processManager.serviceExistsFromOutside(key)
+ }
+
+ public waitServiceReady(key: unknown, timeout?: number) {
+
+ return this.processManager.waitServiceReadyFromOutside(key, timeout)
+ }
+
+ public publishService(key: unknown, event: string, payload: unknown) {
+
+ return this.processManager.publishServiceFromOutside(key, event, payload)
+ }
+
+ public askService(key: unknown, event: string, payload: unknown, timeout = 10_000, signal?: AbortSignal) {
+
+ return this.processManager.askServiceFromOutside(key, event, payload, timeout, signal)
+ }
+
+ public observeService(key: unknown, scope: "lifecycle" | "events", event: string | null, subscriber: (event: string, payload: unknown) => unknown) {
+
+ return this.processManager.observeServiceFromOutside(key, scope, event, subscriber)
+ }
+
+ public get uploads() {
+
+ return this.application.uploads
+ }
+
+ public get storagePath() {
+
+ return this.application.home.path
+ }
+
+ private get programManager() { return this.application.linkManager.authManager.programManager }
+ private get processManager() { return this.application.linkManager.authManager.processManager }
+}
+
+function isHandleAddress(value: unknown): value is { identity: string, reference: string } {
+
+ return typeof value === "object"
+ && value !== null
+ && typeof (value as Record<string, unknown>).identity === "string"
+ && typeof (value as Record<string, unknown>).reference === "string"
+}
diff --git a/source/server/view/gateway/api-request.ts b/source/server/view/gateway/api-request.ts
index ce89122..5c9c786 100644
--- a/source/server/view/gateway/api-request.ts
+++ b/source/server/view/gateway/api-request.ts
@@ -7,24 +7,59 @@ export default async function apiRequest(application: Application, value: unknow
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 application.appearanceManager.value
- if (request.operation === "update") return await application.linkManager.updateAppearance(request.value)
- if (request.operation === "wait") return await waitForAppearance(application, signal)
+ 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: application.uploads.fileManager.path, limit: uploadLimit }
- if (request.operation === "stat") return application.uploads.stat(String(request.file))
+ 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") {
+
+ if (typeof request.program !== "string") throw new Error("A Program API request needs a Program identity")
+
+ const program = system.requireProgram(request.program).program
+
+ 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 === "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)
+ }
+
+ throw new Error(`The Program 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") {
@@ -32,7 +67,7 @@ export default async function apiRequest(application: Application, value: unknow
throw new Error("Reading an Endpoint service role needs a Process and Endpoint")
}
- return processes(application).endpointIsServiceFromOutside(request.process, request.endpoint)
+ return system.endpointIsService(system.requireProcess(request.process), request.endpoint)
}
if (request.capability === "endpoint" && request.operation === "wait") {
@@ -43,25 +78,46 @@ export default async function apiRequest(application: Application, value: unknow
}
if (request.event !== null && typeof request.event !== "string") throw new Error("An Endpoint event must be text or null")
- return await waitForEndpoint(processes(application), request.process, request.endpoint, request.event, timed(signal, request.timeout))
+ 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 manager = processes(application)
const key = request.key
- if (request.operation === "exists") return manager.serviceExistsFromOutside(key)
- if (request.operation === "waitReady") return await manager.waitServiceReadyFromOutside(key, number(request.timeout))
+ 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 manager.publishServiceFromOutside(key, request.event, request.payload)
- return await manager.askServiceFromOutside(key, request.event, request.payload, number(request.timeout) ?? 10_000, signal)
+ 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(manager, key, String(request.scope), request.event, timed(signal, request.timeout))
+ 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)}"`)
@@ -70,11 +126,6 @@ export default async function apiRequest(application: Application, value: unknow
throw new Error(`Unknown System API capability "${String(request.capability)}"`)
}
-function processes(application: Application) {
-
- return application.linkManager.authManager.processManager
-}
-
function number(value: unknown) {
if (value === undefined) return undefined
@@ -82,13 +133,13 @@ function number(value: unknown) {
return value
}
-function waitForService(manager: ReturnType<typeof processes>, key: unknown, scope: string, event: string | null, signal: AbortSignal) {
+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 = manager.observeServiceFromOutside(key, scope, event, (received, payload) => {
+ const stop = system.observeService(key, scope, event, (received, payload) => {
cleanup()
resolve(event === null ? { event: received, payload } : payload)
@@ -114,11 +165,11 @@ function timed(signal: AbortSignal, value: unknown) {
return AbortSignal.any([signal, AbortSignal.timeout(number(value) ?? 10_000)])
}
-function waitForEndpoint(manager: ReturnType<typeof processes>, process: string, endpoint: "server" | "client", event: string | null, signal: AbortSignal) {
+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 = manager.observeEndpoint(process, endpoint, event, (payload, received) => {
+ const stop = system.observeEndpoint(process, endpoint, event, (payload, received) => {
cleanup()
resolve({ event: received, payload })
@@ -143,11 +194,47 @@ function waitForEndpoint(manager: ReturnType<typeof processes>, process: string,
})
}
-function waitForAppearance(application: Application, signal: AbortSignal) {
+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 = application.linkManager.appearance.tunnel.subscribe("change", (value: unknown) => {
+ const stop = system.observeAppearance((value: unknown) => {
cleanup()
resolve(value)
diff --git a/source/server/view/gateway/program-request.ts b/source/server/view/gateway/program-request.ts
index 23a509c..ee6c5fb 100644
--- a/source/server/view/gateway/program-request.ts
+++ b/source/server/view/gateway/program-request.ts
@@ -19,22 +19,24 @@ export default async function programRequest(application: Application, socket: S
for (const identity of attached) {
- application.linkManager.authManager.processManager.exit(identity).catch(() => undefined)
+ const process = application.system.findProcess(identity)
+
+ if (process) application.system.exitProcess(process).catch(() => undefined)
}
attached.clear()
})
- const programManager = application.linkManager.authManager.programManager
+ const system = application.system
if (asked.word === "create") {
if (!asked.program) throw new Error("Creating needs a Program definition")
- const program = await programManager.create(asked.program)
- const entry = programManager.find(program.identity)
+ const program = await system.createProgram(asked.program)
+ const entry = system.requireProgram(program.identity)
- say({ event: "created", program: entry.record() })
+ say({ event: "created", program: system.programSnapshot(entry) })
return done()
}
@@ -42,26 +44,26 @@ export default async function programRequest(application: Application, socket: S
if (!asked.program) throw new Error("Creating needs a Program definition")
- const program = await programManager.forceCreate(asked.program)
- const entry = programManager.find(program.identity)
+ const program = await system.forceCreateProgram(asked.program)
+ const entry = system.requireProgram(program.identity)
- say({ event: "created", program: entry.record() })
+ say({ event: "created", program: system.programSnapshot(entry) })
return done()
}
if (asked.word === "run-process") {
- const program = programManager.held(asked.handle)
+ const program = system.holdProgram(asked.handle)
let identity: string | null = null
let ended = false
let processRecord: ReturnType<Process["record"]> | null = null
- identity = await programManager.runProcess(program, asked.launch ?? {}, {
+ identity = await system.runProcess(program, asked.launch ?? {}, {
started: process => {
processRecord = process.record()
attached.add(process.identity)
- say({ event: "started", process: { ...processRecord, programSnapshot: programManager.find(program.identity).record() } })
+ say({ event: "started", process: system.processSnapshot(process) })
},
output: (stream, text) => say({ event: "output", stream: stream === "err" ? "stderr" : "stdout", text }),
exited: function (code, signal) {
@@ -81,9 +83,9 @@ export default async function programRequest(application: Application, socket: S
if (socket.destroyed) {
- if (application.linkManager.authManager.processManager.processes.has(identity)) {
- await application.linkManager.authManager.processManager.exit(identity)
- }
+ const process = system.findProcess(identity)
+
+ if (process) await system.exitProcess(process)
return
}
@@ -92,8 +94,8 @@ export default async function programRequest(application: Application, socket: S
if (asked.word === "installed") {
- const program = programManager.held(asked.handle)
- const entry = programManager.programs.get(program.identity)
+ const program = system.holdProgram(asked.handle)
+ const entry = system.findProgram(program.identity)
say({ event: "installedState", installed: entry?.installed === true })
return done()
@@ -101,12 +103,12 @@ export default async function programRequest(application: Application, socket: S
if (asked.word === "startup") {
- const program = programManager.held(asked.handle)
+ 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 programManager.startup(program, operation, asked.launch)
+ const launch = await system.programStartup(program, operation, asked.launch)
say({ event: "startup", launch })
return done()
@@ -114,33 +116,33 @@ export default async function programRequest(application: Application, socket: S
if (asked.word === "create-process") {
- const program = programManager.held(asked.handle)
- const identity = await programManager.runProcess(program, asked.launch ?? {})
- const process = application.linkManager.authManager.processManager.processes.get(identity)
+ 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: { ...process.record(), programSnapshot: programManager.find(program.identity).record() } })
+ say({ event: "createdProcess", process: system.processSnapshot(process) })
return done()
}
if (asked.word === "find-or-create-process") {
- const program = programManager.held(asked.handle)
- const identity = await programManager.findOrCreateProcess(program, asked.launch as NonNullable<Asked["launch"]> & { name: string })
- const process = application.linkManager.authManager.processManager.processes.get(identity)
+ 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: { ...process.record(), programSnapshot: programManager.find(program.identity).record() } })
+ say({ event: "createdProcess", process: system.processSnapshot(process) })
return done()
}
if (asked.word === "forget") {
- const program = programManager.held(asked.handle)
+ const program = system.holdProgram(asked.handle)
- await programManager.forget(program)
+ await system.forgetProgram(program)
say({ event: "forgotten", identity: program.identity })
return done()
@@ -148,9 +150,9 @@ export default async function programRequest(application: Application, socket: S
if (asked.word === "install-existing") {
- const program = programManager.held(asked.handle)
+ const program = system.holdProgram(asked.handle)
- for await (const chunk of programManager.installStreaming(program)) say({ event: "output", ...chunk })
+ for await (const chunk of system.installProgram(program)) say({ event: "output", ...chunk })
say({ event: "installed", identity: program.identity })
return done()
@@ -158,9 +160,9 @@ export default async function programRequest(application: Application, socket: S
if (asked.word === "uninstall-existing") {
- const program = programManager.held(asked.handle)
+ const program = system.holdProgram(asked.handle)
- for await (const chunk of programManager.uninstallStreaming(program, asked.everything === true)) say({ event: "output", ...chunk })
+ 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()
@@ -180,6 +182,6 @@ interface Asked {
everything?: boolean
handle?: unknown
operation?: string
- launch?: Parameters<Application["linkManager"]["authManager"]["programManager"]["runProcess"]>[1]
- program?: Parameters<Application["linkManager"]["authManager"]["programManager"]["forceCreate"]>[0]
+ launch?: Parameters<Application["system"]["runProcess"]>[1]
+ program?: Parameters<Application["system"]["forceCreateProgram"]>[0]
}
diff --git a/source/server/core/system-control/system-control.ts b/source/server/view/gateway/system-control.ts
similarity index 62%
rename from source/server/core/system-control/system-control.ts
rename to source/server/view/gateway/system-control.ts
index eb663ad..a4b5e83 100644
--- a/source/server/core/system-control/system-control.ts
+++ b/source/server/view/gateway/system-control.ts
@@ -22,9 +22,9 @@ import {
type WindowWaitInput
} from "@phreshos/core"
import { z } from "zod"
-import type Application from "../application"
-import type Entry from "../link-manager/auth-manager/program-manager/entry"
-import type Process from "../link-manager/auth-manager/process-manager/process"
+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(),
@@ -34,10 +34,10 @@ const envelope = z.object({
const inputs = new WeakMap<SystemControlOperation, z.ZodType>()
-/** Executes the shared System-control contract against authoritative Core state. */
+/** Owner-Gateway adapter for the neutral serialized System operation contract. */
export default class SystemControl {
- public constructor(private readonly application: Application) {}
+ public constructor(private readonly system: System) {}
public async execute(value: unknown, signal?: AbortSignal) {
@@ -69,24 +69,21 @@ export default class SystemControl {
private async program(operation: string, input: ProgramListInput | ProgramInput | ProgramWaitInput, signal?: AbortSignal) {
- const manager = this.programs
-
if (operation === "list") {
const request = input as ProgramListInput
const installedOnly = request.installedOnly ?? true
const query = request.search?.toLocaleLowerCase()
- const found = [...manager.programs.values()].filter(entry => (
- (!installedOnly || entry.installed)
- && (!query || [entry.identity, entry.program.name, entry.program.config.description]
+ 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(programSnapshot)),
+ data: Object.freeze(selected.map(entry => this.system.programSnapshot(entry))),
total: found.length,
truncated: (request.offset ?? 0) + selected.length < found.length
})
@@ -94,11 +91,11 @@ export default class SystemControl {
if (operation === "wait") return this.waitProgram(input as ProgramWaitInput, signal)
- const entry = requiredProgram(manager.programs, (input as ProgramInput).program)
+ const entry = this.system.requireProgram((input as ProgramInput).program)
- if (operation === "inspect") return programSnapshot(entry)
+ if (operation === "inspect") return this.system.programSnapshot(entry)
- const content = entry.program.agent()
+ const content = await this.system.programAgent(entry.program)
if (content === null) throw new Error(`Program "${entry.identity}" has no agent documentation`)
@@ -110,19 +107,18 @@ export default class SystemControl {
if (operation === "list") {
const request = input as ProcessListInput
- const owner = request.program ? requiredProgram(this.programs.programs, request.program).program : null
+ const owner = request.program ? this.system.requireProgram(request.program).program : null
const query = request.search?.toLocaleLowerCase()
- const found = [...this.processes.processes.values()].filter(process => (
- (!owner || process.program === owner)
- && (!query || [process.identity, process.name, process.program.identity]
+ 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(processSnapshot)),
+ data: Object.freeze(selected.map(process => this.system.processSnapshot(process))),
total: found.length,
truncated: (request.offset ?? 0) + selected.length < found.length
})
@@ -134,22 +130,22 @@ export default class SystemControl {
const request = input as ProcessCreateInput | ProcessFindOrCreateInput
const identity = operation === "create"
- ? await this.programs.createProcess(request.program, request.launch)
- : await this.programs.findOrCreateProcess(
+ ? await this.system.createProcess(request.program, request.launch)
+ : await this.system.findOrCreateProcess(
request.program,
(request as ProcessFindOrCreateInput).launch
)
- return processSnapshot(requiredProcess(this.processes.processes, identity))
+ return this.system.processSnapshot(this.system.requireProcess(identity))
}
const request = input as ProcessInput
- const process = resolveProcess(this.processes.processes, this.programs.programs, request)
- const snapshot = processSnapshot(process)
+ const process = this.system.resolveProcess(request)
+ const snapshot = this.system.processSnapshot(process)
if (operation === "exit") {
- await this.processes.exit(process.identity)
+ await this.system.exitProcess(process)
return Object.freeze({ ...snapshot, exited: true })
}
@@ -159,33 +155,33 @@ export default class SystemControl {
private async endpoint(operation: string, input: EndpointInput | EndpointStartInput | EndpointWaitReadyInput | EndpointWaitLifecycleInput | EndpointAskInput | EndpointPublishInput | EndpointWaitInput, signal?: AbortSignal) {
- const process = resolveProcess(this.processes.processes, this.programs.programs, input)
+ 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 endpointSnapshot(process, input.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.processes.startServer(process.identity, request.launch)
- else await this.processes.startClient(process.identity, request.launch)
+ if (request.endpoint === "server") await this.system.startEndpoint(process, "server", request.launch)
+ else await this.system.startEndpoint(process, "client", request.launch)
} else {
- if (input.endpoint === "server") await this.processes.stopServer(process.identity)
- else await this.processes.stopClient(process.identity)
+ await this.system.stopEndpoint(process, input.endpoint)
}
- return endpointSnapshot(process, input.endpoint)
+ return this.system.endpointSnapshot(process, input.endpoint)
}
if (operation === "waitReady") {
await waitReady(process, (input as EndpointWaitReadyInput).timeout, signal)
- return endpointSnapshot(process, "server")
+ return this.system.endpointSnapshot(process, "server")
}
if (operation === "waitLifecycle") {
@@ -193,7 +189,7 @@ export default class SystemControl {
const request = input as EndpointWaitLifecycleInput
const internalEvent = request.event === "start" ? "endpointStart" : "endpointStop"
- await waitFor<void>(resolve => this.processes.observeHost(
+ await waitFor<void>(resolve => this.system.observe(
"process",
internalEvent,
process.reference,
@@ -213,8 +209,8 @@ export default class SystemControl {
const request = input as EndpointAskInput
- return this.processes.askFromOutside(
- process.identity,
+ return this.system.askEndpoint(
+ process,
request.event,
request.payload,
request.timeout,
@@ -226,15 +222,15 @@ export default class SystemControl {
const request = input as EndpointPublishInput
- await this.processes.publishFromOutside(process.identity, request.endpoint, request.event, request.payload)
+ await this.system.publishEndpoint(process, request.endpoint, request.event, request.payload)
- return Object.freeze({ ...endpointSnapshot(process, request.endpoint), event: request.event, published: true })
+ 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.processes.observeEndpoint(
- process.identity,
+ (resolve, reject) => this.system.observeEndpoint(
+ process,
request.endpoint,
request.event,
resolve,
@@ -255,7 +251,7 @@ export default class SystemControl {
private async window(operation: string, input: WindowInput | WindowWaitInput | (WindowInput & Record<string, unknown>), signal?: AbortSignal) {
- const process = resolveProcess(this.processes.processes, this.programs.programs, input)
+ 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`)
@@ -266,7 +262,7 @@ export default class SystemControl {
const payload = await waitFor(
(resolve, reject) => {
- const stopObservation = this.processes.observeHost("window", waiting.event, process.reference, (_event, _subject, value) => resolve(value))
+ 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`)))
@@ -279,25 +275,25 @@ export default class SystemControl {
return Object.freeze({ scope: "window", process: process.identity, event: waiting.event, payload })
}
- if (operation === "move") await this.processes.move(process.identity, request.position as never)
- else if (operation === "resize") await this.processes.resize(process.identity, request.size as never)
- else if (operation === "setGeometry") await this.processes.setGeometry(process.identity, {
+ 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.processes.minimize(process.identity, request.minimized !== false)
- else if (operation === "changeTitle") await this.processes.changeTitle(process.identity, String(request.title))
- else if (operation === "raise") await this.processes.raise(process.identity)
+ 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.processes.windowSnapshot(process.identity) })
+ return Object.freeze({ process: process.identity, ...this.system.windowSnapshot(process) })
}
private async waitProgram(request: ProgramWaitInput, signal?: AbortSignal) {
- const entry = request.program ? requiredProgram(this.programs.programs, request.program) : null
+ const entry = request.program ? this.system.requireProgram(request.program) : null
const subject = entry?.program.reference ?? null
const values = await waitFor<unknown[]>(
- resolve => this.processes.observeHost("program", request.event, subject, (_event, ...payload) => resolve(payload)),
+ resolve => this.system.observe("program", request.event, subject, (_event, ...payload) => resolve(payload)),
request.timeout,
signal
)
@@ -307,28 +303,28 @@ export default class SystemControl {
return Object.freeze({
scope: entry ? "program" : "host",
- ...(entry ? { program: programSnapshot(entry) } : {}),
+ ...(entry ? { program: this.system.programSnapshot(entry) } : {}),
event: request.event,
payload: request.event === "uninstall"
? Object.freeze({
- ...(affected ? { program: programSnapshot(affected) } : {}),
+ ...(affected ? { program: this.system.programSnapshot(affected) } : {}),
everything: values.at(-1) === true
})
- : affected ? programSnapshot(affected) : values
+ : affected ? this.system.programSnapshot(affected) : values
})
}
private async waitProcess(request: ProcessWaitInput, signal?: AbortSignal) {
const process = request.process
- ? resolveProcess(this.processes.processes, this.programs.programs, request as ProcessInput)
+ ? this.system.resolveProcess(request as ProcessInput)
: null
const program = !process && request.program
- ? requiredProgram(this.programs.programs, request.program)
+ ? this.system.requireProgram(request.program)
: null
const subject = process?.reference ?? program?.program.reference ?? null
const values = await waitFor<unknown[]>(
- resolve => this.processes.observeHost("process", request.event, subject, (_event, ...payload) => resolve(payload)),
+ resolve => this.system.observe("process", request.event, subject, (_event, ...payload) => resolve(payload)),
request.timeout,
signal
)
@@ -351,91 +347,6 @@ export default class SystemControl {
})
}
- private get programs() { return this.application.linkManager.authManager.programManager }
- private get processes() { return this.application.linkManager.authManager.processManager }
-}
-
-function requiredProgram(programs: ReadonlyMap<string, Entry>, identity: string) {
-
- const program = programs.get(identity)
-
- if (!program) throw new Error(`Unknown Program "${identity}"`)
-
- return program
-}
-
-function requiredProcess(processes: ReadonlyMap<string, Process>, identity: string) {
-
- const process = processes.get(identity)
-
- if (!process) throw new Error(`Unknown Process "${identity}"`)
-
- return process
-}
-
-function resolveProcess(processes: ReadonlyMap<string, Process>, programs: ReadonlyMap<string, Entry>, input: ProcessInput) {
-
- if (!input.program) return requiredProcess(processes, input.process)
-
- const owner = requiredProgram(programs, input.program).program
- const process = [...processes.values()].find(candidate => (
- candidate.program === owner
- && (candidate.identity === input.process || candidate.name === input.process)
- ))
-
- if (!process) throw new Error(`Unknown Process "${input.process}" in Program "${input.program}"`)
-
- return process
-}
-
-function programSnapshot(entry: Entry) {
-
- const program = entry.program
-
- return Object.freeze({
- reference: program.reference,
- identity: program.identity,
- name: program.name,
- version: program.config.version ?? null,
- description: program.config.description ?? null,
- installed: entry.installed,
- hasAgent: program.agentPath !== null,
- server: program.server ? Object.freeze({ start: program.server.start, service: program.server.service }) : null,
- client: program.client ? Object.freeze({
- start: program.client.start,
- service: program.client.service,
- title: program.client.title ?? null,
- size: program.client.size ?? null,
- position: program.client.position ?? null,
- layer: program.client.layer ?? null,
- minimize: program.client.minimize ?? null
- }) : null
- })
-}
-
-function processSnapshot(process: Process) {
-
- const owner = process.program.record()
-
- return Object.freeze({
- reference: process.reference,
- identity: process.identity,
- name: process.name,
- program: process.program.identity,
- programSnapshot: Object.freeze({
- reference: owner.reference,
- identity: owner.identity,
- name: owner.name,
- version: owner.version,
- description: owner.description,
- hasAgent: owner.hasAgent,
- server: owner.server,
- client: owner.client
- }),
- startedAt: process.startedAt.toISOString(),
- server: Object.freeze({ declared: process.program.server !== null, running: process.server !== null, service: process.server?.service ?? false }),
- client: Object.freeze({ declared: process.program.client !== null, running: process.client !== null, service: process.client?.service ?? false })
- })
}
function processRecordSnapshot(process: ReturnType<Process["record"]>) {
@@ -473,23 +384,14 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
server: record.program.server,
client: record.program.client
}),
+ parent: null,
+ options: Object.freeze({ ...process.options }),
startedAt: new Date(record.startedAt).toISOString(),
server: Object.freeze({ declared: record.program.server !== null, running: record.server !== null, service: record.server?.service ?? false }),
client: Object.freeze({ declared: record.program.client !== null, running: record.client !== null, service: record.client?.service ?? false })
})
}
-function endpointSnapshot(process: Process, endpoint: "server" | "client") {
-
- return Object.freeze({
- process: process.identity,
- program: process.program.identity,
- endpoint,
- declared: process.program[endpoint] !== null,
- running: process[endpoint] !== null,
- service: process[endpoint]?.service ?? false
- })
-}
function waitReady(process: Process, timeout = 10_000, signal?: AbortSignal) {
diff --git a/source/server/view/gateway/system-request.ts b/source/server/view/gateway/system-request.ts
index 7ed6b02..f82161a 100644
--- a/source/server/view/gateway/system-request.ts
+++ b/source/server/view/gateway/system-request.ts
@@ -1,7 +1,18 @@
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) {
- return application.systemControl.execute(request, signal)
+ let adapter = adapters.get(application)
+
+ if (!adapter) {
+
+ adapter = new SystemControl(application.system)
+ adapters.set(application, adapter)
+ }
+
+ return adapter.execute(request, signal)
}