webserver.spec.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /**
  2. * REAL-composition coverage: a test-only cordis.yml booted through the
  3. * vendored Loader mounts the webserver row, and every assertion observes the
  4. * user-visible HTTP surface of the running server (routing precedence, index
  5. * taps, static-fallback semantics, per-request error containment, teardown).
  6. */
  7. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  8. import { mkdir } from 'node:fs/promises'
  9. import { tmpdir } from 'node:os'
  10. import { join } from 'node:path'
  11. import { pathToFileURL } from 'node:url'
  12. import { afterEach, describe, expect, it } from 'vitest'
  13. import { Context, FiberState } from 'cordis'
  14. import Loader from '@cordisjs/plugin-loader'
  15. import Include from '@cordisjs/plugin-include'
  16. import HttpServer from '../src/index.ts'
  17. let root: string | undefined
  18. let context: Context | undefined
  19. afterEach(async () => {
  20. await context?.fiber.dispose()
  21. context = undefined
  22. if (root !== undefined) await rm(root, { recursive: true, force: true })
  23. root = undefined
  24. })
  25. /** Write a dist fixture and a cordis.yml with one webserver row, then boot it through the real Loader. */
  26. async function loadComposition(port = 0): Promise<Context> {
  27. root = await mkdtemp(join(tmpdir(), 'dsh-webserver-loader-'))
  28. const dist = join(root, 'dist')
  29. await mkdir(dist)
  30. const distIndex = join(dist, 'index.html')
  31. await writeFile(distIndex, '<head></head><body>shell</body>')
  32. await writeFile(join(dist, 'app.js'), 'export {}')
  33. const configPath = join(root, 'cordis.yml')
  34. await writeFile(configPath, [
  35. "- name: '@deepseek-ai/dsh-host-webserver'",
  36. ' config:',
  37. " host: '127.0.0.1'",
  38. ` port: ${String(port)}`,
  39. ` distIndex: '${distIndex}'`,
  40. '',
  41. ].join('\n'))
  42. context = new Context()
  43. context.baseUrl = pathToFileURL(root).href + '/'
  44. await context.plugin(Loader)
  45. context.loader.builtins.include = Include
  46. const modules = new Map<string, unknown>([
  47. ['@deepseek-ai/dsh-host-webserver', HttpServer],
  48. ])
  49. context.loader.internal = {
  50. version: 'v2',
  51. async import(specifier: string) {
  52. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  53. return modules.get(specifier)
  54. },
  55. } as unknown as NonNullable<typeof context.loader.internal>
  56. await context.loader.create({
  57. name: 'cordis:include',
  58. config: { path: pathToFileURL(configPath).href },
  59. })
  60. await context.loader.await()
  61. return context
  62. }
  63. /** GET (by default) one path against the running server; returns status plus a body prefix. */
  64. async function request(port: number, path: string, init?: RequestInit): Promise<{ status: number; body: string }> {
  65. const response = await fetch(`http://127.0.0.1:${String(port)}${path}`, init)
  66. return { status: response.status, body: (await response.text()).slice(0, 80) }
  67. }
  68. describe('real Loader composition', () => {
  69. // Real-Loader composition resolves workspace packages through tsx at test
  70. // time; first resolution after the host/client program split is slow enough
  71. // to trip the default 5s budget on cold caches.
  72. it('serves registered routes, index taps, and the static fallback semantics', { timeout: 60_000 }, async () => {
  73. const loaded = await loadComposition()
  74. const unloaded = [...loaded.loader.entries()]
  75. .filter(entry => entry.fiber === undefined && !entry.disabled)
  76. .map(entry => entry.options.name)
  77. expect(unloaded).toEqual([])
  78. const server = loaded.httpServer
  79. expect(server).toBeInstanceOf(HttpServer)
  80. const port = server.port
  81. expect(port).toBeGreaterThan(0)
  82. // Routing precedence: exact beats prefix, longest prefix wins, a prefix
  83. // route answers its own path, and routes own their method handling
  84. // (POST reaches a registered prefix; 405 is fallback-only semantics).
  85. server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } })
  86. server.register({ kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } })
  87. server.register({ kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } })
  88. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  89. expect(await request(port, '/api/anything')).toMatchObject({ status: 200, body: 'API' })
  90. expect(await request(port, '/api/deep/leaf')).toMatchObject({ status: 200, body: 'DEEP' })
  91. expect(await request(port, '/api')).toMatchObject({ status: 200, body: 'API' })
  92. expect(await request(port, '/api/anything', { method: 'POST' })).toMatchObject({ status: 200, body: 'API' })
  93. // Index taps apply in registration order on `/` and on the SPA fallback;
  94. // the disposer removes the transform.
  95. const untap = server.tapIndex(html => html.replace('<head>', '<head><script>window.__T__=1</script>'))
  96. expect((await request(port, '/')).body).toContain('__T__')
  97. expect((await request(port, '/no/such/route')).body).toContain('__T__')
  98. untap()
  99. expect((await request(port, '/')).body).not.toContain('__T__')
  100. // Static fallback semantics: real asset served, traversal 403, non-GET/
  101. // HEAD without a matching route 405.
  102. expect(await request(port, '/app.js')).toMatchObject({ status: 200, body: 'export {}' })
  103. expect((await request(port, '/..%2f..%2fetc%2fpasswd')).status).toBe(403)
  104. expect((await request(port, '/nowhere', { method: 'POST' })).status).toBe(405)
  105. // Per-request error containment: a malformed %-escape answers 400 and the
  106. // server keeps serving afterwards (no process-level failure path).
  107. expect((await request(port, '/%zz')).status).toBe(400)
  108. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  109. // Duplicate (kind, path) is a misconfiguration and throws; the disposer
  110. // restores registrability (register/disposer symmetry).
  111. expect(() => server.register({ kind: 'exact', path: '/probe', handler: () => {} }))
  112. .toThrow(/duplicate exact route/)
  113. const disposeOnce = server.register({ kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } })
  114. expect(await request(port, '/once')).toMatchObject({ status: 200, body: 'ONCE' })
  115. disposeOnce()
  116. expect((await request(port, '/once')).body).toContain('shell') // back to the SPA fallback
  117. expect(() => server.register({ kind: 'exact', path: '/once', handler: () => {} })).not.toThrow()
  118. // Teardown: fiber dispose closes the socket and severs held connections.
  119. await loaded.fiber.dispose()
  120. await expect(request(port, '/probe')).rejects.toThrow()
  121. })
  122. it('fails the fiber when the port is already taken (fail-loud at activation)', { timeout: 60_000 }, async () => {
  123. const first = await loadComposition()
  124. const takenPort = first.httpServer.port
  125. const firstRoot = root
  126. root = undefined // keep the first composition's files until the end
  127. // loader.await() never rejects (allSettled); the bind failure surfaces as
  128. // a FAILED fiber whose error escapes as a late rejection — the shape the
  129. // boot's installFailLoud is contracted to catch. Capture it here the same
  130. // way, and assert it really is the bind error.
  131. const rejections: unknown[] = []
  132. const onUnhandled = (err: unknown): void => { rejections.push(err) }
  133. process.on('unhandledRejection', onUnhandled)
  134. let second: Context | undefined
  135. try {
  136. second = await loadComposition(takenPort)
  137. const entry = [...second.loader.entries()].find(e => e.options.name === '@deepseek-ai/dsh-host-webserver')
  138. expect(entry?.fiber?.state).toBe(FiberState.FAILED)
  139. // The rejection escapes a tick after loader.await() settles; bounded poll.
  140. for (let i = 0; i < 100 && rejections.length === 0; i++) {
  141. await new Promise(resolve => setTimeout(resolve, 10))
  142. }
  143. expect(rejections.map(String).join('\n')).toContain('EADDRINUSE')
  144. } finally {
  145. process.off('unhandledRejection', onUnhandled)
  146. await second?.fiber.dispose()
  147. context = first
  148. if (root !== undefined) await rm(root, { recursive: true, force: true })
  149. root = firstRoot
  150. }
  151. })
  152. })