webserver.spec.ts 10.0 KB

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