Skip to content

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

Route services by endpoint incarnation

zohayrslileh8e455e77950e
diff --git a/scripts/contracts/client-launch.ts b/scripts/contracts/client-launch.ts
index abf0bdc..b5775d0 100644
--- a/scripts/contracts/client-launch.ts
+++ b/scripts/contracts/client-launch.ts
@@ -1,5 +1,6 @@
import assert from "node:assert/strict"
-import ProgramManager, { type LaunchClient } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import type { ClientLaunch } from "@phreshos/core"
import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
const manager = {
@@ -16,7 +17,7 @@ const program = {
title: "Declared title"
}
-const shape = (overrides: LaunchClient) => ProgramManager.prototype.clientShape.call(
+const shape = (overrides: ClientLaunch) => ProgramManager.prototype.clientShape.call(
manager as unknown as ProgramManager,
program as unknown as Program,
overrides
@@ -24,4 +25,4 @@ const shape = (overrides: LaunchClient) => ProgramManager.prototype.clientShape.
assert.equal(shape({ title: "Fetched title" }).title, "Fetched title")
assert.equal(shape({}).title, "Declared title")
-assert.throws(() => shape({ title: 42 } as unknown as LaunchClient), /title must be text/)
+assert.throws(() => shape({ title: 42 } as unknown as ClientLaunch), /title must be text/)
diff --git a/scripts/contracts/endpoint-services.ts b/scripts/contracts/endpoint-services.ts
index 2244023..b3a0267 100644
--- a/scripts/contracts/endpoint-services.ts
+++ b/scripts/contracts/endpoint-services.ts
@@ -23,89 +23,97 @@ assert.throws(() => new Program({
server: { location: ".", startCommand: "true" }
}), /agent documentation/)
-function process(reference: string, program = "program") {
+const program = new Program({
+ identity: "program",
+ server: { location: ".", startCommand: "true" },
+ client: { location: "." }
+})
+
+function process(identity: string, name: string | null, ready = true, service = true) {
+ const waiters = new Set<() => void>()
+ const server = { ready, service }
return {
- reference,
- program: { identity: program },
- server: {},
- client: {}
- } as unknown as Process
+ identity,
+ name,
+ reference: `${identity}-reference`,
+ program,
+ launch: {
+ server: { service },
+ client: { service }
+ },
+ server,
+ client: { service },
+ waitReady(notify: () => void) {
+ if (server.ready) notify()
+ else waiters.add(notify)
+ return () => { waiters.delete(notify) }
+ },
+ becomeReady() {
+ server.ready = true
+ for (const notify of waiters) notify()
+ waiters.clear()
+ }
+ } as unknown as Process & { becomeReady(): void }
}
-const services = new EndpointServices()
-const provider = process("provider")
-const conflicting = process("conflicting")
-const independent = process("independent", "independent")
-const key = { program: "program", endpoint: "server", name: "counter" } satisfies ServiceKey
-const lifecycle: unknown[] = []
+let provider = process("0b231437-513b-4907-8041-c497279c07fa", "main")
+
+const services = new EndpointServices(key => {
+ if (key.program !== undefined && key.program !== program.identity) return null
+ if (key.program === undefined && key.process !== provider.identity) return null
+ if (key.process !== provider.identity && key.process !== provider.name) return null
+ if ((key.endpoint === "server" ? provider.server?.service : provider.client?.service) !== true) return null
+ return { process: provider, endpoint: key.endpoint }
+})
+
+const key = { program: "program", process: "main", endpoint: "server" } satisfies ServiceKey
+const exact = { ...key, process: provider.identity }
+const global = { process: provider.identity, endpoint: "server" } satisfies ServiceKey
+const lifecycle: string[] = []
const publications: unknown[] = []
-let disableTransportCompleted = false
-assert.equal(services.identity(key), services.identity({ ...key }))
-assert.notEqual(services.identity(key), services.identity({ ...key, endpoint: "client" }))
-assert.match(services.identity(key), /^[a-f0-9]{64}$/)
await assert.rejects(() => services.waitReady(key, -1), /non-negative finite number/)
-assert.equal(services.enabled(key), false)
-assert.equal(services.service(provider, "server"), null)
-await services.enable(independent, "server", "independent")
-assert.equal(services.enabled({ program: "independent", endpoint: "server", name: "independent" }), true)
-await services.release(independent, "server")
-
services.follow(key, "lifecycle", null, event => lifecycle.push(event))
-services.follow(key, "lifecycle", "disable", async () => {
- await Promise.resolve()
- disableTransportCompleted = true
-})
-
-await services.enable(provider, "server", "counter")
+services.follow(key, "events", "change", (_event, payload) => publications.push(payload))
-assert.deepEqual(services.service(provider, "server"), key)
-assert.equal(services.enabled(key), true)
-assert.deepEqual(lifecycle, ["enable"])
+await services.started(provider, "server")
+assert.equal(services.exists(key), true)
+assert.equal(services.exists(global), true)
+assert.deepEqual(lifecycle, ["start"])
await services.waitReady(key, 0)
-// Subscriptions are future-only: joining after enable does not replay it.
-const lateLifecycle: unknown[] = []
-services.follow(key, "lifecycle", null, event => lateLifecycle.push(event))
-assert.deepEqual(lateLifecycle, [])
-
-await assert.rejects(() => services.enable(provider, "server", "other"), /already exposes/)
-await assert.rejects(() => services.enable(conflicting, "server", "counter"), /already enabled/)
-
-services.follow(key, "events", "change", (_event, payload) => publications.push(payload))
-
await services.emit(provider, "server", "ignored", 1)
await services.emit(provider, "server", "change", 2)
-
assert.deepEqual(publications, [2])
-await services.release(provider, "server")
-
-assert.equal(services.enabled(key), false)
-assert.deepEqual(lifecycle, ["enable", "disable"])
-assert.deepEqual(lateLifecycle, ["disable"])
-assert.equal(disableTransportCompleted, true)
+provider.server = null
+await services.stopped(provider, "server", true)
+assert.equal(services.exists(key), false)
+assert.deepEqual(lifecycle, ["start", "stop"])
await assert.rejects(() => services.waitReady(key, 0), /timeout/)
-// Once disabled, endpoint output is no longer mirrored into the service.
-await services.emit(provider, "server", "change", 3)
-assert.deepEqual(publications, [2])
+// A name address follows a replacement, while an identity address does not.
+provider = process("234448b9-4661-4bda-8028-ae75438bf5be", "main", false)
+await services.started(provider, "server")
+assert.equal(services.exists(key), true)
+assert.equal(services.exists(exact), false)
+assert.equal(services.exists(global), false)
-// Exact readiness observation does not require a global Service registry.
const ready = services.waitReady(key, 100)
-await services.enable(conflicting, "server", "counter")
+provider.becomeReady()
await ready
-assert.deepEqual(lifecycle, ["enable", "disable", "enable"])
-await services.release(conflicting, "server")
-// Server and Client are distinct coordinates even under one Program and name.
-await services.enable(provider, "client", "counter")
-assert.equal(services.enabled({ ...key, endpoint: "client" }), true)
-assert.equal(services.enabled(key), false)
-await services.release(provider, "client")
+// Server and Client remain distinct coordinates for the same Process.
+assert.equal(services.exists({ ...key, endpoint: "client" }), true)
-await assert.rejects(() => services.enable(provider, "client", { name: "counter" }), /service name/)
+const unconfiguredProgram = new Program({
+ identity: "unconfigured",
+ server: { location: ".", startCommand: "true" }
+})
+assert.equal(unconfiguredProgram.server?.service, false)
-provider.server = null
-await assert.rejects(() => services.enable(provider, "server", "counter"), /not running/)
+// One incarnation can override the Program default without changing the Program.
+provider = process("2c6f42b0-7847-4f80-8373-0cba3f48636b", "main", true, false)
+await services.started(provider, "server")
+assert.equal(services.exists(key), false)
diff --git a/scripts/contracts/process-find-or-create.ts b/scripts/contracts/process-find-or-create.ts
index bba6019..31825c4 100644
--- a/scripts/contracts/process-find-or-create.ts
+++ b/scripts/contracts/process-find-or-create.ts
@@ -1,5 +1,6 @@
import assert from "node:assert/strict"
-import ProgramManager, { type Launch } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import type { Launch } from "@phreshos/core"
import type Program from "@server/core/link-manager/auth-manager/program-manager/program"
interface FixtureProcess {
@@ -11,7 +12,7 @@ interface FixtureProcess {
interface FixtureManager {
start(owner: Program, launch: Launch, watching?: unknown, parent?: unknown, transition?: boolean, prepared?: { intent: unknown }): Promise<`${string}-${string}-${string}-${string}-${string}`>
- resolveLaunch(owner: Program, launch: Launch): { intent: { client: { position: unknown, size: unknown } | null } }
+ resolveLaunch(owner: Program, launch: Launch): { intent: { server: { service: boolean } | null, client: { position: unknown, size: unknown, service: boolean } | null } }
}
const processes = new Map<string, FixtureProcess>()
@@ -96,5 +97,15 @@ const explicit = fixture.resolveLaunch(program, {
assert.deepEqual(omitted, explicit)
assert(omitted.client)
+assert.deepEqual(omitted.server, { service: false })
+assert.equal(omitted.client.service, false)
assert.equal(omitted.client.position, null)
assert.equal(omitted.client.size, null)
+
+const activated = fixture.resolveLaunch(program, {
+ server: { service: true },
+ client: { service: true }
+}).intent
+
+assert.equal(activated.server?.service, true)
+assert.equal(activated.client?.service, true)
diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.ts
index 272e859..3645440 100644
--- a/scripts/contracts/process-lifecycle.ts
+++ b/scripts/contracts/process-lifecycle.ts
@@ -7,7 +7,7 @@ import type Process from "@server/core/link-manager/auth-manager/process-manager
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"
-const launch = { server: false, client: null, options: {} } as const
+const launch = { server: null, client: null, options: {} } as const
function processManager() {
@@ -64,7 +64,7 @@ async function register(manager: ProcessManager, identity: string) {
null,
client,
{},
- { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", location: "/", minimize: false } },
+ { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", location: "/", minimize: false, service: false } },
null,
true,
{ title: "Partial", position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", location: "/", minimize: false },
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 01ffa05..90620d8 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
@@ -6,7 +6,7 @@ import TheLink from "@libs/the-link/the-link"
import AuthManager from "../auth-manager"
import Process from "./process"
import ProcessScope from "./process-scope"
-import { type LaunchClient } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { type ClientLaunch, type ServerLaunch } from "@phreshos/core"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { isPermissionName, type ServiceKey, type WindowLayer } from "@phreshos/core"
import { type ServiceScope } from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"
@@ -83,26 +83,15 @@ export default class ProcessManager extends TheLink {
await this.$outbound.publish("/emit", source, event, payload)
}
- /** Changes the service exposed by the structurally identified Client Context. */
- public async enableService(source: string, definition: unknown) {
+ public async endpointIsService(source: string, target: HandleAddress, endpoint: "server" | "client") {
- await this.$outbound.publishFirst("/service/enable", source, definition)
+ return await this.$outbound.publishFirst("/endpoint/is-service", source, target, endpoint) as boolean
}
- public async disableService(source: string) {
+ /** Reads current Endpoint existence for one exact Service address. */
+ public async serviceExists(key: ServiceKey) {
- await this.$outbound.publishFirst("/service/disable", source)
- }
-
- public async endpointService(source: string, target: HandleAddress, endpoint: "server" | "client") {
-
- return await this.$outbound.publishFirst("/service/current", source, target, endpoint) as ServiceKey | null
- }
-
- /** Explicit snapshot for one exact service key. */
- public async serviceEnabled(key: ServiceKey) {
-
- return await this.$outbound.publishFirst("/service/enabled", key) as boolean
+ return await this.$outbound.publishFirst("/service/exists", key) as boolean
}
public async waitServiceReady(key: ServiceKey, timeout: number | undefined) {
@@ -121,7 +110,7 @@ export default class ProcessManager extends TheLink {
await this.$outbound.publish("/frame/service/unfollow", pane, owner, subscription)
}
- /** Sends to the live Server Endpoint behind one exact service key. */
+ /** Sends to the live Endpoint behind one exact service key. */
public async sendService(source: string, key: ServiceKey, event: string, payload: unknown) {
await this.$outbound.publish("/service/send", source, key, event, payload)
@@ -200,9 +189,9 @@ export default class ProcessManager extends TheLink {
return await this.$outbound.publishFirst("/exit-all", program, asker) as string[]
}
- public async startEndpoint(identity: string, which: "server" | "client", overrides?: LaunchClient) {
+ public async startEndpoint(identity: string, which: "server" | "client", launch?: ServerLaunch | ClientLaunch) {
- await this.$outbound.publish("/endpoint/start", identity, which, overrides)
+ await this.$outbound.publish("/endpoint/start", identity, which, launch)
}
public async stopEndpoint(identity: string, which: "server" | "client") {
@@ -266,11 +255,11 @@ 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: TransmittedProcess | null) {
- if (!identity) return
+ if (!identity || !payload) return
- this.processes.get(identity)?.serverStarted()
+ this.processes.get(identity)?.serverStarted(payload)
return this.list()
}
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 990fa6f..1d001b3 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
@@ -29,7 +29,7 @@ export default class Process {
public readonly startedAt: Date
// Current live endpoint state mirrored from the authoritative host.
- public server: { ready: boolean } | null
+ public server: { ready: boolean, service: boolean } | null
public client: ClientState | null
@@ -78,9 +78,9 @@ export default class Process {
await this.processManager.$outbound.publish("/frame/end-end", this.identity, args)
}
- public serverStarted() {
+ public serverStarted(payload: TransmittedProcess) {
- this.server = { ready: false }
+ if (payload.server) this.server = payload.server
}
public serverStopped() {
@@ -126,7 +126,7 @@ export interface ProcessRecord {
readonly startedAt: Date
- readonly server: Record<string, never> | null
+ readonly server: { service: boolean } | null
- readonly client: Record<string, never> | null
+ readonly client: { service: boolean } | null
}
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 830b8a2..3fc8969 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,10 +1,10 @@
-import { Launch, TransmittedProgramManager } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { TransmittedProgramManager } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
import { Publish, Subscribe } from "@libs/the-link/decorators/escript"
import TheLink from "@libs/the-link/the-link"
import AuthManager from "../auth-manager"
import Program from "./program"
-import { type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"
+import { type Launch, type ProgramCommandChunk, type ProgramIconSize } from "@phreshos/core"
/**
* The peer of the core's programs: born holding them from the
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 cf021b2..feb12e9 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,5 +1,5 @@
import { HostedEntry } from "@server/core/link-manager/auth-manager/program-manager/entry"
-import { Launch } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { type Launch } from "@phreshos/core"
import ProgramManager from "./program-manager"
/**
diff --git a/source/client/view/components/desktop-host/announcements.ts b/source/client/view/components/desktop-host/announcements.ts
index d220298..888720d 100644
--- a/source/client/view/components/desktop-host/announcements.ts
+++ b/source/client/view/components/desktop-host/announcements.ts
@@ -197,7 +197,7 @@ export function uninstalled(panes: readonly (readonly [string, string | undefine
return panes.filter(([, shown]) => shown === program.identity).map(([pane]) => [pane, "program-host", "uninstall", program.reference, everything])
}
-type ExitedProcess = { reference: string, identity: string, program: string, startedAt: Date, name: string | null, options: Record<string, string>, server: { ready: boolean } | null, client: { window: unknown } | null }
+type ExitedProcess = { reference: string, identity: string, program: string, startedAt: Date, name: string | null, options: Record<string, string>, server: { ready: boolean, service: boolean } | null, client: { window: unknown, service: boolean } | null }
type EndpointEvent = "endpointStart" | "endpointStop"
diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.ts
index 89baf6e..375ecfe 100644
--- a/source/client/view/components/desktop-host/client-host.ts
+++ b/source/client/view/components/desktop-host/client-host.ts
@@ -157,7 +157,7 @@ export default function useClientHost(authManager: AuthManager, desktop: RefObje
}, [sources, traffic]))
- // Exact service lifecycle and channel events use their own route. They
+ // Exact Service lifecycle and application events use their own route. They
// reach only the frame lease that registered the opaque subscription.
inbound.useSubscribe("/service-event", useCallback((...results: unknown[]) => {
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index dac3d5b..5d44945 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -1,4 +1,4 @@
-import { type Launch } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import { type Launch } from "@phreshos/core"
import { type ProxyRequest } from "@server/core/protocol/proxy"
import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import { type ClientBody, type ProxiedResponse, type UploadValue } from "@client/core/application"
@@ -140,34 +140,21 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
- if (word === "enable-service") {
+ if (word === "is-service") {
- await processManager.enableService(pane, args[0])
-
- return []
- }
-
- if (word === "disable-service") {
-
- await processManager.disableService(pane)
-
- return []
- }
-
- if (word === "endpoint-service") {
-
- const target = args[0] === null ? process() : scope.sibling(args[0])
+ const target = args[1] === undefined ? process() : scope.sibling(args[1])
+ const endpoint = args[0] ?? "client"
- if (args[1] !== "server" && args[1] !== "client") throw new Error("A service Endpoint must be server or client")
+ if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")
- return [await processManager.endpointService(pane, address(target), args[1])]
+ return [await processManager.endpointIsService(pane, address(target), endpoint)]
}
- if (word === "service-enabled") {
+ if (word === "service-exists") {
if (!isServiceKey(args[0])) throw new Error("A complete service key is required")
- return [await processManager.serviceEnabled(args[0])]
+ return [await processManager.serviceExists(args[0])]
}
if (word === "service-wait-ready") {
@@ -205,7 +192,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "service-send") {
- if (!isServiceKey(args[0]) || args[0].endpoint !== "server" || typeof args[1] !== "string") return []
+ if (!isServiceKey(args[0]) || typeof args[1] !== "string") return []
await processManager.sendService(pane, args[0], args[1], args[2])
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
index e433b12..ad5e201 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-state.ts
@@ -11,8 +11,12 @@ export default class ClientState {
public readonly window: Window
- public constructor(window: Window) {
+ public readonly service: boolean
+
+ public constructor(window: Window, service: boolean) {
this.window = window
+
+ this.service = service
}
}
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 e331934..af7599b 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
@@ -1,132 +1,104 @@
import { isServiceKey, type ServiceKey } from "@phreshos/core"
import TheLink from "@libs/the-link/the-link"
-import { createHash } from "node:crypto"
import type Process from "./process"
import type { Half } from "./process-traffic"
-/**
- * Authoritative runtime bindings for explicitly named public Endpoint services.
- *
- * A key survives absence conceptually, but a binding never does: it points to
- * one live Endpoint incarnation and is removed with that incarnation. Routes
- * retain no value and deliver only to exact live interests.
- */
+/** Routes live Endpoint services without owning their lifecycle or state. */
export default class EndpointServices extends TheLink {
- private readonly bindings = new Map<string, Binding>()
+ public constructor(private readonly resolve: (key: ServiceKey) => ServiceTarget | null) {
- private readonly owners = new Map<string, string>()
-
- public async enable(process: Process, endpoint: Half, value: unknown) {
-
- const name = this.name(value)
-
- if (!this.live(process, endpoint)) throw new Error(`The ${endpoint} endpoint is not running`)
-
- const owner = this.owner(process, endpoint)
-
- if (this.owners.has(owner)) throw new Error(`The ${endpoint} endpoint already exposes a service`)
-
- const key = Object.freeze({ program: process.program.identity, endpoint, name }) satisfies ServiceKey
-
- const identity = this.identity(key)
-
- if (this.bindings.has(identity)) throw new Error(`The "${name}" ${endpoint} service is already enabled for this Program`)
-
- this.bindings.set(identity, { key, process, endpoint })
-
- this.owners.set(owner, identity)
+ super()
+ }
- await this.$inbound.publish(this.event(key, "lifecycle", "enable"), "enable", undefined)
+ public exists(key: unknown) {
- return key
+ return this.target(key) !== null
}
- public async disable(process: Process, endpoint: Half) {
-
- const disabled = await this.release(process, endpoint)
+ public async waitReady(key: unknown, timeout: unknown = 10_000) {
- if (!disabled) throw new Error(`The ${endpoint} endpoint exposes no service`)
- }
+ const resolved = this.key(key)
- /** Removes a binding owned by one exact Endpoint without treating absence as an error. */
- public async release(process: Process, endpoint: Half) {
+ if (resolved.endpoint !== "server") throw new Error("Only a Server service becomes ready")
- const owner = this.owner(process, endpoint)
+ const milliseconds = serviceTimeout(timeout)
- const identity = this.owners.get(owner)
+ await new Promise<void>((resolve, reject) => {
- if (!identity) return false
+ let settled = false
+ let stopReady: () => void = () => undefined
- const binding = this.bindings.get(identity)
+ const finish = (complete: () => void) => {
- this.owners.delete(owner)
+ if (settled) return
- if (!binding || binding.process !== process || binding.endpoint !== endpoint) return false
+ settled = true
+ clearTimeout(timer)
+ stopStart()
+ stopReady()
+ complete()
+ }
- this.bindings.delete(identity)
+ const inspect = () => {
- await this.$inbound.publish(this.event(binding.key, "lifecycle", "disable"), "disable", undefined)
+ stopReady()
+ stopReady = () => undefined
- return true
- }
+ const target = this.resolve(resolved)
- public service(process: Process, endpoint: Half) {
+ if (!target?.process.server) return
- const identity = this.owners.get(this.owner(process, endpoint))
+ if (target.process.server.ready) return finish(resolve)
- return identity ? this.bindings.get(identity)?.key ?? null : null
- }
+ stopReady = target.process.waitReady(() => finish(resolve))
+ }
- public enabled(key: unknown) {
+ 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)
- return this.bindings.has(this.identity(this.key(key)))
+ inspect()
+ })
}
- public async waitReady(key: unknown, timeout: unknown = 10_000) {
+ public target(key: unknown, endpoint?: Half) {
const resolved = this.key(key)
- const milliseconds = serviceTimeout(timeout)
-
- if (this.enabled(resolved)) return
+ const target = this.resolve(resolved)
- await new Promise<void>((resolve, reject) => {
+ if (!target || endpoint && target.endpoint !== endpoint) return null
- let settled = false
+ return this.live(target.process, target.endpoint) ? target : null
+ }
- const finish = (complete: () => void) => {
+ /** Mirrors one service Endpoint emission into its identity and name routes. */
+ public async emit(process: Process, endpoint: Half, event: string, payload: unknown) {
- if (settled) return
+ if (!this.configured(process, endpoint)) return []
- settled = true
- clearTimeout(timer)
- stop()
- complete()
- }
- const stop = this.$inbound.subscribe(this.event(resolved, "lifecycle", "enable"), () => finish(resolve))
- const timer = setTimeout(() => finish(() => reject(new Error("The service did not become ready before the timeout"))), milliseconds)
-
- if (this.enabled(resolved)) finish(resolve)
- })
+ return await Promise.all(this.keys(process, endpoint).map(key => (
+ this.$inbound.publish(this.event(key, "events", event), event, payload)
+ )))
}
- public binding(key: unknown, endpoint?: Half) {
+ /** Mirrors one service Endpoint start into its identity and name routes. */
+ public async started(process: Process, endpoint: Half) {
- const binding = this.bindings.get(this.identity(this.key(key))) ?? null
+ if (!this.configured(process, endpoint)) return []
- return binding && (!endpoint || binding.endpoint === endpoint) && this.live(binding.process, binding.endpoint)
- ? binding
- : null
+ return await Promise.all(this.keys(process, endpoint).map(key => (
+ this.$inbound.publish(this.event(key, "lifecycle", "start"), "start", undefined)
+ )))
}
- /** Mirrors one Endpoint emission into its service route only while enabled. */
- public emit(process: Process, endpoint: Half, event: string, payload: unknown) {
-
- const key = this.service(process, endpoint)
+ /** Mirrors one service Endpoint stop into its identity and name routes. */
+ public async stopped(process: Process, endpoint: Half, service: boolean) {
- if (!key) return Promise.resolve([])
+ if (!service) return []
- return this.$inbound.publish(this.event(key, "events", event), event, payload)
+ return await Promise.all(this.keys(process, endpoint).map(key => (
+ this.$inbound.publish(this.event(key, "lifecycle", "stop"), "stop", undefined)
+ )))
}
public follow(key: unknown, scope: Scope, event: string | null, subscriber: Subscriber) {
@@ -152,11 +124,9 @@ export default class EndpointServices extends TheLink {
return value
}
- private name(value: unknown) {
+ private configured(process: Process, endpoint: Half) {
- if (typeof value !== "string" || value.length === 0) throw new Error("A service name must be a non-empty string")
-
- return value
+ return endpoint === "server" ? process.server?.service === true : process.client?.service === true
}
private live(process: Process, endpoint: Half) {
@@ -164,31 +134,26 @@ export default class EndpointServices extends TheLink {
return endpoint === "server" ? process.server !== null : process.client !== null
}
- private owner(process: Process, endpoint: Half) {
-
- return `${process.reference}:${endpoint}`
- }
-
- /** Stable internal identity of one exact Service coordinate tuple. */
- public identity(value: unknown) {
-
- const key = this.key(value)
+ private keys(process: Process, endpoint: Half) {
- return createHash("sha256")
- .update(JSON.stringify([key.program, key.endpoint, key.name]))
- .digest("hex")
+ return [
+ Object.freeze({ process: process.identity, endpoint }),
+ Object.freeze({ program: process.program.identity, process: process.identity, endpoint }),
+ ...process.name ? [Object.freeze({ program: process.program.identity, process: process.name, endpoint })] : []
+ ] satisfies ServiceKey[]
}
private prefix(key: ServiceKey, scope: Scope) {
- return `${encodeURIComponent(key.program)}/${key.endpoint}/${encodeURIComponent(key.name)}/${scope}/`
+ return key.program === undefined
+ ? `process/${encodeURIComponent(key.process)}/${key.endpoint}/${scope}/`
+ : `program/${encodeURIComponent(key.program)}/${encodeURIComponent(key.process)}/${key.endpoint}/${scope}/`
}
private event(key: ServiceKey, scope: Scope, event: string) {
return this.prefix(key, scope) + encodeURIComponent(event)
}
-
}
export function serviceTimeout(value: unknown = 10_000) {
@@ -203,17 +168,11 @@ export function serviceTimeout(value: unknown = 10_000) {
export type ServiceScope = Scope
-export type ServiceBinding = Binding
-
-type Scope = "lifecycle" | "events"
-
-type Binding = Readonly<{
-
- key: ServiceKey
-
+type ServiceTarget = Readonly<{
process: Process
-
endpoint: Half
}>
+type Scope = "lifecycle" | "events"
+
type Subscriber = (event: string, payload: unknown) => unknown
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 f52f3eb..909b780 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -1,6 +1,6 @@
import { Connect, Subscribe } from "@libs/the-link/decorators/escript"
import { uploadLimit } from "@server/core/upload-manager"
-import { type Launch, type LaunchClient, type Options } from "../program-manager/program-manager"
+import { type Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import { Layer } from "../program-manager/config"
import Window, { Position, Size } from "./window"
@@ -17,7 +17,7 @@ import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
import EndpointServices from "./endpoint-services"
import OutsideQuestions from "./outside-questions"
-import { isPermissionName, isServiceKey, type PermissionName, type WindowGeometry, type WindowLayer } from "@phreshos/core"
+import { isPermissionName, isServiceKey, type ClientLaunch, type Launch, type PermissionName, type ServerLaunch, type ServiceKey, type WindowGeometry, type WindowLayer } from "@phreshos/core"
import type { ServerRuntime } from "./server-runtime"
/**
@@ -46,9 +46,9 @@ export default class ProcessManager extends TheLink {
// Endpoint speaks once; only boundaries following that Endpoint join.
private readonly endpointEvents = new EndpointEvents()
- // Public services retain only exact runtime bindings and exact interests.
- // They neither enumerate service topology nor expose their backing Process.
- private readonly services = new EndpointServices()
+ // Services route to live Endpoint incarnations. They own no registration state
+ // and never control the Process or Endpoint they address.
+ private readonly services: EndpointServices
// Host facts use their own the-link routes. A server boundary joins only
// the event and subject routes its endpoint explicitly requested.
@@ -79,6 +79,8 @@ export default class ProcessManager extends TheLink {
this.authManager = authManager
+ this.services = new EndpointServices(key => this.resolveService(key))
+
this.connectTo(this.authManager, "/process")
}
@@ -92,6 +94,22 @@ export default class ProcessManager extends TheLink {
return process
}
+ private resolveService(key: ServiceKey) {
+
+ const exact = this.processes.get(key.process)
+ const program = key.program === undefined ? null : this.authManager.programManager.reach(key.program)
+ const process = key.program === undefined
+ ? exact
+ : program && exact?.program === program
+ ? exact
+ : program
+ ? [...this.processes.values()].find(candidate => candidate.program === program && candidate.name === key.process)
+ : null
+ const service = key.endpoint === "server" ? process?.server?.service : process?.client?.service
+
+ 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) {
@@ -219,15 +237,16 @@ export default class ProcessManager extends TheLink {
))
}
- /** Read one live Endpoint's public Service without inventing an external Endpoint identity. */
- public serviceFromOutside(identity: string, endpoint: Half) {
+ public serviceExistsFromOutside(key: unknown) {
- return this.services.service(this.find(identity), endpoint)
+ return this.services.exists(key)
}
- public serviceEnabledFromOutside(key: unknown) {
+ public endpointIsServiceFromOutside(identity: string, endpoint: Half) {
- return this.services.enabled(key)
+ const process = this.find(identity)
+
+ return endpoint === "server" ? process.server?.service === true : process.client?.service === true
}
public waitServiceReadyFromOutside(key: unknown, timeout?: number) {
@@ -238,21 +257,21 @@ export default class ProcessManager extends TheLink {
/** Publish through a Service from an owner boundary represented by `from: null`. */
public async publishServiceFromOutside(key: unknown, event: string, payload: unknown) {
- const binding = this.services.binding(key)
+ const target = this.services.target(key)
- if (!binding) throw new Error("The service is disabled")
+ if (!target) throw new Error("The service endpoint does not exist")
- await this.deliver(binding.process.identity, binding.endpoint, [event, { from: null, payload }])
+ await this.deliver(target.process.identity, target.endpoint, [event, { from: null, payload }])
}
/** Ask a Server Service from an owner boundary represented by `from: null`. */
public askServiceFromOutside(key: unknown, event: string, payload: unknown, timeout = 10_000, signal?: AbortSignal) {
- const binding = this.services.binding(key, "server")
+ const target = this.services.target(key, "server")
- if (!binding) return Promise.reject(new Error("The service is disabled"))
+ if (!target) return Promise.reject(new Error("The service endpoint does not exist"))
- return this.askFromOutside(binding.process.identity, event, payload, timeout, signal)
+ return this.askFromOutside(target.process.identity, event, payload, timeout, signal)
}
public observeServiceFromOutside(key: unknown, scope: "lifecycle" | "events", event: string | null, subscriber: (event: string, payload: unknown) => unknown) {
@@ -720,7 +739,10 @@ export default class ProcessManager extends TheLink {
// incarnation exists.
if (process.server?.ready) await this.$outbound.publish("/server-ready", process.identity)
- await this.endpointEvent("endpointStart", process, "server")
+ await Promise.all([
+ this.endpointEvent("endpointStart", process, "server"),
+ this.services.started(process, "server")
+ ])
}
private async serverEnded(process: Process, boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) {
@@ -735,7 +757,7 @@ export default class ProcessManager extends TheLink {
() => { process.serverStopped(boundary, code, signal) },
- () => this.services.release(process, "server"),
+ () => this.services.stopped(process, "server", boundary.service),
() => { boundary.release() },
@@ -770,9 +792,9 @@ export default class ProcessManager extends TheLink {
else await this.transition(process, finish).catch(() => undefined)
}
- private activateServer(process: Process, runtime: ServerRuntime) {
+ private activateServer(process: Process, runtime: ServerRuntime, service: boolean) {
- const server = process.startServer(runtime,
+ const server = process.startServer(runtime, service,
(boundary, code, signal) => this.serverEnded(process, boundary, code, signal),
@@ -834,9 +856,9 @@ export default class ProcessManager extends TheLink {
// order: Process creation, endpoint start, endpoint stop, Process exit.
await this.transition(process, async () => {
- if (client && window) process.startClient(window)
+ if (client && window) process.startClient(window, launch.client?.service ?? false)
- if (runtime) this.activateServer(process, runtime)
+ if (runtime) this.activateServer(process, runtime, launch.server?.service ?? false)
// The subject first, which is what scopes a listener without
// anything being checked: a kit's `Events` refuses a value whose
@@ -858,7 +880,10 @@ export default class ProcessManager extends TheLink {
await this.$outbound.publish("/client-start", process.identity, process.hosted())
- await this.endpointEvent("endpointStart", process, "client")
+ await Promise.all([
+ this.endpointEvent("endpointStart", process, "client"),
+ this.services.started(process, "client")
+ ])
}
})
}
@@ -893,11 +918,14 @@ export default class ProcessManager extends TheLink {
const front = layer && this.front(layer)
- const failures = await settleEvery([
-
- () => this.services.release(process, "server"),
+ const serverWasLive = process.server !== null
+ const clientWasLive = process.client !== null
+ const serverWasService = process.server?.service === true
+ const clientWasService = process.client?.service === true
- () => this.services.release(process, "client")
+ const failures = await settleEvery([
+ ...serverWasLive ? [() => this.services.stopped(process, "server", serverWasService)] : [],
+ ...clientWasLive ? [() => this.services.stopped(process, "client", clientWasService)] : []
])
// Another converging teardown may have completed while services were
@@ -959,7 +987,7 @@ export default class ProcessManager extends TheLink {
throwFailures("The process ended with incomplete cleanup", failures)
}
- public async startServer(identity: string) {
+ public async startServer(identity: string, launch: ServerLaunch = {}) {
const process = this.find(identity)
@@ -969,13 +997,15 @@ export default class ProcessManager extends TheLink {
if (process.server) throw new Error("The server endpoint is already running")
+ if (typeof launch !== "object" || launch === null || Array.isArray(launch) || launch.service !== undefined && typeof launch.service !== "boolean") throw new Error("A Server launch must contain an optional boolean service value")
+
await process.program.validate()
const runtime = this.authManager.programManager.serverRuntime(process.program)
try {
- this.activateServer(process, runtime)
+ this.activateServer(process, runtime, launch.service ?? process.program.server.service)
await this.serverStarted(process)
}
@@ -1029,7 +1059,7 @@ export default class ProcessManager extends TheLink {
return identity
}
- public async startClient(identity: string, overrides?: LaunchClient) {
+ public async startClient(identity: string, launch: ClientLaunch = {}) {
const process = this.find(identity)
@@ -1041,13 +1071,13 @@ export default class ProcessManager extends TheLink {
await process.program.validate()
- const shape = this.authManager.programManager.clientShape(process.program, overrides)
+ const shape = this.authManager.programManager.clientShape(process.program, launch)
const window = this.window(process.program, shape)
const before = this.front(window.layer)
- process.startClient(window)
+ process.startClient(window, launch.service ?? process.program.client.service)
try {
@@ -1055,7 +1085,10 @@ export default class ProcessManager extends TheLink {
this.settleFront(window.layer, before)
- await this.endpointEvent("endpointStart", process, "client")
+ await Promise.all([
+ this.endpointEvent("endpointStart", process, "client"),
+ this.services.started(process, "client")
+ ])
}
catch (error) {
@@ -1089,14 +1122,16 @@ export default class ProcessManager extends TheLink {
const layer = process.client?.window.layer ?? null
+ const service = process.client?.service === true
+
const before = layer ? this.front(layer) : null
await completeEvery("The client endpoint stopped with incomplete cleanup", [
- () => this.services.release(process, "client"),
-
() => { process.stopClient() },
+ () => this.services.stopped(process, "client", service),
+
() => { this.releaseClientForwarders(process.identity) },
() => this.$outbound.publish("/client-stop", process.identity, process.hosted()),
@@ -1216,32 +1251,12 @@ export default class ProcessManager extends TheLink {
])
}
- @Connect("/service/enable")
- protected async enableClientService(source: string, definition: unknown) {
-
- const process = this.find(source)
-
- if (!process.client) throw new Error("The providing client endpoint is not running")
-
- return await this.services.enable(process, "client", definition)
- }
-
- @Connect("/service/disable")
- protected async disableClientService(source: string) {
+ @Connect("/endpoint/is-service")
+ protected async clientEndpointIsService(source: string, target: unknown, endpoint: unknown) {
const process = this.find(source)
- if (!process.client) throw new Error("The providing client endpoint is not running")
-
- await this.services.disable(process, "client")
- }
-
- @Connect("/service/current")
- protected async clientEndpointService(source: string, target: unknown, endpoint: unknown) {
-
- const process = this.find(source)
-
- if (!process.client) throw new Error("The providing client endpoint is not running")
+ if (!process.client) throw new Error("The current client endpoint is not running")
if (endpoint !== "server" && endpoint !== "client") throw new Error("A service Endpoint must be server or client")
@@ -1249,13 +1264,13 @@ export default class ProcessManager extends TheLink {
if (held.program !== process.program) throw new Error("The desktop does not know this process")
- return this.services.service(held, endpoint)
+ return endpoint === "server" ? held.server?.service === true : held.client?.service === true
}
- @Connect("/service/enabled")
- protected async serviceEnabled(key: unknown) {
+ @Connect("/service/exists")
+ protected async serviceExists(key: unknown) {
- return this.services.enabled(key)
+ return this.services.exists(key)
}
@Connect("/service/wait-ready")
@@ -1267,15 +1282,15 @@ export default class ProcessManager extends TheLink {
@Subscribe("/service/send")
protected async sendClientService(source: string, key: unknown, event: unknown, payload: unknown) {
- if (!isServiceKey(key) || key.endpoint !== "server" || typeof event !== "string") return
+ if (!isServiceKey(key) || typeof event !== "string") return
const process = this.find(source)
if (!process.client) return
- const binding = this.services.binding(key, "server")
+ const target = this.services.target(key)
- if (binding) await this.publish(process.identity, "client", binding.process.identity, "server", [event, payload])
+ if (target) await this.publish(process.identity, "client", target.process.identity, target.endpoint, [event, payload])
}
@Subscribe("/frame/own")
@@ -1689,13 +1704,23 @@ export default class ProcessManager extends TheLink {
throw new Error("A Process endpoint is server or client")
}
+ if (word === "is-service") {
+
+ const target = this.heldProcess(rest[1], process)
+ const endpoint = rest[0] ?? "server"
+
+ if (endpoint !== "server" && endpoint !== "client") throw new Error("A Process endpoint is server or client")
+
+ return [endpoint === "server" ? target.server?.service === true : target.client?.service === true]
+ }
+
if (word === "start-endpoint") {
const target = this.heldProcess(rest[0], process)
- if (rest[1] === "server") return [await this.startServer(target.identity)]
+ if (rest[1] === "server") return [await this.startServer(target.identity, rest[2] as ServerLaunch | undefined)]
- if (rest[1] === "client") return [await this.startClient(target.identity, rest[2] as LaunchClient | undefined)]
+ if (rest[1] === "client") return [await this.startClient(target.identity, rest[2] as ClientLaunch | undefined)]
throw new Error("A Process endpoint is server or client")
}
@@ -1713,26 +1738,7 @@ export default class ProcessManager extends TheLink {
if (word === "stop-current") return [await this.stopServer(process.identity)]
- if (word === "enable-service") {
-
- return [await this.services.enable(process, "server", rest[0])]
- }
-
- if (word === "disable-service") {
-
- return [await this.services.disable(process, "server")]
- }
-
- if (word === "endpoint-service") {
-
- if (rest[1] !== "server" && rest[1] !== "client") throw new Error("A service Endpoint must be server or client")
-
- const endpoint = this.heldProcess(rest[0], process)
-
- return [this.services.service(endpoint, rest[1])]
- }
-
- if (word === "service-enabled") return [this.services.enabled(rest[0])]
+ if (word === "service-exists") return [this.services.exists(rest[0])]
if (word === "service-wait-ready") return [await this.services.waitReady(rest[0], rest[1])]
@@ -1762,11 +1768,11 @@ export default class ProcessManager extends TheLink {
const [key, event, payload] = rest
- if (!isServiceKey(key) || key.endpoint !== "server" || typeof event !== "string") return []
+ if (!isServiceKey(key) || typeof event !== "string") return []
- const binding = this.services.binding(key, "server")
+ const target = this.services.target(key)
- if (binding) await this.publish(process.identity, "server", binding.process.identity, "server", [event, payload])
+ if (target) await this.publish(process.identity, "server", target.process.identity, target.endpoint, [event, payload])
return []
}
@@ -1782,18 +1788,18 @@ export default class ProcessManager extends TheLink {
return []
}
- const binding = this.services.binding(key, "server")
+ const target = this.services.target(key, "server")
- if (!binding?.process.server) {
+ if (!target?.process.server) {
- this.rejectQuestion(["wait", question, publicQuestion, event, payload], "The service is disabled")
+ this.rejectQuestion(["wait", question, publicQuestion, event, payload], "The service endpoint does not exist")
return []
}
- server.retain(question, () => binding.process.server?.forget(question))
+ server.retain(question, () => target.process.server?.forget(question))
- this.asked(process.identity, "server", binding.process.identity, [question, publicQuestion, event, payload])
+ this.asked(process.identity, "server", target.process.identity, [question, publicQuestion, event, payload])
return []
}
@@ -2299,16 +2305,16 @@ export default class ProcessManager extends TheLink {
return
}
- const binding = this.services.binding(key, "server")
+ const target = this.services.target(key, "server")
- if (!binding || !this.retainClientQuestion(connection, source, values[0], binding.process.identity)) {
+ if (!target || !this.retainClientQuestion(connection, source, values[0], target.process.identity)) {
- this.rejectClientQuestion(connection, source, ["wait", ...values], "The service is disabled")
+ this.rejectClientQuestion(connection, source, ["wait", ...values], "The service endpoint does not exist")
return
}
- this.asked(source, "client", binding.process.identity, values)
+ this.asked(source, "client", target.process.identity, values)
}
@Subscribe("/frame/cancel")
@@ -2379,11 +2385,11 @@ export default class ProcessManager extends TheLink {
}
@Connect("/endpoint/start")
- protected async startEndpoint(identity: string, which: string, overrides?: LaunchClient) {
+ protected async startEndpoint(identity: string, which: string, launch?: ServerLaunch | ClientLaunch) {
- if (which === "server") return await this.startServer(identity)
+ if (which === "server") return await this.startServer(identity, launch as ServerLaunch | undefined)
- if (which === "client") return await this.startClient(identity, overrides)
+ if (which === "client") return await this.startClient(identity, launch as ClientLaunch | undefined)
throw new Error("A Process endpoint is server or client")
}
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 584475a..94446e2 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
@@ -112,13 +112,13 @@ export default class Process {
this.hostTraffic = hostTraffic
}
- public startServer(runtime: ServerRuntime, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel) {
+ public startServer(runtime: ServerRuntime, service: boolean, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel) {
if (this.server) return this.server
let boundary!: ServerProcessBoundary
- boundary = new ServerProcessBoundary(runtime, this.program.client !== null, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance)
+ boundary = new ServerProcessBoundary(runtime, this.program.client !== null, service, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance)
this.server = boundary
@@ -163,11 +163,11 @@ export default class Process {
return () => { this.readyWaiters.delete(notify) }
}
- public startClient(window: Window) {
+ public startClient(window: Window, service: boolean) {
if (this.client) return false
- this.client = new ClientState(window)
+ this.client = new ClientState(window, service)
return true
}
@@ -286,9 +286,9 @@ export default class Process {
// These are live endpoint snapshots. Program declarations answer
// which endpoint kinds can be started.
- server: this.server ? {} : null,
+ server: this.server ? { service: this.server.service } : null,
- client: this.client ? {} : null
+ client: this.client ? { service: this.client.service } : null
}
}
@@ -300,7 +300,7 @@ export default class Process {
// The trusted desktop counterpart keeps this essential fact
// current. Framed program records are shaped separately.
- server: this.server ? { ready: this.server.ready } : null,
+ server: this.server ? { ready: this.server.ready, service: this.server.service } : null,
// The trusted desktop needs the relationship in order to
// answer a pane locally after the parent has exited. The
@@ -342,7 +342,10 @@ export type { Stream } from "./server-process-boundary"
/** Stable launch meaning, excluding mutable endpoint and Window state. */
export interface ProcessLaunch {
- readonly server: boolean
+ readonly server: Readonly<{
+
+ service: boolean
+ }> | null
readonly client: Readonly<{
@@ -357,6 +360,8 @@ export interface ProcessLaunch {
location: string
minimize: boolean
+
+ service: boolean
}> | null
readonly options: Readonly<Record<string, string>>
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 01e166b..7db9df9 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
@@ -19,6 +19,8 @@ export default class ServerProcessBoundary extends TheLink {
public ready = false
+ public readonly service: boolean
+
private readonly clientDeclared: boolean
private readonly subscriptions = new Map<string, EndpointSubscription>()
@@ -56,12 +58,14 @@ export default class ServerProcessBoundary extends TheLink {
public readonly finished: Promise<{ code: number | null, signal: NodeJS.Signals | null }>
- public constructor(runtime: ServerRuntime, clientDeclared: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel) {
+ public constructor(runtime: ServerRuntime, clientDeclared: boolean, service: boolean, ended: Ending, unanswered: (values: unknown[], reason: string) => void, hostTraffic: HostTraffic, appearance: Tunnel) {
super()
this.clientDeclared = clientDeclared
+ this.service = service
+
this.runtime = runtime
runtime.onMessage(message => { this.receive(message).catch(() => undefined) })
diff --git a/source/server/core/link-manager/auth-manager/program-manager/config.ts b/source/server/core/link-manager/auth-manager/program-manager/config.ts
index ab5ba27..188a51f 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/config.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/config.ts
@@ -61,6 +61,9 @@ interface ServerConfigBase {
// Whether a Process starts this endpoint by default. True when omitted.
start?: boolean
+ // Default service role for each new Server incarnation. False when omitted.
+ service?: boolean
+
// Run once before the program is first started, in that directory.
installCommand?: string
@@ -97,6 +100,9 @@ export interface ClientConfig {
// Whether a Process starts this endpoint by default. True when omitted.
start?: boolean
+ // Default service role for each new Client incarnation. False when omitted.
+ service?: boolean
+
// What its window is called when it opens. The window owns its title
// from then on and may change it; this is what it is born with, so
// there is no moment of showing the wrong thing while the half
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 bd7d5c0..bdd8167 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
@@ -11,8 +11,8 @@ import AuthManager from "../auth-manager"
import { dirname, isAbsolute, join } from "node:path"
import { isDeepStrictEqual } from "node:util"
import Logs, { type LogSource } from "./logs"
-import { isValue, layers, type Layer, type Position, type ProgramConfig, type Size } from "./config"
-import { type PermissionName, type ProgramCommandChunk } from "@phreshos/core"
+import { isValue, layers, type ProgramConfig } from "./config"
+import { type ClientLaunch, type Launch, type PermissionName, type ProgramCommandChunk } from "@phreshos/core"
import { type default as Process, type ProcessLaunch, type Stream } from "../process-manager/process"
import { type StandardShape } from "../process-manager/process-manager"
import Program, { type CommandOutput, type InstallOutput } from "./program"
@@ -1056,17 +1056,24 @@ export default class ProgramManager extends TheLink {
const options = Object.fromEntries(Object.entries(suppliedOptions).sort(([left], [right]) => left.localeCompare(right)))
- if (launch.server !== undefined && typeof launch.server !== "boolean") throw new Error("A launch's server must be true or false")
+ if (launch.server !== undefined && typeof launch.server !== "boolean" && (typeof launch.server !== "object" || launch.server === null || Array.isArray(launch.server))) throw new Error("A launch's server must be true, false, or a server shape")
if (launch.client !== undefined && typeof launch.client !== "boolean" && (typeof launch.client !== "object" || launch.client === null || Array.isArray(launch.client))) throw new Error("A launch's client must be true, false, or a client shape")
- const asked = typeof launch.client === "object" ? launch.client : {}
+ const askedServer = typeof launch.server === "object" ? launch.server : {}
+ const askedClient = typeof launch.client === "object" ? launch.client : {}
- if (launch.server === true && !program.server) throw new Error("This program declared no server half — a launch cannot add one")
+ if (askedServer.service !== undefined && typeof askedServer.service !== "boolean") throw new Error("A launch server's service role must be true or false")
+
+ if (askedClient.service !== undefined && typeof askedClient.service !== "boolean") throw new Error("A launch client's service role must be true or false")
+
+ if ((launch.server === true || typeof launch.server === "object") && !program.server) throw new Error("This program declared no server half — a launch cannot add one")
if ((launch.client === true || typeof launch.client === "object") && !program.client) throw new Error("This program declared no client half — a launch cannot add one")
- const server = program.server && (launch.server ?? program.server.start) ? program.server : null
+ const serverSelected = typeof launch.server === "object" || (launch.server ?? program.server?.start ?? false)
+
+ const server = program.server && serverSelected ? program.server : null
const clientSelected = typeof launch.client === "object" || (launch.client ?? program.client?.start ?? false)
@@ -1077,19 +1084,21 @@ export default class ProgramManager extends TheLink {
// Resolving the Window here validates the same launch grammar even when
// the launch is being stored for a later boot. Only the original launch
// is persisted; system defaults are derived again when it actually runs.
- const shape = client ? this.clientShape(program, asked) : null
+ const shape = client ? this.clientShape(program, askedClient) : null
const intent: ProcessLaunch = {
- server: server !== null,
+ server: server ? { service: askedServer.service ?? server.service ?? false } : null,
client: shape ? {
...shape,
- position: asked.position ?? program.client?.position ?? null,
+ service: askedClient.service ?? client?.service ?? false,
- size: asked.size ?? program.client?.size ?? null
+ position: askedClient.position ?? program.client?.position ?? null,
+
+ size: askedClient.size ?? program.client?.size ?? null
} : null,
options
@@ -1184,7 +1193,7 @@ export default class ProgramManager extends TheLink {
}
/** Resolves and validates one client endpoint incarnation. */
- public clientShape(program: Program, asked: LaunchClient = {}): StandardShape {
+ public clientShape(program: Program, asked: ClientLaunch = {}): StandardShape {
const client = program.client
@@ -1192,6 +1201,8 @@ export default class ProgramManager extends TheLink {
if (typeof asked !== "object" || asked === null || Array.isArray(asked)) throw new Error("A client launch must be a named shape")
+ if (asked.service !== undefined && typeof asked.service !== "boolean") throw new Error("A launch client's service role must be true or false")
+
if (asked.title !== undefined && typeof asked.title !== "string") throw new Error("A launch client's title must be text")
for (const [what, value] of [["size", asked.size], ["position", asked.position]] as const) {
@@ -1266,46 +1277,6 @@ function page(said: string | undefined, fallback: string) {
// the command line can only hand over text.
export type Options = Record<string, string>
-// What a launch says in named parts: which declared halves this process
-// has, what it is told, and how this one instance is shown. Ordered
-// arguments would have been invisible at the place they are written,
-// and two anonymous bags in a row is the shape that grows a third.
-export interface Launch {
-
- // Optional and unique among this program's living processes. It is
- // a meaningful address; the process identity remains random.
- name?: string
-
- // Omitted uses the declaration's default. True starts the declared server
- // endpoint; false leaves it stopped. Neither can declare a new endpoint.
- server?: boolean
-
- // An object starts the declared client endpoint and resolves its Window.
- client?: boolean | LaunchClient
-
- options?: Options
-}
-
-// The declaration's own words, all optional, overriding one Process's initial
-// or restarted client endpoint. Not `location` as a place to serve from — the declared
-// client root stays fixed — but as which page beneath it the frame
-// opens on. And not `icon`, which is the program's identity rather
-// than a fact about a launch.
-export interface LaunchClient {
-
- title?: string
-
- size?: Size
-
- position?: Position
-
- layer?: Layer
-
- location?: string
-
- minimize?: boolean
-}
-
// The two places a program keeps things. One survives an update and one
// may be emptied at any moment; both are the program's, shared by every
// process of it.
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program.ts b/source/server/core/link-manager/auth-manager/program-manager/program.ts
index 7edf4ce..892abf8 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program.ts
@@ -98,7 +98,8 @@ export default class Program {
return this.config.server ? {
...this.config.server,
- start: this.config.server.start ?? true
+ start: this.config.server.start ?? true,
+ service: this.config.server.service ?? false
} : null
}
@@ -106,7 +107,8 @@ export default class Program {
return this.config.client ? {
...this.config.client,
- start: this.config.client.start ?? true
+ start: this.config.client.start ?? true,
+ service: this.config.client.service ?? false
} : null
}
@@ -220,13 +222,17 @@ export default class Program {
server: server && {
- start: server.start
+ start: server.start,
+
+ service: server.service
},
client: client && {
start: client.start,
+ service: client.service,
+
title: client.title ?? null,
size: client.size ?? null,
@@ -361,6 +367,8 @@ function coherent(config: ProgramConfig) {
if (declared.start !== undefined && typeof declared.start !== "boolean") throw new Error(`A declared ${half} endpoint's start default must be true or false`)
+ if (declared.service !== undefined && typeof declared.service !== "boolean") throw new Error(`A declared ${half} endpoint's service default must be true or false`)
+
}
if (config.client && /^https?:\/\//i.test(config.client.location)) {
@@ -401,7 +409,9 @@ function coherent(config: ProgramConfig) {
return config
}
-type Resolved<Half extends { start?: boolean }> = Half extends unknown ? Omit<Half, "start"> & { start: boolean } : never
+type Resolved<Half extends { start?: boolean, service?: boolean }> = Half extends unknown
+ ? Omit<Half, "start" | "service"> & { start: boolean, service: boolean }
+ : never
function execution(server: { startCommand?: unknown, entryFile?: unknown }) {
diff --git a/source/server/core/system-control/system-control.ts b/source/server/core/system-control/system-control.ts
index 531bec9..eb663ad 100644
--- a/source/server/core/system-control/system-control.ts
+++ b/source/server/core/system-control/system-control.ts
@@ -169,8 +169,10 @@ export default class SystemControl {
if (operation === "start" || operation === "stop") {
if (operation === "start") {
- if (input.endpoint === "server") await this.processes.startServer(process.identity)
- else await this.processes.startClient(process.identity, (input as EndpointStartInput).client)
+ 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)
} else {
if (input.endpoint === "server") await this.processes.stopServer(process.identity)
else await this.processes.stopClient(process.identity)
@@ -398,9 +400,10 @@ function programSnapshot(entry: Entry) {
description: program.config.description ?? null,
installed: entry.installed,
hasAgent: program.agentPath !== null,
- server: program.server ? Object.freeze({ start: program.server.start }) : 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,
@@ -430,8 +433,8 @@ function processSnapshot(process: Process) {
client: owner.client
}),
startedAt: process.startedAt.toISOString(),
- server: Object.freeze({ declared: process.program.server !== null, running: process.server !== null }),
- client: Object.freeze({ declared: process.program.client !== null, running: process.client !== null })
+ 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 })
})
}
@@ -451,8 +454,8 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
client: unknown
}
startedAt: Date | string
- server: unknown
- client: unknown
+ server: { service: boolean } | null
+ client: { service: boolean } | null
}
return Object.freeze({
@@ -471,8 +474,8 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
client: record.program.client
}),
startedAt: new Date(record.startedAt).toISOString(),
- server: Object.freeze({ declared: record.program.server !== null, running: record.server !== null }),
- client: Object.freeze({ declared: record.program.client !== null, running: record.client !== null })
+ 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 })
})
}
@@ -483,7 +486,8 @@ function endpointSnapshot(process: Process, endpoint: "server" | "client") {
program: process.program.identity,
endpoint,
declared: process.program[endpoint] !== null,
- running: process[endpoint] !== null
+ running: process[endpoint] !== null,
+ service: process[endpoint]?.service ?? false
})
}
diff --git a/source/server/view/gateway/api-request.ts b/source/server/view/gateway/api-request.ts
index b05c24c..ce89122 100644
--- a/source/server/view/gateway/api-request.ts
+++ b/source/server/view/gateway/api-request.ts
@@ -25,14 +25,14 @@ export default async function apiRequest(application: Application, value: unknow
throw new Error(`The Uploads API does not know "${String(request.operation)}"`)
}
- if (request.capability === "endpoint" && request.operation === "service") {
+ 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 needs a Process and Endpoint")
+ throw new Error("Reading an Endpoint service role needs a Process and Endpoint")
}
- return processes(application).serviceFromOutside(request.process, request.endpoint)
+ return processes(application).endpointIsServiceFromOutside(request.process, request.endpoint)
}
if (request.capability === "endpoint" && request.operation === "wait") {
@@ -51,7 +51,7 @@ export default async function apiRequest(application: Application, value: unknow
const manager = processes(application)
const key = request.key
- if (request.operation === "enabled") return manager.serviceEnabledFromOutside(key)
+ if (request.operation === "exists") return manager.serviceExistsFromOutside(key)
if (request.operation === "waitReady") return await manager.waitServiceReadyFromOutside(key, number(request.timeout))
if (request.operation === "publish" || request.operation === "ask") {