webserver.spec.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 { once } from 'node:events'
  10. import { connect } from 'node:net'
  11. import { tmpdir } from 'node:os'
  12. import { join } from 'node:path'
  13. import { pathToFileURL } from 'node:url'
  14. import { afterEach, describe, expect, it } from 'vitest'
  15. import { Context } from 'cordis'
  16. import Loader from '@cordisjs/plugin-loader'
  17. import Include from '@cordisjs/plugin-include'
  18. import HttpServer from '../src/index.ts'
  19. let root: string | undefined
  20. let context: Context | undefined
  21. afterEach(async () => {
  22. await context?.fiber.dispose()
  23. context = undefined
  24. if (root !== undefined) await rm(root, { recursive: true, force: true })
  25. root = undefined
  26. })
  27. /** Write a dist fixture and a cordis.yml with one webserver row, then boot it through the real Loader. */
  28. async function loadComposition(port = 0): Promise<Context> {
  29. root = await mkdtemp(join(tmpdir(), 'dsh-webserver-loader-'))
  30. const dist = join(root, 'dist')
  31. await mkdir(dist)
  32. const distIndex = join(dist, 'index.html')
  33. await writeFile(distIndex, '<head></head><body>shell</body>')
  34. await writeFile(join(dist, 'app.js'), 'export {}')
  35. const configPath = join(root, 'cordis.yml')
  36. await writeFile(configPath, [
  37. "- name: '@deepseek-ai/dsh-host-webserver'",
  38. ' config:',
  39. " host: '127.0.0.1'",
  40. ` port: ${String(port)}`,
  41. ` distIndex: '${distIndex}'`,
  42. '',
  43. ].join('\n'))
  44. context = new Context()
  45. context.baseUrl = pathToFileURL(root).href + '/'
  46. await context.plugin(Loader)
  47. context.loader.builtins.include = Include
  48. const modules = new Map<string, unknown>([
  49. ['@deepseek-ai/dsh-host-webserver', HttpServer],
  50. ])
  51. context.loader.internal = {
  52. version: 'v2',
  53. async import(specifier: string) {
  54. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  55. return modules.get(specifier)
  56. },
  57. } as unknown as NonNullable<typeof context.loader.internal>
  58. await context.loader.create({
  59. name: 'cordis:include',
  60. config: { path: pathToFileURL(configPath).href },
  61. })
  62. await context.loader.await()
  63. return context
  64. }
  65. /** GET (by default) one path against the running server; returns status plus a body prefix. */
  66. async function request(port: number, path: string, init?: RequestInit): Promise<{ status: number; body: string }> {
  67. const response = await fetch(`http://127.0.0.1:${String(port)}${path}`, init)
  68. return { status: response.status, body: (await response.text()).slice(0, 80) }
  69. }
  70. /** Open one raw upgrade request and return after the handler writes its response. */
  71. async function upgrade(port: number, path: string): Promise<ReturnType<typeof connect>> {
  72. const socket = connect(port, '127.0.0.1')
  73. await once(socket, 'connect')
  74. const response = once(socket, 'data')
  75. socket.write([
  76. `GET ${path} HTTP/1.1`,
  77. `Host: 127.0.0.1:${String(port)}`,
  78. 'Connection: Upgrade',
  79. 'Upgrade: dsh-test',
  80. '',
  81. '',
  82. ].join('\r\n'))
  83. const [data] = await response as [Buffer]
  84. expect(String(data)).toContain('101 Switching Protocols')
  85. return socket
  86. }
  87. describe('real Loader composition', () => {
  88. // Real-Loader composition resolves workspace packages through tsx at test
  89. // time; first resolution after the host/client program split is slow enough
  90. // to trip the default 5s budget on cold caches.
  91. it('serves registered routes, index taps, and the static fallback semantics', { timeout: 60_000 }, async () => {
  92. const loaded = await loadComposition()
  93. const unloaded = [...loaded.loader.entries()]
  94. .filter(entry => entry.fiber === undefined && !entry.disabled)
  95. .map(entry => entry.options.name)
  96. expect(unloaded).toEqual([])
  97. const server = loaded.httpServer
  98. expect(server).toBeInstanceOf(HttpServer)
  99. const port = server.port
  100. expect(port).toBeGreaterThan(0)
  101. // Routing precedence: exact beats prefix, longest prefix wins, a prefix
  102. // route answers its own path, and routes own their method handling
  103. // (POST reaches a registered prefix; 405 is fallback-only semantics).
  104. server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } })
  105. server.register({ kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } })
  106. server.register({ kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } })
  107. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  108. expect(await request(port, '/api/anything')).toMatchObject({ status: 200, body: 'API' })
  109. expect(await request(port, '/api/deep/leaf')).toMatchObject({ status: 200, body: 'DEEP' })
  110. expect(await request(port, '/api')).toMatchObject({ status: 200, body: 'API' })
  111. expect(await request(port, '/api/anything', { method: 'POST' })).toMatchObject({ status: 200, body: 'API' })
  112. // Index taps apply in registration order on `/` and on the SPA fallback;
  113. // the disposer removes the transform.
  114. const untap = server.tapIndex(html => html.replace('<head>', '<head><script>window.__T__=1</script>'))
  115. expect((await request(port, '/')).body).toContain('__T__')
  116. expect((await request(port, '/no/such/route')).body).toContain('__T__')
  117. untap()
  118. expect((await request(port, '/')).body).not.toContain('__T__')
  119. // Static fallback semantics: real asset served, traversal 403, non-GET/
  120. // HEAD without a matching route 405.
  121. expect(await request(port, '/app.js')).toMatchObject({ status: 200, body: 'export {}' })
  122. await writeFile(join(root!, 'dist', 'app.js'), 'export const rebuilt = true')
  123. expect(await request(port, '/app.js')).toMatchObject({ status: 200, body: 'export const rebuilt = true' })
  124. expect((await request(port, '/..%2f..%2fetc%2fpasswd')).status).toBe(403)
  125. expect((await request(port, '/nowhere', { method: 'POST' })).status).toBe(405)
  126. // Per-request error containment: a malformed %-escape answers 400 and the
  127. // server keeps serving afterwards (no process-level failure path).
  128. expect((await request(port, '/%zz')).status).toBe(400)
  129. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  130. // Duplicate (kind, path) is a misconfiguration and throws; the disposer
  131. // restores registrability (register/disposer symmetry).
  132. expect(() => server.register({ kind: 'exact', path: '/probe', handler: () => {} }))
  133. .toThrow(/duplicate exact route/)
  134. const disposeOnce = server.register({ kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } })
  135. expect(await request(port, '/once')).toMatchObject({ status: 200, body: 'ONCE' })
  136. disposeOnce()
  137. expect((await request(port, '/once')).body).toContain('shell') // back to the SPA fallback
  138. expect(() => server.register({ kind: 'exact', path: '/once', handler: () => {} })).not.toThrow()
  139. // Upgrade routes match exact pathnames, reject duplicate ownership, and
  140. // become registrable again after disposal. The accepted socket stays open
  141. // so the teardown assertion also covers upgraded-connection ownership.
  142. let upgradedServerClosed = false
  143. const disposeUpgrade = server.registerUpgrade({
  144. path: '/events',
  145. handler: (_req, socket) => {
  146. socket.once('close', () => { upgradedServerClosed = true })
  147. socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n')
  148. },
  149. })
  150. expect(() => server.registerUpgrade({ path: '/events', handler: () => {} }))
  151. .toThrow(/duplicate upgrade route/)
  152. const upgraded = await upgrade(port, '/events?stream=mux')
  153. disposeUpgrade()
  154. expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })).not.toThrow()
  155. // The webserver contains raw-socket errors even before an upgrade handler
  156. // has installed its protocol implementation.
  157. server.registerUpgrade({
  158. path: '/upgrade-error',
  159. handler: async (_req, socket) => {
  160. await Promise.resolve()
  161. socket.destroy(new Error('test upgrade transport failure'))
  162. },
  163. })
  164. const failedUpgrade = connect(port, '127.0.0.1')
  165. failedUpgrade.on('error', () => { /* The server-side reset is the fixture outcome. */ })
  166. await once(failedUpgrade, 'connect')
  167. const failedUpgradeClosed = once(failedUpgrade, 'close')
  168. failedUpgrade.write([
  169. 'GET /upgrade-error HTTP/1.1',
  170. `Host: 127.0.0.1:${String(port)}`,
  171. 'Connection: Upgrade',
  172. 'Upgrade: dsh-test',
  173. '',
  174. '',
  175. ].join('\r\n'))
  176. await failedUpgradeClosed
  177. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  178. // Teardown closes both ordinary and upgraded sockets before it resolves.
  179. await loaded.fiber.dispose()
  180. expect(upgradedServerClosed).toBe(true)
  181. upgraded.destroy()
  182. await expect(request(port, '/probe')).rejects.toThrow()
  183. })
  184. it('fails the fiber when the port is already taken (fail-loud at activation)', { timeout: 60_000 }, async () => {
  185. const first = await loadComposition()
  186. const takenPort = first.httpServer.port
  187. const firstRoot = root
  188. root = undefined // keep the first composition's files until the end
  189. let second: Context | undefined
  190. try {
  191. let failure: unknown
  192. try {
  193. await loadComposition(takenPort)
  194. } catch (error) {
  195. failure = error
  196. }
  197. second = context
  198. expect(String(failure)).toMatch(/failed to apply loader entry.*EADDRINUSE/)
  199. } finally {
  200. await second?.fiber.dispose()
  201. context = first
  202. if (root !== undefined) await rm(root, { recursive: true, force: true })
  203. root = firstRoot
  204. }
  205. })
  206. })