web-failure-matrix.expected.e2e.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /** Failure policy through the built Web process and native configuration watcher. */
  2. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { createServer } from 'node:http'
  5. import { join } from 'node:path'
  6. import { fileURLToPath, pathToFileURL } from 'node:url'
  7. import { execa } from 'execa'
  8. import { describe, expect, it } from 'vitest'
  9. import { FiberState } from '@deepseek-ai/cordis'
  10. const repoRoot = fileURLToPath(new URL('../../../../../../', import.meta.url))
  11. const bin = join(repoRoot, 'apps/cli/lib/bin.js')
  12. const built = existsSync(bin) && existsSync(join(repoRoot, 'apps/web/dist/index.html'))
  13. const failures = [
  14. ['import', 'missing.mjs'],
  15. ['module evaluation', 'matrix module evaluation'],
  16. ['schema', 'matrix schema failure'],
  17. ['config expression', 'matrix config expression'],
  18. ['disabled expression', 'matrix disabled expression'],
  19. ['sync apply', 'matrix sync apply'],
  20. ['async apply', 'matrix async apply'],
  21. ['dependency', 'matrixMissingService'],
  22. ] as const
  23. type Failure = typeof failures[number][0]
  24. function fixture() {
  25. const root = mkdtempSync(join(tmpdir(), 'dsh-web-failure-matrix-'))
  26. const home = join(root, 'home')
  27. mkdirSync(home)
  28. const events = join(root, 'events')
  29. const diagnostics = join(root, 'diagnostics')
  30. const serverUrl = join(root, 'server-url')
  31. const states = join(root, 'states')
  32. const stop = join(root, 'stop')
  33. const patch = join(home, 'cordis.patch.yml')
  34. const watcher = join(root, 'watcher.patch.yml')
  35. // Native delivery remains real; completed writes bypass Chokidar's 50 ms change suppression.
  36. writeFileSync(watcher, JSON.stringify([{ id: 'hmr', disabled: false, config: {
  37. root: [], awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 20 },
  38. } }]) + '\n')
  39. writeFileSync(events, '')
  40. writeFileSync(diagnostics, '')
  41. writeFileSync(states, '{}')
  42. const observerPath = join(root, 'observer.mjs')
  43. // HMR reports through Cordis logger exporters; WARN is above their default INFO threshold.
  44. writeFileSync(observerPath, [
  45. "import { appendFileSync, writeFileSync, renameSync, rmSync } from 'node:fs'",
  46. "import { inspect } from 'node:util'",
  47. 'export function apply(ctx, config) {',
  48. ' const report = message => appendFileSync(config.path, message.args.map(arg => inspect(arg)).join(" ") + "\\n")',
  49. ' ctx.logger.buffer.forEach(report)',
  50. ' ctx.logger.exporter({ levels: { default: 3 }, export: report })',
  51. ' const timer = setInterval(() => {',
  52. ' const loader = ctx.get("loader")',
  53. ' if (!loader) return',
  54. ' writeFileSync(config.states + ".tmp", JSON.stringify(Object.fromEntries([...loader.entries()].map(entry => [entry.options.id, entry.fiber?.state]))))',
  55. ' renameSync(config.states + ".tmp", config.states)',
  56. ' }, 20)',
  57. ' ctx.effect(() => () => { clearInterval(timer) })',
  58. ' ctx.inject(["webServer", "connection"], scope => {',
  59. ' writeFileSync(config.url, scope.connection.authenticatedUrl(`http://127.0.0.1:${scope.webServer.port}`))',
  60. ' scope.effect(() => () => { rmSync(config.url, { force: true }) })',
  61. ' })',
  62. '}',
  63. '',
  64. ].join('\n'))
  65. const observer = { id: 'matrix-log-observer', name: pathToFileURL(observerPath).href, config: { path: diagnostics, url: serverUrl, states } }
  66. const plugin = join(root, 'probe.mjs')
  67. writeFileSync(plugin, [
  68. "import { appendFileSync, existsSync } from 'node:fs'",
  69. 'export const Config = { "~standard": { version: 1, vendor: "matrix", validate(value) {',
  70. ' return value.mode === "schema" ? { issues: [{ message: "matrix schema failure" }] } : { value }',
  71. '} } }',
  72. 'export const apply = (ctx, config) => {',
  73. ' if (config.mode === "sync apply") throw new Error("matrix sync apply")',
  74. ' return activate(ctx, config)',
  75. '}',
  76. 'async function activate(ctx, config) {',
  77. ' if (config.mode === "async apply") { await Promise.resolve(); throw new Error("matrix async apply") }',
  78. ' if (config.provider) ctx.provide(config.provider, true)',
  79. ' if (config.mode === "detached") setImmediate(() => { void Promise.reject(new Error("matrix detached failure")) })',
  80. ' appendFileSync(config.events, `${config.label} apply ${config.generation}\\n`)',
  81. ' const timer = setInterval(() => { if (existsSync(config.stop)) process.emit("SIGTERM") }, 20)',
  82. ' ctx.effect(() => () => { clearInterval(timer); appendFileSync(config.events, `${config.label} dispose ${config.generation}\\n`) })',
  83. '}',
  84. '',
  85. ].join('\n'))
  86. writeFileSync(join(root, 'evaluation.mjs'), 'throw new Error("matrix module evaluation")\n')
  87. const url = pathToFileURL(plugin).href
  88. const config = (label: string, generation: number, mode = '') => ({ label, generation, mode, events, stop })
  89. const witness = (generation: number) => ({ id: 'matrix-witness', name: url, config: config('witness', generation) })
  90. const target = (id: string, failure?: Failure, generation = 1) => ({
  91. id,
  92. name: failure === 'import' ? pathToFileURL(join(root, 'missing.mjs')).href
  93. : failure === 'module evaluation' ? pathToFileURL(join(root, 'evaluation.mjs')).href : url,
  94. ...(failure === 'dependency' ? { inject: ['matrixMissingService'] } : {}),
  95. config: config('target', generation, failure),
  96. })
  97. const render = (id: string, failure?: Failure, generation = 1) => {
  98. let text = `- insert: ${JSON.stringify([observer, witness(generation), target(id, failure, generation)])}`
  99. if (failure === 'config expression') text += `\n- id: ${id}\n config: !!js "(() => { throw new Error('matrix config expression') })()"\n`
  100. if (failure === 'disabled expression') text += `\n- id: ${id}\n disabled: !!js "(() => { throw new Error('matrix disabled expression') })()"\n`
  101. return text + '\n'
  102. }
  103. writeFileSync(patch, JSON.stringify([{ insert: [observer, witness(0)] }]) + '\n')
  104. return { root, home, events, diagnostics, serverUrl, states, observer, stop, patch, watcher, render, url, config, witness, target }
  105. }
  106. function start(f: ReturnType<typeof fixture>, extra: string[] = []) {
  107. const child = execa(process.execPath, [bin, '--profile', 'web', '--patch', f.watcher, ...extra, '--no-open', '--port', '0'], {
  108. cwd: f.root,
  109. env: { ...process.env, DSH_HOME: f.home, DSH_AGENTS_HOME: join(f.root, '.agents'), DSH_TELEMETRY_DISABLED: '1', DEEPSEEK_API_KEY: 'keyless-matrix-no-call', NODE_NO_WARNINGS: '1' },
  110. input: '', reject: false, timeout: 110_000, killSignal: 'SIGKILL',
  111. })
  112. let stdout = ''
  113. let stderr = ''
  114. child.stdout?.setEncoding('utf8').on('data', (text: string) => { stdout += text })
  115. child.stderr?.setEncoding('utf8').on('data', (text: string) => { stderr += text })
  116. let exited = false
  117. void child.then(() => { exited = true })
  118. async function wait(predicate: () => boolean) {
  119. try {
  120. await expect.poll(() => {
  121. if (exited) throw new Error('Web process exited')
  122. return predicate()
  123. }, { timeout: 45_000 }).toBe(true)
  124. } catch (cause) { throw new Error(`Web condition failed\n${stdout}\n${stderr}\n${readFileSync(f.diagnostics, 'utf8')}\n${readFileSync(f.events, 'utf8')}`, { cause }) }
  125. }
  126. async function serves(currentServer = false) {
  127. await wait(() => /dsh web: http:\/\//u.test(stdout))
  128. const url = currentServer ? readFileSync(f.serverUrl, 'utf8') : /dsh web: (http:\/\/[^\s]+)/u.exec(stdout)?.[1]
  129. if (!url) throw new Error('Missing Web URL')
  130. const auth = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(10_000) })
  131. const cookie = auth.headers.get('set-cookie')?.split(';', 1)[0]
  132. if (!cookie) throw new Error('Missing Web authentication cookie')
  133. const response = await fetch(new URL('/', url), { headers: { cookie }, signal: AbortSignal.timeout(10_000) })
  134. expect(response.status).toBe(200)
  135. const html = await response.text()
  136. expect(html).toContain('__DSH_BOOT__')
  137. const bundlePath = /<script src="(\/plugins\/[^"]+)"/u.exec(html)?.[1]?.replaceAll('&amp;', '&')
  138. if (!bundlePath) throw new Error('Missing bootstrap bundle URL')
  139. const bundle = await fetch(new URL(bundlePath, url), { headers: { cookie }, signal: AbortSignal.timeout(10_000) })
  140. expect(bundle.status).toBe(200)
  141. expect(await bundle.text()).not.toBe('')
  142. }
  143. async function close() {
  144. writeFileSync(f.stop, 'stop')
  145. // Assertions may fail before a probe applies; forceful teardown still awaits exit.
  146. const timer = setTimeout(() => child.kill('SIGKILL'), 10_000)
  147. try {
  148. const result = await child
  149. return { timedOut: result.timedOut, signal: result.signal, exitCode: result.exitCode, stderr: result.stderr, events: readFileSync(f.events, 'utf8') }
  150. } finally {
  151. clearTimeout(timer)
  152. rmSync(f.root, { recursive: true, force: true })
  153. }
  154. }
  155. const state = (id: string) => (JSON.parse(readFileSync(f.states, 'utf8')) as Record<string, number | undefined>)[id]
  156. return { child, wait, serves, close, state, stderr: () => stderr, logs: () => readFileSync(f.diagnostics, 'utf8'), events: () => readFileSync(f.events, 'utf8') }
  157. }
  158. function exit(result: { timedOut: boolean; signal?: string | undefined; exitCode?: number | undefined; stderr: string }, code: number) {
  159. expect(result.timedOut, result.stderr).toBe(false)
  160. expect(result.signal, result.stderr).toBeUndefined()
  161. expect(result.exitCode, result.stderr).toBe(code)
  162. }
  163. describe.skipIf(!built)('Web process failure matrix', () => {
  164. for (const required of [false, true]) {
  165. const id = required ? 'acp' : 'matrix-optional'
  166. it.each(failures)(`${required ? 'required' : 'optional'} startup %s`, async (failure, diagnostic) => {
  167. const f = fixture()
  168. writeFileSync(f.patch, f.render(id, failure))
  169. const app = start(f)
  170. try {
  171. if (required) {
  172. const result = await app.child
  173. exit(result, 1)
  174. expect(result.stdout).not.toContain('dsh web: http://')
  175. expect(result.stderr).toContain('required startup failure')
  176. expect(app.events()).toBe('witness apply 1\nwitness dispose 1\n')
  177. } else {
  178. await app.serves()
  179. await app.wait(() => (app.stderr() + app.logs()).includes(diagnostic))
  180. expect(app.stderr()).toContain('warning: 1 entry did not activate')
  181. expect(app.events()).toBe('witness apply 1\n')
  182. }
  183. expect(app.stderr() + app.logs()).toContain(diagnostic)
  184. } finally {
  185. const result = await app.close()
  186. exit(result, required ? 1 : 0)
  187. expect(result.events).toContain('witness dispose 1\n')
  188. }
  189. })
  190. it.each(failures)(`${required ? 'required' : 'optional'} native HMR %s keeps siblings and recovers`, async (failure, diagnostic) => {
  191. const f = fixture()
  192. const app = start(f)
  193. try {
  194. await app.serves()
  195. writeFileSync(f.patch, f.render(id, failure))
  196. await app.wait(() => app.events().includes('witness apply 1\n') && (failure === 'dependency' ? app.state(id) === FiberState.PENDING : app.logs().includes(diagnostic)))
  197. expect(app.events()).not.toContain('witness dispose 1\n')
  198. expect(app.events()).not.toContain('target apply')
  199. expect(readFileSync(f.patch, 'utf8')).toBe(f.render(id, failure))
  200. await app.serves()
  201. if (failure === 'dependency') {
  202. writeFileSync(f.patch, JSON.stringify([
  203. { insert: [f.observer, f.witness(1), f.target(id, failure)] },
  204. { insert: [{ id: 'matrix-provider', name: f.url, config: { ...f.config('provider', 2), provider: 'matrixMissingService' } }] },
  205. ]) + '\n')
  206. } else writeFileSync(f.patch, f.render(id, undefined, 2))
  207. await app.wait(() => app.events().includes(`target apply ${failure === 'dependency' ? 1 : 2}\n`))
  208. await app.serves()
  209. expect(app.stderr()).not.toContain('required startup failure')
  210. } finally {
  211. const result = await app.close()
  212. exit(result, 0)
  213. expect(result.events).toContain(`witness dispose ${failure === 'dependency' ? 1 : 2}\n`)
  214. expect(result.events).toContain(`target dispose ${failure === 'dependency' ? 1 : 2}\n`)
  215. }
  216. })
  217. }
  218. it.each([
  219. ['missing', undefined, 'failed to read overlay'],
  220. ['unreadable directory', undefined, 'failed to read overlay'],
  221. ['malformed', 'invalid: [unclosed\n', 'failed to parse overlay'],
  222. ['non-array', 'entries: []\n', 'top-level YAML array'],
  223. ['non-mapping', '- null\n', 'must be a mapping'],
  224. ])('rejects a %s explicit overlay before readiness', async (_kind, content, diagnostic) => {
  225. const f = fixture()
  226. const overlay = join(f.root, 'invalid.patch.yml')
  227. if (_kind === 'unreadable directory') mkdirSync(overlay)
  228. else if (content !== undefined) writeFileSync(overlay, content)
  229. const app = start(f, ['--patch', overlay])
  230. try {
  231. const result = await app.child
  232. exit(result, 1)
  233. expect(result.stderr).toContain(diagnostic)
  234. expect(result.stdout).not.toContain('dsh web: http://')
  235. expect(app.events()).toBe('')
  236. } finally { exit(await app.close(), 1) }
  237. })
  238. it.each([
  239. ['malformed', 'invalid: [unclosed\n', 'failed to parse patches'],
  240. ['non-array', 'entries: []\n', 'top-level YAML array'],
  241. ['non-mapping', '- null\n', 'must be a mapping'],
  242. ])('native HMR rejects %s patches, preserves the app and accepts a correction', async (_kind, content, diagnostic) => {
  243. const f = fixture()
  244. const app = start(f)
  245. try {
  246. await app.serves()
  247. writeFileSync(f.patch, content)
  248. await app.wait(() => app.logs().includes(diagnostic))
  249. expect(app.events()).toBe('witness apply 0\n')
  250. await app.serves()
  251. writeFileSync(f.patch, f.render('matrix-optional'))
  252. await app.wait(() => app.events().includes('target apply 1\n'))
  253. await app.serves()
  254. } finally { exit(await app.close(), 0) }
  255. })
  256. it('native HMR schema failure retains the existing config until a valid correction', async () => {
  257. const f = fixture()
  258. writeFileSync(f.patch, f.render('acp', undefined, 1))
  259. const app = start(f)
  260. try {
  261. await app.serves()
  262. writeFileSync(f.patch, f.render('acp', 'schema', 2))
  263. await app.wait(() => app.logs().includes('matrix schema failure') && app.events().includes('witness apply 2\n'))
  264. expect(app.events()).toContain('target apply 1\n')
  265. expect(app.events()).not.toContain('target dispose 1\n')
  266. expect(app.events()).not.toContain('target apply 2\n')
  267. await app.serves()
  268. writeFileSync(f.patch, f.render('acp', undefined, 3))
  269. await app.wait(() => app.events().includes('target apply 3\n'))
  270. expect(app.events()).toContain('target dispose 1\n')
  271. await app.serves()
  272. } finally { exit(await app.close(), 0) }
  273. })
  274. it('ignores absent and explicitly disabled required entries at startup', async () => {
  275. const f = fixture()
  276. writeFileSync(f.patch, f.render('acp', 'import') + '- id: acp\n disabled: true\n')
  277. const app = start(f)
  278. try {
  279. await app.serves()
  280. expect(app.stderr()).not.toContain('required startup failure')
  281. expect(app.stderr()).not.toContain('failed to import')
  282. } finally { exit(await app.close(), 0) }
  283. })
  284. it('detached rejection from a hot-loaded plugin terminates and disposes the app', async () => {
  285. const f = fixture()
  286. const app = start(f)
  287. try {
  288. await app.serves()
  289. writeFileSync(f.patch, JSON.stringify([{ insert: [f.observer, f.witness(0), {
  290. id: 'matrix-detached', name: f.url, config: f.config('detached', 1, 'detached'),
  291. }] }]) + '\n')
  292. const result = await app.child
  293. exit(result, 1)
  294. expect(result.stderr).toContain('fatal load failure: Error: matrix detached failure')
  295. expect(app.events()).toContain('witness dispose 0\n')
  296. expect(app.events()).toContain('detached dispose 1\n')
  297. } finally { exit(await app.close(), 1) }
  298. })
  299. it('native HMR reports a required Web server bind failure without terminating the process', async () => {
  300. const f = fixture()
  301. const blocker = createServer()
  302. const app = start(f)
  303. try {
  304. await new Promise<void>((resolve, reject) => {
  305. blocker.once('error', reject)
  306. blocker.listen(0, '127.0.0.1', resolve)
  307. })
  308. const address = blocker.address()
  309. if (!address || typeof address === 'string') throw new Error('Missing blocker address')
  310. await app.serves()
  311. writeFileSync(f.patch, f.render('matrix-optional') + `- id: webserver\n config:\n host: 127.0.0.1\n port: ${address.port}\n`)
  312. await app.wait(() => app.logs().includes('EADDRINUSE') && app.events().includes('witness apply 1\n'))
  313. expect(app.stderr()).not.toContain('required startup failure')
  314. expect(app.events()).not.toContain('witness dispose 1\n')
  315. expect(existsSync(f.serverUrl)).toBe(false)
  316. writeFileSync(f.patch, f.render('matrix-optional', undefined, 2))
  317. await app.wait(() => app.events().includes('witness apply 2\n') && existsSync(f.serverUrl))
  318. await app.serves(true)
  319. } finally {
  320. try { exit(await app.close(), 0) } finally {
  321. await new Promise<void>((resolve, reject) => blocker.close((error) => { if (error) reject(error); else resolve() }))
  322. }
  323. }
  324. })
  325. it.each(['startup', 'HMR'])('optional HTTP bind failure at %s leaves Web serving', async (phase) => {
  326. const f = fixture()
  327. const blocker = createServer()
  328. let app: ReturnType<typeof start> | undefined
  329. try {
  330. const plugin = join(f.root, 'http.mjs')
  331. writeFileSync(plugin, [
  332. 'import { createServer } from "node:http"',
  333. 'export async function apply(ctx, config) {',
  334. ' const server = createServer()',
  335. ' ctx.effect(() => () => new Promise(resolve => server.close(() => resolve())))',
  336. ' await new Promise((resolve, reject) => { server.once("error", reject); server.listen(config.port, "127.0.0.1", resolve) })',
  337. '}',
  338. '',
  339. ].join('\n'))
  340. await new Promise<void>((resolve, reject) => {
  341. blocker.once('error', reject)
  342. blocker.listen(0, '127.0.0.1', resolve)
  343. })
  344. const address = blocker.address()
  345. if (!address || typeof address === 'string') throw new Error('Missing blocker address')
  346. const patch = JSON.stringify([{ insert: [f.observer, f.witness(0), {
  347. id: 'matrix-optional-http', name: pathToFileURL(plugin).href, config: { port: address.port },
  348. }] }]) + '\n'
  349. if (phase === 'startup') writeFileSync(f.patch, patch)
  350. app = start(f)
  351. const running = app
  352. await app.serves()
  353. if (phase === 'HMR') writeFileSync(f.patch, patch)
  354. await app.wait(() => (running.logs() + running.stderr()).includes('EADDRINUSE'))
  355. expect(app.events()).toBe('witness apply 0\n')
  356. await app.serves()
  357. } finally {
  358. try {
  359. if (app) exit(await app.close(), 0)
  360. else rmSync(f.root, { recursive: true, force: true })
  361. } finally {
  362. if (blocker.listening) {
  363. await new Promise<void>((resolve, reject) => blocker.close((error) => { if (error) reject(error); else resolve() }))
  364. }
  365. }
  366. }
  367. })
  368. it.each(['modules', 'connection'])('native HMR recovers the shipped required %s entry', async (id) => {
  369. const f = fixture()
  370. const app = start(f)
  371. try {
  372. await app.serves()
  373. // Entry-level injection requirements are captured when the fiber is created.
  374. writeFileSync(f.patch, f.render('matrix-optional') + `- id: ${id}\n disabled: true\n`)
  375. await app.wait(() => app.state(id) === FiberState.DISPOSED)
  376. const inject = id === 'connection' ? ['webRuntime', 'matrixMissingWebDependency'] : ['matrixMissingWebDependency']
  377. const pending = f.render('matrix-optional', undefined, 2) + `- id: ${id}\n inject: ${JSON.stringify(inject)}\n`
  378. writeFileSync(f.patch, pending)
  379. await app.wait(() => app.state(id) === FiberState.PENDING && app.events().includes('witness apply 2\n'))
  380. expect(app.events()).not.toContain('witness dispose 2\n')
  381. expect(app.stderr()).not.toContain('required startup failure')
  382. writeFileSync(f.patch, pending + `- insert: ${JSON.stringify([{
  383. id: 'matrix-provider', name: f.url, config: { ...f.config('provider', 3), provider: 'matrixMissingWebDependency' },
  384. }])}\n`)
  385. await app.wait(() => app.state(id) === FiberState.ACTIVE && existsSync(f.serverUrl))
  386. await app.serves(true)
  387. } finally { exit(await app.close(), 0) }
  388. })
  389. })