An open-source, self-hosted system for apps built with web technologies.
Unify Endpoint readiness handling
zohayrslilehb28ac3bddb0b
diff --git a/scripts/contracts/endpoint-services.ts b/scripts/contracts/endpoint-services.tsindex b3a0267..170cec0 100644--- a/scripts/contracts/endpoint-services.ts+++ b/scripts/contracts/endpoint-services.ts@@ -28,6 +28,7 @@ const program = new Program({server: { location: ".", startCommand: "true" },client: { location: "." }})+const waits: string[] = []function process(identity: string, name: string | null, ready = true, service = true) {const waiters = new Set<() => void>()@@ -43,8 +44,10 @@ function process(identity: string, name: string | null, ready = true, service =},server,client: { service },- waitReady(notify: () => void) {- if (server.ready) notify()+ waitReady(endpoint: "server" | "client", notify: () => void) {++ waits.push(endpoint)+ if (endpoint === "client" || server.ready) notify()else waiters.add(notify)return () => { waiters.delete(notify) }},@@ -67,6 +70,7 @@ const services = new EndpointServices(key => {})const key = { program: "program", process: "main", endpoint: "server" } satisfies ServiceKey+const clientKey = { ...key, endpoint: "client" } satisfies ServiceKeyconst exact = { ...key, process: provider.identity }const global = { process: provider.identity, endpoint: "server" } satisfies ServiceKeyconst lifecycle: string[] = []@@ -82,6 +86,8 @@ assert.equal(services.exists(key), true)assert.equal(services.exists(global), true)assert.deepEqual(lifecycle, ["start"])await services.waitReady(key, 0)+await services.waitReady(clientKey, 0)+assert.deepEqual(waits, ["server", "client"])await services.emit(provider, "server", "ignored", 1)await services.emit(provider, "server", "change", 2)@@ -105,7 +111,7 @@ provider.becomeReady()await ready// Server and Client remain distinct coordinates for the same Process.-assert.equal(services.exists({ ...key, endpoint: "client" }), true)+assert.equal(services.exists(clientKey), true)const unconfiguredProgram = new Program({identity: "unconfigured",diff --git a/scripts/contracts/gateway.ts b/scripts/contracts/gateway.tsindex e5375be..8ff9f37 100644--- a/scripts/contracts/gateway.ts+++ b/scripts/contracts/gateway.ts@@ -23,6 +23,19 @@ const programSnapshot = {server: null,client: { start: true }}+const process = {+ reference: "process-reference",+ identity: "process-identity",+ program: { identity: entry.program.identity, client: {} },+ waitReady(endpoint: "server" | "client", notify: () => void) {++ assert.equal(endpoint, "client")+ notify()++ return () => undefined+ },+ onExit() { return () => undefined }+}const application = {system: {listPrograms() { return [] },@@ -35,7 +48,12 @@ const application = {return entry.program},async *installProgram() {},- findProcess() { return null }+ findProcess() { return null },+ resolveProcess() { return process },+ endpointSnapshot(_process: unknown, endpoint: string) {++ return { process: process.identity, endpoint, running: true }+ }},linkManager: {authManager: {@@ -55,6 +73,20 @@ try {assert.deepEqual(system, [{ success: true, result: { data: [], total: 0, truncated: false } }])+ const ready = await exchange(path, {+ target: "system",+ request: {+ capability: "endpoint",+ operation: "waitReady",+ input: { process: process.identity, endpoint: "client" }+ }+ })++ assert.deepEqual(ready, [{+ success: true,+ result: { process: process.identity, endpoint: "client", running: true }+ }])+const created = await exchange(path, {target: "program",request: { word: "force-create", program: { identity: "example", storage: "/tmp/example", client: { location: "/tmp/client" } } }diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.tsindex 01ad888..2aed9a9 100644--- a/scripts/contracts/process-lifecycle.ts+++ b/scripts/contracts/process-lifecycle.ts@@ -181,7 +181,7 @@ type HostWait = {let exitListeners = 0let becomeReady: () => void = () => undefined- target.waitReady = notify => {+ target.waitReady = (_endpoint, notify) => {let active = true@@ -218,7 +218,7 @@ type HostWait = {requester,original.boundary,"ready",- ["wait-ready", { identity: target.identity, reference: target.reference }, false]+ ["wait-ready", { identity: target.identity, reference: target.reference }, "server", false])requester.server = replacement.boundary@@ -233,7 +233,7 @@ type HostWait = {requester,original.boundary,"cancelled",- ["wait-ready", { identity: target.identity, reference: target.reference }, false]+ ["wait-ready", { identity: target.identity, reference: target.reference }, "server", false])assert.equal(readyListeners, 1)diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex bd59ed1..839432f 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -460,7 +460,7 @@ export default class ClientProcessBoundary extends TheLink {if (args[0] === "wait-ready") {- this.waitReady(question, args[1], args[2] === true)+ this.waitReady(question, args[1], args[2], args[3] === true)return}@@ -572,7 +572,7 @@ export default class ClientProcessBoundary extends TheLink {})}- private waitReady(question: string, target: unknown, requireCurrentIncarnation: boolean) {+ private waitReady(question: string, target: unknown, endpoint: unknown, requireCurrentIncarnation: boolean) {const mine = this.authManager.processManager.processes.get(this.pane)@@ -589,23 +589,30 @@ export default class ClientProcessBoundary extends TheLink {return}+ if (endpoint !== "server" && endpoint !== "client") {++ this.deliver("host-end", "answer", question, failed(new Error("Readiness needs an Endpoint"))).catch(() => undefined)++ return+ }+const program = this.authManager.programManager.programs.get(process.program)- if (!program?.server) {+ if (!program?.[endpoint]) {- this.deliver("host-end", "answer", question, failed(new Error("This program declared no server half"))).catch(() => undefined)+ this.deliver("host-end", "answer", question, failed(new Error(`This program declared no ${endpoint} Endpoint`))).catch(() => undefined)return}- if (requireCurrentIncarnation && !process.server) {+ if (requireCurrentIncarnation && !process[endpoint]) {- this.deliver("host-end", "answer", question, failed(new Error("This process has no live server endpoint"))).catch(() => undefined)+ this.deliver("host-end", "answer", question, failed(new Error(`This process has no live ${endpoint} Endpoint`))).catch(() => undefined)return}- if (process.server?.ready) {+ if (endpoint === "server" ? process.server?.ready : process.client) {this.deliver("host-end", "answer", question, succeeded([])).catch(() => undefined)@@ -613,8 +620,9 @@ export default class ClientProcessBoundary extends TheLink {}let active = true+ const incarnation = requireCurrentIncarnation ? process[endpoint] : null- const stopReady = this.authManager.processManager.$inbound.subscribe("/server-ready", (identity: unknown) => {+ const stopReady = this.authManager.processManager.$inbound.subscribe(endpoint === "server" ? "/server-ready" : "/client-start", (identity: unknown) => {if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process || !this.expected.has(question)) return@@ -633,20 +641,22 @@ export default class ClientProcessBoundary extends TheLink {this.requests.delete(question)- this.deliver("host-end", "answer", question, failed(new Error("The process ended before its server became ready"))).catch(() => undefined)+ this.deliver("host-end", "answer", question, failed(new Error(`The process ended before its ${endpoint} Endpoint became ready`))).catch(() => undefined)})- const stopServer = requireCurrentIncarnation- ? this.authManager.processManager.$inbound.subscribe("/server-stop", (identity: unknown) => {+ const endpointStopped = (identity: unknown) => {++ if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process) return- if (!active || identity !== process.identity || this.authManager.processManager.processes.get(process.identity) !== process) return+ stop()- stop()+ this.requests.delete(question)- this.requests.delete(question)+ this.deliver("host-end", "answer", question, failed(new Error(`The ${endpoint} Endpoint stopped before becoming ready`))).catch(() => undefined)+ }- this.deliver("host-end", "answer", question, failed(new Error("The server endpoint stopped before becoming ready"))).catch(() => undefined)- })+ const stopEndpoint = requireCurrentIncarnation+ ? this.authManager.processManager.$inbound.subscribe(`/${endpoint}-stop`, endpointStopped): () => undefinedconst stop = () => {@@ -659,10 +669,12 @@ export default class ClientProcessBoundary extends TheLink {stopExit()- stopServer()+ stopEndpoint()}this.requests.set(question, stop)++ if (incarnation && process[endpoint] !== incarnation) endpointStopped(process.identity)}private accepts(kind: TrafficKind, route: string, event: string, payload: unknown[]) {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.tsindex df735d0..6a873f8 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@@ -20,8 +20,6 @@ export default class EndpointServices extends TheLink {const resolved = this.key(key)- if (resolved.endpoint !== "server") throw new Error("Only a Server service becomes ready")-const milliseconds = serviceTimeout(timeout)await new Promise<void>((resolve, reject) => {@@ -47,11 +45,9 @@ export default class EndpointServices extends TheLink {const target = this.resolve(resolved)- if (!target?.process.server) return-- if (target.process.server.ready) return finish(resolve)+ if (!target) return- stopReady = target.process.waitReady(() => finish(resolve))+ stopReady = target.process.waitReady(resolved.endpoint, () => finish(resolve))}const stopStart = this.$inbound.subscribe(this.event(resolved, "lifecycle", "start"), inspect)diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.tsindex 00f3466..5d4eb04 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@@ -2075,13 +2075,17 @@ export default class ProcessManager extends TheLink {const target = this.system.holdProcess(args[1], process)- const requireCurrentIncarnation = args[2] === true+ const endpoint = args[2]- if (!target.program.server) throw new Error("This program declared no server half")+ if (endpoint !== "server" && endpoint !== "client") throw new Error("Readiness needs an Endpoint")- if (requireCurrentIncarnation && !target.server) throw new Error("This process has no live server endpoint")+ const requireCurrentIncarnation = args[3] === true- if (target.server?.ready) {+ if (!target.program[endpoint]) throw new Error(`This program declared no ${endpoint} Endpoint`)++ if (requireCurrentIncarnation && !target[endpoint]) throw new Error(`This process has no live ${endpoint} Endpoint`)++ if (endpoint === "server" ? target.server?.ready : target.client) {this.say(server, "host-end", "answer", question, succeeded([]))@@ -2090,10 +2094,11 @@ export default class ProcessManager extends TheLink {let active = true- const incarnation = requireCurrentIncarnation ? target.server : null+ const incarnation = requireCurrentIncarnation ? target[endpoint] : nulllet stopReady: () => void = () => undefinedlet stopExit: () => void = () => undefined+ let stopEndpoint: () => void = () => undefinedconst finish = (outcome?: Outcome<unknown[]>) => {@@ -2105,10 +2110,12 @@ export default class ProcessManager extends TheLink {stopExit()+ stopEndpoint()+if (outcome) this.say(server, "host-end", "answer", question, outcome)}- stopReady = target.waitReady(() => finish(succeeded([])))+ stopReady = target.waitReady(endpoint, () => finish(succeeded([])))// waitReady may answer synchronously.if (!active) {@@ -2118,7 +2125,7 @@ export default class ProcessManager extends TheLink {return}- stopExit = target.onExit(() => finish(failed(new Error("The process ended before its server became ready"))))+ stopExit = target.onExit(() => finish(failed(new Error(`The process ended before its ${endpoint} Endpoint became ready`))))// onExit may answer synchronously for an already-ending target.if (!active) {@@ -2128,10 +2135,16 @@ export default class ProcessManager extends TheLink {return}- incarnation?.finished.then(() => {+ if (incarnation) {- finish(failed(new Error("The server endpoint stopped before becoming ready")))- }).catch(() => undefined)+ const stopped = () => finish(failed(new Error(`The ${endpoint} Endpoint stopped before becoming ready`)))++ stopEndpoint = endpoint === "server"+ ? target.onServerStop(stopped)+ : target.onClientStop(stopped)++ if (target[endpoint] !== incarnation) stopped()+ }server.retain(question, () => finish())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.tsindex aa4fb16..9d6da50 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@@ -87,7 +87,12 @@ export default class Process {private readonly clientStops: (() => void)[] = []- private readonly readyWaiters = new Set<() => void>()+ private readonly readyWaiters = {++ server: new Set<() => void>(),++ client: new Set<() => void>()+ }private readonly endings: Ending[] = []@@ -142,25 +147,21 @@ export default class Process {if (this.server !== boundary || !boundary.ready) return- const waiters = [...this.readyWaiters]-- this.readyWaiters.clear()-- for (const waiter of waiters) waiter()+ this.becameReady("server")}- public waitReady(notify: () => void) {+ public waitReady(endpoint: "server" | "client", notify: () => void) {- if (this.server?.ready) {+ if (endpoint === "server" ? this.server?.ready : this.client) {notify()return () => undefined}- this.readyWaiters.add(notify)+ this.readyWaiters[endpoint].add(notify)- return () => { this.readyWaiters.delete(notify) }+ return () => { this.readyWaiters[endpoint].delete(notify) }}public startClient(window: Window, service: boolean) {@@ -169,6 +170,8 @@ export default class Process {this.client = new ClientState(window, service)+ this.becameReady("client")+return true}@@ -188,6 +191,15 @@ export default class Process {return this.server !== null || this.client !== null}+ private becameReady(endpoint: "server" | "client") {++ const waiters = [...this.readyWaiters[endpoint]]++ this.readyWaiters[endpoint].clear()++ for (const waiter of waiters) waiter()+ }+public onServerStart(listener: (server: ServerProcessBoundary) => void) {this.serverStarts.push(listener)@@ -258,7 +270,9 @@ export default class Process {this.ending = { code, signal }- this.readyWaiters.clear()+ this.readyWaiters.server.clear()++ this.readyWaiters.client.clear()const endings = this.endings.splice(0)diff --git a/source/server/view/gateway/system-control.ts b/source/server/view/gateway/system-control.tsindex a4b5e83..56a91ac 100644--- a/source/server/view/gateway/system-control.ts+++ b/source/server/view/gateway/system-control.ts@@ -179,9 +179,11 @@ export default class SystemControl {if (operation === "waitReady") {- await waitReady(process, (input as EndpointWaitReadyInput).timeout, signal)+ const request = input as EndpointWaitReadyInput- return this.system.endpointSnapshot(process, "server")+ await waitReady(process, request.endpoint, request.timeout, signal)++ return this.system.endpointSnapshot(process, request.endpoint)}if (operation === "waitLifecycle") {@@ -393,15 +395,14 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {}-function waitReady(process: Process, timeout = 10_000, signal?: AbortSignal) {+function waitReady(process: Process, endpoint: "server" | "client", timeout = 10_000, signal?: AbortSignal) {return waitFor<void>((resolve, reject) => {- const stopReady = process.waitReady(resolve)- const stopExit = process.onExit(() => reject(new Error(`Process "${process.identity}" exited before its Server became ready`)))- const stopServer = process.onServerStop(() => reject(new Error(`The Server Endpoint stopped before Process "${process.identity}" became ready`)))+ const stopReady = process.waitReady(endpoint, resolve)+ const stopExit = process.onExit(() => reject(new Error(`Process "${process.identity}" exited before its ${endpoint} Endpoint became ready`)))- return () => { stopReady(); stopExit(); stopServer() }+ return () => { stopReady(); stopExit() }}, timeout, signal)}