bootstrap.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import { describe, expect, it } from 'vitest'
  2. import { EventEmitter } from 'node:events'
  3. import { LogBuffer, makeConsoleShim, makeNamespaces, captureStreamWrites, prepareValue, runWorkerMain, truncateUtf8Bytes, wireReplies } from '@deepseek-ai/dsh-code-runtime-worker/src/bootstrap.ts'
  4. import type { BootstrapPort, PatchableStream, PendingCall } from '@deepseek-ai/dsh-code-runtime-worker/src/bootstrap.ts'
  5. import type { ReplyMessage, WorkerToHost } from '@deepseek-ai/dsh-code-runtime-worker/src/protocol.ts'
  6. import type { CodeLogEntry } from '@deepseek-ai/dsh-code-runtime'
  7. /**
  8. * An in-process stand-in for the worker's parentPort: the test plays the
  9. * HOST side — inspect what the bootstrap posted, feed replies back — so
  10. * every line of worker-side logic runs under coverage without spawning an
  11. * isolate (real-worker behavior is pinned by runtime.spec.ts).
  12. */
  13. class FakePort implements BootstrapPort {
  14. sent: WorkerToHost[] = []
  15. private readonly emitter = new EventEmitter()
  16. /** Host-scripted responder; return undefined to leave the call pending. */
  17. respond: (message: WorkerToHost) => ReplyMessage | undefined = () => undefined
  18. postMessage(message: WorkerToHost): void {
  19. this.sent.push(message)
  20. const reply = this.respond(message)
  21. if (reply) queueMicrotask(() => this.emitter.emit('message', reply))
  22. }
  23. on(event: 'message', listener: (message: ReplyMessage) => void): void {
  24. this.emitter.on(event, listener)
  25. }
  26. deliver(message: ReplyMessage): void {
  27. this.emitter.emit('message', message)
  28. }
  29. logs(): CodeLogEntry[] {
  30. return this.sent.filter(message => message.type === 'log').map(message => message.entry)
  31. }
  32. done(): WorkerToHost | undefined {
  33. return this.sent.find(message => message.type === 'done')
  34. }
  35. }
  36. function fakeStreams(): { stdout: PatchableStream; stderr: PatchableStream } {
  37. return { stdout: { write: () => true }, stderr: { write: () => true } }
  38. }
  39. const BOOT = { maxLogBytes: 65_536, maxValueBytes: 32_768 }
  40. describe('LogBuffer', () => {
  41. it('streams entries to the sink until the byte budget, then emits one marker and drops the rest', () => {
  42. const seen: CodeLogEntry[] = []
  43. const buffer = new LogBuffer(10, entry => seen.push(entry))
  44. buffer.push({ source: 'console', level: 'log', text: '12345' })
  45. buffer.push({ source: 'console', level: 'log', text: '123456' })
  46. buffer.push({ source: 'console', level: 'log', text: 'dropped' })
  47. expect(seen.map(entry => entry.text)).toEqual([
  48. '12345',
  49. '[dsh-code-runtime-worker] log capture truncated at 10 bytes',
  50. ])
  51. })
  52. })
  53. describe('makeConsoleShim', () => {
  54. it('captures the five levels and renders non-strings inspect-style', () => {
  55. const seen: CodeLogEntry[] = []
  56. const shim = makeConsoleShim(new LogBuffer(1_000, entry => seen.push(entry)))
  57. shim.log('plain', { a: 1 })
  58. shim.info('i')
  59. shim.warn('w')
  60. shim.error('e')
  61. shim.debug('d')
  62. expect(seen.map(entry => entry.level)).toEqual(['log', 'info', 'warn', 'error', 'debug'])
  63. expect(seen[0]?.text).toBe('plain { a: 1 }')
  64. expect(seen.every(entry => entry.source === 'console')).toBe(true)
  65. })
  66. })
  67. describe('captureStreamWrites', () => {
  68. it('redirects writes into the buffer and restores on request', () => {
  69. const seen: CodeLogEntry[] = []
  70. const buffer = new LogBuffer(1_000, entry => seen.push(entry))
  71. let underlying = ''
  72. const stream: PatchableStream = { write: (chunk: unknown) => { underlying += String(chunk); return true } }
  73. const restore = captureStreamWrites(buffer, stream, 'stdout')
  74. stream.write('captured', 'utf8')
  75. stream.write(Buffer.from('bytes'))
  76. restore()
  77. stream.write('after')
  78. expect(seen.map(entry => entry.text)).toEqual(['captured', 'bytes'])
  79. expect(seen[0]).toMatchObject({ source: 'stdout' })
  80. expect(underlying).toBe('after')
  81. })
  82. it('invokes the write callback asynchronously, in both optional-encoding shapes', async () => {
  83. const buffer = new LogBuffer(1_000, () => {})
  84. const stream: PatchableStream = { write: () => true }
  85. captureStreamWrites(buffer, stream, 'stdout')
  86. const calls: (Error | null | undefined)[] = []
  87. stream.write('two-arg', (error?: Error | null) => calls.push(error))
  88. stream.write('three-arg', 'utf8', (error?: Error | null) => calls.push(error))
  89. // Node's contract: the callback fires after the write call returns.
  90. expect(calls).toEqual([])
  91. await new Promise<void>(resolve => stream.write('awaited flush', resolve))
  92. expect(calls).toEqual([null, null])
  93. })
  94. it('still fires the callback for a write the exhausted budget drops', async () => {
  95. const buffer = new LogBuffer(4, () => {})
  96. const stream: PatchableStream = { write: () => true }
  97. captureStreamWrites(buffer, stream, 'stdout')
  98. stream.write('this write overflows the budget and is dropped')
  99. await new Promise<void>(resolve => stream.write('also dropped', resolve))
  100. })
  101. })
  102. describe('prepareValue', () => {
  103. it('omits undefined, passes small cloneable values raw', () => {
  104. expect(prepareValue(undefined, 100)).toEqual({})
  105. expect(prepareValue({ a: [1, 'two'] }, 100)).toEqual({ value: { a: [1, 'two'] } })
  106. })
  107. it('replaces a non-cloneable value with its rendering', () => {
  108. const { value } = prepareValue({ fn: () => 1 }, 1_000)
  109. expect(typeof value).toBe('string')
  110. expect(value).toContain('fn')
  111. })
  112. it('replaces an oversized value with a truncation-marked capped rendering', () => {
  113. const { value } = prepareValue('x'.repeat(50), 10)
  114. expect(value).toBe(`${'x'.repeat(10)}… [truncated]`)
  115. })
  116. it('measures a container by its structured-clone wire size, not its bounded rendering', () => {
  117. // The bounded inspect rendering of a huge array is tiny ("... N more
  118. // items"), but its real cross-boundary size is not — the cap must catch
  119. // it, replacing the value with that bounded rendering.
  120. const huge = new Array(50_000).fill(7)
  121. const { value } = prepareValue(huge, 1_000)
  122. expect(typeof value).toBe('string')
  123. expect(value).toContain('more items')
  124. })
  125. it('caps a multibyte string by UTF-8 bytes, not UTF-16 length', () => {
  126. // 4 code units but 12 UTF-8 bytes: a length-counting cap would pass the
  127. // full string through untruncated.
  128. expect(prepareValue('€€€€', 4)).toEqual({ value: '€… [truncated]' })
  129. })
  130. it('caps a multibyte rendering by UTF-8 bytes too', () => {
  131. // Wire size (24-byte string inside an array) exceeds the cap, so the
  132. // value crosses as its rendering — whose truncation must also be
  133. // byte-exact: "[ '" (3 bytes) + two € (6 bytes) = 9; a third € would
  134. // overflow the 10-byte budget.
  135. expect(prepareValue(['€€€€€€€€'], 10)).toEqual({ value: "[ '€€… [truncated]" })
  136. })
  137. })
  138. describe('truncateUtf8Bytes', () => {
  139. it('returns a fitting string whole', () => {
  140. expect(truncateUtf8Bytes('fits', 4)).toBe('fits')
  141. })
  142. it('cuts at a code-point boundary, never mid-surrogate-pair', () => {
  143. // Each 😀 is one code point, two code units, four UTF-8 bytes: a 5-byte
  144. // budget fits exactly one — and never leaves a lone surrogate behind.
  145. const cut = truncateUtf8Bytes('😀😀', 5)
  146. expect(cut).toBe('😀')
  147. expect(Buffer.byteLength(truncateUtf8Bytes('😀😀', 3), 'utf8')).toBe(0)
  148. })
  149. })
  150. describe('makeNamespaces', () => {
  151. it('exposes prototype-colliding names as ordinary own properties', async () => {
  152. const port = new FakePort()
  153. port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: true, value: `${message.name}-ok` } : undefined
  154. const pending = new Map<number, PendingCall>()
  155. wireReplies(port, pending)
  156. const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['__proto__', 'constructor', 'toString'] }] }, port, pending, { value: 1 }) as [Record<string, (args: unknown) => Promise<unknown>>]
  157. expect(Object.getPrototypeOf(tools)).toBeNull()
  158. await expect(tools['__proto__']?.({})).resolves.toBe('__proto__-ok')
  159. await expect(tools['constructor']?.({})).resolves.toBe('constructor-ok')
  160. await expect(tools['toString']?.({})).resolves.toBe('toString-ok')
  161. })
  162. it('rejects a non-cloneable argument without leaking the pending entry', async () => {
  163. let firstCall = true
  164. const throwingPort: BootstrapPort = {
  165. // First call throws an Error (the real DataCloneError shape), the
  166. // second a bare string — the rejection renders both.
  167. postMessage: () => {
  168. if (firstCall) { firstCall = false; throw new Error('DataCloneError-ish') }
  169. throw 'raw-clone-failure'
  170. },
  171. on: () => {},
  172. }
  173. const pending = new Map<number, PendingCall>()
  174. const [tools] = makeNamespaces({ namespaces: [{ global: 'tools', names: ['x'] }] }, throwingPort, pending, { value: 1 }) as [Record<string, (args: unknown) => Promise<unknown>>]
  175. await expect(tools.x?.(() => 1)).rejects.toThrow(/structured-cloneable: DataCloneError-ish/)
  176. await expect(tools.x?.(() => 1)).rejects.toThrow(/structured-cloneable: raw-clone-failure/)
  177. expect(pending.size).toBe(0)
  178. })
  179. })
  180. describe('runWorkerMain', () => {
  181. it('runs a program end-to-end: bindings, console, return value', async () => {
  182. const port = new FakePort()
  183. port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: true, value: (message.args as { n: number }).n * 2 } : undefined
  184. await runWorkerMain(port, {
  185. ...BOOT,
  186. code: 'const doubled = await tools.double({ n: 21 }); console.log("got", doubled); return { doubled };',
  187. namespaces: [{ global: 'tools', names: ['double'] }],
  188. }, fakeStreams())
  189. expect(port.logs()).toEqual([{ source: 'console', level: 'log', text: 'got 42' }])
  190. expect(port.done()).toEqual({ type: 'done', value: { doubled: 42 } })
  191. })
  192. it('reports a thrown program error on the done message', async () => {
  193. const port = new FakePort()
  194. await runWorkerMain(port, { ...BOOT, code: 'throw new Error("boom")', namespaces: [] }, fakeStreams())
  195. const done = port.done()
  196. expect(done?.type).toBe('done')
  197. expect(done?.type === 'done' ? done.error?.message : undefined).toContain('boom')
  198. expect(done?.type === 'done' ? done.value : undefined).toBeUndefined()
  199. })
  200. it('renders non-Error throws and stack-less Errors on the done message', async () => {
  201. const rawPort = new FakePort()
  202. await runWorkerMain(rawPort, { ...BOOT, code: 'throw "raw-throw"', namespaces: [] }, fakeStreams())
  203. expect(rawPort.done()).toEqual({ type: 'done', error: { message: 'raw-throw' } })
  204. const barePort = new FakePort()
  205. await runWorkerMain(barePort, { ...BOOT, code: 'const e = new Error("bare"); e.stack = undefined; throw e', namespaces: [] }, fakeStreams())
  206. expect(barePort.done()).toEqual({ type: 'done', error: { message: 'bare' } })
  207. })
  208. it('surfaces a host failure reply as a program-side rejection it can catch', async () => {
  209. const port = new FakePort()
  210. port.respond = message => message.type === 'call' ? { type: 'reply', id: message.id, ok: false, message: 'denied by host' } : undefined
  211. await runWorkerMain(port, {
  212. ...BOOT,
  213. code: 'try { await tools.x({}) } catch (error) { return `caught: ${error.message}` }',
  214. namespaces: [{ global: 'tools', names: ['x'] }],
  215. }, fakeStreams())
  216. expect(port.done()).toEqual({ type: 'done', value: 'caught: denied by host' })
  217. })
  218. it('ignores replies for unknown pending ids', async () => {
  219. const port = new FakePort()
  220. port.respond = (message) => {
  221. if (message.type !== 'call') return undefined
  222. // Deliver a stray reply first; the real one follows.
  223. port.deliver({ type: 'reply', id: 9_999, ok: true, value: 'stray' })
  224. return { type: 'reply', id: message.id, ok: true, value: 'real' }
  225. }
  226. await runWorkerMain(port, {
  227. ...BOOT,
  228. code: 'return await tools.x({})',
  229. namespaces: [{ global: 'tools', names: ['x'] }],
  230. }, fakeStreams())
  231. expect(port.done()).toEqual({ type: 'done', value: 'real' })
  232. })
  233. it('captures raw stream writes through the patched process streams', async () => {
  234. const port = new FakePort()
  235. const streams = fakeStreams()
  236. await runWorkerMain(port, { ...BOOT, code: 'return 1', namespaces: [] }, streams)
  237. streams.stdout.write('never seen — already restored? no: patch persists in worker')
  238. // The patch stays installed for the worker's lifetime; writes during the
  239. // program landed in order. Here the program wrote nothing via streams, so
  240. // only the post-run write above went through the patched slot.
  241. expect(port.logs().at(-1)).toMatchObject({ source: 'stdout' })
  242. })
  243. })