fix(app-boot): audit rejected entry options and isolate dump snapshots

This commit is contained in:
Shigma committed 2026-11-16 17:11:48 +08:00
1 parent a85b27fdd4
commit 897de8769b
16 files changed
+208 -57

No files matched your search

@@ -37,7 +37,7 @@
"boolean",
"null"
],
"description": "Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation."
"description": "Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation."
},
"disabled": {
"anyOf": [
@@ -249,6 +249,28 @@
{
"$ref": "#/$defs/entryMetadata"
},
{
"if": {
"properties": {
"group": {
"const": true
}
},
"required": [
"group"
]
},
"then": {
"properties": {
"config": {
"$ref": "#/$defs/entryList"
}
},
"required": [
"config"
]
}
},
{
"if": {
"properties": {
+1 -1
View File
@@ -28,7 +28,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:58`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` |
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
| `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` |
+1 -1
View File
@@ -30,7 +30,7 @@
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:56`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:58`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` |
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
| `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` |
@@ -9,8 +9,8 @@
en: cf5dc11adadfd1e1
zh: 4656ed9a0d4e9087
/loader-validates-entry-options-and-include-parses-yaml-1-2/change:
en: b345762ab470b57b
zh: 0f931faf28da0d27
en: 3a403b763d8059c8
zh: cbbdd8c71474130e
/loader-validates-entry-options-and-include-parses-yaml-1-2/migration:
en: ff01b0eddb91d5b1
zh: 81478d5e1594db65
@@ -12,7 +12,7 @@ English | [中文](guide.zh.md)
`@deepseek-ai/cordis-plugin-loader` now carries upstream Loader 1.0.0-rc.9, and `@deepseek-ai/cordis-plugin-include` carries Include 1.2.0. Hand-written `cordis.yml`, `cordis.patch.yml` and overlay files, and code that calls the Include or Loader exports, are affected:
- Include and `parseEntryYaml` parse YAML 1.2 under the core schema instead of the js-yaml JSON schema. A binary integer such as `0b101` now reads as the string `'0b101'`. An empty `!!js` scalar now reads as an empty expression, which evaluates to `undefined`, instead of failing to parse.
- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` must have a `config` list, even an empty one; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and logged, and its siblings still start. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted.
- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; an entry with `group: true` must have a `config` list, even an empty one; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and its siblings still start; `dsh` stops startup when the rejected entry is required, such as `webserver`, and warns otherwise. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted.
- Parse, entry option and config validation errors name the file position as `file:line:column`. When an entry's own module cannot be found, the error is a `ModuleNotFoundError` without Node's `imported from` part; its `code` is still `ERR_MODULE_NOT_FOUND`.
- A patch that replaces a group's `config` brings child entries that later patches can address, and the children it replaces can no longer be patched.
- `applyEntryPatches(data, patches, warn)` returns `{ data, index }` instead of the entry list, and writes generated ids into the anonymous entries of a replaced group `config` in `patches`. `parseEntryYaml` throws the `YAMLError` of the `yaml` package instead of a js-yaml `YAMLException`.
@@ -12,7 +12,7 @@ description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、
`@deepseek-ai/cordis-plugin-loader` 现在包含上游 Loader 1.0.0-rc.9,`@deepseek-ai/cordis-plugin-include` 包含 Include 1.2.0。受影响的是手写的 `cordis.yml`、`cordis.patch.yml` 与 overlay 文件,以及调用 Include 或 Loader 导出的代码:
- Include 和 `parseEntryYaml` 按 YAML 1.2 core schema 解析,不再使用 js-yaml 的 JSON schema。`0b101` 这样的二进制整数现在读作字符串 `'0b101'`。空的 `!!js` 标量现在读作空表达式,求值结果为 `undefined`,不再解析失败。
- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;`group: true` 的条目必须带有 `config` 列表,空列表也要写出;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝并记录日志,同级条目仍会启动。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。
- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;`group: true` 的条目必须带有 `config` 列表,空列表也要写出;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝,同级条目仍会启动;被拒绝的条目若是 `webserver` 等必需条目,`dsh` 会终止启动,否则输出警告。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。
- 解析错误、条目选项错误和配置校验错误都会以 `file:line:column` 指出文件位置。条目自身的模块找不到时,错误为 `ModuleNotFoundError`,不含 Node 的 `imported from` 部分;其 `code` 仍为 `ERR_MODULE_NOT_FOUND`。
- 替换 group `config` 的 patch 带来的子条目可以被后续 patch 定位,被替换掉的子条目则不能再被 patch。
- `applyEntryPatches(data, patches, warn)` 返回 `{ data, index }`,不再直接返回条目列表;它会把生成的 id 写入 `patches` 中被替换的 group `config` 里的匿名条目。`parseEntryYaml` 抛出 `yaml` 包的 `YAMLError`,不再抛出 js-yaml 的 `YAMLException`。
+2 -2
View File
@@ -36,8 +36,8 @@
en: 91d80c444ac0cfe5
zh: e7db496043528ffb
/deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures:
en: 9b9e08c8638a975b
zh: 8a3f906c4d98cb89
en: 53a9bfee48468abe
zh: 34d36ae0e46d8e49
/deepseek-ai-dsh-app-boot/understand-the-implementation:
en: f4a2695cb4c8a570
zh: 89837235d2f376cf
+1 -1
View File
@@ -97,7 +97,7 @@ The profile templates, installation-owned profile tuples, and retired bundle lis
Profile reconciliation returns diagnostics for unchanged inactive entries without failing an unrelated mutation. A new inactive entry, a changed configuration or fiber, or a changed diagnostic fails reconciliation; removed fibers must still finish disposal. Explicit enablement targets must activate even when their failure predates the operation. `recomposeProfile(ctx, patches, binName, { requiredIds, running })` runs one recomposition together with the runtime resolution: it removes the rows the generation no longer lists and waits for their disposal while their packages are still mapped, publishes the latest generation of a recomputable resolution, runs the compatibility preflight against the published packages, applies the generation, starts the `running` entries and entries whose import failed that the update left without a running fiber, and judges activation. `running` lists the entries that ran before the caller stopped some of them; each that failed afterwards counts as a new failure. A failure before the generation applies puts the removed rows back at their places, which starts them again, and starts the `running` entries again. An entry waiting for a service is reported as a warning unless it is required, so it starts once a provider appears; `reconcileProfilePatches()` judges it the same way. A publication the resolution rejects is such a failure and reports `package-moved`. `reconcileProfilePatches()`, which the Config Editor uses, applies and judges the patches without publishing the resolution or retrying failed imports. An entry whose import failed is reported with the error Loader's import returns again, so judging it evaluates the module when the import now succeeds; the state recorded before the change imports nothing, so an entry whose import failed before counts as the same failure whatever its error now is. Successful reconciliation emits `app-boot/config-reload` after lifecycle settlement and diagnostic checks, including programmatic updates without HMR. The event carries no diff or parsed config. Successful reconciliation returns after lifecycle settlement and diagnostic checks; volatile-only entry changes are committed by Loader during the update.
After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update.
After the Loader settles, app-boot warns when only optional entries are inactive. If an enabled required entry cannot activate, `boot()` rejects with `StartupError` after disposal. Entry options that their group rejects count as an entry that could not activate, with the Loader's validation issues and source positions as its error. An independently owned logger exporter retains warning and error records through asynchronous disposal and is released before `boot()` settles. Its message groups all failed plugins and pending services, marks required entries, and retains original stacks, nested causes, and aggregate members. The CLI prints that message once and saves [full startup diagnostics](../../../apps/cli/reference/README.md#startup-diagnostics) before exiting with code 1; unrelated exceptions retain their normal stack output. In the table, stopping startup means disposing any mounted plugins and exiting nonzero without reporting readiness; continuing keeps successful plugins running. Later configuration HMR does not repeat the required-startup audit and does not roll back the whole update.
| Failure pattern | Optional entry at startup | Required entry at startup | Later configuration HMR |
|---|---|---|---|
+1 -1
View File
@@ -97,7 +97,7 @@ app-boot 应用的 profile 模板、安装方拥有的 profile 组合包元组
profile 重载返回未变化的已有故障诊断,不让无关修改因此失败。新增未激活条目、配置或 fiber 变化、诊断变化都会使重载失败;被移除的 fiber 仍须完成释放。显式启用的目标必须成功激活,即使它的故障早于本次操作。`recomposeProfile(ctx, patches, binName, { requiredIds, running })` 与 runtime resolution 一起执行一次重新组合:它移除新一代组合不再列出的行,并在其包仍有映射时等待这些行释放完成,发布可重新计算的 resolution 的最新一代,使兼容性预检读取已发布的包,应用新一代组合,启动更新后没有运行中 fiber 的 `running` 条目和导入失败的条目,然后判定激活结果。`running` 列出调用方停止其中部分条目之前正在运行的条目;之后每个失败的条目都计为新的故障。新一代组合应用之前的失败会把移除的行放回原位置,从而重新启动它们,并重新启动 `running` 条目。等待服务的条目报告为警告(required 条目除外),因此出现提供方后它即启动;`reconcileProfilePatches()` 以同样方式判定它。resolution 拒绝的发布属于这种失败,并报告 `package-moved`。Config Editor 使用的 `reconcileProfilePatches()` 应用并判定 patch,不发布 resolution,也不重试失败的导入。导入失败的条目以 Loader 再次导入时返回的错误报告,因此若导入现在成功,判定该条目时会对模块求值;变更前记录的激活状态不执行任何导入,因此之前导入失败的条目无论现在的错误是什么,都计为同一个故障。成功重载在生命周期结束及诊断检查通过后发出 `app-boot/config-reload`,包括未启用 HMR 时的程序化更新。事件不携带 diff 或解析后的配置。成功重载在生命周期结束及诊断检查通过后返回;仅 volatile 的条目变化由 Loader 在更新过程中提交。
Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。
Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如果已启用的 required 条目无法激活,`boot()` 会在释放资源后以 `StartupError` 拒绝。被所在 group 拒绝的条目选项也视为无法激活的条目,其错误是 Loader 的校验问题及源码位置。独立管理生命周期的 logger exporter 会保留异步资源释放期间的警告和错误记录,并在 `boot()` 结算前释放。其消息分组列出所有失败插件和等待的服务,标记 required 条目,并保留原始堆栈、嵌套原因和聚合错误成员。CLI 仅输出该消息一次,并在保存[完整启动诊断](../../../apps/cli/reference/README.zh.md#startup-diagnostics)后以退出码 1 结束;其他异常保留正常堆栈输出。表中的“终止启动”指释放已挂载插件并以非零码退出,不报告就绪;“继续”指保留成功运行的插件。后续配置 HMR 不会再次执行 required 启动审计,也不会回滚整个更新。
| 失败模式 | Optional 条目启动时 | Required 条目启动时 | 后续配置 HMR |
|---|---|---|---|
@@ -13,7 +13,7 @@ function metadata(): Record<string, ConfigJsonSchema> {
id: { type: 'string', description: 'Entry id. Loader generates an id when an entry omits it; patches use the configured id.' },
name: { type: 'string', description: 'Plugin module specifier. Inserted relative plugin paths are anchored beside their patch file.' },
config: {},
group: { type: ['boolean', 'null'], description: 'Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation.' },
group: { type: ['boolean', 'null'], description: 'Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation.' },
disabled: { anyOf: [{ type: ['boolean', 'null'] }, ref('loaderExpression')], description: 'Boolean or !!js expression. The Loader coerces other truthy values as disabled; this schema rejects them.' },
inject: { anyOf: [{ type: 'array', items: { type: 'string' } }, { type: 'object' }, { type: 'null' }] },
intercept: { type: ['object', 'null'] },
@@ -129,8 +129,13 @@ export async function buildConfigSchemaDocument(
diagnostics.push({ level: 'warning', message: `Plugin ${JSON.stringify(name)} has multiple collected schemas; entry validation accepts their union because module resolution depends on the owning tree.` })
}
}
// The Loader rejects a group entry without an entry-list config, disabled or not.
const groupRule: ConfigJsonSchema = {
if: { properties: { group: { const: true } }, required: ['group'] },
then: { properties: { config: ref('entryList') }, required: ['config'] },
}
definitions.entry = {
type: 'object', required: ['name'], allOf: [ref('entryMetadata'), ...entryRules],
type: 'object', required: ['name'], allOf: [ref('entryMetadata'), groupRule, ...entryRules],
description: 'Loader entry. Unknown metadata and plugin names are accepted; plugin-specific validation is available only for the names collected in this profile. Distinct resolutions of one name use a union of their schemas.',
}
+90 -39
View File
@@ -13,7 +13,9 @@ import { captureStartupComposition, type StartupCompositionDiagnostic } from './
export type { StartupCompositionDiagnostic, StartupPluginState, StartupServiceState } from './startup-diagnostics.ts'
import { basename, dirname, isAbsolute, resolve } from 'node:path'
import { Context, type Fiber, type FiberState } from '@deepseek-ai/cordis'
import Loader, { type Entry, type EntryGroup, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
import Loader, {
EntryTree, EntryValidationError, formatIssues, relocate, validateOptions, type Entry, type EntryGroup, type EntryOptions,
} from '@deepseek-ai/cordis-plugin-loader'
import Include, { applyEntryPatches, parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import Group from '@deepseek-ai/cordis-plugin-group'
import { dshHomePath, dshPath, resolveDshHome } from '@deepseek-ai/dsh-home-paths'
@@ -349,9 +351,10 @@ async function recompose(
if (entry === undefined) throw new Error(`${binName}: profile reload requires the root Include entry`)
// Reading the prior state imports nothing, so plugin code does not run before the next resolution publishes.
const previousFailures = (await inactiveEntries(ctx, false)).map((failure): RecordedFailure => ({
entry: failure.entry, fiber: failure.entry.fiber, options: JSON.stringify(failure.entry.options),
entry: failure.entry, fiber: failure.entry?.fiber, options: JSON.stringify(failure.options),
// An entry without a running fiber has no import error yet; the judgment after the update reads it.
diagnostic: failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined,
// Rejected options have no entry, and their diagnostic depends only on the options.
diagnostic: failure.entry === undefined || failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined,
}))
// Removed entries leave the Loader store before their async disposers finish.
const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [row.fiber])
@@ -410,11 +413,11 @@ async function recompose(
await ctx.loader.await()
const failures = await inactiveEntries(ctx)
const introduced = failures.filter((failure) => {
if (requiredIds.includes(failure.entry.options.id)) return true
if (requiredIds.includes(failure.id)) return true
// An entry waiting for a service starts once a provider appears.
if (failure.outcome.kind === 'pending') return false
// An entry that ran before the caller stopped it is a new failure even when it failed the same way before.
if (running.includes(failure.entry)) return true
if (failure.entry !== undefined && running.includes(failure.entry)) return true
return !previousFailures.some(previous => sameFailure(previous, failure))
})
if (introduced.length > 0) throw new Error(activationDiagnostic(binName, introduced, false).trimEnd())
@@ -435,7 +438,7 @@ async function recompose(
// A restored row is a new Loader entry with the id of the one that ran.
const ran = new Set(running.map(row => row.options.id))
for (const failure of await inactiveEntries(ctx)) {
if (ran.has(failure.entry.options.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`)
if (ran.has(failure.id)) ctx.logger.warn(`${binName}: ${reloadDiagnostic(failure)}`)
}
} catch (error) {
// The recomposition's own failure is the outcome.
@@ -447,7 +450,7 @@ async function recompose(
/** An inactive entry as a recomposition found it before changing anything. */
interface RecordedFailure {
entry: Entry
entry: Entry | undefined
fiber: Fiber | undefined
/** The entry's options as JSON. */
options: string
@@ -457,8 +460,8 @@ interface RecordedFailure {
/** Whether an inactive entry is the failure recorded before: the same entry, fiber and options, and a matching diagnostic. */
function sameFailure(previous: RecordedFailure, failure: InactiveEntry): boolean {
return previous.entry === failure.entry && previous.fiber === failure.entry.fiber
&& previous.options === JSON.stringify(failure.entry.options)
return previous.entry === failure.entry && previous.fiber === failure.entry?.fiber
&& previous.options === JSON.stringify(failure.options)
&& (previous.diagnostic === undefined || previous.diagnostic === reloadDiagnostic(failure))
}
@@ -670,15 +673,17 @@ export function renderConfigDump(
const base = parsed as Parameters<typeof applyEntryPatches>[0]
// snapshot_k = ONE application of layers 1..k flattened, using the exact
// arguments boot passes for that prefix. snapshot_N is the mounted composition.
// Every snapshot reads one clone of the patches: applyEntryPatches writes the
// ids it generates for anonymous children of a replaced group config into
// that clone, so each prefix assigns them the same ids. The snapshots share
// override values by reference and only read them.
// applyEntryPatches writes the ids it generates for anonymous children of a
// replaced group config onto those patch entries, so one full composition
// assigns them first and every prefix reuses them. Composition holds a
// supplied `config` array by reference and appends later inserts to it, so
// that run reads copies of the arrays, and each snapshot composes its own clone.
const patches = structuredClone(layers.flatMap(layer => layer.patches))
applyEntryPatches(base, patches.map(patch => Array.isArray(patch.config) ? { ...patch, config: patch.config.slice() } : patch))
const ends: number[] = []
for (const layer of layers) ends.push((ends.at(-1) ?? 0) + layer.patches.length)
const snapshot = (count: number, warnings: string[]): ReturnType<typeof applyEntryPatches>['data'] => {
return applyEntryPatches(base, patches.slice(0, ends[count - 1]), (message: string, ...args: unknown[]) => {
return applyEntryPatches(base, structuredClone(patches.slice(0, ends[count - 1])), (message: string, ...args: unknown[]) => {
// The include logs through cordis's printf-style logger (`%C` = code); a
// dump has no logger, so substitute inline for a plain line.
let index = 0
@@ -993,8 +998,14 @@ function formatActivationError(error: unknown, stacks = true): string {
}
interface InactiveEntry {
/** Loader entry used to identify the bootstrap Include and required ids. */
entry: Entry
/** Loader entry used to identify the bootstrap Include; absent for options their group rejected before creating one. */
entry: Entry | undefined
/** Entry id used for required ids, or `(no id)` for rejected options without a string id. */
id: string
/** Module specifier; for rejected options, a non-string `name` rendered as JSON. */
name: string
/** The options the group lists for this entry. */
options: unknown
/** Activation errors and missing services remain distinct for presentation. */
outcome: { kind: 'failed'; error: unknown; phase?: string }
| { kind: 'pending'; missing: string[] }
@@ -1049,8 +1060,45 @@ async function importFailure(entry: Entry): Promise<unknown> {
}
}
/** Identity fields of an inactive Loader entry. */
function identify(entry: Entry): Pick<InactiveEntry, 'entry' | 'id' | 'name' | 'options'> {
return { entry, id: entry.options.id, name: entry.options.name, options: entry.options }
}
/** Groups whose option lists the Loader reconciled: the root group and those of active group and Include entries. */
function activeGroups(ctx: Context): EntryGroup[] {
const groups = [ctx.loader.root]
for (const entry of ctx.loader.entries()) {
if (entry.subgroup !== undefined && entry.fiber?.state === FIBER_ACTIVE) groups.push(entry.subgroup)
}
return groups
}
/**
* Collect Loader activation failures and disabled-expression errors. Failed
* Options that a group lists but rejected before creating an entry, checked with the Loader's own rule.
* The group only logs such a rejection, so each one is reported here with its source position when its tree has one.
*/
function rejectedOptions(ctx: Context): InactiveEntry[] {
return activeGroups(ctx).flatMap(group => group.data.flatMap((options: unknown): InactiveEntry[] => {
const issues = validateOptions(options, EntryTree.sep)
if (issues.length === 0) return []
const row: { id?: unknown; name?: unknown } = typeof options === 'object' && options !== null ? options : {}
const id = typeof row.id === 'string' ? row.id : undefined
const error = new EntryValidationError(issues)
// Source positions are found by id, so options without one keep the plain message.
if (id !== undefined) {
const frames = group.getOuterStack(id)
if (frames.length > 0) relocate(error, formatIssues('invalid entry options', issues, path => group.tree.getLocation(id, path)), frames)
}
return [{
entry: undefined, id: id ?? '(no id)', name: typeof row.name === 'string' ? row.name : row.name === undefined ? 'undefined' : JSON.stringify(row.name),
options, outcome: { kind: 'failed', error, phase: 'invalid entry options' },
}]
}))
}
/**
* Collect Loader activation failures, disabled-expression errors and options their group rejected. Failed
* fibers are awaited to recover their recorded rejection reason and coalesce
* duplicate Loader notifications through the next process rejection checkpoint.
* An entry whose import failed reports the error importing it raises now; without
@@ -1063,14 +1111,14 @@ async function inactiveEntries(ctx: Context, importNow = true): Promise<Inactive
try {
if (entry.disabled) continue
} catch (error) {
failures.push({ entry, outcome: { kind: 'failed', error, phase: 'disabled expression failed' } })
failures.push({ ...identify(entry), outcome: { kind: 'failed', error, phase: 'disabled expression failed' } })
continue
}
const fiber = entry.fiber
// An entry whose import failed has no fiber, or keeps the disposed fiber of its previous activation.
if (fiber === undefined || fiber.state === FIBER_DISPOSED) {
const error = importNow ? await importFailure(entry) : undefined
failures.push({ entry, outcome: error === undefined
failures.push({ ...identify(entry), outcome: error === undefined
? { kind: 'failed', error: fiber === undefined ? 'failed to import' : `fiber state ${String(fiber.state)}` }
: { kind: 'failed', error, phase: 'failed to import' } })
continue
@@ -1082,20 +1130,21 @@ async function inactiveEntries(ctx: Context, importNow = true): Promise<Inactive
await fiber.await()
} catch (error) {
rejectionReasons.push(error)
failures.push({ entry, outcome: { kind: 'failed', error } })
failures.push({ ...identify(entry), outcome: { kind: 'failed', error } })
}
continue
}
if (state === FIBER_PENDING) {
const missing = Object.keys(fiber.inject).filter(service => fiber.ctx.get(service) === undefined)
failures.push({
entry,
...identify(entry),
outcome: { kind: 'pending', missing },
})
} else {
failures.push({ entry, outcome: { kind: 'failed', error: `fiber state ${String(state)}` } })
failures.push({ ...identify(entry), outcome: { kind: 'failed', error: `fiber state ${String(state)}` } })
}
}
failures.push(...rejectedOptions(ctx))
if (rejectionReasons.length > 0) await observeLoaderRejectionCheckpoint(rejectionReasons)
return failures
}
@@ -1121,31 +1170,31 @@ function reloadDiagnostic(failure: InactiveEntry): string {
}
/** Stable per-entry text for reload comparisons and optional warnings. */
function inactiveDiagnostic({ entry, outcome }: InactiveEntry, stacks = true): string {
function inactiveDiagnostic({ id, name, outcome }: InactiveEntry, stacks = true): string {
const detail = outcome.kind === 'failed' ? failureDetail(outcome, stacks)
: `pending (waiting for ${outcome.missing.length === 1 ? 'service' : 'services'}: ${outcome.missing.join(', ') || 'unknown'})`
return `${entry.options.id} (${entry.options.name}): ${detail}`
return `${id} (${name}): ${detail}`
}
/** Group startup failures and pending services, marking every required entry. */
function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], required: ReadonlySet<Entry>): string {
function startupDiagnostic(binName: string, failures: readonly InactiveEntry[], required: ReadonlySet<InactiveEntry>): string {
const lines = [`${binName}: startup failed: ${String(required.size)} required ${required.size === 1 ? 'plugin' : 'plugins'} did not activate`]
const failed = failures.flatMap(({ entry, outcome }) => outcome.kind === 'failed' ? [{ entry, outcome }] : [])
const pending = failures.flatMap(({ entry, outcome }) => outcome.kind === 'pending' ? [{ entry, outcome }] : [])
pending.sort((left, right) => Number(required.has(right.entry)) - Number(required.has(left.entry)))
const label = (entry: Entry): string => `${entry.options.id}${required.has(entry) ? ' (required)' : ''}`
const failed = failures.flatMap(failure => failure.outcome.kind === 'failed' ? [{ failure, outcome: failure.outcome }] : [])
const pending = failures.flatMap(failure => failure.outcome.kind === 'pending' ? [{ failure, outcome: failure.outcome }] : [])
pending.sort((left, right) => Number(required.has(right.failure)) - Number(required.has(left.failure)))
const label = (failure: InactiveEntry): string => `${failure.id}${required.has(failure) ? ' (required)' : ''}`
if (failed.length > 0) {
lines.push('', `Failed plugins (${String(failed.length)}):`)
for (const { entry, outcome } of failed) {
lines.push(` ${label(entry)}`, ` Package: ${entry.options.name}`)
for (const { failure, outcome } of failed) {
lines.push(` ${label(failure)}`, ` Package: ${failure.name}`)
lines.push(...failureDetail(outcome).split('\n').map(line => ` ${line}`))
}
}
if (pending.length > 0) {
const width = Math.max('Plugin'.length, ...pending.map(({ entry }) => label(entry).length)) + 2
const width = Math.max('Plugin'.length, ...pending.map(({ failure }) => label(failure).length)) + 2
lines.push('', `Plugins waiting for services (${String(pending.length)}):`, ` ${'Plugin'.padEnd(width)}Missing services`)
for (const { entry, outcome } of pending) {
lines.push(` ${label(entry).padEnd(width)}${outcome.missing.join(', ') || 'unknown'}`)
for (const { failure, outcome } of pending) {
lines.push(` ${label(failure).padEnd(width)}${outcome.missing.join(', ') || 'unknown'}`)
}
}
return lines.join('\n')
@@ -1154,7 +1203,8 @@ function startupDiagnostic(binName: string, failures: readonly InactiveEntry[],
/**
* Apply DSH startup policy to a settled Loader tree.
*
* Inactive entries from the global required list reject startup. Other
* Inactive entries from the global required list reject startup, including
* options that their group rejected before creating an entry. Other
* inactive entries join that failure diagnostic, or produce one warning when
* no required entry failed and leave successful siblings running.
* Required ids absent from the tree, and disabled required entries, are ignored.
@@ -1173,11 +1223,12 @@ export async function auditStartupEntries(
warn: (line: string) => void = line => void process.stderr.write(line),
): Promise<void> {
const failures = await inactiveEntries(ctx)
const required = new Set(failures.filter(({ entry }) => entry === bootstrapIncludes.get(ctx)
|| requiredStartupEntryIds.has(entry.options.id)).map(({ entry }) => entry))
const required = new Set(failures.filter(failure => (failure.entry !== undefined && failure.entry === bootstrapIncludes.get(ctx))
|| requiredStartupEntryIds.has(failure.id)))
if (required.size > 0) {
throw new StartupError(startupDiagnostic(binName, failures, required), failures.map(({ entry, outcome }) => ({
id: entry.options.id, module: entry.options.name, required: required.has(entry), fiberState: entry.fiber?.state, outcome,
throw new StartupError(startupDiagnostic(binName, failures, required), failures.map(failure => ({
id: failure.id, module: failure.name, required: required.has(failure),
fiberState: failure.entry?.fiber?.state, outcome: failure.outcome,
})))
}
if (failures.length > 0) warn(activationDiagnostic(binName, failures))
+34 -4
View File
@@ -25,6 +25,13 @@ const tmp = (): string => {
return dir
}
/** Give a fake Loader the root group that the startup audit reads for rejected options. */
function withRoot(ctx: Context, rows: unknown[] = []): Context {
const root = { data: rows, getOuterStack: () => [] }
Object.assign(ctx.loader, { root })
return ctx
}
describe('resolveConfigPath', () => {
it('resolves relative to the given cwd outside replay mode', () => {
expect(resolveConfigPath('./cordis.yml', undefined, `${sep}base`)).toBe(resolve(`${sep}base`, 'cordis.yml'))
@@ -484,7 +491,7 @@ describe('installFailLoud', () => {
installFailLoud(NAME, proc)
const error = new Error('assembled activation failure')
const warn = vi.fn()
const audit = auditStartupEntries({
const audit = auditStartupEntries(withRoot({
loader: {
entries: () => ['broken-a', 'broken-b'].map(name => ({
options: { id: name, name },
@@ -496,7 +503,7 @@ describe('installFailLoud', () => {
},
})),
},
} as unknown as Context, NAME, warn)
} as unknown as Context), NAME, warn)
await Promise.resolve()
await Promise.resolve()
proc.rejection(error)
@@ -631,9 +638,9 @@ describe('auditStartupEntries', () => {
parent?: { tree: { import(name: string): Promise<unknown> } }
}
const ctxWith = (entries: FakeEntry[]): Context => ({
const ctxWith = (entries: FakeEntry[], rows: unknown[] = []): Context => withRoot(({
loader: { entries: () => entries.values() },
}) as unknown as Context
}) as unknown as Context, rows)
const fiber = (
state: number,
@@ -792,6 +799,29 @@ describe('auditStartupEntries', () => {
expect(warn).not.toHaveBeenCalled()
})
it('fails startup for required options their group rejected and lists optional ones', async () => {
const error = await auditStartupEntries(ctxWith([], [
{ id: 'webserver', name: './webserver.mjs', disabled: 'yes' },
{ id: 'tool-todo', name: 7 },
{ id: 'valid', name: './valid.mjs' },
]), NAME, vi.fn()).catch((error: unknown) => error)
expect(error).toBeInstanceOf(StartupError)
const message = (error as Error).message
expect(message).toContain(`${NAME}: startup failed: 1 required plugin did not activate`)
expect(message).toContain(' webserver (required)\n Package: ./webserver.mjs\n invalid entry options: EntryValidationError: invalid entry options:\n - disabled must be a boolean (at disabled)')
expect(message).toContain(' tool-todo\n Package: 7\n')
expect(message).not.toContain('valid.mjs')
expect((error as StartupError).entries.map(entry => [entry.id, entry.required, entry.fiberState])).toEqual([
['webserver', true, undefined], ['tool-todo', false, undefined],
])
})
it('warns about rejected options without an id', async () => {
const warn = vi.fn()
await auditStartupEntries(ctxWith([], [null]), NAME, warn)
expect(warn).toHaveBeenCalledWith(expect.stringContaining('(no id) (undefined): invalid entry options:'))
})
it('omits an error cause when required plugins are only waiting for services', async () => {
const error = await auditStartupEntries(ctxWith([
{ fiber: fiber(0, undefined, { webStartup: {} }), options: { id: 'connection', name: './connection.mjs' } },
@@ -157,6 +157,19 @@ describe('renderConfigDump', () => {
expect(patches).toEqual([{ id: 'g', config: [{ name: './noop.mjs' }] }])
})
it('keeps each layer\'s snapshot when a later layer inserts into a config array an earlier layer supplied', () => {
const dir = tmp()
const base = join(dir, 'base.yml')
writeFileSync(base, '- id: x\n name: ./group.mjs\n')
const dump = renderConfigDump(NAME, base, [
{ label: 'a.yml', patches: [{ id: 'x', config: [] }] },
{ label: 'b.yml', patches: [{ id: 'x', group: true }] },
{ label: 'c.yml', patches: [{ id: 'x', insert: [{ id: 'child', name: './noop.mjs' }] }] },
], () => {})
expect((parseEntryYaml(dump) as { config: unknown[] }[])[0]!.config).toEqual([{ id: 'child', name: './noop.mjs' }])
expect(dump).toContain('# == base.yml, patched by a.yml, b.yml, c.yml\n- id: x')
})
it('drops the children of a replaced group config from the patch index', () => {
const dir = tmp()
const base = join(dir, 'base.yml')
@@ -467,6 +467,16 @@ describe('collectConfigSchemas', () => {
}
})
it('requires an entry-list config on every group: true entry, as the Loader does', async () => {
const result = await collectConfigSchemas(profile, [row('noop')], resolution)
expect(validates(result, [{ name: 'noop', group: true, config: [] }])).toBe(true)
expect(validates(result, [{ name: 'noop', group: false }])).toBe(true)
for (const value of [{ name: 'noop', group: true }, { name: 'noop', group: true, config: {} }, { name: 'noop', group: true, disabled: true }]) {
expect(validates(result, [value])).toBe(false)
}
expect(validates(result, [{ id: 'g', config: [] }], 'patchList')).toBe(true)
})
it('allows disabled config omission without disabling group:true or supplied-config validation', async () => {
modules.set('required', { Config: Schema.string().required() })
const result = await collectConfigSchemas(profile, [row('required')], resolution)
@@ -18,6 +18,7 @@ import {
loadOverlayPatches,
PROFILE_PATCH_FILENAME,
reconcileProfilePatches,
StartupError,
} from '../src/index.ts'
const NAME = 'dsh-test-bin'
@@ -348,6 +349,25 @@ describe('profile reconciliation settlement', () => {
expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual([expect.stringMatching(diagnostic)])
})
it('fails startup for a required row whose options the Loader rejects, at its source position', async () => {
const dir = tmp()
writeFileSync(join(dir, 'cordis.yml'), '- id: webserver\n name: ./webserver.mjs\n disabled: maybe\n')
const error = await boot(NAME, join(dir, 'cordis.yml')).catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(StartupError)
expect((error as Error).message).toContain(' webserver (required)\n Package: ./webserver.mjs')
expect((error as Error).message).toContain(`disabled must be a boolean (at disabled, ${join(dir, 'cordis.yml')}:3:13)`)
})
it('rejects a recomposition that introduces rows the Loader rejects', async () => {
const dir = tmp()
writeFileSync(join(dir, 'cordis.yml'), '[]\n')
const ctx = await boot(NAME, join(dir, 'cordis.yml'))
onTestFinished(() => ctx.fiber.dispose())
const patches = [{ insert: [{ id: 'bad-group', name: 'cordis:group', group: true }] }]
await expect(reconcileProfilePatches(ctx, patches, NAME)).rejects
.toThrow('bad-group (cordis:group): invalid entry options: EntryValidationError: invalid entry options:\n - config is required (at config)')
})
it('rejects a context without the launcher root Include', async () => {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
@@ -17,7 +17,7 @@ async function setup(options: { origin?: string; ssh?: 'SSH_CONNECTION' | 'SSH_T
{ source: 'process', values: options.ssh === undefined ? {} : { [options.ssh]: 'remote-launch' } },
{ source: 'project-env', path: '/project/.env', values: { SSH_TTY: 'project-setting' } },
]))
if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [] } as never)
if (options.settle !== undefined) ctx.provide('loader', { await: options.settle, entries: () => [], root: { data: [] } } as never)
const server: Pick<WebServer, 'host' | 'protocol' | 'registerFallback'> = {
host: '127.0.0.1', protocol: 'http:', registerFallback: () => () => {},
}