linux-scope.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import { EventEmitter } from 'node:events'
  2. import { existsSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'
  3. import { PassThrough } from 'node:stream'
  4. import { afterEach, describe, expect, it, vi } from 'vitest'
  5. import {
  6. launchLinuxScope,
  7. prepareLinuxTerminalScope,
  8. probeLinuxBootstrap,
  9. probeLinuxManager,
  10. probeLinuxNative,
  11. probeLinuxScope,
  12. } from '../src/linux-scope.ts'
  13. import type { LinuxScopeInternals } from '../src/linux-scope.ts'
  14. import {
  15. consumeLinuxLaunchRequest,
  16. linuxLaunchFilesFromLocator,
  17. writeLinuxStartupError,
  18. } from '../src/runner-protocol.ts'
  19. import { SUBPROCESS_RUNNER_ENV } from '../src/runner-launch.ts'
  20. import { bindManagedProcess } from '../src/spawn.ts'
  21. const childProcessMocks = vi.hoisted(() => ({
  22. execFile: vi.fn(),
  23. spawn: vi.fn(),
  24. spawnSync: vi.fn(),
  25. }))
  26. vi.mock('node:child_process', async (importOriginal) => {
  27. const actual = await importOriginal<typeof import('node:child_process')>()
  28. return {
  29. ...actual,
  30. execFile: childProcessMocks.execFile as unknown as typeof actual.execFile,
  31. spawn: childProcessMocks.spawn as typeof actual.spawn,
  32. spawnSync: childProcessMocks.spawnSync as typeof actual.spawnSync,
  33. }
  34. })
  35. class FakeChild extends EventEmitter {
  36. pid: number | undefined = 321
  37. exitCode: number | null = null
  38. signalCode: NodeJS.Signals | null = null
  39. stdin = new PassThrough()
  40. stdout = new PassThrough()
  41. stderr = new PassThrough()
  42. kills: NodeJS.Signals[] = []
  43. kill(signal: NodeJS.Signals): boolean {
  44. this.kills.push(signal)
  45. return true
  46. }
  47. exit(exitCode: number | null, signal: NodeJS.Signals | null): void {
  48. this.exitCode = exitCode
  49. this.signalCode = signal
  50. this.emit('exit', exitCode, signal)
  51. }
  52. }
  53. const directories: string[] = []
  54. afterEach(() => {
  55. for (const directory of directories.splice(0)) {
  56. rmSync(directory, { recursive: true, force: true })
  57. }
  58. vi.restoreAllMocks()
  59. childProcessMocks.execFile.mockReset()
  60. childProcessMocks.spawn.mockReset()
  61. childProcessMocks.spawnSync.mockReset()
  62. })
  63. function missingUnit() {
  64. return { status: 1, stdout: '', stderr: 'Unit dsh.scope could not be found.' }
  65. }
  66. function activeUnit(state = 'active') {
  67. return { status: 0, stdout: `LoadState=loaded\nActiveState=${state}\n`, stderr: '' }
  68. }
  69. function unloadedUnit() {
  70. return { status: 0, stdout: 'LoadState=not-found\nActiveState=inactive\n', stderr: '' }
  71. }
  72. function unitState(loadState: string, activeState: string) {
  73. return { status: 0, stdout: `LoadState=${loadState}\nActiveState=${activeState}\n`, stderr: '' }
  74. }
  75. function spec() {
  76. return {
  77. argv: ['tool', 'literal arg'],
  78. cwd: '/target',
  79. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' },
  80. graceMs: 100,
  81. env: { TARGET: 'yes' },
  82. } as const
  83. }
  84. function launch(
  85. query: LinuxScopeInternals['systemctlQuery'],
  86. overrides: LinuxScopeInternals = {},
  87. ) {
  88. const child = new FakeChild()
  89. let options: { env?: NodeJS.ProcessEnv; cwd?: string; detached?: boolean } | undefined
  90. const spawn = vi.fn((_command: string, _args: readonly string[], received: typeof options) => {
  91. options = received
  92. return child
  93. })
  94. const spawnSync = vi.fn(() => ({ status: 0, stdout: '', stderr: '' }))
  95. const systemctlQuery = overrides.systemctlQuery ?? query
  96. const result = launchLinuxScope(spec(), { TARGET: 'yes' }, {
  97. spawn: overrides.spawn ?? spawn as never,
  98. spawnSync: overrides.spawnSync ?? spawnSync as never,
  99. ...systemctlQuery === undefined ? {} : { systemctlQuery },
  100. systemdRun: overrides.systemdRun ?? '/bin/systemd-run',
  101. systemctl: overrides.systemctl ?? '/bin/systemctl',
  102. runnerInvocation: overrides.runnerInvocation ?? ['/usr/bin/node', '/runner.js'],
  103. ...overrides.runnerAvailable === undefined ? {} : { runnerAvailable: overrides.runnerAvailable },
  104. ...overrides.loadLinuxExecve === undefined ? {} : { loadLinuxExecve: overrides.loadLinuxExecve },
  105. ...overrides.sleep === undefined ? {} : { sleep: overrides.sleep },
  106. })
  107. const requestPath = options?.env?.[SUBPROCESS_RUNNER_ENV]
  108. if (requestPath === undefined) throw new Error('launch did not publish a request locator')
  109. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  110. return { child, result, requestPath, spawn, spawnSync, options }
  111. }
  112. describe('Linux native capability selection', () => {
  113. it('rechecks bootstrap and literal transient-scope support', () => {
  114. const spawnSync = vi.fn(() => ({ status: 0, error: undefined }))
  115. const runnerAvailable = vi.fn(() => true)
  116. const loadLinuxExecve = vi.fn(() => vi.fn() as never)
  117. const inputs = {
  118. spawnSync: spawnSync as never,
  119. runnerAvailable,
  120. runnerInvocation: ['/usr/bin/node', '/runner.js'] as [string, ...string[]],
  121. loadLinuxExecve,
  122. systemdRun: '/bin/systemd-run',
  123. systemctl: '/bin/systemctl',
  124. }
  125. expect(probeLinuxNative(inputs)).toBe(true)
  126. expect(probeLinuxNative(inputs)).toBe(true)
  127. expect(runnerAvailable).toHaveBeenCalledTimes(2)
  128. expect(loadLinuxExecve).toHaveBeenCalledTimes(2)
  129. expect(spawnSync).toHaveBeenCalledTimes(2)
  130. expect(probeLinuxBootstrap({
  131. ...inputs,
  132. loadLinuxExecve: () => { throw new Error('libc execve missing') },
  133. })).toBe(false)
  134. })
  135. it('reports each failed dynamic prerequisite without executing a target', () => {
  136. expect(probeLinuxScope({
  137. spawnSync: vi.fn(() => ({ status: null, error: new Error('missing') })) as never,
  138. })).toBe(false)
  139. expect(probeLinuxBootstrap({
  140. loadLinuxExecve: () => vi.fn() as never,
  141. runnerInvocation: ['/missing'],
  142. runnerAvailable: () => false,
  143. })).toBe(false)
  144. expect(probeLinuxBootstrap({
  145. loadLinuxExecve: () => vi.fn() as never,
  146. resolveRunnerInvocation: () => { throw new Error('runner resolution failed') },
  147. })).toBe(false)
  148. })
  149. it('uses the default command adapters and runner resolution', () => {
  150. childProcessMocks.spawnSync.mockReturnValue({ status: 0, error: undefined })
  151. expect(probeLinuxScope()).toBe(true)
  152. expect(probeLinuxManager()).toBe(true)
  153. expect(childProcessMocks.spawnSync).toHaveBeenCalledTimes(2)
  154. expect(probeLinuxBootstrap({ loadLinuxExecve: () => vi.fn() as never })).toBe(true)
  155. expect(probeLinuxBootstrap({
  156. runnerInvocation: [process.execPath],
  157. runnerAvailable: () => true,
  158. })).toBe(process.platform !== 'win32')
  159. })
  160. it('keeps quieting on the transient-scope probe but preserves manager diagnostics', () => {
  161. const spawnSync = vi.fn((
  162. _command: string,
  163. _args: readonly string[],
  164. _options: unknown,
  165. ) => ({ status: 0, error: undefined }))
  166. expect(probeLinuxScope({ spawnSync: spawnSync as never })).toBe(true)
  167. expect(probeLinuxManager({ spawnSync: spawnSync as never })).toBe(true)
  168. const scopeOptions = spawnSync.mock.calls[0]?.[2] as { env: NodeJS.ProcessEnv }
  169. const managerOptions = spawnSync.mock.calls[1]?.[2] as { env: NodeJS.ProcessEnv }
  170. expect(scopeOptions.env).toMatchObject({ LC_ALL: 'C', SYSTEMD_LOG_TARGET: 'null' })
  171. expect(managerOptions.env).toMatchObject({ LC_ALL: 'C' })
  172. expect(managerOptions.env).not.toHaveProperty('SYSTEMD_LOG_TARGET')
  173. expect(probeLinuxManager({
  174. spawnSync: vi.fn(() => ({ status: 1, error: undefined })) as never,
  175. })).toBe(false)
  176. expect(probeLinuxManager({
  177. spawnSync: vi.fn(() => ({ status: null, error: new Error('missing') })) as never,
  178. })).toBe(false)
  179. })
  180. })
  181. describe('Linux scope establishment and quiescence', () => {
  182. it.each(['abort', 'terminate'] as const)('settles and cleans a managed handle after early %s', async (action) => {
  183. const { child, result, requestPath } = launch(async () => missingUnit())
  184. const controller = new AbortController()
  185. const handle = bindManagedProcess({ ...spec(), signal: controller.signal }, result)
  186. if (action === 'abort') controller.abort(new Error('cancelled'))
  187. else handle.terminate()
  188. expect(child.kills).toEqual(['SIGTERM'])
  189. child.exit(null, 'SIGTERM')
  190. child.stdout.end()
  191. child.stderr.end()
  192. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  193. await expect(handle.waitForExit()).resolves.toBe(true)
  194. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  195. })
  196. it.each([
  197. { exitCode: 1, signal: null },
  198. { exitCode: null, signal: 'SIGSEGV' as const },
  199. ])('retains unrelated bootstrap failure $exitCode / $signal after a termination request', async (outcome) => {
  200. const { child, result } = launch(async () => missingUnit())
  201. result.owner.signal('SIGTERM')
  202. child.exit(outcome.exitCode, outcome.signal)
  203. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  204. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  205. result.owner.cleanup?.()
  206. })
  207. it('does not mistake pre-establishment unit absence for quiescence and settles an empty range after cancellation', async () => {
  208. const { child, result, requestPath, spawnSync } = launch(async () => missingUnit())
  209. const waiting = result.owner.waitForExit()
  210. result.owner.signal('SIGTERM')
  211. expect(child.kills).toEqual(['SIGTERM'])
  212. expect(spawnSync).toHaveBeenCalledWith('/bin/systemctl', expect.arrayContaining([
  213. 'kill', '--kill-whom=all', '--signal=SIGTERM',
  214. ]), expect.anything())
  215. const direct = expect(result.direct).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  216. child.exit(null, 'SIGTERM')
  217. await direct
  218. await expect(waiting).resolves.toBeUndefined()
  219. expect(existsSync(requestPath)).toBe(true)
  220. result.owner.cleanup?.()
  221. })
  222. it('accepts request consumption followed by rapid --collect unload as stopped', async () => {
  223. const states = [activeUnit(), unloadedUnit()]
  224. const { child, result, requestPath } = launch(async () => states.shift() ?? missingUnit())
  225. expect(consumeLinuxLaunchRequest(requestPath)).toEqual({ cwd: '/target', env: { TARGET: 'yes' } })
  226. const waiting = result.owner.waitForExit()
  227. child.exit(0, null)
  228. await expect(result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  229. await expect(waiting).resolves.toBeUndefined()
  230. result.owner.signal('SIGKILL')
  231. result.owner.cleanup?.()
  232. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  233. })
  234. it('uses the scope alone after establishment and the direct range only when scope signalling fails', async () => {
  235. const spawnSync = vi.fn()
  236. .mockReturnValueOnce({ status: 0, stdout: '', stderr: '' })
  237. .mockReturnValueOnce({ status: 1, stdout: '', stderr: 'scope signal failed' })
  238. const { child, result, requestPath } = launch(async () => activeUnit(), {
  239. spawnSync: spawnSync as never,
  240. })
  241. consumeLinuxLaunchRequest(requestPath)
  242. const processKill = vi.spyOn(process, 'kill').mockReturnValue(true)
  243. result.owner.signal('SIGTERM')
  244. expect(processKill).not.toHaveBeenCalled()
  245. result.owner.signal('SIGKILL')
  246. expect(processKill).toHaveBeenCalledExactlyOnceWith(-321, 'SIGKILL')
  247. expect(spawnSync).toHaveBeenCalledTimes(2)
  248. child.exit(null, 'SIGKILL')
  249. await expect(result.direct).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  250. result.owner.cleanup?.()
  251. })
  252. it('uses manager-observed unit existence as establishment proof', async () => {
  253. const { child, result } = launch(async () => activeUnit('inactive'))
  254. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  255. child.exit(1, null)
  256. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  257. result.owner.cleanup?.()
  258. })
  259. it('keeps waiting while the unit is absent and the direct launcher is still running', async () => {
  260. const states = [missingUnit(), activeUnit('inactive')]
  261. const { child, result } = launch(async () => states.shift() ?? activeUnit('inactive'))
  262. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  263. child.exit(1, null)
  264. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  265. result.owner.cleanup?.()
  266. })
  267. it('treats status-zero not-found as pending until the direct launcher proves the range was never created', async () => {
  268. const state: { child?: FakeChild } = {}
  269. const launched = launch(async () => unloadedUnit(), {
  270. sleep: async () => { state.child?.exit(127, null) },
  271. })
  272. state.child = launched.child
  273. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  274. await expect(launched.result.direct).rejects.toThrow('before its bootstrap consumed')
  275. launched.result.owner.cleanup?.()
  276. })
  277. it('polls promptly before establishment and backs off established active scopes', async () => {
  278. const delays: number[] = []
  279. const states = [
  280. missingUnit(),
  281. activeUnit(),
  282. activeUnit(),
  283. activeUnit(),
  284. activeUnit(),
  285. activeUnit(),
  286. activeUnit(),
  287. activeUnit(),
  288. activeUnit(),
  289. activeUnit('inactive'),
  290. ]
  291. const launched = launch(
  292. async () => states.shift() ?? activeUnit('inactive'),
  293. { sleep: async (delayMs) => { delays.push(delayMs) } },
  294. )
  295. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  296. expect(delays).toEqual([50, 50, 100, 200, 400, 800, 1_600, 3_200, 5_000])
  297. launched.result.owner.cleanup?.()
  298. })
  299. it('keeps reloading scopes active and lets terminate wake a backed-off observation', async () => {
  300. const states = [activeUnit('reloading'), activeUnit('inactive')]
  301. const sleeping = Promise.withResolvers<undefined>()
  302. const sleep = vi.fn(async (_delayMs: number, signal?: AbortSignal) => {
  303. sleeping.resolve(undefined)
  304. if (signal === undefined) throw new Error('missing sleep cancellation signal')
  305. await new Promise<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
  306. })
  307. const launched = launch(async () => states.shift() ?? activeUnit('inactive'), { sleep })
  308. consumeLinuxLaunchRequest(launched.requestPath)
  309. const waiting = launched.result.owner.waitForExit()
  310. await sleeping.promise
  311. launched.result.owner.signal('SIGTERM')
  312. await expect(waiting).resolves.toBeUndefined()
  313. expect(sleep).toHaveBeenCalledOnce()
  314. expect(sleep.mock.calls[0]?.[0]).toBe(50)
  315. expect(sleep.mock.calls[0]?.[1]?.aborted).toBe(true)
  316. expect(launched.spawnSync).toHaveBeenCalledOnce()
  317. launched.result.owner.cleanup?.()
  318. })
  319. it('skips the next poll delay when terminate arrives during a manager query', async () => {
  320. const firstQuery = Promise.withResolvers<ReturnType<typeof activeUnit>>()
  321. const query = vi.fn()
  322. .mockImplementationOnce(async () => await firstQuery.promise)
  323. .mockResolvedValueOnce(activeUnit('inactive'))
  324. const sleep = vi.fn(async () => {})
  325. const launched = launch(query, { sleep })
  326. consumeLinuxLaunchRequest(launched.requestPath)
  327. const waiting = launched.result.owner.waitForExit()
  328. launched.result.owner.signal('SIGTERM')
  329. firstQuery.resolve(activeUnit())
  330. await expect(waiting).resolves.toBeUndefined()
  331. expect(sleep).not.toHaveBeenCalled()
  332. launched.result.owner.cleanup?.()
  333. })
  334. it.each([
  335. { exitCode: 127, signal: null },
  336. { exitCode: null, signal: 'SIGTERM' as const },
  337. ])('rejects unexpected bootstrap exit $exitCode / $signal and settles the empty range', async (outcome) => {
  338. const { child, result } = launch(async () => missingUnit())
  339. child.exit(outcome.exitCode, outcome.signal)
  340. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  341. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  342. result.owner.cleanup?.()
  343. })
  344. it('preserves a recorded pre-exec failure even when cancellation also terminates the bootstrap', async () => {
  345. const { child, result, requestPath } = launch(async () => missingUnit())
  346. const files = linuxLaunchFilesFromLocator(requestPath)
  347. result.owner.signal('SIGTERM')
  348. unlinkSync(requestPath)
  349. writeLinuxStartupError(files, {
  350. type: 'error',
  351. error: { name: 'Error', message: 'spawn tool ENOENT', code: 'ENOENT' },
  352. })
  353. child.exit(null, 'SIGTERM')
  354. await expect(result.direct).rejects.toMatchObject({ code: 'ENOENT' })
  355. result.owner.cleanup?.()
  356. })
  357. it('retries a failed state query and rejects unknown states or failed final kills', async () => {
  358. const query = vi.fn()
  359. .mockResolvedValueOnce({ status: null, stdout: '', stderr: '', error: new Error('query failed') })
  360. .mockResolvedValueOnce(missingUnit())
  361. const { result, requestPath } = launch(query)
  362. unlinkSync(requestPath)
  363. await expect(result.owner.waitForExit()).rejects.toThrow('query failed')
  364. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  365. result.owner.cleanup?.()
  366. const unknown = launch(async () => activeUnit('mystery'))
  367. await expect(unknown.result.owner.waitForExit()).rejects.toThrow('unknown ActiveState')
  368. unknown.result.owner.cleanup?.()
  369. const unknownLoad = launch(async () => unitState('masked', 'inactive'))
  370. await expect(unknownLoad.result.owner.waitForExit()).rejects.toThrow('unknown state')
  371. unknownLoad.result.owner.cleanup?.()
  372. const killFailed = launch(async () => activeUnit(), {
  373. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'permission denied' })) as never,
  374. })
  375. killFailed.result.owner.signal('SIGKILL')
  376. await expect(killFailed.result.owner.waitForExit()).rejects.toThrow('could not signal')
  377. killFailed.result.owner.cleanup?.()
  378. })
  379. it('reports command-query failures from the default systemctl adapter', async () => {
  380. childProcessMocks.execFile.mockImplementationOnce((...args: unknown[]) => {
  381. const callback = args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void
  382. const options = args[2] as { env: NodeJS.ProcessEnv }
  383. expect(options.env).toMatchObject({ LC_ALL: 'C' })
  384. expect(options.env).not.toHaveProperty('SYSTEMD_LOG_TARGET')
  385. callback(null, 'LoadState=loaded\nActiveState=inactive\n', 'manager diagnostic remains readable')
  386. return new EventEmitter()
  387. })
  388. const stopped = launch(undefined)
  389. await expect(stopped.result.owner.waitForExit()).resolves.toBeUndefined()
  390. stopped.result.owner.cleanup?.()
  391. const queryError = Object.assign(new Error('systemctl execution failed'), { code: 'ENOENT' })
  392. childProcessMocks.execFile.mockImplementationOnce((...args: unknown[]) => {
  393. const callback = args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void
  394. callback(queryError, '', '')
  395. return new EventEmitter()
  396. })
  397. const failed = launch(undefined)
  398. await expect(failed.result.owner.waitForExit()).rejects.toBe(queryError)
  399. failed.result.owner.cleanup?.()
  400. })
  401. it('rejects malformed, duplicate, incomplete, and extra manager state fields', async () => {
  402. for (const [stdout, message] of [
  403. ['loaded\nActiveState=active\n', 'malformed state'],
  404. ['LoadState=loaded\nLoadState=loaded\nActiveState=active\n', 'duplicate LoadState'],
  405. ['LoadState=loaded\n', 'incomplete state'],
  406. ['LoadState=loaded\nActiveState=inactive\nOther=value\n', 'incomplete state'],
  407. ] as const) {
  408. const launched = launch(async () => ({ status: 0, stdout, stderr: '' }))
  409. await expect(launched.result.owner.waitForExit()).rejects.toThrow(message)
  410. launched.result.owner.cleanup?.()
  411. }
  412. })
  413. it('keeps signal failures scoped to final kill proof and stays idempotent after stop', async () => {
  414. const spawnSync = vi.fn()
  415. .mockReturnValueOnce({ status: 1, stdout: '', stderr: '' })
  416. .mockReturnValueOnce({ status: 1, stderr: 'Unit dsh.scope could not be found.' })
  417. .mockReturnValueOnce({ status: 1, stdout: '', stderr: '' })
  418. .mockReturnValueOnce({ status: 0, stdout: '', stderr: '' })
  419. const states = [activeUnit(), activeUnit('failed')]
  420. const launched = launch(async () => states.shift() ?? missingUnit(), {
  421. spawnSync: spawnSync as never,
  422. })
  423. launched.child.pid = undefined
  424. unlinkSync(launched.requestPath)
  425. launched.result.owner.signal('SIGTERM')
  426. launched.result.owner.signal('SIGKILL')
  427. launched.result.owner.signal('SIGKILL')
  428. launched.result.owner.signal('SIGKILL')
  429. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  430. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  431. launched.result.owner.terminateForHostExit()
  432. expect(spawnSync).toHaveBeenCalledTimes(4)
  433. launched.result.owner.cleanup?.()
  434. })
  435. it('reports unreadable manager output and a failed kill before establishment', async () => {
  436. const withOutput = launch(async () => ({
  437. status: 5, stdout: '', stderr: 'permission denied',
  438. }))
  439. await expect(withOutput.result.owner.waitForExit()).rejects.toThrow('permission denied')
  440. withOutput.result.owner.cleanup?.()
  441. const withoutOutput = launch(async () => ({ status: null, stdout: '', stderr: '' }))
  442. await expect(withoutOutput.result.owner.waitForExit()).rejects.toThrow('exit null')
  443. withoutOutput.result.owner.cleanup?.()
  444. const killFailed = launch(async () => missingUnit(), {
  445. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'kill denied' })) as never,
  446. })
  447. vi.spyOn(process, 'kill').mockImplementation(() => { throw new Error('missing process group') })
  448. killFailed.result.owner.signal('SIGKILL')
  449. await expect(killFailed.result.owner.waitForExit()).rejects.toThrow('kill denied')
  450. killFailed.result.owner.cleanup?.()
  451. })
  452. it('settles direct outcomes once and reports malformed startup errors', async () => {
  453. const childError = launch(async () => missingUnit())
  454. const spawnError = new Error('systemd-run failed')
  455. childError.child.emit('error', spawnError)
  456. childError.child.exit(1, null)
  457. await expect(childError.result.direct).rejects.toBe(spawnError)
  458. childError.result.owner.cleanup?.()
  459. const lateError = launch(async () => missingUnit())
  460. consumeLinuxLaunchRequest(lateError.requestPath)
  461. lateError.child.exit(0, null)
  462. lateError.child.emit('error', new Error('late child error'))
  463. await expect(lateError.result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  464. lateError.result.owner.cleanup?.()
  465. const malformed = launch(async () => missingUnit())
  466. const files = linuxLaunchFilesFromLocator(malformed.requestPath)
  467. unlinkSync(malformed.requestPath)
  468. writeFileSync(files.startupErrorPath, '{', { mode: 0o600 })
  469. malformed.child.exit(127, null)
  470. await expect(malformed.result.direct).rejects.toBeInstanceOf(SyntaxError)
  471. malformed.result.owner.cleanup?.()
  472. })
  473. it('does not signal a direct group before the launcher publishes a pid', async () => {
  474. const launched = launch(async () => activeUnit('inactive'))
  475. launched.child.pid = undefined
  476. const processKill = vi.spyOn(process, 'kill')
  477. launched.result.owner.signal('SIGTERM')
  478. expect(processKill).not.toHaveBeenCalled()
  479. expect(launched.child.kills).toEqual([])
  480. consumeLinuxLaunchRequest(launched.requestPath)
  481. launched.child.exit(0, null)
  482. await expect(launched.result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  483. launched.result.owner.cleanup?.()
  484. })
  485. it('does not signal the direct group after the launcher exits', async () => {
  486. const { child, result, requestPath, spawnSync } = launch(async () => activeUnit())
  487. consumeLinuxLaunchRequest(requestPath)
  488. child.exit(0, null)
  489. await expect(result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  490. const processKill = vi.spyOn(process, 'kill')
  491. result.owner.signal('SIGTERM')
  492. result.owner.terminateForHostExit()
  493. expect(processKill).not.toHaveBeenCalled()
  494. expect(child.kills).toEqual([])
  495. expect(spawnSync).toHaveBeenCalledTimes(2)
  496. result.owner.cleanup?.()
  497. })
  498. it('runs direct fallback before the exact synchronous scope kill on host exit', () => {
  499. const events: string[] = []
  500. const { child, result } = launch(async () => missingUnit(), {
  501. spawnSync: vi.fn(() => { events.push('scope'); return { status: 0 } }) as never,
  502. })
  503. child.kill = vi.fn(() => { events.push('direct'); return true })
  504. vi.spyOn(process, 'kill').mockImplementation(() => { events.push('direct'); return true })
  505. result.owner.terminateForHostExit()
  506. expect(events).toEqual(['direct', 'scope'])
  507. result.owner.cleanup?.()
  508. })
  509. })
  510. describe('Linux PTY bootstrap reuse', () => {
  511. const terminalSpec = {
  512. argv: ['bash', '--noprofile'],
  513. cwd: '/target',
  514. env: { TARGET: 'yes' },
  515. rows: 24,
  516. cols: 80,
  517. graceMs: 100,
  518. } as const
  519. it.each(['SIGTERM', 'SIGKILL'] as const)('preserves %s before bootstrap consumption and joins the empty scope', async (signal) => {
  520. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' }, {
  521. spawnSync: vi.fn(() => missingUnit()) as never,
  522. systemctlQuery: async () => missingUnit(),
  523. })
  524. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  525. if (requestPath === undefined) throw new Error('missing PTY request')
  526. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  527. let running = true
  528. const kill = vi.fn()
  529. const owner = scope.bindOwner({ running: () => running, signal: kill })
  530. owner.signal(signal)
  531. expect(kill).toHaveBeenCalledExactlyOnceWith(signal)
  532. running = false
  533. expect(existsSync(requestPath)).toBe(true)
  534. expect(scope.resolveOutcome({ exitCode: 0, signal })).toEqual({ exitCode: 0, signal })
  535. await expect(owner.waitForExit()).resolves.toBeUndefined()
  536. scope.cleanup()
  537. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  538. })
  539. it('uses the same request/bootstrap, preserves argv, and cleans after owner settlement', async () => {
  540. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' }, {
  541. systemdRun: '/bin/systemd-run',
  542. systemctl: '/bin/systemctl',
  543. runnerInvocation: ['/usr/bin/node', '/runner.js'],
  544. spawnSync: vi.fn(() => ({ status: 0 })) as never,
  545. systemctlQuery: async () => missingUnit(),
  546. })
  547. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  548. if (requestPath === undefined) throw new Error('missing PTY request')
  549. expect(scope.args.slice(-3)).toEqual(['--', 'bash', '--noprofile'])
  550. expect(consumeLinuxLaunchRequest(requestPath)).toEqual({ cwd: '/target', env: { TARGET: 'yes' } })
  551. const owner = scope.bindOwner({ running: () => false, signal: vi.fn() })
  552. await expect(owner.waitForExit()).resolves.toBeUndefined()
  553. expect(scope.resolveOutcome({ exitCode: 0, signal: null })).toEqual({ exitCode: 0, signal: null })
  554. scope.cleanup()
  555. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  556. })
  557. it('surfaces PTY pre-exec errors instead of launcher outcomes', () => {
  558. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' })
  559. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  560. if (requestPath === undefined) throw new Error('missing PTY request')
  561. const files = linuxLaunchFilesFromLocator(requestPath)
  562. unlinkSync(requestPath)
  563. writeLinuxStartupError(files, {
  564. type: 'error', error: { name: 'Error', message: 'bad cwd', code: 'ENOENT' },
  565. })
  566. expect(() => scope.resolveOutcome({ exitCode: 127, signal: null })).toThrow('bad cwd')
  567. scope.cleanup()
  568. })
  569. it('uses default owner dependencies and rejects an unconsumed request', () => {
  570. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' })
  571. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  572. if (requestPath === undefined) throw new Error('missing PTY request')
  573. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  574. scope.bindOwner({ running: () => true, signal: vi.fn() })
  575. expect(() => scope.resolveOutcome({ exitCode: 1, signal: null })).toThrow(
  576. 'before its bootstrap consumed',
  577. )
  578. scope.cleanup()
  579. })
  580. })
  581. describe('Linux ordinary launch adapters', () => {
  582. it('uses the default launch dependencies without changing the target request', async () => {
  583. const child = new FakeChild()
  584. childProcessMocks.spawn.mockReturnValue(child)
  585. const result = launchLinuxScope(spec(), { TARGET: 'yes' })
  586. const call = childProcessMocks.spawn.mock.calls[0]
  587. const options = call?.[2] as { env?: NodeJS.ProcessEnv } | undefined
  588. const requestPath = options?.env?.[SUBPROCESS_RUNNER_ENV]
  589. if (requestPath === undefined) throw new Error('launch did not publish a request locator')
  590. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  591. expect(call?.[0]).toBe('systemd-run')
  592. expect(consumeLinuxLaunchRequest(requestPath)).toEqual({ cwd: '/target', env: { TARGET: 'yes' } })
  593. child.exit(0, null)
  594. await expect(result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  595. result.owner.cleanup?.()
  596. })
  597. it('removes the private launch directory when spawn throws synchronously', () => {
  598. const spawnError = new Error('synchronous spawn failure')
  599. let requestPath: string | undefined
  600. expect(() => launchLinuxScope(spec(), { TARGET: 'yes' }, {
  601. runnerInvocation: ['/usr/bin/node', '/runner.js'],
  602. spawn: vi.fn((_command: string, _args: readonly string[], options: { env?: NodeJS.ProcessEnv }) => {
  603. requestPath = options.env?.[SUBPROCESS_RUNNER_ENV]
  604. throw spawnError
  605. }) as never,
  606. })).toThrow(spawnError)
  607. if (requestPath === undefined) throw new Error('spawn did not receive a request locator')
  608. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  609. })
  610. })