Skip to content

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

feat: coordinate endpoint services

zohayrslileh747b80479f2c
diff --git a/package.json b/package.json
index 84bb89e..92f6548 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"build": "node --import tsx source/build.ts",
"start": "node --run build && node dist/server/main.js",
"pack": "node --run build && node --import tsx source/pack.ts",
- "verify:contracts": "node --import tsx scripts/verify-client-launch.mjs && node --import tsx scripts/verify-readiness.mjs",
+ "verify:contracts": "node --import tsx scripts/verify-client-launch.mjs && node --import tsx scripts/verify-readiness.mjs && node --import tsx scripts/verify-endpoint-services.mjs",
"verify:distribution": "node scripts/verify-distribution.mjs",
"verify": "node --run check && node --run verify:contracts && node --run verify:distribution"
},
diff --git a/scripts/verify-endpoint-services.mjs b/scripts/verify-endpoint-services.mjs
new file mode 100644
index 0000000..9a0bfe8
--- /dev/null
+++ b/scripts/verify-endpoint-services.mjs
@@ -0,0 +1,74 @@
+import assert from "node:assert/strict"
+import EndpointServices from "../source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts"
+
+function process(reference, program = "program") {
+ return {
+ reference,
+ program: { identity: program },
+ server: {},
+ client: {}
+ }
+}
+
+const services = new EndpointServices()
+const provider = process("provider")
+const conflicting = process("conflicting")
+const key = { program: "program", endpoint: "server", name: "counter" }
+const lifecycle = []
+const publications = []
+let disableTransportCompleted = false
+
+assert.equal(services.disabled(key), true)
+assert.equal(services.service(provider, "server"), null)
+
+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")
+
+assert.deepEqual(services.service(provider, "server"), key)
+assert.equal(services.disabled(key), false)
+assert.deepEqual(lifecycle, ["enable"])
+
+// Subscriptions are future-only: joining after enable does not replay it.
+const lateLifecycle = []
+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, "channel", "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.disabled(key), true)
+assert.deepEqual(lifecycle, ["enable", "disable"])
+assert.deepEqual(lateLifecycle, ["disable"])
+assert.equal(disableTransportCompleted, true)
+
+// Once disabled, endpoint output is no longer mirrored into the service.
+await services.emit(provider, "server", "change", 3)
+assert.deepEqual(publications, [2])
+
+// A later Endpoint incarnation may explicitly claim the same stable key.
+await services.enable(conflicting, "server", "counter")
+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.disabled({ ...key, endpoint: "client" }), false)
+assert.equal(services.disabled(key), true)
+await services.release(provider, "client")
+
+provider.server = null
+await assert.rejects(() => services.enable(provider, "server", "counter"), /not running/)
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 63c79dc..629bfef 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
@@ -7,7 +7,8 @@ import AuthManager from "../auth-manager"
import Process from "./process"
import { type LaunchClient } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
-import { isPermissionName } from "@phreshos/core"
+import { isPermissionName, type ServiceKey } from "@phreshos/core"
+import { type ServiceScope } from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"
/**
* The peer of the core's processes: born holding them from the
@@ -54,6 +55,50 @@ export default class ProcessManager extends TheLink {
await this.$outbound.publish("/emit", source, event, payload)
}
+ /** Changes the service exposed by the structurally identified Client Channel. */
+ public async enableService(source: string, name: string) {
+
+ await this.$outbound.publishFirst("/service/enable", source, name)
+ }
+
+ public async disableService(source: string) {
+
+ 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 serviceDisabled(key: ServiceKey) {
+
+ return await this.$outbound.publishFirst("/service/disabled", key) as boolean
+ }
+
+ /** Registers one exact service interest for this frame lease. */
+ public async followService(pane: string, owner: string, subscription: string, key: ServiceKey, scope: ServiceScope, event: string | null) {
+
+ await this.$outbound.publish("/frame/service/follow", pane, owner, subscription, key, scope, event)
+ }
+
+ public async unfollowService(pane: string, owner: string, subscription: string) {
+
+ await this.$outbound.publish("/frame/service/unfollow", pane, owner, subscription)
+ }
+
+ /** Sends to the live Server 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)
+ }
+
+ public async askService(source: string, key: ServiceKey, values: unknown[]) {
+
+ await this.$outbound.publish("/frame/service/ask", source, key, values)
+ }
+
// Handed on, not awaited. Whoever asked is holding the question by
// its own name and will recognise the answer when it arrives.
public async askOf(source: string, identity: string, values: unknown[]) {
diff --git a/source/client/view/desktop/client-host/client-host.ts b/source/client/view/desktop/client-host/client-host.ts
index e1aee4c..a8e760a 100644
--- a/source/client/view/desktop/client-host/client-host.ts
+++ b/source/client/view/desktop/client-host/client-host.ts
@@ -165,6 +165,20 @@ export default function useClientHost(desktop: RefObject<HTMLDivElement | null>,
}, [sources, traffic]))
+ // Exact service lifecycle and channel events use their own route. They
+ // reach only the frame lease that registered the opaque subscription.
+ inbound.useSubscribe("/service-event", useCallback((...results: unknown[]) => {
+
+ const [observer, owner, subscription, json] = results
+
+ if (typeof observer !== "string" || typeof owner !== "string" || typeof subscription !== "string" || typeof json !== "string") return
+
+ if (frameOwners.current.get(observer) !== owner) return
+
+ traffic.emit(observer, "service-event", subscription, ...JSON.parse(json) as unknown[]).catch(() => undefined)
+
+ }, [sources, traffic]))
+
inbound.useSubscribe("/impossible", useCallback((...results: unknown[]) => {
const [observer, owner, subscription, reason] = results
diff --git a/source/client/view/desktop/client-host/client-process-boundary.ts b/source/client/view/desktop/client-host/client-process-boundary.ts
index 8109a11..9f1502a 100644
--- a/source/client/view/desktop/client-host/client-process-boundary.ts
+++ b/source/client/view/desktop/client-host/client-process-boundary.ts
@@ -186,6 +186,16 @@ export default class ClientProcessBoundary extends TheLink {
})
}
+ if (values[0] === "service-ask" && typeof values[2] === "string") {
+
+ const question = values[2]
+
+ this.requests.set(question, () => {
+
+ this.authManager.processManager.cancel(this.pane, question).catch(() => undefined)
+ })
+ }
+
if (values[0] === "pointerSample") {
this.samplePointer(values[1], values[2])
@@ -723,6 +733,8 @@ export default class ClientProcessBoundary extends TheLink {
if (route === "end-host" && operation === "ask") return message[4] !== question
+ if (route === "end-host" && operation === "service-ask") return message[3] !== question
+
return true
})
diff --git a/source/client/view/desktop/client-host/host.ts b/source/client/view/desktop/client-host/host.ts
index 79abe75..6c8031c 100644
--- a/source/client/view/desktop/client-host/host.ts
+++ b/source/client/view/desktop/client-host/host.ts
@@ -6,7 +6,7 @@ import { type ClientBody, type ProxiedResponse, type ServedValue } from "@client
import { type PointerHost } from "./pointer"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { sdkProcess, sdkProgram } from "./sdk-records"
-import { isPermissionName, type ProgramIconSize } from "@phreshos/core"
+import { isPermissionName, isServiceKey, type ProgramIconSize } from "@phreshos/core"
/** A host answer whose stream must be transferred rather than cloned. */
export class TransferredAnswer {
@@ -29,11 +29,12 @@ export interface Space {
* that frames it.
*
* A client half has the capabilities a server half has, narrowed to a
- * world containing exactly one program — its own. That is the boundary
- * between programs: there is no word here that could name another one.
- * It is not a claim of network confinement — `fetch` deliberately reaches
- * arbitrary URLs, but carries neither a Program subject nor the desktop's
- * authorization.
+ * world containing exactly one program — its own. Public services are the
+ * deliberate exception: a complete service key may name another Program, but
+ * it reveals no topology and resolves only through the authoritative service
+ * registry. It is not a claim of network confinement — `fetch` deliberately
+ * reaches arbitrary URLs, but carries neither a Program subject nor the
+ * desktop's authorization.
*
* Program operations take no subject at all: the frame a message arrived
* in decides which program is meant, and what was asked is discarded.
@@ -217,6 +218,82 @@ export default function host(authManager: AuthManager, pane: string, space: (lay
return []
}
+ if (word === "enable-service") {
+
+ if (typeof args[0] !== "string" || args[0].length === 0) throw new Error("A service name must be a non-empty string")
+
+ 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() : sibling(args[0])
+
+ if (args[1] !== "server" && args[1] !== "client") throw new Error("A service Endpoint must be server or client")
+
+ return [await processManager.endpointService(pane, address(target), args[1])]
+ }
+
+ if (word === "service-disabled") {
+
+ if (!isServiceKey(args[0])) throw new Error("A complete service key is required")
+
+ return [await processManager.serviceDisabled(args[0])]
+ }
+
+ if (word === "service-follow") {
+
+ const [subscription, key, scope, event] = args
+
+ if (typeof subscription !== "string" || !isServiceKey(key)) return []
+
+ if (scope !== "lifecycle" && scope !== "channel") return []
+
+ if (event !== null && typeof event !== "string") return []
+
+ const owner = frameOwner()
+
+ if (owner) await processManager.followService(pane, owner, subscription, key, scope, event)
+
+ return []
+ }
+
+ if (word === "service-unfollow") {
+
+ const owner = frameOwner()
+
+ if (owner) await processManager.unfollowService(pane, owner, String(args[0]))
+
+ return []
+ }
+
+ if (word === "service-send") {
+
+ if (!isServiceKey(args[0]) || args[0].endpoint !== "server" || typeof args[1] !== "string") return []
+
+ await processManager.sendService(pane, args[0], args[1], args[2])
+
+ return []
+ }
+
+ if (word === "service-ask") {
+
+ if (!isServiceKey(args[0]) || args[0].endpoint !== "server") throw new Error("Only a Server service can be asked")
+
+ await processManager.askService(pane, args[0], args.slice(1))
+
+ return []
+ }
+
// A pane may receive a parent only inside the one program it is
// already a face of. No parent and a cross-program parent are
// the same `null`, so the relationship cannot reveal a stranger.
diff --git a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
index 07e86b9..e3031a2 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/client-process-forwarder.ts
@@ -1,6 +1,8 @@
import AuthManager from "../auth-manager"
import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
import EndpointEvents from "./endpoint-events"
+import EndpointServices, { type ServiceScope } from "./endpoint-services"
+import type { ServiceKey } from "@phreshos/core"
/**
* Server-host counterpart of one client Process boundary lease.
@@ -27,6 +29,8 @@ export default class ClientProcessForwarder {
private readonly endpointSubscriptions = new Map<string, () => void>()
+ private readonly serviceSubscriptions = new Map<string, () => void>()
+
private readonly requests = new Map<string, () => void>()
private readonly subscriptions = new Map<string, string | null>()
@@ -137,6 +141,27 @@ export default class ClientProcessForwarder {
this.endpointSubscriptions.delete(subscription)
}
+ public followService(services: EndpointServices, subscription: string, key: ServiceKey, scope: ServiceScope, event: string | null) {
+
+ this.unfollowService(subscription)
+
+ const stop = services.follow(key, scope, event, (word, payload) => {
+
+ const values = event === null ? [word, payload] : [payload]
+
+ return this.authManager.publishToConnection(this.connection, "/process/service-event", this.pane, this.owner, subscription, JSON.stringify(values)).catch(() => undefined)
+ })
+
+ this.serviceSubscriptions.set(subscription, stop)
+ }
+
+ public unfollowService(subscription: string) {
+
+ this.serviceSubscriptions.get(subscription)?.()
+
+ this.serviceSubscriptions.delete(subscription)
+ }
+
public retain(question: string, stop: () => void) {
this.requests.get(question)?.()
@@ -157,12 +182,16 @@ export default class ClientProcessForwarder {
for (const stop of this.endpointSubscriptions.values()) stop()
+ for (const stop of this.serviceSubscriptions.values()) stop()
+
for (const stop of this.requests.values()) stop()
this.observations.clear()
this.endpointSubscriptions.clear()
+ this.serviceSubscriptions.clear()
+
this.requests.clear()
this.subscriptions.clear()
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
new file mode 100644
index 0000000..f7a16e0
--- /dev/null
+++ b/source/server/core/link-manager/auth-manager/process-manager/endpoint-services.ts
@@ -0,0 +1,168 @@
+import { isServiceKey, type ServiceKey } from "@phreshos/core"
+import TheLink from "@libs/the-link/the-link"
+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.
+ */
+export default class EndpointServices extends TheLink {
+
+ private readonly bindings = new Map<string, Binding>()
+
+ private readonly owners = new Map<string, string>()
+
+ public async enable(process: Process, endpoint: Half, name: unknown) {
+
+ if (typeof name !== "string" || name.length === 0) throw new Error("A service name must be a non-empty string")
+
+ 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)
+
+ await this.$inbound.publish(this.event(key, "lifecycle", "enable"), "enable", undefined)
+
+ return key
+ }
+
+ public async disable(process: Process, endpoint: Half) {
+
+ const disabled = await this.release(process, endpoint)
+
+ if (!disabled) throw new Error(`The ${endpoint} endpoint exposes no service`)
+ }
+
+ /** Removes a binding owned by one exact Endpoint without treating absence as an error. */
+ public async release(process: Process, endpoint: Half) {
+
+ const owner = this.owner(process, endpoint)
+
+ const identity = this.owners.get(owner)
+
+ if (!identity) return false
+
+ const binding = this.bindings.get(identity)
+
+ this.owners.delete(owner)
+
+ if (!binding || binding.process !== process || binding.endpoint !== endpoint) return false
+
+ this.bindings.delete(identity)
+
+ await this.$inbound.publish(this.event(binding.key, "lifecycle", "disable"), "disable", undefined)
+
+ return true
+ }
+
+ public service(process: Process, endpoint: Half) {
+
+ const identity = this.owners.get(this.owner(process, endpoint))
+
+ return identity ? this.bindings.get(identity)?.key ?? null : null
+ }
+
+ public disabled(key: unknown) {
+
+ return !this.bindings.has(this.identity(this.key(key)))
+ }
+
+ public binding(key: unknown, endpoint?: Half) {
+
+ const binding = this.bindings.get(this.identity(this.key(key))) ?? null
+
+ return binding && (!endpoint || binding.endpoint === endpoint) && this.live(binding.process, binding.endpoint)
+ ? binding
+ : null
+ }
+
+ /** 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)
+
+ if (!key) return Promise.resolve([])
+
+ return this.$inbound.publish(this.event(key, "channel", event), event, payload)
+ }
+
+ public follow(key: unknown, scope: Scope, event: string | null, subscriber: Subscriber) {
+
+ const resolved = this.key(key)
+
+ if (scope !== "lifecycle" && scope !== "channel") throw new Error("A service subscription scope is invalid")
+
+ const prefix = this.prefix(resolved, scope)
+
+ if (event !== null) return this.$inbound.subscribe(prefix + encodeURIComponent(event), (_word, payload) => subscriber(event, payload))
+
+ return this.$inbound.forwardTo((_route, word, payload) => {
+
+ if (typeof word === "string") return subscriber(word, payload)
+ }, prefix)
+ }
+
+ private key(value: unknown) {
+
+ if (!isServiceKey(value)) throw new Error("A complete service key is required")
+
+ return value
+ }
+
+ private live(process: Process, endpoint: Half) {
+
+ return endpoint === "server" ? process.server !== null : process.client !== null
+ }
+
+ private owner(process: Process, endpoint: Half) {
+
+ return `${process.reference}:${endpoint}`
+ }
+
+ private identity(key: ServiceKey) {
+
+ return JSON.stringify([key.program, key.endpoint, key.name])
+ }
+
+ private prefix(key: ServiceKey, scope: Scope) {
+
+ return `${encodeURIComponent(key.program)}/${key.endpoint}/${encodeURIComponent(key.name)}/${scope}/`
+ }
+
+ private event(key: ServiceKey, scope: Scope, event: string) {
+
+ return this.prefix(key, scope) + encodeURIComponent(event)
+ }
+}
+
+export type ServiceScope = Scope
+
+export type ServiceBinding = Binding
+
+type Scope = "lifecycle" | "channel"
+
+type Binding = Readonly<{
+
+ key: ServiceKey
+
+ process: Process
+
+ endpoint: Half
+}>
+
+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 54d2407..2f351b0 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
@@ -17,7 +17,8 @@ import HostTraffic from "./host-traffic"
import { failed, succeeded, type Outcome } from "@server/core/outcome"
import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
-import { isPermissionName, type PermissionName, type WindowLayer } from "@phreshos/core"
+import EndpointServices from "./endpoint-services"
+import { isPermissionName, isServiceKey, type PermissionName, type WindowLayer } from "@phreshos/core"
/**
* The core's processes: the wire and the collection. Each process owns
@@ -45,6 +46,10 @@ 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()
+
// Host facts use their own the-link routes. A server boundary joins only
// the event and subject routes its endpoint explicitly requested.
private readonly hostTraffic = new HostTraffic()
@@ -621,6 +626,8 @@ export default class ProcessManager extends TheLink {
if (!process.serverStopped(boundary, code, signal)) return
+ await this.services.release(process, "server")
+
boundary.release()
await this.$outbound.publish("/server-stop", process.identity, process.hosted(), code, signal)
@@ -751,6 +758,13 @@ export default class ProcessManager extends TheLink {
const front = layer && this.front(layer)
+ await Promise.all([
+
+ this.services.release(process, "server"),
+
+ this.services.release(process, "client")
+ ])
+
if (!this.processes.delete(identity)) return
process.server?.release("The process ended before answering")
@@ -907,6 +921,8 @@ export default class ProcessManager extends TheLink {
const before = layer ? this.front(layer) : null
+ await this.services.release(process, "client")
+
process.stopClient()
for (const [key, boundary] of this.clientForwarders) {
@@ -989,9 +1005,72 @@ export default class ProcessManager extends TheLink {
@Connect("/emit")
public async emitClient(source: string, event: string, payload: unknown) {
- if (!this.find(source).client) return
+ const process = this.find(source)
+
+ if (!process.client) return
+
+ await Promise.all([
+
+ this.endpointEvents.emit(process.reference, "client", event, payload),
+
+ this.services.emit(process, "client", event, payload)
+ ])
+ }
+
+ @Connect("/service/enable")
+ protected async enableClientService(source: string, name: 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", name)
+ }
+
+ @Connect("/service/disable")
+ protected async disableClientService(source: string) {
+
+ 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 (endpoint !== "server" && endpoint !== "client") throw new Error("A service Endpoint must be server or client")
+
+ const held = this.heldProcess(target)
+
+ if (held.program !== process.program) throw new Error("The desktop does not know this process")
- await this.endpointEvents.emit(this.find(source).reference, "client", event, payload)
+ return this.services.service(held, endpoint)
+ }
+
+ @Connect("/service/disabled")
+ protected async serviceDisabled(key: unknown) {
+
+ return this.services.disabled(key)
+ }
+
+ @Subscribe("/service/send")
+ protected async sendClientService(source: string, key: unknown, event: unknown, payload: unknown) {
+
+ if (!isServiceKey(key) || key.endpoint !== "server" || typeof event !== "string") return
+
+ const process = this.find(source)
+
+ if (!process.client) return
+
+ const binding = this.services.binding(key, "server")
+
+ if (binding) await this.publish(process.identity, "client", binding.process.identity, "server", [event, payload])
}
@Subscribe("/frame/own")
@@ -1050,6 +1129,28 @@ export default class ProcessManager extends TheLink {
this.removeClientFollow(connection, pane, owner, subscription)
}
+ @Subscribe("/frame/service/follow")
+ protected followClientService(connection: string, pane: string, owner: string, subscription: unknown, key: unknown, scope: unknown, event: unknown) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner !== owner || typeof subscription !== "string" || !isServiceKey(key)) return
+
+ if (scope !== "lifecycle" && scope !== "channel") return
+
+ if (event !== null && typeof event !== "string") return
+
+ boundary.followService(this.services, subscription, key, scope, event)
+ }
+
+ @Subscribe("/frame/service/unfollow")
+ protected unfollowClientService(connection: string, pane: string, owner: string, subscription: unknown) {
+
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+
+ if (boundary?.owner === owner && typeof subscription === "string") boundary.unfollowService(subscription)
+ }
+
@Subscribe("/frame/log")
protected logClientFrame(_connection: string, pane: string, kind: unknown, content: unknown) {
@@ -1413,6 +1514,89 @@ 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-disabled") return [this.services.disabled(rest[0])]
+
+ if (word === "service-follow") {
+
+ const [subscription, key, scope, event] = rest
+
+ if (typeof subscription !== "string" || !isServiceKey(key)) return []
+
+ if (scope !== "lifecycle" && scope !== "channel") return []
+
+ if (event !== null && typeof event !== "string") return []
+
+ process.server?.followService(this.services, subscription, key, scope, event)
+
+ return []
+ }
+
+ if (word === "service-unfollow") {
+
+ process.server?.unfollowService(String(rest[0]))
+
+ return []
+ }
+
+ if (word === "service-send") {
+
+ const [key, event, payload] = rest
+
+ if (!isServiceKey(key) || key.endpoint !== "server" || typeof event !== "string") return []
+
+ const binding = this.services.binding(key, "server")
+
+ if (binding) await this.publish(process.identity, "server", binding.process.identity, "server", [event, payload])
+
+ return []
+ }
+
+ if (word === "service-ask") {
+
+ const [key, question, publicQuestion, event, payload] = rest
+
+ if (!isServiceKey(key) || key.endpoint !== "server" || typeof question !== "string" || typeof publicQuestion !== "string" || typeof event !== "string") {
+
+ if (typeof question === "string") this.rejectQuestion(["wait", question, publicQuestion, event, payload], "A Server service question is invalid")
+
+ return []
+ }
+
+ const binding = this.services.binding(key, "server")
+
+ if (!binding?.process.server) {
+
+ this.rejectQuestion(["wait", question, publicQuestion, event, payload], "The service is disabled")
+
+ return []
+ }
+
+ process.server?.retain(question, () => binding.process.server?.forget(question))
+
+ this.asked(process.identity, "server", binding.process.identity, [question, publicQuestion, event, payload])
+
+ return []
+ }
+
// The one word here that answers about a process the host does
// not know, because that absence is its whole subject. Every
// other refuses it: for those there is nothing to answer about,
@@ -1587,7 +1771,12 @@ export default class ProcessManager extends TheLink {
if (typeof rest[0] !== "string") return []
- await this.endpointEvents.emit(process.reference, "server", rest[0], rest[1])
+ await Promise.all([
+
+ this.endpointEvents.emit(process.reference, "server", rest[0], rest[1]),
+
+ this.services.emit(process, "server", rest[0], rest[1])
+ ])
return []
}
@@ -1822,6 +2011,28 @@ export default class ProcessManager extends TheLink {
this.asked(source, "client", identity, values)
}
+ @Subscribe("/frame/service/ask")
+ protected askClientService(connection: string, source: string, key: unknown, values: unknown[]) {
+
+ if (!isServiceKey(key) || key.endpoint !== "server" || typeof values[0] !== "string" || typeof values[1] !== "string" || typeof values[2] !== "string") {
+
+ this.rejectClientQuestion(connection, source, ["wait", ...values], "A Server service question is invalid")
+
+ return
+ }
+
+ const binding = this.services.binding(key, "server")
+
+ if (!binding || !this.retainClientQuestion(connection, source, values[0], binding.process.identity)) {
+
+ this.rejectClientQuestion(connection, source, ["wait", ...values], "The service is disabled")
+
+ return
+ }
+
+ this.asked(source, "client", binding.process.identity, values)
+ }
+
@Subscribe("/frame/cancel")
protected cancelClientFrame(connection: string, source: string, question: 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 b38ee8e..84968bd 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
@@ -4,6 +4,8 @@ import { type ChildProcess } from "node:child_process"
import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
import HostTraffic from "./host-traffic"
import EndpointEvents from "./endpoint-events"
+import EndpointServices, { type ServiceScope } from "./endpoint-services"
+import type { ServiceKey } from "@phreshos/core"
import Tunnel from "@libs/the-link/tunnel"
/**
@@ -36,6 +38,8 @@ export default class ServerProcessBoundary extends ProcessLink {
private readonly endpointSubscriptions = new Map<string, () => void>()
+ private readonly serviceSubscriptions = new Map<string, () => void>()
+
private readonly hostSubscriptions = new Map<string, () => void>()
private readonly themeSubscriptions = new Set<string>()
@@ -192,6 +196,28 @@ export default class ServerProcessBoundary extends ProcessLink {
this.endpointSubscriptions.delete(subscription)
}
+ /** Follow one exact service route for this boundary's lifetime. */
+ public followService(services: EndpointServices, subscription: string, key: ServiceKey, scope: ServiceScope, event: string | null) {
+
+ this.unfollowService(subscription)
+
+ const stop = services.follow(key, scope, event, (word, payload) => {
+
+ const values = event === null ? [word, payload] : [payload]
+
+ return this.deliver("service-event", subscription, ...values).catch(() => undefined)
+ })
+
+ this.serviceSubscriptions.set(subscription, stop)
+ }
+
+ public unfollowService(subscription: string) {
+
+ this.serviceSubscriptions.get(subscription)?.()
+
+ this.serviceSubscriptions.delete(subscription)
+ }
+
/** Remove a question whether it is waiting here or inside the SDK. */
public forget(question: string) {
@@ -216,6 +242,8 @@ export default class ServerProcessBoundary extends ProcessLink {
for (const stop of this.endpointSubscriptions.values()) stop()
+ for (const stop of this.serviceSubscriptions.values()) stop()
+
for (const stop of this.hostSubscriptions.values()) stop()
this.requests.clear()
@@ -224,6 +252,8 @@ export default class ServerProcessBoundary extends ProcessLink {
this.endpointSubscriptions.clear()
+ this.serviceSubscriptions.clear()
+
this.hostSubscriptions.clear()
this.themeSubscriptions.clear()