Skip to content

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

Compose Program lifecycle primitives

zohayrslileh0fa2db0a205c
diff --git a/scripts/contracts/gateway.ts b/scripts/contracts/gateway.ts
index 1a9ce56..7c0a5b9 100644
--- a/scripts/contracts/gateway.ts
+++ b/scripts/contracts/gateway.ts
@@ -19,16 +19,28 @@ const application = {
async exit() {}
},
programManager: {
- async *installSource(program: { identity: string, name: string, version: string }) {
- yield {
- stage: "installed",
- replaced: false,
- entry: {
- identity: program.identity,
- program: { name: program.name, config: { version: program.version } }
+ async forceCreate() { return { identity: "example" } },
+ find() {
+ return {
+ record() {
+ return {
+ reference: "example-reference",
+ identity: "example",
+ name: "Example",
+ version: "1.0.0",
+ description: null,
+ hasAgent: false,
+ server: null,
+ client: { start: true }
+ }
}
}
- }
+ },
+ held(handle: { identity?: string, reference?: string }) {
+ assert.deepEqual(handle, { identity: "example", reference: "example-reference" })
+ return { identity: "example" }
+ },
+ async *installStreaming() {}
}
}
}
@@ -41,15 +53,33 @@ try {
assert.deepEqual(system, [{ success: true, result: { received: { capability: "program", operation: "list", input: {} } } }])
- const program = await exchange(path, {
+ const created = await exchange(path, {
target: "program",
- request: { word: "install", program: { identity: "example", name: "Example", version: "1.0.0" } }
+ request: { word: "force-create", program: { identity: "example", storage: "/tmp/example", client: { location: "/tmp/client" } } }
})
- assert.deepEqual(program, [{
+ assert.deepEqual(created, [{
+ event: "created",
+ program: {
+ reference: "example-reference",
+ identity: "example",
+ name: "Example",
+ version: "1.0.0",
+ description: null,
+ hasAgent: false,
+ server: null,
+ client: { start: true }
+ }
+ }])
+
+ const installed = await exchange(path, {
+ target: "program",
+ request: { word: "install-existing", handle: { identity: "example", reference: "example-reference" } }
+ })
+
+ assert.deepEqual(installed, [{
event: "installed",
- replaced: false,
- program: { identity: "example", name: "Example", version: "1.0.0" }
+ identity: "example"
}])
} finally {
await server.close()
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 bd13121..a9a266a 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
@@ -1477,6 +1477,17 @@ export default class ProcessManager extends TheLink {
return [programManager.find(created.identity)]
}
+ if (word === "host-program-force-create") {
+
+ const source = rest[0]
+
+ if (typeof source !== "string" && (typeof source !== "object" || source === null)) throw new Error("A program is created from a config or a path")
+
+ const created = await programManager.forceCreate(source as Parameters<typeof programManager.forceCreate>[0], process.identity)
+
+ return [programManager.find(created.identity)]
+ }
+
if (word === "appearance") return [this.authManager.linkManager.appearance.value]
if (word === "update-appearance") {
@@ -2070,8 +2081,10 @@ export default class ProcessManager extends TheLink {
private async endHostStream(process: Process, question: string, args: unknown[]) {
let active = true
+ let cancel = () => { active = false }
+ const programManager = this.authManager.programManager
- process.server?.retain(question, () => { active = false })
+ process.server?.retain(question, () => cancel())
await this.say(process.server, "host-end", "stream", question, "open")
@@ -2079,6 +2092,59 @@ export default class ProcessManager extends TheLink {
const operation = args[0]
const program = this.heldProgram(args[1])
+
+ if (operation === "run") {
+
+ let running: Process | null = null
+ let settled = false
+ let finish!: () => void
+ const completion = new Promise<void>(resolve => { finish = resolve })
+ let sending = Promise.resolve()
+ const emit = (value: unknown) => {
+
+ if (!active) return
+
+ sending = sending.then(() => this.say(process.server, "host-end", "stream", question, "data", value))
+ }
+
+ cancel = () => {
+
+ active = false
+
+ if (running) this.exit(running.identity).catch(() => undefined)
+ }
+
+ const identity = await programManager.runProcess(program, args[2] as Launch ?? {}, {
+ started: created => {
+
+ running = created
+ emit({ event: "started", process: processReference(created) })
+ },
+ output: (stream, text) => emit({ event: "output", stream: stream === "err" ? "stderr" : "stdout", text }),
+ exited: (code, signal) => {
+
+ if (settled) return
+
+ settled = true
+ emit({
+ event: "exited",
+ process: running && processReference(running),
+ exit: { status: signal ? "signaled" : "exited", code, signal }
+ })
+ finish()
+ }
+ }, process)
+
+ if (!active) await this.exit(identity)
+
+ await completion
+ await sending
+
+ if (active) await this.say(process.server, "host-end", "stream", question, "answer", succeeded(undefined))
+
+ return
+ }
+
const stream = operation === "install"
? this.authManager.programManager.installStreaming(program, process.identity)
: operation === "uninstall"
diff --git a/source/server/core/link-manager/auth-manager/program-manager/entry.ts b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
index 1c00823..534d092 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/entry.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/entry.ts
@@ -11,11 +11,16 @@ export default class Entry {
public installed: boolean
- public constructor(program: Program, installed = true) {
+ /** Restore the durable installed Program when this runtime overlay ends. */
+ public restoreInstalled: boolean
+
+ public constructor(program: Program, installed = true, restoreInstalled = false) {
this.program = program
this.installed = installed
+
+ this.restoreInstalled = restoreInstalled
}
public get identity() {
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 04b0ef1..bd7d5c0 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
@@ -181,6 +181,19 @@ export default class ProgramManager extends TheLink {
return this.programs.get(identity)?.program ?? null
}
+ /** Resolve an exact runtime Program handle without retargeting a replacement. */
+ public held(value: unknown) {
+
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("A Program handle is required")
+
+ const address = value as { identity?: unknown, reference?: unknown }
+ const program = typeof address.identity === "string" ? this.reach(address.identity) : null
+
+ if (!program || program.reference !== address.reference) throw new Error("The Program represented by this handle does not exist")
+
+ return program
+ }
+
// Resolve the browser-only hosting address. This is intentionally a
// separate lookup from public identity: stable program identities
// must never become stable asset routes.
@@ -203,17 +216,63 @@ export default class ProgramManager extends TheLink {
// absolute itself.
public async create(source: ProgramConfig | string) {
+ const entry = await this.register(this.runtimeProgram(source), false)
+
+ await this.created(entry)
+
+ return entry.program
+ }
+
+ /** Atomically replace the runtime occupant of one Program identity. */
+ public async forceCreate(source: ProgramConfig | string, asker: string | null = null) {
+
+ const program = this.runtimeProgram(source)
+
+ const restoreInstalled = existsSync(this.fileManager.join(program.identity, "program.json"))
+
+ // Refuse an invalid replacement before disturbing the coherent entity
+ // that currently owns this public identity.
+ await program.validate()
+
+ return await this.change(program.identity, async () => {
+
+ const existing = this.programs.get(program.identity)
+
+ if (existing) {
+
+ await this.authManager.processManager.exitAll(existing.identity, asker)
+
+ await this.forgetEntry(existing, false)
+ }
+
+ const entry = this.remember(program, false, true, restoreInstalled)
+
+ try {
+
+ await this.created(entry)
+
+ return entry.program
+ }
+
+ catch (exception) {
+
+ if (this.programs.get(entry.identity) === entry) await this.forgetEntry(entry)
+
+ throw exception
+ }
+ })
+ }
+
+ /** Resolve one external runtime source without consulting System cwd. */
+ private runtimeProgram(source: ProgramConfig | string) {
+
if (typeof source === "string") {
if (!isAbsolute(source)) throw new Error("A program is created from an absolute path — the system's working directory is not the caller's")
const path = statSync(source, { throwIfNoEntry: false })?.isDirectory() ? join(source, "program.json") : source
- const entry = await this.register(new Program(path), false)
-
- await this.created(entry)
-
- return entry.program
+ return new Program(path)
}
// Storage is where what it keeps outlives its processes, and
@@ -233,11 +292,7 @@ export default class ProgramManager extends TheLink {
if (client !== undefined && !/^https?:\/\//i.test(client) && !isAbsolute(client)) throw new Error("A created program's client must be an absolute filesystem path or an HTTP(S) URL")
- const entry = await this.register(new Program(source), false)
-
- await this.created(entry)
-
- return entry.program
+ return new Program(source)
}
public async fork(program: Program, identity: string) {
@@ -253,6 +308,12 @@ export default class ProgramManager extends TheLink {
await program.validate()
+ return this.remember(program, installed, transitionOwnsIdentity)
+ }
+
+ /** Commit one already validated Program to the authoritative registry. */
+ private remember(program: Program, installed: boolean, transitionOwnsIdentity = false, restoreInstalled = false) {
+
// The runtime map is the live registry, while an installed
// declaration is the durable reservation reconstructed on boot.
// Forgetting an installed Program removes the former but cannot
@@ -261,7 +322,7 @@ export default class ProgramManager extends TheLink {
// that deliberately owns this identity across both representations.
if (this.programs.has(program.identity) || (!transitionOwnsIdentity && (this.changing.has(program.identity) || existsSync(this.fileManager.join(program.identity, "program.json"))))) throw new Error("The system already knows this program identity")
- const entry = new Entry(program, installed)
+ const entry = new Entry(program, installed, restoreInstalled)
this.programs.set(entry.identity, entry)
@@ -587,38 +648,6 @@ export default class ProgramManager extends TheLink {
return program.identity
}
- // A local project addresses the durable installation, not a handle it
- // already holds. Attached use may have replaced or forgotten the runtime
- // entry while the installed declaration still exists, so this resolves
- // from the installed area first and reconstructs the runtime counterpart
- // only when the operation needs one.
- public async uninstallInstalled(identity: string, everything = false, asker: string | null = null, output: CommandOutput = () => undefined) {
-
- return await this.change(identity, async () => {
-
- const declaration = this.fileManager.join(identity, "program.json")
-
- if (!existsSync(declaration)) throw new Error("This program is not installed — there is nothing here to remove")
-
- let entry = this.programs.get(identity)
-
- if (!entry) {
-
- entry = await this.register(new Program(declaration), true, true)
-
- await this.created(entry)
- }
-
- return await this.uninstallEntry(entry, everything, asker, output)
- })
- }
-
- /** Uninstall an installed Program while exposing cleanup command output. */
- public uninstallInstalledStreaming(identity: string, everything = false, asker: string | null = null) {
-
- return this.commandStreaming(output => this.uninstallInstalled(identity, everything, asker, output))
- }
-
@Connect("/forget-program")
public async forgetNamed(identity: string, asker: string | null = null) {
@@ -629,67 +658,6 @@ export default class ProgramManager extends TheLink {
return await this.forget(program, asker)
}
- /**
- * Install one external Program description and coordinate every requested
- * follow-up as one Core operation. Each yielded stage lets a View represent
- * progress without taking ownership of the workflow.
- */
- public async *installSource(source: ProgramConfig, options: InstallSourceOptions = {}): AsyncGenerator<InstallSourceStage> {
-
- const program = new Program(source)
-
- await program.validate()
-
- // A runtime Program may have been forgotten while its installed
- // declaration remains. Replacement is therefore a fact about the
- // durable files, not the current registry entry's installed flag.
- const replaced = existsSync(this.fileManager.join(program.identity, "program.json"))
-
- const installation = this.installStreaming(program)
-
- let entry: Entry
-
- while (true) {
-
- const next = await installation.next()
-
- if (next.done) {
-
- entry = next.value
-
- break
- }
-
- yield { stage: "output", chunk: next.value }
- }
-
- yield { stage: "installed", entry, replaced }
-
- const launch = {}
-
- if (options.startup) {
-
- await this.startup(entry.program, "enable", launch)
-
- yield { stage: "startup-enabled" }
- }
-
- if (options.run) {
-
- const process = await this.runInstalled(entry.program, launch)
-
- yield { stage: "running", process }
- }
- }
-
- /** Run a durable Program independently of a local gateway connection. */
- public async runInstalled(program: Program, launch: Launch = {}) {
-
- if (!this.installed(program)) throw new Error("Only an installed program can run independently")
-
- return await this.start(program, launch)
- }
-
/** Install while exposing command output with consumer-driven backpressure. */
public installStreaming(source: Program, asker: string | null = null) {
@@ -844,6 +812,8 @@ export default class ProgramManager extends TheLink {
entry.program.replace(installed)
entry.installed = true
+
+ entry.restoreInstalled = false
}
else {
@@ -958,7 +928,7 @@ export default class ProgramManager extends TheLink {
})
}
- private async forgetEntry(entry: Entry) {
+ private async forgetEntry(entry: Entry, restore = true) {
if (this.programs.get(entry.identity) !== entry) throw new Error("The system no longer knows this program")
@@ -972,6 +942,18 @@ export default class ProgramManager extends TheLink {
await this.$outbound.publish("/forget", entry.identity)
+ if (restore && entry.restoreInstalled) {
+
+ const declaration = this.fileManager.join(entry.identity, "program.json")
+
+ if (existsSync(declaration)) {
+
+ const installed = await this.register(new Program(declaration), true, true)
+
+ await this.created(installed)
+ }
+ }
+
return entry.identity
}
@@ -1012,8 +994,21 @@ export default class ProgramManager extends TheLink {
})
}
+ /** Create one Process whose output and ending are observed before startup. */
+ public async runProcess(program: Program, launch: Launch = {}, watching?: Watching, parent: Process | null = null) {
+
+ return await this.serializeCreation(program.identity, async () => {
+
+ if (this.reach(program.identity) !== program) throw new Error("The Program represented by this handle does not exist")
+
+ return await this.start(program, launch, watching, parent)
+ })
+ }
+
@Connect("/find-or-create-process")
- public async findOrCreateProcess(identity: string, launch: Launch & { name: string }, parent: Process | string | null = null) {
+ public async findOrCreateProcess(subject: string | Program, launch: Launch & { name: string }, parent: Process | string | null = null) {
+
+ const identity = typeof subject === "string" ? subject : subject.identity
return await this.serializeCreation(identity, async () => {
@@ -1021,6 +1016,8 @@ export default class ProgramManager extends TheLink {
if (!program) throw new Error("The system does not know this program")
+ if (typeof subject !== "string" && program !== subject) throw new Error("The Program represented by this handle does not exist")
+
const resolved = this.resolveLaunch(program, launch)
if (typeof launch.name !== "string" || !launch.name) throw new Error("findOrCreate requires a non-empty process name")
@@ -1042,92 +1039,6 @@ export default class ProgramManager extends TheLink {
})
}
- // An attached launch is the local project's authoritative runtime use of
- // its declared identity. Replacement is one transition: every old process
- // exits, the old Program is forgotten with its ordinary announcements,
- // and only then does the new uninstalled Program become reachable. The
- // installed files, if any, are deliberately untouched and may be installed
- // over later or reconstructed on the next system start.
- public async launchAttached(source: ProgramConfig, options: Options, watching: Watching) {
-
- // Unlike an installed Program, an attached one has no canonical
- // system-owned directory from which an omitted storage path can be
- // derived. The authoring tool supplies the project storage explicitly.
- if (typeof source.storage !== "string") throw new Error("An attached program names its storage")
-
- if (!isAbsolute(source.storage)) throw new Error("An attached program's storage must be an absolute filesystem path")
-
- const program = new Program(source)
-
- // Refuse a bad incoming declaration before taking a coherent existing
- // Program down. `start` asks again immediately before spawning because
- // files can move between these two moments.
- await program.validate()
-
- return await this.change(program.identity, async () => {
-
- const existing = this.programs.get(program.identity)
-
- if (existing) {
-
- await this.authManager.processManager.exitAll(existing.identity)
-
- await this.forgetEntry(existing)
- }
-
- // This transition owns the identity. In particular, an installed
- // declaration may still reserve it on disk after its runtime
- // Program was forgotten; attached use is explicitly allowed to
- // stand there without deleting or changing that installation.
- const entry = await this.register(program, false, true)
-
- try {
-
- await this.created(entry)
-
- return await this.start(program, { options }, {
-
- output: watching.output,
-
- exited: (code, signal) => {
-
- // The launcher hears the ending only after the attached
- // Program has left the registry. Otherwise a command
- // started immediately afterwards can collide with a life
- // whose process has already ended.
- this.finishAttached(program).then(
-
- () => watching.exited(code, signal),
-
- () => watching.exited(code, signal)
- )
- }
- }, null, true)
- }
-
- catch (exception) {
-
- if (this.programs.get(program.identity) === entry) {
-
- await this.authManager.processManager.exitAll(program.identity)
-
- await this.forgetEntry(entry)
- }
-
- throw exception
- }
- })
- }
-
- private async finishAttached(program: Program) {
-
- const changing = this.changing.get(program.identity)
-
- if (changing) await changing
-
- if (this.programs.get(program.identity)?.program === program) await this.forget(program)
- }
-
// One interpretation of a Process launch, used both when it is created now
// and when a future startup launch is persisted. Runtime-only facts such as
// name occupancy and capacity remain in `start`.
@@ -1247,6 +1158,8 @@ export default class ProgramManager extends TheLink {
if (watching) {
+ watching.started?.(record)
+
record.onServerStart(server => server.onOutput(watching.output))
record.onExit(watching.exited)
@@ -1327,23 +1240,6 @@ export default class ProgramManager extends TheLink {
export type TransmittedProgramManager = Transmitted<ProgramManager>
-export interface InstallSourceOptions {
-
- run?: boolean
-
- startup?: boolean
-}
-
-export type InstallSourceStage =
-
- | { stage: "output", chunk: ProgramCommandChunk }
-
- | { stage: "installed", entry: Entry, replaced: boolean }
-
- | { stage: "startup-enabled" }
-
- | { stage: "running", process: string }
-
// Which of a half's own pages a launch asked for.
//
// A launch location is rooted in the client half's declared place,
@@ -1420,6 +1316,8 @@ export type Area = "data" | "cache"
// decided twice.
export interface Watching {
+ started?: (process: Process) => void
+
output: (stream: Stream, text: string) => void
exited: (code: number | null, signal: NodeJS.Signals | null) => void
diff --git a/source/server/core/system-control/system-control.ts b/source/server/core/system-control/system-control.ts
index 282c936..e954ee6 100644
--- a/source/server/core/system-control/system-control.ts
+++ b/source/server/core/system-control/system-control.ts
@@ -375,6 +375,7 @@ function programSnapshot(entry: Entry) {
const program = entry.program
return Object.freeze({
+ reference: program.reference,
identity: program.identity,
name: program.name,
version: program.config.version ?? null,
@@ -402,6 +403,7 @@ function processSnapshot(process: Process) {
name: process.name,
program: process.program.identity,
programSnapshot: Object.freeze({
+ reference: owner.reference,
identity: owner.identity,
name: owner.name,
version: owner.version,
@@ -422,6 +424,7 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
identity: string
name: string | null
program: {
+ reference: string
identity: string
name: string
version: string | null
@@ -440,6 +443,7 @@ function processRecordSnapshot(process: ReturnType<Process["record"]>) {
name: record.name,
program: record.program.identity,
programSnapshot: Object.freeze({
+ reference: record.program.reference,
identity: record.program.identity,
name: record.program.name,
version: record.program.version,
diff --git a/source/server/view/gateway/program-request.ts b/source/server/view/gateway/program-request.ts
index 4f6b121..0b3d90b 100644
--- a/source/server/view/gateway/program-request.ts
+++ b/source/server/view/gateway/program-request.ts
@@ -1,4 +1,5 @@
import type Application from "@server/core/application"
+import type Process from "@server/core/link-manager/auth-manager/process-manager/process"
import type { Socket } from "node:net"
/** Execute a streamed owner-local Program lifecycle request. */
@@ -31,128 +32,141 @@ export default async function programRequest(application: Application, socket: S
if (!asked.program) throw new Error("Creating needs a Program description")
const program = await programManager.create(asked.program)
+ const entry = programManager.find(program.identity)
- say({ event: "created", identity: program.identity })
+ say({ event: "created", program: entry.record() })
return done()
}
- if (asked.word === "installed") {
+ if (asked.word === "force-create") {
- if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Reading installation needs a Program identity")
+ if (!asked.program) throw new Error("Creating needs a Program description")
- const entry = programManager.programs.get(asked.identity)
+ const program = await programManager.forceCreate(asked.program)
+ const entry = programManager.find(program.identity)
- say({ event: "installedState", installed: entry?.installed === true })
+ say({ event: "created", program: entry.record() })
return done()
}
- if (asked.word === "forget") {
+ if (asked.word === "run-process") {
- if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Forgetting needs a Program identity")
+ const program = programManager.held(asked.handle)
+ let identity: string | null = null
+ let ended = false
+ let processRecord: ReturnType<Process["record"]> | null = null
- await programManager.forgetNamed(asked.identity)
+ identity = await programManager.runProcess(program, asked.launch ?? {}, {
+ started: process => {
- say({ event: "forgotten", identity: asked.identity })
- return done()
- }
+ processRecord = process.record()
+ attached.add(process.identity)
+ say({ event: "started", process: { ...processRecord, programSnapshot: programManager.find(program.identity).record() } })
+ },
+ output: (stream, text) => say({ event: "output", stream: stream === "err" ? "stderr" : "stdout", text }),
+ exited: function (code, signal) {
- if (asked.word === "install-existing") {
+ ended = true
+ if (identity) attached.delete(identity)
+ say({
+ event: "exited",
+ process: processRecord,
+ exit: { status: signal ? "signaled" : "exited", code, signal }
+ })
+ done()
+ }
+ })
+
+ if (ended) return
+
+ if (socket.destroyed) {
- if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Installing needs a Program identity")
+ if (application.linkManager.authManager.processManager.processes.has(identity)) {
+ await application.linkManager.authManager.processManager.exit(identity)
+ }
- const entry = programManager.programs.get(asked.identity)
+ return
+ }
+ return
+ }
- if (!entry) throw new Error(`Unknown Program "${asked.identity}"`)
+ if (asked.word === "installed") {
- for await (const chunk of programManager.installStreaming(entry.program)) say({ event: "output", ...chunk })
+ const program = programManager.held(asked.handle)
+ const entry = programManager.programs.get(program.identity)
- say({ event: "installed", identity: asked.identity })
+ say({ event: "installedState", installed: entry?.installed === true })
return done()
}
- if (asked.word === "uninstall-existing") {
-
- if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")
+ if (asked.word === "startup") {
- const entry = programManager.programs.get(asked.identity)
+ const program = programManager.held(asked.handle)
+ const operation = asked.operation
- if (!entry) throw new Error(`Unknown Program "${asked.identity}"`)
+ if (operation !== "get" && operation !== "enable" && operation !== "disable") throw new Error("Startup must be read, enabled, or disabled")
- for await (const chunk of programManager.uninstallStreaming(entry.program, asked.everything === true)) say({ event: "output", ...chunk })
+ const launch = await programManager.startup(program, operation, asked.launch)
- say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })
+ say({ event: "startup", launch })
return done()
}
- if (asked.word === "uninstall") {
+ if (asked.word === "create-process") {
- if (typeof asked.identity !== "string" || !asked.identity) throw new Error("Uninstalling needs a Program identity")
- if (asked.everything !== undefined && typeof asked.everything !== "boolean") throw new Error("Uninstalling everything must be true or false")
+ const program = programManager.held(asked.handle)
+ const identity = await programManager.runProcess(program, asked.launch ?? {})
+ const process = application.linkManager.authManager.processManager.processes.get(identity)
- for await (const chunk of programManager.uninstallInstalledStreaming(asked.identity, asked.everything === true)) {
+ if (!process) throw new Error("The created Process no longer exists")
- say({ event: "output", ...chunk })
- }
+ say({ event: "createdProcess", process: { ...process.record(), programSnapshot: programManager.find(program.identity).record() } })
+ return done()
+ }
+
+ if (asked.word === "find-or-create-process") {
+
+ const program = programManager.held(asked.handle)
+ const identity = await programManager.findOrCreateProcess(program, asked.launch as NonNullable<Asked["launch"]> & { name: string })
+ const process = application.linkManager.authManager.processManager.processes.get(identity)
- say({ event: "uninstalled", identity: asked.identity, everything: asked.everything === true })
+ if (!process) throw new Error("The created Process no longer exists")
+
+ say({ event: "createdProcess", process: { ...process.record(), programSnapshot: programManager.find(program.identity).record() } })
return done()
}
- if (asked.word === "install") {
-
- if (!asked.program) throw new Error("Installing needs a Program description")
- if (asked.run !== undefined && typeof asked.run !== "boolean") throw new Error("Running after installation must be true or false")
- if (asked.startup !== undefined && typeof asked.startup !== "boolean") throw new Error("Enabling startup during installation must be true or false")
-
- for await (const stage of programManager.installSource(asked.program, { run: asked.run, startup: asked.startup })) {
-
- if (stage.stage === "output") say({ event: "output", ...stage.chunk })
- else if (stage.stage === "installed") say({
- event: "installed",
- replaced: stage.replaced,
- program: {
- identity: stage.entry.identity,
- name: stage.entry.program.name,
- version: stage.entry.program.config.version ?? null
- }
- })
- else if (stage.stage === "startup-enabled") say({ event: "startupEnabled" })
- else say({ event: "running", process: stage.process })
- }
+ if (asked.word === "forget") {
+
+ const program = programManager.held(asked.handle)
+ await programManager.forget(program)
+
+ say({ event: "forgotten", identity: program.identity })
return done()
}
- if (asked.word !== "run") throw new Error(`The Program gateway does not know the word "${String(asked.word)}"`)
- if (!asked.program) throw new Error("Running needs a Program description")
+ if (asked.word === "install-existing") {
- let identity: string | null = null
- let ended = false
+ const program = programManager.held(asked.handle)
- identity = await programManager.launchAttached(asked.program, asked.options ?? {}, {
- output: (stream, text) => say({ event: "output", stream, text }),
- exited: function (code, signal) {
+ for await (const chunk of programManager.installStreaming(program)) say({ event: "output", ...chunk })
- ended = true
- if (identity) attached.delete(identity)
- say({ event: "exited", code, signal })
- done()
- }
- })
+ say({ event: "installed", identity: program.identity })
+ return done()
+ }
- if (ended) return
+ if (asked.word === "uninstall-existing") {
- if (socket.destroyed) {
+ const program = programManager.held(asked.handle)
- if (application.linkManager.authManager.processManager.processes.has(identity)) {
- await application.linkManager.authManager.processManager.exit(identity)
- }
+ for await (const chunk of programManager.uninstallStreaming(program, asked.everything === true)) say({ event: "output", ...chunk })
- return
+ say({ event: "uninstalled", identity: program.identity, everything: asked.everything === true })
+ return done()
}
- attached.add(identity)
- say({ event: "started", process: identity })
+ throw new Error(`The Program transport does not know the word "${String(asked.word)}"`)
}
function record(value: unknown): value is Record<string, unknown> {
@@ -163,10 +177,9 @@ function record(value: unknown): value is Record<string, unknown> {
interface Asked {
word?: string
- identity?: string
everything?: boolean
- run?: boolean
- startup?: boolean
- program?: Parameters<Application["linkManager"]["authManager"]["programManager"]["launchAttached"]>[0]
- options?: Record<string, string>
+ handle?: unknown
+ operation?: string
+ launch?: Parameters<Application["linkManager"]["authManager"]["programManager"]["runProcess"]>[1]
+ program?: Parameters<Application["linkManager"]["authManager"]["programManager"]["forceCreate"]>[0]
}