webserver.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 '@deepseek-ai/cordis'
  15. import Loader from '@deepseek-ai/cordis-plugin-loader'
  16. import Include from '@deepseek-ai/cordis-plugin-include'
  17. import HttpServer, { renderIndexInjections } 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, gzip = false): 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. ...(gzip
  36. ? [
  37. ' compression: gzip',
  38. ' compressionLevel: 1',
  39. ' compressionThresholdBytes: 16',
  40. ]
  41. : []),
  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(
  67. port: number,
  68. path: string,
  69. init?: RequestInit,
  70. ): Promise<{ status: number; body: string; headers: Headers }> {
  71. const response = await fetch(`http://127.0.0.1:${String(port)}${path}`, init)
  72. return { status: response.status, body: (await response.text()).slice(0, 80), headers: response.headers }
  73. }
  74. /** Open one raw upgrade request and return after the handler writes its response. */
  75. async function upgrade(port: number, path: string): Promise<ReturnType<typeof connect>> {
  76. const socket = connect(port, '127.0.0.1')
  77. await once(socket, 'connect')
  78. const response = once(socket, 'data')
  79. socket.write([
  80. `GET ${path} HTTP/1.1`,
  81. `Host: 127.0.0.1:${String(port)}`,
  82. 'Connection: Upgrade',
  83. 'Upgrade: dsh-test',
  84. '',
  85. '',
  86. ].join('\r\n'))
  87. const [data] = await response as [Buffer]
  88. expect(String(data)).toContain('101 Switching Protocols')
  89. return socket
  90. }
  91. describe('real Loader composition', () => {
  92. it('applies gzip only to eligible socket-backed HTTP responses', { timeout: 60_000 }, async () => {
  93. expect(HttpServer.Config({ host: '127.0.0.1', port: 0 })).toEqual({
  94. host: '127.0.0.1',
  95. port: 0,
  96. compression: 'none',
  97. compressionLevel: 1,
  98. compressionThresholdBytes: 1024,
  99. })
  100. expect(() => HttpServer.Config({
  101. host: '127.0.0.1', port: 0, compressionLevel: 10,
  102. })).toThrow()
  103. const loaded = await loadComposition(0, true)
  104. const server = loaded.webServer
  105. const body = 'compressible response '.repeat(8)
  106. server.register({
  107. kind: 'exact',
  108. path: '/text',
  109. handler: (_req, res) => {
  110. res.writeHead(200, {
  111. 'content-type': 'text/plain; charset=utf-8',
  112. 'content-length': String(Buffer.byteLength(body)),
  113. })
  114. res.end(body)
  115. },
  116. })
  117. server.register({
  118. kind: 'exact',
  119. path: '/stream',
  120. handler: (_req, res) => {
  121. res.writeHead(200, { 'content-type': 'application/json' })
  122. res.write(body.slice(0, 40))
  123. res.end(body.slice(40))
  124. },
  125. })
  126. server.register({
  127. kind: 'exact',
  128. path: '/small',
  129. handler: (_req, res) => {
  130. res.writeHead(200, { 'content-type': 'text/plain', 'content-length': '5' })
  131. res.end('small')
  132. },
  133. })
  134. server.register({
  135. kind: 'exact',
  136. path: '/events',
  137. handler: (_req, res) => {
  138. res.writeHead(200, { 'content-type': 'text/event-stream' })
  139. res.end(body)
  140. },
  141. })
  142. server.register({
  143. kind: 'exact',
  144. path: '/archive',
  145. handler: (_req, res) => {
  146. res.writeHead(200, { 'content-type': 'application/gzip' })
  147. res.end(body)
  148. },
  149. })
  150. server.register({
  151. kind: 'exact',
  152. path: '/range',
  153. handler: (_req, res) => {
  154. res.writeHead(206, { 'content-type': 'text/plain', 'content-range': 'bytes 0-15/160' })
  155. res.end(body.slice(0, 16))
  156. },
  157. })
  158. const compressed = await request(server.port, '/text', { headers: { 'accept-encoding': 'br, gzip, deflate' } })
  159. expect(compressed).toMatchObject({ status: 200, body: body.slice(0, 80) })
  160. expect(compressed.headers.get('content-encoding')).toBe('gzip')
  161. expect(compressed.headers.get('content-length')).toBeNull()
  162. expect(compressed.headers.get('vary')).toBe('Accept-Encoding')
  163. const streamed = await request(server.port, '/stream', { headers: { 'accept-encoding': 'gzip' } })
  164. expect(streamed).toMatchObject({ body: body.slice(0, 80) })
  165. expect(streamed.headers.get('content-encoding')).toBe('gzip')
  166. expect((await request(server.port, '/small', { headers: { 'accept-encoding': 'gzip' } }))
  167. .headers.get('content-encoding')).toBeNull()
  168. const identity = await request(server.port, '/text', {
  169. headers: { 'accept-encoding': 'gzip;q=0.5, identity;q=1' },
  170. })
  171. expect(identity.headers.get('content-encoding')).toBeNull()
  172. expect(identity.headers.get('vary')).toBe('Accept-Encoding')
  173. expect((await request(server.port, '/events', { headers: { 'accept-encoding': 'gzip' } }))
  174. .headers.get('content-encoding')).toBeNull()
  175. expect((await request(server.port, '/archive', { headers: { 'accept-encoding': 'gzip' } }))
  176. .headers.get('content-encoding')).toBeNull()
  177. expect((await request(server.port, '/range', { headers: { 'accept-encoding': 'gzip' } }))
  178. .headers.get('content-encoding')).toBeNull()
  179. })
  180. // Real-Loader composition resolves workspace packages through tsx at test
  181. // time; first resolution after the host/client program split is slow enough
  182. // to trip the default 5s budget on cold caches.
  183. it('serves registered routes, index taps, and the fallback-seat semantics', { timeout: 60_000 }, async () => {
  184. const loaded = await loadComposition()
  185. const unloaded = [...loaded.loader.entries()]
  186. .filter(entry => entry.fiber === undefined && !entry.disabled)
  187. .map(entry => entry.options.name)
  188. expect(unloaded).toEqual([])
  189. const server = loaded.webServer
  190. expect(server).toBeInstanceOf(HttpServer)
  191. const port = server.port
  192. expect(port).toBeGreaterThan(0)
  193. // Routing precedence: exact beats prefix, longest prefix wins, a prefix
  194. // route answers its own path, and routes own their method handling
  195. // (POST reaches a registered prefix; 405 is fallback-only semantics).
  196. server.register({ kind: 'exact', path: '/probe', handler: (_req, res) => { res.writeHead(200); res.end('EXACT') } })
  197. server.register({ kind: 'prefix', path: '/api', handler: (_req, res) => { res.writeHead(200); res.end('API') } })
  198. server.register({ kind: 'prefix', path: '/api/deep', handler: (_req, res) => { res.writeHead(200); res.end('DEEP') } })
  199. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  200. expect(await request(port, '/api/anything')).toMatchObject({ status: 200, body: 'API' })
  201. expect(await request(port, '/api/deep/leaf')).toMatchObject({ status: 200, body: 'DEEP' })
  202. expect(await request(port, '/api')).toMatchObject({ status: 200, body: 'API' })
  203. expect(await request(port, '/api/anything', { method: 'POST' })).toMatchObject({ status: 200, body: 'API' })
  204. // Fallback seat: 404 while unclaimed; the owner answers everything no
  205. // named route matches; index taps are the owner's to apply; the seat
  206. // admits exactly one owner and the disposer releases it.
  207. expect((await request(port, '/no/such/route')).status).toBe(404)
  208. const untap = server.tapIndex(html => html.replace('<head>', '<head><script>window.__T__=1</script>'))
  209. expect(server.applyIndexTaps('<head></head>')).toContain('__T__')
  210. const releaseFallback = server.registerFallback((req, res) => {
  211. // Decode like a real static server would — a malformed %-escape throws
  212. // here, probing the webserver's per-request error containment.
  213. decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname)
  214. res.writeHead(200, { 'content-type': 'text/html' })
  215. res.end(server.applyIndexTaps('<head></head><body>shell</body>'))
  216. })
  217. expect(() => server.registerFallback(() => {})).toThrow(/fallback already registered/)
  218. expect((await request(port, '/no/such/route')).body).toContain('__T__')
  219. untap()
  220. expect((await request(port, '/no/such/route')).body).not.toContain('__T__')
  221. expect((await request(port, '/no/such/route')).body).toContain('shell')
  222. // Per-request error containment: a malformed %-escape answers 400 and the
  223. // server keeps serving afterwards (no process-level failure path).
  224. expect((await request(port, '/%zz')).status).toBe(400)
  225. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  226. // Duplicate (kind, path) is a misconfiguration and throws; the disposer
  227. // restores registrability (register/disposer symmetry).
  228. expect(() => server.register({ kind: 'exact', path: '/probe', handler: () => {} }))
  229. .toThrow(/duplicate exact route/)
  230. const disposeOnce = server.register({ kind: 'exact', path: '/once', handler: (_req, res) => { res.writeHead(200); res.end('ONCE') } })
  231. expect(await request(port, '/once')).toMatchObject({ status: 200, body: 'ONCE' })
  232. disposeOnce()
  233. expect((await request(port, '/once')).body).toContain('shell') // back to the fallback owner
  234. expect(() => server.register({ kind: 'exact', path: '/once', handler: () => {} })).not.toThrow()
  235. // Releasing the seat restores the unclaimed 404 and registrability.
  236. releaseFallback()
  237. expect((await request(port, '/no/such/route')).status).toBe(404)
  238. expect(() => server.registerFallback(() => {})).not.toThrow()
  239. // Upgrade routes match exact pathnames, reject duplicate ownership, and
  240. // become registrable again after disposal. The accepted socket stays open
  241. // so the teardown assertion also covers upgraded-connection ownership.
  242. let upgradedServerClosed = false
  243. const disposeUpgrade = server.registerUpgrade({
  244. path: '/events',
  245. handler: (_req, socket) => {
  246. socket.once('close', () => { upgradedServerClosed = true })
  247. socket.write('HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: dsh-test\r\n\r\n')
  248. },
  249. })
  250. expect(() => server.registerUpgrade({ path: '/events', handler: () => {} }))
  251. .toThrow(/duplicate upgrade route/)
  252. const upgraded = await upgrade(port, '/events?stream=mux')
  253. disposeUpgrade()
  254. expect(() => server.registerUpgrade({ path: '/events', handler: () => {} })).not.toThrow()
  255. // The webserver contains raw-socket errors even before an upgrade handler
  256. // has installed its protocol implementation.
  257. server.registerUpgrade({
  258. path: '/upgrade-error',
  259. handler: async (_req, socket) => {
  260. await Promise.resolve()
  261. socket.destroy(new Error('test upgrade transport failure'))
  262. },
  263. })
  264. const failedUpgrade = connect(port, '127.0.0.1')
  265. failedUpgrade.on('error', () => { /* The server-side reset is the fixture outcome. */ })
  266. await once(failedUpgrade, 'connect')
  267. const failedUpgradeClosed = once(failedUpgrade, 'close')
  268. failedUpgrade.write([
  269. 'GET /upgrade-error HTTP/1.1',
  270. `Host: 127.0.0.1:${String(port)}`,
  271. 'Connection: Upgrade',
  272. 'Upgrade: dsh-test',
  273. '',
  274. '',
  275. ].join('\r\n'))
  276. await failedUpgradeClosed
  277. expect(await request(port, '/probe')).toMatchObject({ status: 200, body: 'EXACT' })
  278. // Teardown closes both ordinary and upgraded sockets before it resolves.
  279. await loaded.fiber.dispose()
  280. expect(upgradedServerClosed).toBe(true)
  281. upgraded.destroy()
  282. await expect(request(port, '/probe')).rejects.toThrow()
  283. })
  284. it('collects injection rows fresh per render and layers taps over the rendered rows', { timeout: 60_000 }, async () => {
  285. const loaded = await loadComposition()
  286. const server = loaded.webServer
  287. let flag = 'dark'
  288. loaded.on('webserver/index-inject', (table) => {
  289. table.push(
  290. { kind: 'script', placement: 'head', text: 'window.__Q__=1' },
  291. { kind: 'script-src', placement: 'head', src: '/plugins/a.js?rev="1"&x=<y>' },
  292. { kind: 'script-preload', src: '/plugins/b.js?rev="2"&x=<z>' },
  293. { kind: 'global', name: '__DSH_BOOT__', value: { rev: '</script><b>' } },
  294. { kind: 'style', text: 'body{margin:0}' },
  295. { kind: 'html', placement: 'head', html: '<meta name="probe">' },
  296. { kind: 'script', placement: 'body', text: `window.__P__=${JSON.stringify(flag)}` },
  297. )
  298. })
  299. const html = server.renderIndex('<html><head></head><body>shell</body></html>')
  300. // Head rows land right after the opening head tag in table order; the body
  301. // row lands right after the opening body tag.
  302. const order = [
  303. '<head>',
  304. '<script>window.__Q__=1</script>',
  305. '<script src="/plugins/a.js?rev=&quot;1&quot;&amp;x=&lt;y&gt;"></script>',
  306. '<link rel="preload" as="script" href="/plugins/b.js?rev=&quot;2&quot;&amp;x=&lt;z&gt;">',
  307. 'globalThis["__DSH_BOOT__"] = {"rev":"\\u003c/script>\\u003cb>"}',
  308. '<style>body{margin:0}</style>',
  309. '<meta name="probe">',
  310. '<body>',
  311. '<script>window.__P__="dark"</script>',
  312. 'shell',
  313. ].map(part => html.indexOf(part))
  314. expect(order).toEqual([...order].sort((a, b) => a - b))
  315. expect(order.every(at => at !== -1)).toBe(true)
  316. // Fresh collection per render: the listener reads live state at emit time.
  317. flag = 'light'
  318. expect(server.renderIndex('<head></head><body></body>')).toContain('window.__P__="light"')
  319. // Raw taps still run, over the already-rendered rows.
  320. const untap = server.tapIndex(h => h.replace('window.__Q__=1', 'window.__Q__=2'))
  321. expect(server.renderIndex('<head></head><body></body>')).toContain('window.__Q__=2')
  322. untap()
  323. // Tag-less fragments: head rows prepend, body rows append, and the
  324. // boot-readiness tail lands after the last body row.
  325. expect(renderIndexInjections('<main>x</main>', [
  326. { kind: 'script', placement: 'head', text: 'H' },
  327. { kind: 'script', placement: 'body', text: 'B' },
  328. ])).toBe('<script>H</script><main>x</main><script>B</script>'
  329. + '<script>(globalThis.__DSH_BOOT_READY__ ??= Promise.withResolvers()).resolve()</script>')
  330. })
  331. it('fails the fiber when the port is already taken (fail-loud at activation)', { timeout: 60_000 }, async () => {
  332. const first = await loadComposition()
  333. const takenPort = first.webServer.port
  334. const firstRoot = root
  335. root = undefined // keep the first composition's files until the end
  336. let second: Context | undefined
  337. try {
  338. let failure: unknown
  339. try {
  340. await loadComposition(takenPort)
  341. } catch (error) {
  342. failure = error
  343. }
  344. second = context
  345. expect(String(failure)).toMatch(/failed to apply loader entry.*EADDRINUSE/)
  346. } finally {
  347. await second?.fiber.dispose()
  348. context = first
  349. if (root !== undefined) await rm(root, { recursive: true, force: true })
  350. root = firstRoot
  351. }
  352. })
  353. })