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:
@@ -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