Skip to content

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

12.5 KB
Raw Blame
import type { OpenTarget } from "@phreshos/core"
import { Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
import Window, { Position, Size } from "./window"
import ServerProcessBoundary, { type HostVisibility } from "./server-process-boundary"
import HostTraffic from "./host-traffic"
import ClientState from "./client-state"
import { randomUUID } from "node:crypto"
import { type Layer } from "@phreshos/core"
import { Tunnel } from "@the-link/core"
import type { ServerRuntime } from "@server/core/server-runtime"

/**
 * One live execution of a Program.
 *
 * Its immutable options are the launch state carried by this particular
 * life. They are available to either half without becoming part of the
 * Program definition that later launches inherit.
 *
 * Endpoint presence is mutable live state. Each start creates a fresh
 * execution context; each stop removes that context's boundary and everything
 * it owns. The Process remains the stable aggregate around those contexts
 * and must always have at least one live endpoint.
 *
 * The Server runtime boundary lives here beside the transmitted values and is
 * left out of toJSON: what crosses is declared, so a host-only execution
 * mechanism needs no second structure to hide in.
 */
export default class Process {

    /** Opaque identity of this one Process entity, never a public address. */
    public readonly reference = randomUUID()

    public readonly identity: string

    // A meaningful address within this program. Null means this process
    // has no role beyond its random identity.
    public readonly name: string | null

    // The program it is an instance of, held rather than named: a
    // process is derived from a program, and a name is only what that
    // program calls itself.
    public readonly program: Program

    // What its launch said. Attached the moment it started and carried
    // wherever it goes — a process is exactly one launch, so this is
    // the process's own state rather than a message it was sent.
    public readonly options: Options

    /** Immutable normalized intent used only to converge named creation. */
    public readonly launch: ProcessLaunch

    // When this instance began. A process's birth is its construction,
    // so nothing hands this over — there is no earlier moment to mean.
    //
    // A `Date` in the public representation contract. Every boundary adapter
    // must preserve that value without changing the domain shape.
    public readonly startedAt = new Date()

    // The current Server execution context. Null is current live state, not a
    // declaration or a permanent launch-shape decision.
    public server: ServerProcessBoundary | null = null

    // The current Client execution context. Its nearby iframe boundary
    // belongs to the Desktop session and ends when this context stops.
    public client: ClientState | null = null

    /** Permanent Client Endpoint handle; its Window state exists only while running. */
    public readonly clientEndpoint: Readonly<{ window: Window }> | null

    // The process whose call to `program.createProcess()` created this
    // one. Lineage only: keeping this handle neither owns nor prolongs
    // either life.
    public readonly parent: Process | null

    private readonly hostTraffic: HostTraffic

    private readonly serverStarts: ((server: ServerProcessBoundary) => void)[] = []

    private readonly serverStops: ((code: number | null, signal: NodeJS.Signals | null) => void)[] = []

    private readonly clientStops: (() => void)[] = []

    private readonly readyWaiters = {

        server: new Set<() => void>(),

        client: new Set<() => void>()
    }

    private readonly endings: Ending[] = []

    private ending: { code: number | null, signal: NodeJS.Signals | null } | null = null

    private exitProcess: (() => Promise<unknown>) | null = null

    /** What this Process was started to open; `null` when it was not. Part of its launch, as its options are. */
    public readonly opened: OpenTarget | null

    public constructor(identity: string, name: string | null, program: Program, options: Options, launch: ProcessLaunch, parent: Process | null, hostTraffic: HostTraffic, window: Window | null = null, opened: OpenTarget | null = null) {

        this.identity = identity

        this.name = name

        this.program = program

        this.options = options

        this.opened = opened

        this.launch = launch

        this.parent = parent

        this.hostTraffic = hostTraffic

        this.clientEndpoint = window ? Object.freeze({ window }) : null
    }

    public startServer(runtime: ServerRuntime, service: string | false, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel, hostVisible: HostVisibility) {

        if (this.server) return this.server

        let boundary!: ServerProcessBoundary

        boundary = new ServerProcessBoundary(runtime, this.program.client !== null, service, (code, signal) => ended(boundary, code, signal), unanswered, this.hostTraffic, appearance, hostVisible)

        this.server = boundary

        for (const listener of this.serverStarts) listener(boundary)

        return boundary
    }

    public serverStopped(boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) {

        if (this.server !== boundary) return false

        this.server = null

        for (const listener of this.serverStops) listener(code, signal)

        return true
    }

    public serverBecameReady(boundary: ServerProcessBoundary) {

        if (this.server !== boundary || !boundary.ready) return

        this.becameReady("server")
    }

    public waitReady(endpoint: "server" | "client", notify: () => void) {

        if (endpoint === "server" ? this.server?.ready : this.client) {

            notify()

            return () => undefined
        }

        this.readyWaiters[endpoint].add(notify)

        return () => { this.readyWaiters[endpoint].delete(notify) }
    }

    public startClient(service: string | false) {

        if (this.client) return false

        if (!this.clientEndpoint) throw new Error("This Program declared no Client Endpoint")

        this.client = new ClientState(service)

        this.becameReady("client")

        return true
    }

    public stopClient() {

        if (!this.client) return false

        this.client.memory.close()

        this.client = null

        // Stopping ends this incarnation rather than retaining values for the
        // next start. Subscriptions remain attached to the stable handle.
        this.clientEndpoint?.window.stop()

        for (const listener of this.clientStops) listener()

        return true
    }

    public get live() {

        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)

        if (this.server) listener(this.server)
    }

    /** Internal aggregate exit used by lifecycle owners and focused probes. */
    public async exit() {

        if (!this.exitProcess) throw new Error("This Process has no lifecycle owner")

        await this.exitProcess()
    }

    public ownExit(exit: () => Promise<unknown>) {

        this.exitProcess = exit
    }

    public onServerStop(listener: (code: number | null, signal: NodeJS.Signals | null) => void) {

        this.serverStops.push(listener)

        return () => removeListener(this.serverStops, listener)
    }

    public onClientStop(listener: () => void) {

        this.clientStops.push(listener)

        return () => removeListener(this.clientStops, listener)
    }

    // Every aggregate ending, one word. Endpoint stops are separate lifecycle
    // transitions and reach this only when the complete Process is gone.
    //
    // The code and signal come with it, because whoever launched a
    // process may have to exit with its status. A listener that took
    // nothing dropped both.
    public onExit(listener: Ending) {

        if (this.ending) {

            listener(this.ending.code, this.ending.signal)

            return () => undefined
        }

        this.endings.push(listener)

        return () => {

            const index = this.endings.indexOf(listener)

            if (index !== -1) this.endings.splice(index, 1)
        }
    }

    // Said once, however many ways it could be said: a Server runtime's exit
    // removes the record, and removing the record is itself an ending.
    // The result remains terminal state rather than becoming lost history:
    // process creation announces externally before every internal owner has
    // finished attaching, and a fast runtime can exit during that announcement.
    public ended(code: number | null, signal: NodeJS.Signals | null) {

        if (this.ending) return

        this.ending = { code, signal }

        this.readyWaiters.server.clear()

        this.readyWaiters.client.clear()

        const endings = this.endings.splice(0)

        for (const listener of endings) listener(code, signal)
    }

    // The process value every road carries. Parentage is deliberately
    // absent: it is asked through `context.parent()`, so a client gate
    // can hide a cross-program parent without first exposing it here.
    public record() {

        return {

            reference: this.reference,

            identity: this.identity,

            name: this.name,

            program: this.program.identity,

            options: this.options,

            opened: this.opened,

            startedAt: this.startedAt,

            /** Whether this Process's Program declared a Server Endpoint. */
            serverEndpoint: this.program.server !== null,

            /** Whether this Process's Program declared a Client Endpoint. */
            clientEndpoint: this.clientEndpoint !== null,

            // These are live endpoint snapshots. Program definitions answer
            // which endpoint kinds can be started.
            server: this.server ? { service: this.server.service } : null,

            client: this.client ? { service: this.client.service } : null
        }
    }

    public hosted() {

        return {

            ...this.record(),

            // The trusted desktop counterpart keeps this essential fact
            // current. Surfaced program records are shaped separately.
            server: this.server ? { ready: this.server.ready, service: this.server.service } : null,

            // The trusted desktop needs the relationship in order to
            // answer a pane locally after the parent has exited. The
            // pane never receives this record whole.
            parent: this.parent?.record() ?? null,

            clientEndpoint: this.clientEndpoint
                ? { window: this.client ? this.clientEndpoint.window.toJSON() : null }
                : null,

            client: this.client ? { ...this.client, sandbox: this.program.client?.sandbox ?? true } : null
        }
    }

    public toJSON() {

        return this.record()
    }
}

function removeListener<Listener>(listeners: Listener[], listener: Listener) {

    const index = listeners.indexOf(listener)

    if (index >= 0) listeners.splice(index, 1)
}

export type HostedProcess = ReturnType<Process["hosted"]>

/** Public Process data from which an endpoint SDK reconstructs a handle. */
export type ProcessRecord = ReturnType<Process["record"]>

export type ProcessSnapshot = HostedProcess

export type Ending = (code: number | null, signal: NodeJS.Signals | null) => void

export type { Position, Size }

export type { Stream } from "./server-process-boundary"

/** Stable launch meaning, excluding mutable endpoint and Window state. */
export interface ProcessLaunch {

    readonly server: Readonly<{

        /** The Service name it is reached by, or `false` for none. */
        service: string | false
    }> | null

    readonly client: Readonly<{

        title: string

        header: boolean

        position: Position | null

        size: Size | null

        layer: Layer

        minimize: boolean
        maximize: boolean

        /** The Service name it is reached by, or `false` for none. */
        service: string | false
    }> | null

    readonly options: Readonly<Record<string, string>>
}