worker-lifecycle.host.spec.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /** Host-side Worker lifecycle behavior. */
  2. import { Worker } from 'node:worker_threads'
  3. import { describe, expect, it } from 'vitest'
  4. import { InspectorWorkerLifecycle } from '../src/host/bridge/lifecycle.ts'
  5. describe('Inspector Worker lifecycle', () => {
  6. it('keeps the runtime error listener and treats an already-exited Worker as stopped', async () => {
  7. const worker = new Worker('setImmediate(() => { throw new Error("runtime crash") })', { eval: true })
  8. const lifecycle = new InspectorWorkerLifecycle(worker)
  9. const failed = new Promise<Error>((resolve) => { lifecycle.markRunning(resolve) })
  10. await expect(failed).resolves.toMatchObject({ message: 'runtime crash' })
  11. await expect(lifecycle.stop(100)).resolves.toBeUndefined()
  12. expect(lifecycle.exitCode).toBeTypeOf('number')
  13. })
  14. it('reads readiness and completes graceful shutdown through one persistent owner', async () => {
  15. const worker = new Worker([
  16. "const { parentPort } = require('node:worker_threads')",
  17. "parentPort.postMessage({ type: 'ready', host: '127.0.0.1', port: 9230, targetId: 'test-target' })",
  18. "parentPort.on('message', message => { if (message.type === 'shutdown') process.exit(0) })",
  19. ].join('\n'), { eval: true })
  20. const lifecycle = new InspectorWorkerLifecycle(worker)
  21. await expect(lifecycle.waitForReady(1_000)).resolves.toMatchObject({
  22. host: '127.0.0.1',
  23. port: 9_230,
  24. targetId: 'test-target',
  25. })
  26. lifecycle.markRunning(() => { throw new Error('graceful exit reported as unexpected') })
  27. await expect(lifecycle.stop(1_000)).resolves.toBeUndefined()
  28. expect(lifecycle.exitCode).toBe(0)
  29. })
  30. })