control.spec.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import { mkdtemp, rm } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. import { once } from 'node:events'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { Context } from '@deepseek-ai/cordis'
  8. import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
  9. import { SUBPROCESS_CONTROL_ENV } from '@deepseek-ai/dsh-subprocess/control'
  10. import { LocalSubprocessRuntime } from '../src/index.ts'
  11. import { spawnSubprocess } from '../src/spawn.ts'
  12. const fixture = fileURLToPath(new URL('./fixtures/control-child.ts', import.meta.url))
  13. const helper = fileURLToPath(new URL('../../subprocess/src/control.ts', import.meta.url))
  14. let ctx: Context | undefined
  15. let root: string | undefined
  16. let handle: SubprocessHandle | undefined
  17. afterEach(async () => {
  18. handle?.control?.destroy()
  19. handle?.terminate()
  20. await handle?.waitForExit()
  21. await ctx?.fiber.dispose()
  22. if (root !== undefined) await rm(root, { recursive: true, force: true })
  23. ctx = undefined
  24. root = undefined
  25. handle = undefined
  26. })
  27. describe('managed subprocess control pipe', () => {
  28. it('joins an exited range and disposes its paused control endpoint without draining it', async () => {
  29. ctx = new Context()
  30. await ctx.plugin(LocalSubprocessRuntime)
  31. handle = ctx.subprocess.spawn({
  32. argv: [process.execPath, '--input-type=module', '-e',
  33. 'import { Socket } from "node:net"; const c = new Socket({fd:7,readable:true,writable:true}); c.write(Buffer.alloc(4096),()=>c.destroy())'],
  34. cwd: process.cwd(),
  35. stdio: { stdin: 'ignore', stdout: { maxBytes: 32 }, stderr: { maxBytes: 32 }, control: 'pipe' },
  36. graceMs: 1000,
  37. })
  38. const channel = handle.control
  39. if (channel === undefined) throw new Error('requested control pipe is absent')
  40. channel.pause()
  41. expect(await handle.done).toEqual({ exitCode: 0, signal: null })
  42. expect(channel.destroyed).toBe(false)
  43. expect(await handle.waitForExit(AbortSignal.timeout(10_000))).toBe(true)
  44. await ctx.fiber.dispose()
  45. expect(channel.destroyed).toBe(true)
  46. expect(channel.closed).toBe(true)
  47. }, 15_000)
  48. it('closes the caller endpoint when service disposal terminates an active program', async () => {
  49. ctx = new Context()
  50. await ctx.plugin(LocalSubprocessRuntime)
  51. handle = ctx.subprocess.spawn({
  52. argv: [process.execPath, '--input-type=module', '-e',
  53. 'import { Socket } from "node:net"; const c = new Socket({fd:7,readable:true,writable:true}); c.write("ready"); setInterval(()=>{},60000)'],
  54. cwd: process.cwd(),
  55. stdio: { stdin: 'ignore', stdout: { maxBytes: 32 }, stderr: { maxBytes: 32 }, control: 'pipe' },
  56. graceMs: 1000,
  57. })
  58. const channel = handle.control
  59. if (channel === undefined) throw new Error('requested control pipe is absent')
  60. await once(channel, 'data')
  61. await ctx.fiber.dispose()
  62. expect(channel.destroyed).toBe(true)
  63. expect(await handle.waitForExit()).toBe(true)
  64. })
  65. it('leaves the channel absent on an ordinary spawn', async () => {
  66. ctx = new Context()
  67. await ctx.plugin(LocalSubprocessRuntime)
  68. handle = ctx.subprocess.spawn({
  69. argv: [process.execPath, '-e', 'process.stdout.write("plain")'],
  70. cwd: process.cwd(),
  71. stdio: { stdin: 'ignore', stdout: { maxBytes: 32 }, stderr: { maxBytes: 32 } },
  72. graceMs: 1000,
  73. })
  74. expect(handle.control).toBeUndefined()
  75. expect(await handle.done).toEqual({ exitCode: 0, signal: null })
  76. expect(handle.collected.stdout?.readFrom(0).text).toBe('plain')
  77. expect(await handle.waitForExit()).toBe(true)
  78. })
  79. it.each(['managed', 'fallback'] as const)('returns exact binary control bytes through %s independently of stdio', async (backend) => {
  80. root = await mkdtemp(join(tmpdir(), 'dsh-control-'))
  81. ctx = new Context()
  82. await ctx.plugin(LocalSubprocessRuntime)
  83. const input = Buffer.alloc(256 * 1024)
  84. for (let index = 0; index < input.length; index++) input[index] = index % 256
  85. const request: SubprocessSpawnSpec = {
  86. argv: [process.execPath, fixture, helper, String(input.length)],
  87. cwd: root,
  88. stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 }, control: 'pipe' },
  89. graceMs: 1000,
  90. }
  91. handle = backend === 'managed' ? ctx.subprocess.spawn(request) : spawnSubprocess(request)
  92. const channel = handle.control
  93. if (channel === undefined) throw new Error('requested control pipe is absent')
  94. const received = (async () => {
  95. const chunks: Buffer[] = []
  96. for await (const chunk of channel) chunks.push(Buffer.from(chunk as Uint8Array))
  97. return Buffer.concat(chunks)
  98. })()
  99. channel.write(input)
  100. expect(await received).toEqual(input)
  101. expect(await handle.done).toEqual({ exitCode: 0, signal: null })
  102. expect(handle.collected.stdout?.readFrom(0).text).toBe('ordinary stdout\n')
  103. expect(handle.collected.stderr?.readFrom(0).text).toBe('ordinary stderr\n')
  104. expect(await handle.waitForExit()).toBe(true)
  105. })
  106. it('rejects a caller-authored control marker before starting a child', async () => {
  107. ctx = new Context()
  108. await ctx.plugin(LocalSubprocessRuntime)
  109. expect(() => ctx?.subprocess.spawn({
  110. argv: [process.execPath, '-e', 'throw new Error("must not execute")'],
  111. cwd: process.cwd(),
  112. env: { [SUBPROCESS_CONTROL_ENV]: 'pipe' },
  113. stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' },
  114. graceMs: 1000,
  115. })).toThrow('reserved')
  116. })
  117. })