Skip to content

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

Expose complete owner-local Gateway API

zohayrslileh794c40cd65e1
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 55bd12a..bd13121 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
@@ -181,13 +181,13 @@ export default class ProcessManager extends TheLink {
}
/** Observe destinationless events from one exact live Endpoint. */
- public observeEndpoint(identity: string, half: Half, event: string, subscriber: (payload: unknown) => void, impossible?: (reason: string) => void) {
+ public observeEndpoint(identity: string, half: Half, event: string | null, subscriber: (payload: unknown, event: string) => void, impossible?: (reason: string) => void) {
const process = this.find(identity)
if (half === "server" ? !process.server : !process.client) throw new Error(`This process has no live ${half} endpoint`)
- return this.endpointEvents.follow(process.reference, half, event, (_word, payload) => subscriber(payload), impossible)
+ return this.endpointEvents.follow(process.reference, half, event, (word, payload) => subscriber(payload, word), impossible)
}
/** Publish from a trusted execution boundary whose identity is not a Program Endpoint. */
@@ -219,6 +219,47 @@ 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) {
+
+ return this.services.service(this.find(identity), endpoint)
+ }
+
+ public serviceEnabledFromOutside(key: unknown) {
+
+ return this.services.enabled(key)
+ }
+
+ public waitServiceReadyFromOutside(key: unknown, timeout?: number) {
+
+ return this.services.waitReady(key, timeout)
+ }
+
+ /** 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)
+
+ if (!binding) throw new Error("The service is disabled")
+
+ await this.deliver(binding.process.identity, binding.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")
+
+ if (!binding) return Promise.reject(new Error("The service is disabled"))
+
+ return this.askFromOutside(binding.process.identity, event, payload, timeout, signal)
+ }
+
+ public observeServiceFromOutside(key: unknown, scope: "lifecycle" | "channel", event: string | null, subscriber: (event: string, payload: unknown) => unknown) {
+
+ return this.services.follow(key, scope, event, subscriber)
+ }
+
// The boundary owns its server runtime transport. A stopped child remains
// fire-and-forget: there is no receiver to promise once it has gone.
private say(server: ServerProcessBoundary | null | undefined, event: string, ...values: unknown[]) {
diff --git a/source/server/core/system-control/system-control.ts b/source/server/core/system-control/system-control.ts
index 74f83cd..282c936 100644
--- a/source/server/core/system-control/system-control.ts
+++ b/source/server/core/system-control/system-control.ts
@@ -4,6 +4,7 @@ import {
type EndpointAskInput,
type EndpointInput,
type EndpointPublishInput,
+ type EndpointStartInput,
type EndpointWaitInput,
type EndpointWaitReadyInput,
type ProcessCreateInput,
@@ -81,12 +82,12 @@ export default class SystemControl {
))
const selected = found
.sort((left, right) => left.identity.localeCompare(right.identity))
- .slice(0, request.limit ?? 30)
+ .slice(request.offset ?? 0, (request.offset ?? 0) + (request.limit ?? 30))
return Object.freeze({
data: Object.freeze(selected.map(programSnapshot)),
total: found.length,
- truncated: found.length > selected.length
+ truncated: (request.offset ?? 0) + selected.length < found.length
})
}
@@ -117,12 +118,12 @@ export default class SystemControl {
))
const selected = found
.sort((left, right) => right.startedAt.getTime() - left.startedAt.getTime())
- .slice(0, request.limit ?? 30)
+ .slice(request.offset ?? 0, (request.offset ?? 0) + (request.limit ?? 30))
return Object.freeze({
data: Object.freeze(selected.map(processSnapshot)),
total: found.length,
- truncated: found.length > selected.length
+ truncated: (request.offset ?? 0) + selected.length < found.length
})
}
@@ -155,7 +156,7 @@ export default class SystemControl {
return snapshot
}
- private async endpoint(operation: string, input: EndpointInput | EndpointWaitReadyInput | EndpointAskInput | EndpointPublishInput | EndpointWaitInput, signal?: AbortSignal) {
+ private async endpoint(operation: string, input: EndpointInput | EndpointStartInput | EndpointWaitReadyInput | EndpointAskInput | EndpointPublishInput | EndpointWaitInput, signal?: AbortSignal) {
const process = resolveProcess(this.processes.processes, this.programs.programs, input)
const declaration = process.program[input.endpoint]
@@ -168,7 +169,7 @@ export default class SystemControl {
if (operation === "start") {
if (input.endpoint === "server") await this.processes.startServer(process.identity)
- else await this.processes.startClient(process.identity)
+ else await this.processes.startClient(process.identity, (input as EndpointStartInput).client)
} else {
if (input.endpoint === "server") await this.processes.stopServer(process.identity)
else await this.processes.stopClient(process.identity)
@@ -317,12 +318,17 @@ export default class SystemControl {
payload: request.event === "exit"
? Object.freeze({
process: record?.identity ?? process?.identity ?? null,
+ ...(record ? { processSnapshot: processRecordSnapshot(record) } : {}),
status: values.at(-1) ? "signaled" : "exited",
code: values.at(-2) ?? null,
signal: values.at(-1) ?? null
})
: request.event === "endpointStart" || request.event === "endpointStop"
- ? Object.freeze({ process: record?.identity ?? process?.identity ?? null, endpoint: values.at(-1) })
+ ? Object.freeze({
+ process: record?.identity ?? process?.identity ?? null,
+ ...(record ? { processSnapshot: processRecordSnapshot(record) } : {}),
+ endpoint: values.at(-1)
+ })
: record ? processRecordSnapshot(record) : values
})
}
@@ -389,10 +395,21 @@ function programSnapshot(entry: Entry) {
function processSnapshot(process: Process) {
+ const owner = process.program.record()
+
return Object.freeze({
identity: process.identity,
name: process.name,
program: process.program.identity,
+ programSnapshot: Object.freeze({
+ identity: owner.identity,
+ name: owner.name,
+ version: owner.version,
+ description: owner.description,
+ hasAgent: owner.hasAgent,
+ server: owner.server,
+ client: owner.client
+ }),
startedAt: process.startedAt.toISOString(),
server: Object.freeze({ declared: process.program.server !== null, running: process.server !== null }),
client: Object.freeze({ declared: process.program.client !== null, running: process.client !== null })
@@ -404,7 +421,15 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
const record = process as unknown as {
identity: string
name: string | null
- program: { identity: string, server: unknown, client: unknown }
+ program: {
+ identity: string
+ name: string
+ version: string | null
+ description: string | null
+ hasAgent: boolean
+ server: unknown
+ client: unknown
+ }
startedAt: Date | string
server: unknown
client: unknown
@@ -414,6 +439,15 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
identity: record.identity,
name: record.name,
program: record.program.identity,
+ programSnapshot: Object.freeze({
+ identity: record.program.identity,
+ name: record.program.name,
+ version: record.program.version,
+ description: record.program.description,
+ hasAgent: record.program.hasAgent,
+ server: record.program.server,
+ 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 })
diff --git a/source/server/view/gateway/api-request.ts b/source/server/view/gateway/api-request.ts
new file mode 100644
index 0000000..ddfb425
--- /dev/null
+++ b/source/server/view/gateway/api-request.ts
@@ -0,0 +1,169 @@
+import type Application from "@server/core/application"
+import { uploadLimit } from "@server/core/upload-manager"
+
+/** Execute one operation belonging to the shared System SDK contract. */
+export default async function apiRequest(application: Application, value: unknown, signal: AbortSignal) {
+
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The System API request must be an object")
+
+ const request = value as Record<string, unknown>
+
+ if (request.capability === "appearance") {
+
+ if (request.operation === "snapshot") return application.appearanceManager.value
+ if (request.operation === "update") return await application.linkManager.updateAppearance(request.value)
+ if (request.operation === "wait") return await waitForAppearance(application, signal)
+
+ throw new Error(`The Appearance API does not know "${String(request.operation)}"`)
+ }
+
+ if (request.capability === "uploads") {
+
+ if (request.operation === "access") return { path: application.uploads.fileManager.path, limit: uploadLimit }
+ if (request.operation === "stat") return application.uploads.stat(String(request.file))
+
+ throw new Error(`The Uploads API does not know "${String(request.operation)}"`)
+ }
+
+ if (request.capability === "endpoint" && request.operation === "service") {
+
+ if (typeof request.process !== "string" || request.endpoint !== "server" && request.endpoint !== "client") {
+
+ throw new Error("Reading an Endpoint Service needs a Process and Endpoint")
+ }
+
+ return processes(application).serviceFromOutside(request.process, request.endpoint)
+ }
+
+ if (request.capability === "endpoint" && request.operation === "wait") {
+
+ if (typeof request.process !== "string" || request.endpoint !== "server" && request.endpoint !== "client") {
+
+ throw new Error("Waiting for an Endpoint needs a Process and Endpoint")
+ }
+ if (request.event !== null && typeof request.event !== "string") throw new Error("An Endpoint event must be text or null")
+
+ return await waitForEndpoint(processes(application), request.process, request.endpoint, request.event, timed(signal, request.timeout))
+ }
+
+ if (request.capability === "service") {
+
+ const manager = processes(application)
+ const key = request.key
+
+ if (request.operation === "enabled") return manager.serviceEnabledFromOutside(key)
+ if (request.operation === "waitReady") return await manager.waitServiceReadyFromOutside(key, number(request.timeout))
+
+ if (request.operation === "publish" || request.operation === "ask") {
+ if (typeof request.event !== "string") throw new Error("A Service event must be text")
+ if (request.operation === "publish") return await manager.publishServiceFromOutside(key, request.event, request.payload)
+ return await manager.askServiceFromOutside(key, request.event, request.payload, number(request.timeout) ?? 10_000, signal)
+ }
+ if (request.operation === "wait") {
+ if (request.event !== null && typeof request.event !== "string") throw new Error("A Service event must be text or null")
+ return await waitForService(manager, key, String(request.scope), request.event, timed(signal, request.timeout))
+ }
+
+ throw new Error(`The Service API does not know "${String(request.operation)}"`)
+ }
+
+ throw new Error(`Unknown System API capability "${String(request.capability)}"`)
+}
+
+function processes(application: Application) {
+
+ return application.linkManager.authManager.processManager
+}
+
+function number(value: unknown) {
+
+ if (value === undefined) return undefined
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("A timeout must be a non-negative finite number")
+ return value
+}
+
+function waitForService(manager: ReturnType<typeof processes>, key: unknown, scope: string, event: string | null, signal: AbortSignal) {
+
+ if (scope !== "lifecycle" && scope !== "channel") throw new Error("A Service wait scope must be lifecycle or channel")
+
+ return new Promise((resolve, reject) => {
+
+ const stop = manager.observeServiceFromOutside(key, scope, event, (received, payload) => {
+
+ cleanup()
+ resolve(event === null ? { event: received, payload } : payload)
+ })
+ const abort = () => {
+
+ cleanup()
+ reject(signal.reason instanceof Error ? signal.reason : new Error("The Service wait was cancelled"))
+ }
+ const cleanup = () => {
+
+ stop()
+ signal.removeEventListener("abort", abort)
+ }
+
+ if (signal.aborted) abort()
+ else signal.addEventListener("abort", abort, { once: true })
+ })
+}
+
+function timed(signal: AbortSignal, value: unknown) {
+
+ return AbortSignal.any([signal, AbortSignal.timeout(number(value) ?? 10_000)])
+}
+
+function waitForEndpoint(manager: ReturnType<typeof processes>, process: string, endpoint: "server" | "client", event: string | null, signal: AbortSignal) {
+
+ return new Promise((resolve, reject) => {
+
+ const stop = manager.observeEndpoint(process, endpoint, event, (payload, received) => {
+
+ cleanup()
+ resolve({ event: received, payload })
+ }, reason => {
+
+ cleanup()
+ reject(new Error(reason))
+ })
+ const abort = () => {
+
+ cleanup()
+ reject(signal.reason instanceof Error ? signal.reason : new Error("The Endpoint wait was cancelled"))
+ }
+ const cleanup = () => {
+
+ stop()
+ signal.removeEventListener("abort", abort)
+ }
+
+ if (signal.aborted) abort()
+ else signal.addEventListener("abort", abort, { once: true })
+ })
+}
+
+function waitForAppearance(application: Application, signal: AbortSignal) {
+
+ return new Promise((resolve, reject) => {
+
+ const stop = application.linkManager.appearance.tunnel.subscribe("change", (value: unknown) => {
+
+ cleanup()
+ resolve(value)
+ })
+ const abort = () => {
+
+ cleanup()
+ reject(signal.reason instanceof Error ? signal.reason : new Error("The Appearance wait was cancelled"))
+ }
+ const cleanup = () => {
+
+ stop()
+ signal.removeEventListener("abort", abort)
+ }
+
+ if (signal.aborted) abort()
+ else signal.addEventListener("abort", abort, { once: true })
+ })
+}
diff --git a/source/server/view/gateway/gateway.ts b/source/server/view/gateway/gateway.ts
index 943a0c5..1af4140 100644
--- a/source/server/view/gateway/gateway.ts
+++ b/source/server/view/gateway/gateway.ts
@@ -1,5 +1,6 @@
import type Application from "@server/core/application"
import localServer from "./local-server"
+import apiRequest from "./api-request"
import programRequest from "./program-request"
import systemRequest from "./system-request"
@@ -43,6 +44,15 @@ export default function gateway(application: Application, path: string) {
return
}
+ if (envelope.target === "api") {
+
+ apiRequest(application, envelope.request, controller.signal).then(
+ result => finish(socket, { success: true, result }),
+ error => finish(socket, { success: false, error: reason(error) })
+ )
+ return
+ }
+
systemRequest(application, envelope.request, controller.signal).then(
result => finish(socket, { success: true, result }),
error => finish(socket, { success: false, error: reason(error) })
@@ -67,7 +77,7 @@ function parseEnvelope(line: string): GatewayEnvelope {
if (Object.keys(envelope).some(key => key !== "target" && key !== "request")) throw new Error("The gateway request contains an unknown field")
- if (envelope.target !== "program" && envelope.target !== "system") throw new Error("The gateway target must be program or system")
+ if (envelope.target !== "api" && envelope.target !== "program" && envelope.target !== "system") throw new Error("The Gateway target must be api, program, or system")
if (!("request" in envelope)) throw new Error("The gateway request is missing")
return { target: envelope.target, request: envelope.request }
@@ -90,6 +100,6 @@ function reason(error: unknown) {
interface GatewayEnvelope {
- target: "program" | "system"
+ target: "api" | "program" | "system"
request: unknown
}
diff --git a/source/server/view/gateway/program-request.ts b/source/server/view/gateway/program-request.ts
index 8c30eea..4f6b121 100644
--- a/source/server/view/gateway/program-request.ts
+++ b/source/server/view/gateway/program-request.ts
@@ -26,6 +26,64 @@ export default async function programRequest(application: Application, socket: S
const programManager = application.linkManager.authManager.programManager
+ if (asked.word === "create") {
+
+ if (!asked.program) throw new Error("Creating needs a Program description")
+
+ const program = await programManager.create(asked.program)
+
+ say({ event: "created", identity: program.identity })
+ return done()
+ }
+
+ if (asked.word === "installed") {
+
+ if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Reading installation needs a Program identity")
+
+ const entry = programManager.programs.get(asked.identity)
+
+ say({ event: "installedState", installed: entry?.installed === true })
+ return done()
+ }
+
+ if (asked.word === "forget") {
+
+ if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Forgetting needs a Program identity")
+
+ await programManager.forgetNamed(asked.identity)
+
+ say({ event: "forgotten", identity: asked.identity })
+ return done()
+ }
+
+ if (asked.word === "install-existing") {
+
+ if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Installing needs a Program identity")
+
+ const entry = programManager.programs.get(asked.identity)
+
+ if (!entry) throw new Error(`Unknown Program "${asked.identity}"`)
+
+ for await (const chunk of programManager.installStreaming(entry.program)) say({ event: "output", ...chunk })
+
+ say({ event: "installed", identity: asked.identity })
+ return done()
+ }
+
+ if (asked.word === "uninstall-existing") {
+
+ if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")
+
+ const entry = programManager.programs.get(asked.identity)
+
+ if (!entry) throw new Error(`Unknown Program "${asked.identity}"`)
+
+ for await (const chunk of programManager.uninstallStreaming(entry.program, asked.everything === true)) say({ event: "output", ...chunk })
+
+ say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })
+ return done()
+ }
+
if (asked.word === "uninstall") {
if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")