refactor(cmdline)!: an app's entrypoint provides values its rows read
Replaces the patch round trip. An app's entrypoint resolves the command
line into a service, and the rows it configures read that service from
their own config — port: !!js ctx.get('webStartup')?.port ?? 3080 — so the
resolved value beats the value written beside it and nothing is written
back into a row or handed to the launcher.
A bundle names the entrypoint row in its manifest (dsh.bundle.entrypoint),
which is what lets the boot mount in two passes: entrypoints alone, then
the whole composition. That ordering is required, not cosmetic — a row's
config expressions are evaluated when the include applies the row, and a
strict ctx.get only answers for a service whose providing fiber is already
active.
What this removes: ctx.appPatches and the launcher-owned patch layer, the
disable/re-enable recycle and its in-flight-mount barrier, overrideConfig,
and the reload hazard they existed for. A live config edit now re-applies
the second pass against services that are still up, so a served port
survives by construction.
What it adds: ctx.appReady, because Loader settlement no longer means the
app is up — a row mounted in the second pass can observe a settled tree
while that pass is still running, or already rolling back. The web URL line
waits for it, so a boot that fails in the second pass announces nothing.
This commit is contained in:
@@ -26,9 +26,10 @@
|
||||
- id: headless-startup
|
||||
name: '@deepseek-ai/dsh-headless/startup'
|
||||
|
||||
# Shipped off, not merely waiting: the runner's schema requires the task.
|
||||
# The startup row enables it with the task after parsing this app's argv.
|
||||
# Reads its task from the headlessStartup service after the startup row
|
||||
# resolves this app's command line.
|
||||
- id: headless-runner
|
||||
name: '@deepseek-ai/dsh-headless'
|
||||
inject: [headlessStartup]
|
||||
disabled: true
|
||||
config:
|
||||
task: !!js ctx.get('headlessStartup')?.task
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
"license": "BSD-3-Clause",
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
"patch": "./cordis.patch.yml",
|
||||
"entrypoint": "headless-startup"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
import { Command } from 'commander'
|
||||
import type { Context } from 'cordis'
|
||||
import type { EntryOptions } from '@cordisjs/plugin-loader'
|
||||
import { overrideConfig, runStartup, type RowChange } from '@deepseek-ai/dsh-cmdline'
|
||||
import { runStartup } from '@deepseek-ai/dsh-cmdline'
|
||||
import { WEB_STARTUP_SERVICE } from '@deepseek-ai/dsh-web-app/startup'
|
||||
|
||||
/** Stable Cordis plugin name. */
|
||||
@@ -24,12 +24,18 @@ export const name = 'headless-startup'
|
||||
/** Services required before the task can be resolved. */
|
||||
export const inject = ['cmdlineArgs']
|
||||
|
||||
/** The startup service the one-shot runner row injects. */
|
||||
/** The service this row provides and the one-shot runner row reads. */
|
||||
export const HEADLESS_STARTUP_SERVICE = 'headlessStartup'
|
||||
|
||||
/** The runner row this app configures. */
|
||||
/** The row that runs the task, and the only reason this app has a command line. */
|
||||
const RUNNER_ROW_ID = 'headless-runner'
|
||||
|
||||
/** What the runner row reads from {@link HEADLESS_STARTUP_SERVICE}. */
|
||||
export interface HeadlessStartupValues {
|
||||
/** The task text this invocation asked for. */
|
||||
task: string
|
||||
}
|
||||
|
||||
/**
|
||||
* This app's command: the task positional, its description, and its help text.
|
||||
* @returns a fresh program, so one process can parse more than once (tests).
|
||||
@@ -49,22 +55,25 @@ Examples:
|
||||
/**
|
||||
* Turn the parsed command line into the runner row's task.
|
||||
* @param program - the parsed headless command.
|
||||
* @param rows - the waiting rows' composed options, in tree order.
|
||||
* @returns row id → changes.
|
||||
* @param rows - the rows waiting on this app's service, in tree order.
|
||||
* @returns the runner row's service value.
|
||||
* @throws when the composition has no runner row, which would otherwise accept
|
||||
* a task and silently run nothing.
|
||||
*/
|
||||
function planHeadlessStartup(program: Command, rows: readonly EntryOptions[]): Map<string, RowChange> {
|
||||
function planHeadlessStartup(program: Command, rows: readonly EntryOptions[]): HeadlessStartupValues {
|
||||
const task = program.args.join(' ')
|
||||
if (task === '') program.error('error: a task is required, for example: dsh --profile headless "run the tests"')
|
||||
const runner = rows.find(row => row.id === RUNNER_ROW_ID)
|
||||
if (runner === undefined) throw new Error(`headless-startup: the composition has no waiting "${RUNNER_ROW_ID}" row to run the task`)
|
||||
return new Map([[RUNNER_ROW_ID, overrideConfig(runner, { task })]])
|
||||
if (!rows.some(row => row.id === RUNNER_ROW_ID)) {
|
||||
throw new Error(`headless-startup: the composition has no waiting "${RUNNER_ROW_ID}" row to run the task`)
|
||||
}
|
||||
return { task }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the task and start the rows waiting for it.
|
||||
* Resolve the task and start the runner that reads it.
|
||||
* @param ctx - plugin context carrying the command line and the Loader.
|
||||
* @returns nothing once the runner is released, or once `--help` or a missing task requested exit.
|
||||
* @returns nothing once the runner is started, or once `--help` or a missing task requested exit.
|
||||
*/
|
||||
export function apply(ctx: Context): Promise<void> {
|
||||
return runStartup(ctx, [HEADLESS_STARTUP_SERVICE, WEB_STARTUP_SERVICE], headlessCommand(), planHeadlessStartup)
|
||||
export function apply(ctx: Context): void {
|
||||
runStartup(ctx, [HEADLESS_STARTUP_SERVICE, WEB_STARTUP_SERVICE], headlessCommand(), planHeadlessStartup)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* The one-shot app's startup row over a REAL Loader tree: the task
|
||||
* positional reaches the runner row, a missing task is a usage error, and the
|
||||
* web startup service this app absorbs releases its rows on the composed values.
|
||||
* The one-shot app's entrypoint row over a REAL Loader tree: the task
|
||||
* positional becomes the value the runner row reads, a missing task is a usage
|
||||
* error, and the web service this app absorbs is provided too, so the web rows
|
||||
* it rides over resolve on their own fallbacks.
|
||||
*/
|
||||
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs'
|
||||
@@ -9,21 +10,17 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { Context } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
import Loader from '@cordisjs/plugin-loader'
|
||||
import Include from '@cordisjs/plugin-include'
|
||||
import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import { WEB_STARTUP_SERVICE } from '@deepseek-ai/dsh-web-app/startup'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { apply, HEADLESS_STARTUP_SERVICE } from '../src/startup.ts'
|
||||
import { apply, HEADLESS_STARTUP_SERVICE, type HeadlessStartupValues } from '../src/startup.ts'
|
||||
|
||||
/** What one boot of the fixture tree observed. */
|
||||
interface Observed {
|
||||
started: Record<string, Record<string, unknown>>
|
||||
exits: number[]
|
||||
out: string
|
||||
/** Patches the startup row handed the launcher for later compositions. */
|
||||
contributed: unknown[]
|
||||
}
|
||||
|
||||
const disposers: (() => Promise<void>)[] = []
|
||||
@@ -35,112 +32,90 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
/**
|
||||
* Boot the real headless startup row over stand-ins for the runner row and one
|
||||
* web row it absorbs.
|
||||
* Mount the real entrypoint row over stand-ins for the runner row and one web
|
||||
* row this app absorbs, the way a profile mounts phase one.
|
||||
* @param args - the invocation's inner arguments.
|
||||
* @returns what the boot observed.
|
||||
* @param options - fixture knobs for the shapes a composition can take.
|
||||
* @returns the resolved service values (absent when the app requested exit) and what the boot observed.
|
||||
*/
|
||||
async function bootStartup(args: string[], options: { withoutRunner?: boolean } = {}): Promise<Observed> {
|
||||
async function bootStartup(
|
||||
args: string[],
|
||||
options: { withoutRunner?: boolean } = {},
|
||||
): Promise<{ task: HeadlessStartupValues | undefined; web: unknown; observed: Observed }> {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-headless-startup-'))
|
||||
const observed: Observed = { started: {}, exits: [], out: '', contributed: [] }
|
||||
// The runner's real schema requires the task, which is exactly what makes a
|
||||
// waiting-but-enabled row fail at fiber creation; the stand-in keeps that.
|
||||
writeFileSync(join(dir, 'row.mjs'), `
|
||||
export const Config = globalThis.__headlessRunnerConfigSchema
|
||||
export function apply(ctx, config) { globalThis.__headlessStartupObserved.started[ctx.fiber.entry.options.id] = config ?? {} }
|
||||
`)
|
||||
writeFileSync(join(dir, 'plain-row.mjs'), `
|
||||
export function apply(ctx, config) { globalThis.__headlessStartupObserved.started[ctx.fiber.entry.options.id] = config ?? {} }
|
||||
`)
|
||||
const observed: Observed = { exits: [], out: '' }
|
||||
writeFileSync(join(dir, 'row.mjs'), 'export function apply() {}\n')
|
||||
// The Loader imports a row through Node's own resolver, which cannot resolve
|
||||
// this workspace's sources; the row delegates to the real plugin the test
|
||||
// imported through the source-plane path mapping.
|
||||
writeFileSync(join(dir, 'startup-row.mjs'), `
|
||||
writeFileSync(join(dir, 'entrypoint.mjs'), `
|
||||
export const name = 'headless-startup'
|
||||
export const inject = ['cmdlineArgs']
|
||||
export const apply = ctx => globalThis.__headlessStartupApply(ctx)
|
||||
`)
|
||||
const rowUrl = pathToFileURL(join(dir, 'row.mjs')).href
|
||||
const plainRowUrl = pathToFileURL(join(dir, 'plain-row.mjs')).href
|
||||
writeFileSync(join(dir, 'cordis.yml'), [
|
||||
// A composition that lost the runner still injects the startup service, so
|
||||
// the startup row reaches its own row check rather than the generic one.
|
||||
// A composition that lost the runner still injects the service, so the
|
||||
// entrypoint reaches its own row check rather than the generic one.
|
||||
options.withoutRunner === true ? '- id: displaced-runner' : '- id: headless-runner',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${HEADLESS_STARTUP_SERVICE}]`,
|
||||
// Shipped off, like the bundle patch: the schema below requires the task,
|
||||
// which only the startup row can supply.
|
||||
' disabled: true',
|
||||
'- id: webserver',
|
||||
` name: ${plainRowUrl}`,
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' config:',
|
||||
' port: 0',
|
||||
' disabled: true',
|
||||
'- id: headless-startup',
|
||||
` name: ${pathToFileURL(join(dir, 'startup-row.mjs')).href}`,
|
||||
` name: ${pathToFileURL(join(dir, 'entrypoint.mjs')).href}`,
|
||||
'',
|
||||
].join('\n'))
|
||||
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
|
||||
internals.stdout = observing
|
||||
internals.stderr = observing
|
||||
const globals = globalThis as unknown as {
|
||||
__headlessStartupObserved: Observed
|
||||
__headlessStartupApply: typeof apply
|
||||
__headlessRunnerConfigSchema: unknown
|
||||
}
|
||||
globals.__headlessStartupObserved = observed
|
||||
globals.__headlessStartupApply = apply
|
||||
globals.__headlessRunnerConfigSchema = z.object({ task: z.string().required() })
|
||||
;(globalThis as unknown as { __headlessStartupApply: typeof apply }).__headlessStartupApply = apply
|
||||
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(Loader)
|
||||
ctx.loader.builtins.include = Include
|
||||
provideCmdline(ctx, {
|
||||
args,
|
||||
exit: code => void observed.exits.push(code),
|
||||
contribute: patches => void observed.contributed.push(...patches),
|
||||
})
|
||||
provideCmdline(ctx, { args, exit: code => void observed.exits.push(code) })
|
||||
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(join(dir, 'cordis.yml')).href } })
|
||||
await ctx.loader.await()
|
||||
disposers.push(async () => { await ctx.fiber.dispose() })
|
||||
return observed
|
||||
return {
|
||||
task: ctx.get(HEADLESS_STARTUP_SERVICE) as HeadlessStartupValues | undefined,
|
||||
web: ctx.get(WEB_STARTUP_SERVICE),
|
||||
observed,
|
||||
}
|
||||
}
|
||||
|
||||
describe('headless startup', () => {
|
||||
it('joins the task positional and starts the runner with it', async () => {
|
||||
const observed = await bootStartup(['run', 'the', 'tests'])
|
||||
expect(observed.started['headless-runner']).toEqual({ task: 'run the tests' })
|
||||
it('joins the task positional into the value the runner reads', async () => {
|
||||
const { task, observed } = await bootStartup(['run', 'the', 'tests'])
|
||||
expect(task).toEqual({ task: 'run the tests' })
|
||||
expect(observed.exits).toEqual([])
|
||||
})
|
||||
|
||||
it('hands the task to the launcher as a patch, so a recomposition keeps it', async () => {
|
||||
const observed = await bootStartup(['run', 'the', 'tests'])
|
||||
expect(observed.contributed).toEqual([
|
||||
{ id: 'headless-runner', disabled: false, config: { task: 'run the tests' } },
|
||||
])
|
||||
})
|
||||
|
||||
it('starts the web rows it absorbed on the composed one-shot values', async () => {
|
||||
const observed = await bootStartup(['task'])
|
||||
expect(observed.started.webserver).toEqual({ port: 0 })
|
||||
it('provides the web service it absorbed, so those rows resolve on their own fallbacks', async () => {
|
||||
const { web } = await bootStartup(['task'])
|
||||
expect(web).toEqual({ task: 'task' })
|
||||
})
|
||||
|
||||
it('rejects an invocation with no task instead of failing inside the runner schema', async () => {
|
||||
const observed = await bootStartup([])
|
||||
const { task, observed } = await bootStartup([])
|
||||
expect(observed.out).toContain('a task is required')
|
||||
expect(observed.started).toEqual({})
|
||||
expect(task).toBeUndefined()
|
||||
expect(observed.exits).toEqual([1])
|
||||
})
|
||||
|
||||
it('prints its own help and resolves nothing', async () => {
|
||||
const { task, observed } = await bootStartup(['--help'])
|
||||
expect(observed.out).toContain('dsh --profile headless')
|
||||
expect(task).toBeUndefined()
|
||||
expect(observed.exits).toEqual([0])
|
||||
})
|
||||
|
||||
it('fails the boot when the composition has no runner row to give the task to', async () => {
|
||||
await expect(bootStartup(['task'], { withoutRunner: true }))
|
||||
.rejects.toThrow('the composition has no waiting "headless-runner" row')
|
||||
})
|
||||
|
||||
it('prints its own help and starts nothing', async () => {
|
||||
const observed = await bootStartup(['--help'])
|
||||
expect(observed.out).toContain('dsh --profile headless')
|
||||
expect(observed.started).toEqual({})
|
||||
expect(observed.exits).toEqual([0])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
# A patch replaces the targeted row's whole `config`, so each row below
|
||||
# restates every key it owns.
|
||||
#
|
||||
# Rows this app configures from flags declare `inject: [webStartup]`: they wait
|
||||
# until the web-startup row has parsed --host/--port/--dev/--workspace-root/
|
||||
# --trusted-host and provided that service with the resolved values.
|
||||
# `dsh --profile web --help` therefore prints this app's own help and exits
|
||||
# without ever binding a port.
|
||||
# Rows this app configures from flags read them from the `webStartup` service:
|
||||
# each names the key it takes and the value it falls back to, so a flag wins
|
||||
# over the value written beside it. The web-startup row is this bundle's
|
||||
# manifest-declared entrypoint, so it runs before any of them and has already
|
||||
# parsed --host/--port/--dev/--workspace-root/--trusted-host by the time their
|
||||
# config is resolved. `dsh --profile web --help` therefore prints this app's own
|
||||
# help and exits before the rest of the composition mounts at all.
|
||||
|
||||
# ── surface-specific values the base deliberately omits ─────────────────────
|
||||
|
||||
@@ -79,9 +81,13 @@
|
||||
# shares. The base layer's agent-default-model service owns the default model.
|
||||
- id: api-gateway
|
||||
name: '@deepseek-ai/dsh-host-apiproxy'
|
||||
inject: [webStartup]
|
||||
config:
|
||||
workspaceRoot: !!js ctx.get('webStartup')?.workspaceRoot
|
||||
|
||||
# Owns the web flag family and its --help; provides webStartup with the
|
||||
# values this invocation resolved. Nothing waiting on it starts first.
|
||||
# This bundle's entrypoint (declared in its package.json): it owns the web
|
||||
# flag family and its --help, and provides webStartup with the values this
|
||||
# invocation resolved. The boot runs it before every row above.
|
||||
- id: web-startup
|
||||
name: '@deepseek-ai/dsh-web-app/startup'
|
||||
|
||||
@@ -94,8 +100,8 @@
|
||||
name: '@deepseek-ai/dsh-host-webserver'
|
||||
inject: [webStartup]
|
||||
config:
|
||||
host: 127.0.0.1
|
||||
port: 3080
|
||||
host: !!js ctx.get('webStartup')?.host ?? '127.0.0.1'
|
||||
port: !!js ctx.get('webStartup')?.port ?? 3080
|
||||
|
||||
# Web glue owned by this bundle: resolves the built frontend dist (an
|
||||
# assembly fact of dsh-web-app, never user config), mounts the
|
||||
@@ -108,11 +114,15 @@
|
||||
name: '@deepseek-ai/dsh-web-app'
|
||||
inject: [webStartup]
|
||||
config:
|
||||
mode: production
|
||||
mode: !!js ctx.get('webStartup')?.mode ?? 'production'
|
||||
printUrl: true
|
||||
surfaceContext: true
|
||||
lanAddresses: !!js ctx.get('webStartup')?.lanAddresses ?? []
|
||||
|
||||
# The client-plugin HMR receiver ships disabled; `--dev` enables it.
|
||||
# The client-plugin reload chain: a dev-only row this bundle ships off,
|
||||
# which the entrypoint turns on for `--dev`. It is a row rather than a
|
||||
# child of web-runtime because its node half is a client-side package,
|
||||
# which a host-side bundle cannot import.
|
||||
- id: client-hmr
|
||||
name: '@deepseek-ai/dsh-client-hmr'
|
||||
inject: [webStartup]
|
||||
@@ -132,6 +142,11 @@
|
||||
- id: connection
|
||||
name: '@deepseek-ai/dsh-client-connection'
|
||||
inject: [webStartup]
|
||||
config:
|
||||
# The LAN literals an all-interfaces bind derived plus the
|
||||
# --trusted-host extras. A deployment that configures its own fence
|
||||
# authorities adds them to this list.
|
||||
trustedHosts: !!js ctx.get('webStartup')?.trustedHosts ?? []
|
||||
|
||||
- id: api-remotes
|
||||
name: '@deepseek-ai/dsh-api-remotes'
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
"license": "BSD-3-Clause",
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
"patch": "./cordis.patch.yml",
|
||||
"entrypoint": "web-startup"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { enableRow } from '@deepseek-ai/dsh-cmdline'
|
||||
import * as FrontendStatic from '@deepseek-ai/dsh-frontend-static'
|
||||
import type {} from '@deepseek-ai/cordis-plugin-loader'
|
||||
import type {} from '@deepseek-ai/dsh-host-webserver'
|
||||
@@ -22,6 +23,9 @@ import type {} from '@deepseek-ai/dsh-bash-env'
|
||||
/** Stable Cordis plugin name. */
|
||||
export const name = 'web-app'
|
||||
|
||||
/** The client-plugin reload chain row this bundle ships disabled, for `--dev`. */
|
||||
const HMR_ROW_ID = 'client-hmr'
|
||||
|
||||
/** Services required before the web runtime can mount. */
|
||||
export const inject = ['httpServer']
|
||||
|
||||
@@ -112,6 +116,11 @@ export const internals: { resolveDistIndex: () => string } = { resolveDistIndex
|
||||
*/
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
ctx.plugin(FrontendStatic, { distIndex: internals.resolveDistIndex() })
|
||||
// The client-plugin reload chain is a row this bundle ships off, because it
|
||||
// exists only in development. Turning it on belongs here rather than in the
|
||||
// entrypoint: it needs the host rows this phase of the boot mounts, and the
|
||||
// entrypoint runs before them.
|
||||
if (config.mode === 'development') void enableRow(ctx, HMR_ROW_ID)
|
||||
if (config.surfaceContext) {
|
||||
ctx.inject(['systemPrompt'], (promptCtx) => {
|
||||
promptCtx.systemPrompt.section({
|
||||
@@ -143,15 +152,20 @@ export function apply(ctx: Context, config: Config): void {
|
||||
const port = ctx.httpServer.port
|
||||
console.log(`dsh web: ${localWebUrl(ctx)}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${String(port)})`}`)
|
||||
}
|
||||
const loader = ctx.get('loader')
|
||||
if (loader === undefined) printUrl()
|
||||
// A launcher that mounts in phases tells this row when the whole
|
||||
// composition is up; Loader settlement alone would let the line print
|
||||
// between phases, announcing a server whose boot can still fail. A
|
||||
// hand-built tree has neither and prints at once.
|
||||
const settled = ctx.get('appReady') ?? ctx.get('loader')?.await()
|
||||
if (settled === undefined) printUrl()
|
||||
else {
|
||||
void loader.await().then(() => {
|
||||
// The tree can be disposed while settlement was in flight (early
|
||||
void settled.then(() => {
|
||||
// The tree can be disposed while the boot was in flight (early
|
||||
// SIGTERM); a URL line for a dead server would only mislead, and
|
||||
// reading the torn-down port would turn a clean shutdown into a crash.
|
||||
if (ctx.get('httpServer') !== undefined) printUrl()
|
||||
})
|
||||
// A failed boot is reported by the launcher; this row only stays quiet.
|
||||
}, () => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { networkInterfaces } from 'node:os'
|
||||
import { Command } from 'commander'
|
||||
import type { Context } from 'cordis'
|
||||
import type { EntryOptions } from '@cordisjs/plugin-loader'
|
||||
import { overrideConfig, runStartup, type RowChange } from '@deepseek-ai/dsh-cmdline'
|
||||
import { runStartup } from '@deepseek-ai/dsh-cmdline'
|
||||
|
||||
/** Stable Cordis plugin name. */
|
||||
export const name = 'web-startup'
|
||||
@@ -21,12 +21,32 @@ export const name = 'web-startup'
|
||||
export const inject = ['cmdlineArgs']
|
||||
|
||||
/**
|
||||
* The startup service every flag-configured web row injects. The rows are
|
||||
* listed in this bundle's `cordis.patch.yml`; a row this startup plans changes
|
||||
* for without injecting the service fails loud.
|
||||
* The service this row provides and every flag-configured web row reads. The
|
||||
* rows are listed in this bundle's `cordis.patch.yml`, where each names the key
|
||||
* it takes from here and the value it falls back to.
|
||||
*/
|
||||
export const WEB_STARTUP_SERVICE = 'webStartup'
|
||||
|
||||
/** What the web rows read from {@link WEB_STARTUP_SERVICE}. */
|
||||
export interface WebStartupValues {
|
||||
/** `--host`, absent when the invocation did not name one. */
|
||||
host?: string
|
||||
/** `--port`, absent when the invocation did not name one. */
|
||||
port?: number
|
||||
/** `--workspace-root`, absent when the invocation did not name one. */
|
||||
workspaceRoot?: string
|
||||
/** Web runtime mode; `--dev` selects development, which also mounts the client-plugin reload chain. */
|
||||
mode: 'production' | 'development'
|
||||
/**
|
||||
* The `/api` fence authorities for this invocation: the LAN literals an
|
||||
* all-interfaces bind derived, plus the `--trusted-host` extras, over what
|
||||
* the composition already configured.
|
||||
*/
|
||||
trustedHosts: string[]
|
||||
/** The LAN literals the fence was configured with, for display. */
|
||||
lanAddresses: string[]
|
||||
}
|
||||
|
||||
/** The webserver schema's all-interfaces bind literal: only this bind derives LAN authorities. */
|
||||
const ALL_INTERFACES_HOST = '0.0.0.0'
|
||||
|
||||
@@ -95,58 +115,39 @@ Examples:
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the parsed flags into the changes each waiting row needs.
|
||||
* Turn the parsed flags into the values the web rows read.
|
||||
* @param program - the parsed web command.
|
||||
* @param rows - the waiting rows' composed options, in tree order.
|
||||
* @returns row id → changes; rows absent from the map start on their composed values.
|
||||
* @returns the web rows' service value.
|
||||
*/
|
||||
function planWebStartup(program: Command, rows: readonly EntryOptions[]): Map<string, RowChange> {
|
||||
function planWebStartup(program: Command, rows: readonly EntryOptions[]): WebStartupValues {
|
||||
const options = program.opts<WebOptions>()
|
||||
if (options.port !== undefined && !/^\d+$/.test(options.port)) {
|
||||
program.error(`error: --port must be a number, got ${JSON.stringify(options.port)}`)
|
||||
}
|
||||
const row = (id: string): EntryOptions => {
|
||||
const found = rows.find(candidate => candidate.id === id)
|
||||
if (found === undefined) throw new Error(`web-startup: the web composition has no waiting "${id}" row to configure`)
|
||||
return found
|
||||
}
|
||||
const plan = new Map<string, RowChange>()
|
||||
const webserver = row('webserver')
|
||||
const composedHost = (webserver.config as { host?: string } | undefined)?.host
|
||||
plan.set('webserver', overrideConfig(webserver, {
|
||||
const webserver = rows.find(row => row.id === 'webserver')
|
||||
if (webserver === undefined) throw new Error('web-startup: the web composition has no waiting "webserver" row to configure')
|
||||
// The bind this invocation ends on: the flag, else what the row falls back
|
||||
// to, which is the same literal its config expression names.
|
||||
const bindHost = options.host ?? (webserver.config as { host?: string } | undefined)?.host
|
||||
const { lanAddresses, trustedHosts } = resolveLanTrust(bindHost, options.trustedHost ?? [])
|
||||
return {
|
||||
...options.host !== undefined && { host: options.host },
|
||||
...options.port !== undefined && { port: Number(options.port) },
|
||||
}))
|
||||
if (options.workspaceRoot !== undefined) {
|
||||
plan.set('api-gateway', overrideConfig(row('api-gateway'), { workspaceRoot: options.workspaceRoot }))
|
||||
}
|
||||
const { lanAddresses, trustedHosts } = resolveLanTrust(options.host ?? composedHost, options.trustedHost ?? [])
|
||||
if (trustedHosts.length > 0) {
|
||||
// Additive over the composed value: a cordis.patch.yml-configured fence
|
||||
// authority must survive the derived LAN literals and the flag extras —
|
||||
// dropping it silently would weaken security-relevant configuration.
|
||||
const connection = row('connection')
|
||||
const composedTrusted = (connection.config as { trustedHosts?: string[] } | undefined)?.trustedHosts ?? []
|
||||
plan.set('connection', overrideConfig(connection, { trustedHosts: [...composedTrusted, ...trustedHosts] }))
|
||||
}
|
||||
// mode and lanAddresses are resolved on every boot, never pass-throughs of
|
||||
// composed values: they describe this invocation, not the deployment.
|
||||
plan.set('web-runtime', overrideConfig(row('web-runtime'), {
|
||||
...options.workspaceRoot !== undefined && { workspaceRoot: options.workspaceRoot },
|
||||
// mode and lanAddresses describe this invocation, never the deployment, so
|
||||
// they are resolved on every boot.
|
||||
mode: options.dev === true ? 'development' : 'production',
|
||||
trustedHosts,
|
||||
lanAddresses,
|
||||
}))
|
||||
// The receiver ships disabled so `--dev` is a row toggle rather than a
|
||||
// runtime insert (the Loader cannot resolve a row inserted from inside a
|
||||
// mounting plugin).
|
||||
if (options.dev === true) plan.set('client-hmr', { disabled: false })
|
||||
return plan
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the web flag family and start the rows waiting for it.
|
||||
* Resolve the web flag family and start the rows that read it.
|
||||
* @param ctx - plugin context carrying the command line and the Loader.
|
||||
* @returns nothing once the waiting rows are released, or once `--help` requested exit.
|
||||
* @returns nothing once the web rows are started, or once `--help` requested exit.
|
||||
*/
|
||||
export function apply(ctx: Context): Promise<void> {
|
||||
return runStartup(ctx, WEB_STARTUP_SERVICE, webCommand(), planWebStartup)
|
||||
export function apply(ctx: Context): void {
|
||||
runStartup(ctx, WEB_STARTUP_SERVICE, webCommand(), planWebStartup)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* The web app's startup row over a REAL Loader tree carrying this bundle's
|
||||
* waiting row ids: flags reach the rows they configure, absent flags leave the
|
||||
* composed values standing, `--dev` enables the shipped-disabled HMR receiver,
|
||||
* and `--help` leaves the app unstarted.
|
||||
* The web app's entrypoint row over a REAL Loader tree: every flag lands in the
|
||||
* `webStartup` service the web rows read, the bind it reports comes from the
|
||||
* flag or from what the composition falls back to, `--help` resolves nothing,
|
||||
* and a rejected argument exits without resolving anything.
|
||||
*/
|
||||
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs'
|
||||
@@ -14,7 +14,7 @@ import Loader from '@cordisjs/plugin-loader'
|
||||
import Include from '@cordisjs/plugin-include'
|
||||
import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { apply, WEB_STARTUP_SERVICE } from '../src/startup.ts'
|
||||
import { apply, WEB_STARTUP_SERVICE, type WebStartupValues } from '../src/startup.ts'
|
||||
|
||||
vi.mock('node:os', async importOriginal => ({
|
||||
...await importOriginal<typeof import('node:os')>(),
|
||||
@@ -26,8 +26,6 @@ vi.mock('node:os', async importOriginal => ({
|
||||
|
||||
/** What one boot of the fixture tree observed. */
|
||||
interface Observed {
|
||||
/** Config each waiting row started with, by row id; absent means it never started. */
|
||||
started: Record<string, Record<string, unknown>>
|
||||
exits: number[]
|
||||
out: string
|
||||
}
|
||||
@@ -40,57 +38,57 @@ afterEach(async () => {
|
||||
internals.stderr = process.stderr
|
||||
})
|
||||
|
||||
/** One stand-in for a row this bundle's patch makes wait for the web startup. */
|
||||
interface WaitingRow {
|
||||
id: string
|
||||
config?: Record<string, unknown>
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
/** The waiting rows this bundle's patch declares, with the composed values they ship. */
|
||||
const WAITING_ROWS: WaitingRow[] = [
|
||||
{ id: 'webserver', config: { host: '127.0.0.1', port: 3080 } },
|
||||
{ id: 'api-gateway', config: { provider: 'deepseek-official' } },
|
||||
{ id: 'connection', config: { trustedHosts: ['configured.internal'] } },
|
||||
{ id: 'web-runtime', config: { mode: 'production', printUrl: true } },
|
||||
{ id: 'client-hmr', disabled: true },
|
||||
]
|
||||
|
||||
/**
|
||||
* Boot the real startup row over stand-ins for this bundle's waiting rows.
|
||||
* Mount the real entrypoint row over a stand-in for the `webserver` row whose
|
||||
* composed bind it reads, the way a profile mounts phase one.
|
||||
* @param args - the invocation's inner arguments.
|
||||
* @returns what the boot observed.
|
||||
* @param webserverConfig - the composed `webserver` row config, or `null` to omit the row.
|
||||
* @returns the resolved service value (absent when the app requested exit) and what the boot observed.
|
||||
*/
|
||||
async function bootStartup(args: string[], rows: readonly WaitingRow[] = WAITING_ROWS): Promise<Observed> {
|
||||
async function bootStartup(
|
||||
args: string[],
|
||||
webserverConfig: Record<string, unknown> | null = { host: '127.0.0.1', port: 3080 },
|
||||
): Promise<{ values: WebStartupValues | undefined; observed: Observed; ctx: Context }> {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-web-startup-'))
|
||||
const observed: Observed = { started: {}, exits: [], out: '' }
|
||||
writeFileSync(join(dir, 'row.mjs'), `
|
||||
export function apply(ctx, config) { globalThis.__webStartupObserved.started[ctx.fiber.entry.options.id] = config ?? {} }
|
||||
`)
|
||||
const observed: Observed = { exits: [], out: '' }
|
||||
writeFileSync(join(dir, 'row.mjs'), 'export function apply() {}\n')
|
||||
// The Loader imports a row through Node's own resolver, which cannot resolve
|
||||
// this workspace's sources; the row delegates to the real plugin the test
|
||||
// imported through the source-plane path mapping.
|
||||
writeFileSync(join(dir, 'startup-row.mjs'), `
|
||||
writeFileSync(join(dir, 'entrypoint.mjs'), `
|
||||
export const name = 'web-startup'
|
||||
export const inject = ['cmdlineArgs']
|
||||
export const apply = ctx => globalThis.__webStartupApply(ctx)
|
||||
`)
|
||||
const rowUrl = pathToFileURL(join(dir, 'row.mjs')).href
|
||||
const lines = rows.flatMap(row => [
|
||||
`- id: ${row.id}`,
|
||||
writeFileSync(join(dir, 'cordis.yml'), [
|
||||
...webserverConfig === null ? [] : [
|
||||
'- id: webserver',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' disabled: true',
|
||||
' config:',
|
||||
...Object.entries(webserverConfig).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`),
|
||||
],
|
||||
// A second reader keeps the composition honest when the webserver row is
|
||||
// the one under test: the service must still have someone to serve.
|
||||
'- id: web-runtime',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
...row.disabled === true ? [' disabled: true'] : [],
|
||||
...row.config === undefined ? [] : [' config:', ...Object.entries(row.config).map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)],
|
||||
])
|
||||
lines.push('- id: web-startup', ` name: ${pathToFileURL(join(dir, 'startup-row.mjs')).href}`)
|
||||
writeFileSync(join(dir, 'cordis.yml'), lines.join('\n') + '\n')
|
||||
' disabled: true',
|
||||
// The reload chain this bundle ships off, which `--dev` turns on.
|
||||
'- id: client-hmr',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' disabled: true',
|
||||
'- id: web-startup',
|
||||
` name: ${pathToFileURL(join(dir, 'entrypoint.mjs')).href}`,
|
||||
'',
|
||||
].join('\n'))
|
||||
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
|
||||
internals.stdout = observing
|
||||
internals.stderr = observing
|
||||
const globals = globalThis as unknown as { __webStartupObserved: Observed; __webStartupApply: typeof apply }
|
||||
globals.__webStartupObserved = observed
|
||||
globals.__webStartupApply = apply
|
||||
;(globalThis as unknown as { __webStartupApply: typeof apply }).__webStartupApply = apply
|
||||
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(Loader)
|
||||
@@ -99,65 +97,67 @@ export const apply = ctx => globalThis.__webStartupApply(ctx)
|
||||
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(join(dir, 'cordis.yml')).href } })
|
||||
await ctx.loader.await()
|
||||
disposers.push(async () => { await ctx.fiber.dispose() })
|
||||
return observed
|
||||
return { values: ctx.get(WEB_STARTUP_SERVICE) as WebStartupValues | undefined, observed, ctx }
|
||||
}
|
||||
|
||||
|
||||
describe('web startup', () => {
|
||||
it('applies each flag to the row that owns it and leaves the rest composed', async () => {
|
||||
const observed = await bootStartup(['--port', '8080', '--workspace-root', '/w'])
|
||||
expect(observed.started.webserver).toEqual({ host: '127.0.0.1', port: 8080 })
|
||||
expect(observed.started['api-gateway']).toEqual({ provider: 'deepseek-official', workspaceRoot: '/w' })
|
||||
expect(observed.started['web-runtime']).toEqual({ mode: 'production', printUrl: true, lanAddresses: [] })
|
||||
expect(observed.started['client-hmr']).toBeUndefined()
|
||||
expect(observed.exits).toEqual([])
|
||||
it('resolves each flag into the value its row reads', async () => {
|
||||
const { values } = await bootStartup(['--port', '8080', '--workspace-root', '/w'])
|
||||
expect(values).toEqual({
|
||||
port: 8080,
|
||||
workspaceRoot: '/w',
|
||||
mode: 'production',
|
||||
trustedHosts: [],
|
||||
lanAddresses: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('starts every row on its composed values when the invocation carries no flags', async () => {
|
||||
const observed = await bootStartup([])
|
||||
expect(observed.started.webserver).toEqual({ host: '127.0.0.1', port: 3080 })
|
||||
expect(observed.started.connection).toEqual({ trustedHosts: ['configured.internal'] })
|
||||
it('names no value for a flag the invocation left out, so each row keeps its own', async () => {
|
||||
const { values } = await bootStartup([])
|
||||
expect(values).toEqual({ mode: 'production', trustedHosts: [], lanAddresses: [] })
|
||||
expect(values).not.toHaveProperty('host')
|
||||
expect(values).not.toHaveProperty('port')
|
||||
})
|
||||
|
||||
it('adds the LAN literals over the configured fence authorities for an all-interfaces bind', async () => {
|
||||
const observed = await bootStartup(['--host', '0.0.0.0', '--trusted-host', 'lab.internal'])
|
||||
expect(observed.started.webserver).toEqual({ host: '0.0.0.0', port: 3080 })
|
||||
expect(observed.started.connection).toEqual({ trustedHosts: ['configured.internal', '192.168.1.5', 'lab.internal'] })
|
||||
it('derives the LAN literals for an all-interfaces bind, and the extras with them', async () => {
|
||||
const { values } = await bootStartup(['--host', '0.0.0.0', '--trusted-host', 'lab.internal'])
|
||||
expect(values?.trustedHosts).toEqual(['192.168.1.5', 'lab.internal'])
|
||||
// Display gets the same single sample the fence was configured with.
|
||||
expect(observed.started['web-runtime']).toEqual({ mode: 'production', printUrl: true, lanAddresses: ['192.168.1.5'] })
|
||||
expect(values?.lanAddresses).toEqual(['192.168.1.5'])
|
||||
})
|
||||
|
||||
it('enables the shipped-disabled HMR receiver for --dev', async () => {
|
||||
const observed = await bootStartup(['--dev'])
|
||||
expect(observed.started['client-hmr']).toEqual({})
|
||||
expect(observed.started['web-runtime']).toEqual({ mode: 'development', printUrl: true, lanAddresses: [] })
|
||||
it('reads the composed bind when no flag names one, so a configured 0.0.0.0 still derives them', async () => {
|
||||
const { values } = await bootStartup([], { host: '0.0.0.0', port: 3080 })
|
||||
expect(values?.lanAddresses).toEqual(['192.168.1.5'])
|
||||
})
|
||||
|
||||
it('prints its own help and starts nothing', async () => {
|
||||
const observed = await bootStartup(['--help'])
|
||||
it('reports the development mode for --dev, which the web runtime reads', async () => {
|
||||
const { values } = await bootStartup(['--dev'])
|
||||
// The runtime row is what turns the reload chain on, in the phase whose
|
||||
// host rows it needs; this row only reports the mode.
|
||||
expect(values?.mode).toBe('development')
|
||||
})
|
||||
|
||||
it('prints its own help and resolves nothing', async () => {
|
||||
const { values, observed } = await bootStartup(['--help'])
|
||||
expect(observed.out).toContain('dsh --profile web')
|
||||
expect(observed.out).toContain('--trusted-host')
|
||||
expect(observed.started).toEqual({})
|
||||
expect(values).toBeUndefined()
|
||||
expect(observed.exits).toEqual([0])
|
||||
})
|
||||
|
||||
it('fails the boot when the composition lost a row this app configures', async () => {
|
||||
// The bundle patch and this startup plugin must agree on the row set; a
|
||||
// missing row would otherwise silently drop the flag that targets it.
|
||||
const withoutWebserver = WAITING_ROWS.filter(row => row.id !== 'webserver')
|
||||
await expect(bootStartup([], withoutWebserver))
|
||||
.rejects.toThrow('the web composition has no waiting "webserver" row')
|
||||
})
|
||||
|
||||
it('derives the fence authorities alone when the composition configured none', async () => {
|
||||
const withoutTrust = WAITING_ROWS.map(row => row.id === 'connection' ? { id: 'connection' } : row)
|
||||
const observed = await bootStartup(['--host', '0.0.0.0'], withoutTrust)
|
||||
expect(observed.started.connection).toEqual({ trustedHosts: ['192.168.1.5'] })
|
||||
})
|
||||
|
||||
it('rejects a non-numeric port before anything binds', async () => {
|
||||
const observed = await bootStartup(['--port', 'abc'])
|
||||
const { values, observed } = await bootStartup(['--port', 'abc'])
|
||||
expect(observed.out).toContain('--port must be a number')
|
||||
expect(observed.started).toEqual({})
|
||||
expect(values).toBeUndefined()
|
||||
expect(observed.exits).toEqual([1])
|
||||
})
|
||||
|
||||
it('fails the boot when the composition lost the row whose bind it reads', async () => {
|
||||
// The bundle patch and this entrypoint must agree on the row set; a
|
||||
// missing row would otherwise silently drop the flag that targets it.
|
||||
await expect(bootStartup([], null))
|
||||
.rejects.toThrow('the web composition has no waiting "webserver" row to configure')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -131,6 +131,38 @@ describe('web-app runtime glue', () => {
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
it('waits for the launcher readiness the phased boot provides, and stays quiet when that boot failed', async () => {
|
||||
stageDist()
|
||||
// The launcher-provided readiness wins over Loader settlement: a phased
|
||||
// boot settles the Loader between phases, long before the app is up.
|
||||
const ready = new Context()
|
||||
ready.provide('httpServer', fakeHttpServer().server)
|
||||
ready.provide('loader', { await: () => Promise.resolve() } as never)
|
||||
let announce: () => void
|
||||
ready.provide('appReady', new Promise<void>((resolve) => { announce = resolve }))
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
apply(ready, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).not.toHaveBeenCalled()
|
||||
announce!()
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567')
|
||||
await ready.fiber.dispose()
|
||||
|
||||
// A boot that failed announces nothing: the launcher reports it, and a URL
|
||||
// for a process that is about to exit would only mislead.
|
||||
log.mockClear()
|
||||
const failed = new Context()
|
||||
failed.provide('httpServer', fakeHttpServer().server)
|
||||
const rejection = Promise.reject(new Error('boot failed'))
|
||||
rejection.catch(() => {})
|
||||
failed.provide('appReady', rejection)
|
||||
apply(failed, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).not.toHaveBeenCalled()
|
||||
await failed.fiber.dispose()
|
||||
})
|
||||
|
||||
it('defers the URL line until Loader settlement and drops it when the server is gone', async () => {
|
||||
stageDist()
|
||||
// Settlement path: the line waits for loader.await() so supervisors can
|
||||
|
||||
Reference in New Issue
Block a user