client-handler.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /**
  2. * Wire-protocol coverage over the isomorphic point: InProcessApiClient →
  3. * toFetchHandler(scripted impl) runs the real envelope wrap/unwrap, zod
  4. * two-level parse, rpcId discipline, and SSE framing with no network and no
  5. * browser. Each case scripts its own minimal ApiProxy.
  6. */
  7. import { describe, expect, it, vi } from 'vitest'
  8. import type { SessionId } from '@deepseek-ai/dsh-session'
  9. import type { ApiProxy, HostFrame, MuxFrame, RpcMessage, RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy'
  10. import { InProcessApiClient, RpcId, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
  11. const sid = (id: string): SessionId => id as SessionId
  12. function ok<T>(request: RpcRequest<unknown>, value: T): Promise<RpcResponse<T>> {
  13. return Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value } })
  14. }
  15. /** Scripted impl: every method resolves an empty-ish OK unless a case overrides it. */
  16. function scriptedApi(overrides: {
  17. sessions?: Partial<ApiProxy['sessions']>
  18. host?: Partial<ApiProxy['host']>
  19. events?: Partial<ApiProxy['events']>
  20. respond?: ApiProxy['respond']
  21. } = {}): ApiProxy {
  22. async function *empty<F>(): AsyncGenerator<RpcRequest<F>> { /* no frames */ }
  23. return {
  24. sessions: {
  25. list: r => ok(r, { items: [] }),
  26. create: r => ok(r, { sessionId: sid('s-new') }),
  27. history: r => ok(r, { events: [], hasMore: false }),
  28. prompt: r => ok(r, { accepted: true as const }),
  29. cancel: r => ok(r, { accepted: true as const }),
  30. ...overrides.sessions,
  31. },
  32. host: { describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0 }), ...overrides.host },
  33. workspace: {
  34. list: r => ok(r, { items: [] }),
  35. create: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' }, created: true }),
  36. },
  37. events: { mux: () => empty<MuxFrame>(), host: () => empty<HostFrame>(), ...overrides.events },
  38. respond: overrides.respond ?? (() => Promise.resolve({ accepted: false as const, reason: 'not-pending' as const })),
  39. }
  40. }
  41. function client(api: ApiProxy, timeoutMs?: number): InProcessApiClient {
  42. return new InProcessApiClient(toFetchHandler(api), timeoutMs)
  43. }
  44. describe('unary round trip', () => {
  45. it('carries payload out and value back through the full wire form', async () => {
  46. let seen: RpcRequest<{ cursor?: string }> | undefined
  47. const api = scriptedApi({
  48. sessions: {
  49. list: (r) => {
  50. seen = r
  51. return ok(r, { items: [{ sessionId: sid('s1'), updatedAt: 7, running: false }] })
  52. },
  53. },
  54. })
  55. const response = await client(api).sessions.list({ cursor: 'c1' })
  56. // Impl received the narrow form with a minted id; client returned the same id and value.
  57. expect(seen?.payload).toEqual({ cursor: 'c1' })
  58. expect(seen?.rpcId).toBeTruthy()
  59. expect(response.rpcId).toBe(seen?.rpcId)
  60. expect(response.result).toEqual({ ok: true, value: { items: [{ sessionId: 's1', updatedAt: 7, running: false }] } })
  61. })
  62. it('passes business errors through as 200 + err result, not a throw', async () => {
  63. const api = scriptedApi({
  64. sessions: {
  65. cancel: r => Promise.resolve({ rpcId: r.rpcId, result: { ok: false, error: { code: 'session-not-found', message: 'nope', details: { sessionId: sid('sx') } } } }),
  66. },
  67. })
  68. const response = await client(api).sessions.cancel({ sessionId: sid('sx') })
  69. expect(response.result).toEqual({ ok: false, error: { code: 'session-not-found', message: 'nope', details: { sessionId: 'sx' } } })
  70. })
  71. it('throws on rpcId echo mismatch', async () => {
  72. const api = scriptedApi({
  73. sessions: { list: () => Promise.resolve({ rpcId: RpcId('forged'), result: { ok: true, value: { items: [] } } }) },
  74. })
  75. await expect(client(api).sessions.list({})).rejects.toThrow(/rpcId mismatch/)
  76. })
  77. it('rejects an invalid payload at the handler as 200 + bad-request with issues', async () => {
  78. const api = scriptedApi()
  79. const response = await client(api).sessions.history({ sessionId: 123 as unknown as SessionId })
  80. expect(response.result.ok).toBe(false)
  81. if (!response.result.ok) {
  82. expect(response.result.error.code).toBe('bad-request')
  83. expect((response.result.error.details as { issues: unknown[] }).issues.length).toBeGreaterThan(0)
  84. }
  85. })
  86. it('rejects a method/path mismatch as bad-request', async () => {
  87. const handler = toFetchHandler(scriptedApi())
  88. const body = { type: 'client-request', rpcId: 'r1', method: 'session.create', payload: {} }
  89. const response = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify(body) })
  90. expect(response.status).toBe(200)
  91. const parsed = await response.json() as { result: { ok: boolean; error?: { code: string; message: string } } }
  92. expect(parsed.result.ok).toBe(false)
  93. expect(parsed.result.error?.code).toBe('bad-request')
  94. expect(parsed.result.error?.message).toMatch(/does not match path/)
  95. })
  96. it('rejects a malformed envelope as bad-request, salvaging the rpcId or falling back to the sentinel', async () => {
  97. const handler = toFetchHandler(scriptedApi())
  98. // No salvageable rpcId → the fixed invalid-request sentinel keeps the response a valid ServerResponse.
  99. const noId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify({ nonsense: true }) })
  100. expect(noId.status).toBe(200)
  101. const noIdParsed = await noId.json() as { rpcId: string; result: { ok: boolean } }
  102. expect(noIdParsed.result.ok).toBe(false)
  103. expect(noIdParsed.rpcId).toBe('invalid-request')
  104. // A string rpcId in the otherwise-bad body is salvaged for correlation.
  105. const withId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify({ rpcId: 'salvage-me', nonsense: true }) })
  106. const withIdParsed = await withId.json() as { rpcId: string; result: { ok: boolean } }
  107. expect(withIdParsed.result.ok).toBe(false)
  108. expect(withIdParsed.rpcId).toBe('salvage-me')
  109. })
  110. it('maps carrier failures to HTTP statuses and the client throws transport failure', async () => {
  111. const handler = toFetchHandler(scriptedApi())
  112. // Unknown method → 404.
  113. const notFound = await handler.fetch('http://dsh.internal/api/no.such', { method: 'POST', body: '{}' })
  114. expect(notFound.status).toBe(404)
  115. // Non-JSON body → 400.
  116. const badBody = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: '{oops' })
  117. expect(badBody.status).toBe(400)
  118. // Impl crash → 500, and through the client that is a throw, not an err result.
  119. const crashing = scriptedApi({ sessions: { list: () => { throw new Error('impl exploded') } } })
  120. await expect(client(crashing).sessions.list({})).rejects.toThrow(/transport failure .*500/)
  121. })
  122. it('rejects when the transport never resolves within timeoutMs', async () => {
  123. // AbortSignal.timeout is immune to fake timers; a short real timeout keeps this fast.
  124. const never = new InProcessApiClient({
  125. fetch: (_i: RequestInfo | URL, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
  126. init?.signal?.addEventListener('abort', () => { reject(new Error('aborted by timeout')) })
  127. }),
  128. }, 25)
  129. await expect(never.sessions.list({})).rejects.toThrow()
  130. })
  131. it('aborts a unary call through the caller-supplied external signal', async () => {
  132. // Real-fetch semantics: on abort the rejection is the signal's reason, and the abort
  133. // works even when the transport ignores the signal entirely (hung impl).
  134. const gate = new AbortController()
  135. const hung = new InProcessApiClient({ fetch: () => new Promise<Response>(() => {}) }, 60_000)
  136. const call = hung.sessions.list({}, gate.signal)
  137. gate.abort(new Error('externally aborted'))
  138. await expect(call).rejects.toThrow(/externally aborted/)
  139. })
  140. it('rejects an already-aborted signal before touching the transport, mapping a string reason to an Error', async () => {
  141. let touched = false
  142. const c = new InProcessApiClient({
  143. fetch: () => {
  144. touched = true
  145. return Promise.resolve(new Response('{}'))
  146. },
  147. }, 60_000)
  148. const gate = new AbortController()
  149. gate.abort('gone before start')
  150. await expect(c.sessions.list({}, gate.signal)).rejects.toThrow('gone before start')
  151. expect(touched).toBe(false)
  152. })
  153. it('maps a non-Error, non-string abort reason to the default AbortError message', async () => {
  154. const gate = new AbortController()
  155. const hung = new InProcessApiClient({ fetch: () => new Promise<Response>(() => {}) }, 60_000)
  156. const call = hung.sessions.list({}, gate.signal)
  157. gate.abort(42)
  158. await expect(call).rejects.toThrow('This operation was aborted')
  159. })
  160. it('passes a signal-less doFetch straight through to the handler', async () => {
  161. class Probe extends InProcessApiClient {
  162. direct(url: URL): Promise<Response> {
  163. return this.doFetch(url)
  164. }
  165. }
  166. const probe = new Probe({ fetch: () => Promise.resolve(new Response('raw')) })
  167. const response = await probe.direct(new URL('http://dsh.internal/probe'))
  168. expect(await response.text()).toBe('raw')
  169. })
  170. it('throws on an S→C ok value that fails the method value schema (second-level parse)', async () => {
  171. // Impl echoes rpcId but returns a wrong-shaped value: envelope parse passes, value parse must reject.
  172. const api = scriptedApi({
  173. sessions: { list: r => Promise.resolve({ rpcId: r.rpcId, result: { ok: true, value: { items: 'not-an-array' } } }) as never },
  174. })
  175. await expect(client(api).sessions.list({})).rejects.toThrow()
  176. })
  177. })
  178. describe('workspace domain round trip', () => {
  179. it('routes both workspace methods through their handler rows and value schemas', async () => {
  180. const c = client(scriptedApi())
  181. const list = await c.workspace.list({})
  182. expect(list.result).toEqual({ ok: true, value: { items: [] } })
  183. const created = await c.workspace.create({ path: '/t' })
  184. expect(created.result.ok).toBe(true)
  185. if (created.result.ok) expect(created.result.value.created).toBe(true)
  186. })
  187. it('rejects a create payload violating the exactly-one refine at the handler', async () => {
  188. const response = await client(scriptedApi()).workspace.create({})
  189. expect(response.result.ok).toBe(false)
  190. if (!response.result.ok) expect(response.result.error.code).toBe('bad-request')
  191. })
  192. })
  193. describe('SSE stream path', () => {
  194. it('yields frames in order and skips the comment preamble', async () => {
  195. const frames: MuxFrame[] = [
  196. { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: 3 },
  197. { type: 'stream/error', error: { code: 'internal', message: 'x', details: {} } },
  198. ]
  199. const api = scriptedApi({
  200. events: {
  201. async *mux(request) {
  202. let n = 0
  203. for (const frame of frames) yield { rpcId: RpcId(`push-${n++}-${request.rpcId}`), payload: frame }
  204. },
  205. },
  206. })
  207. const seen: MuxFrame[] = []
  208. for await (const envelope of client(api).events.mux({}, new AbortController().signal)) {
  209. seen.push(envelope.payload)
  210. }
  211. expect(seen).toEqual(frames)
  212. })
  213. it('reassembles frames across arbitrary chunk boundaries', async () => {
  214. // Two SSE frames split so one frame spans chunks and one chunk carries parts of both.
  215. const f1 = { type: 'server-request', rpcId: 'a', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's1', lastSeq: 1 } }
  216. const f2 = { type: 'server-request', rpcId: 'b', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's2', lastSeq: 2 } }
  217. const wire = `: connected\n\ndata: ${JSON.stringify(f1)}\n\ndata: ${JSON.stringify(f2)}\n\n`
  218. const cuts = [5, 40, wire.indexOf('data: ', 40) + 3]
  219. const encoder = new TextEncoder()
  220. const doFetch = (): Promise<Response> => Promise.resolve(new Response(new ReadableStream<Uint8Array>({
  221. start(controller) {
  222. let prev = 0
  223. for (const cut of [...cuts, wire.length]) {
  224. controller.enqueue(encoder.encode(wire.slice(prev, cut)))
  225. prev = cut
  226. }
  227. controller.close()
  228. },
  229. }), { status: 200 }))
  230. const chopped = new InProcessApiClient({ fetch: doFetch })
  231. const seen: string[] = []
  232. for await (const envelope of chopped.events.mux({}, new AbortController().signal)) {
  233. seen.push((envelope.payload as { sessionId: string }).sessionId)
  234. expect(envelope.rpcId).toBe(seen.length === 1 ? 'a' : 'b')
  235. }
  236. expect(seen).toEqual(['s1', 's2'])
  237. })
  238. it('emits a stream/error frame then closes when the impl throws mid-stream', async () => {
  239. const api = scriptedApi({
  240. events: {
  241. async *host(request): AsyncGenerator<RpcRequest<HostFrame>> {
  242. yield { rpcId: RpcId(`p-${request.rpcId}`), payload: { type: 'host/session-added', sessionId: sid('s1') } }
  243. throw new Error('impl died mid-stream')
  244. },
  245. },
  246. })
  247. const seen: HostFrame[] = []
  248. for await (const envelope of client(api).events.host({}, new AbortController().signal)) {
  249. seen.push(envelope.payload)
  250. }
  251. expect(seen.map(f => f.type)).toEqual(['host/session-added', 'stream/error'])
  252. const last = seen.at(-1)
  253. if (last?.type === 'stream/error') expect(last.error.message).toMatch(/impl died mid-stream/)
  254. })
  255. it('drops a malformed SSE frame and keeps the stream alive (S→C two-level parse)', async () => {
  256. const good = { type: 'server-request', rpcId: 'g1', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's1', lastSeq: 1 } }
  257. const badEnvelope = { type: 'server-response', rpcId: 'x' } // wrong quadrant for a stream
  258. const badFrame = { type: 'server-request', rpcId: 'b1', method: 'nope', payload: { type: 'no/such-frame' } }
  259. const wire = [
  260. 'data: {oops', // not JSON
  261. `data: ${JSON.stringify(badEnvelope)}`,
  262. `data: ${JSON.stringify(badFrame)}`,
  263. `data: ${JSON.stringify(good)}`,
  264. ].map(l => `${l}\n\n`).join('')
  265. const doFetch = (): Promise<Response> => Promise.resolve(new Response(new ReadableStream<Uint8Array>({
  266. start(controller) {
  267. controller.enqueue(new TextEncoder().encode(wire))
  268. controller.close()
  269. },
  270. }), { status: 200 }))
  271. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  272. try {
  273. const seen: MuxFrame[] = []
  274. for await (const envelope of new InProcessApiClient({ fetch: doFetch }).events.mux({}, new AbortController().signal)) {
  275. seen.push(envelope.payload)
  276. }
  277. // The three corrupt frames are reported and skipped; the good one still arrives.
  278. expect(seen).toEqual([{ type: 'session/subscribed', sessionId: 's1', lastSeq: 1 }])
  279. expect(errorSpy.mock.calls.length).toBe(3)
  280. } finally {
  281. errorSpy.mockRestore()
  282. }
  283. })
  284. it('fires onOpen once headers are in, before the first frame, and not on transport failure', async () => {
  285. const api = scriptedApi({
  286. events: {
  287. async *mux(request): AsyncGenerator<RpcRequest<MuxFrame>> {
  288. yield { rpcId: RpcId(`p-${request.rpcId}`), payload: { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: 0 } }
  289. },
  290. },
  291. })
  292. const order: string[] = []
  293. const iterator = client(api).events.mux({}, new AbortController().signal, () => order.push('open'))
  294. expect(order).toEqual([]) // lazy generator: no fetch (and no onOpen) before iteration
  295. for await (const _ of iterator) order.push('frame')
  296. expect(order).toEqual(['open', 'frame'])
  297. // Transport failure path: onOpen must not fire.
  298. const failing = new InProcessApiClient({ fetch: () => Promise.resolve(new Response('down', { status: 503 })) })
  299. const failOrder: string[] = []
  300. await expect((async () => {
  301. for await (const _ of failing.events.mux({}, new AbortController().signal, () => failOrder.push('open'))) { /* unreachable */ }
  302. })()).rejects.toThrow(/transport failure/)
  303. expect(failOrder).toEqual([])
  304. })
  305. it('stops consuming when the caller aborts', async () => {
  306. let implSawAbort = false
  307. const api = scriptedApi({
  308. events: {
  309. async *mux(_request, signal): AsyncGenerator<RpcRequest<MuxFrame>> {
  310. try {
  311. let n = 0
  312. while (true) {
  313. yield { rpcId: RpcId(`p${n}`), payload: { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: n++ } }
  314. await new Promise(resolve => setTimeout(resolve, 5))
  315. if (signal.aborted) return
  316. }
  317. } finally {
  318. implSawAbort = true
  319. }
  320. },
  321. },
  322. })
  323. const abort = new AbortController()
  324. let count = 0
  325. // In-process abort ends the stream (impl returns on signal.aborted); over a real
  326. // network fetch the same abort surfaces as a rejection — both stop the loop.
  327. await (async () => {
  328. for await (const _ of client(api).events.mux({}, abort.signal)) {
  329. if (++count === 2) abort.abort()
  330. }
  331. })().catch(() => undefined)
  332. expect(count).toBe(2)
  333. // Generator teardown may lag the abort by a microtask; poll briefly.
  334. await vi.waitFor(() => { expect(implSawAbort).toBe(true) })
  335. })
  336. })
  337. describe('respond path', () => {
  338. it('round-trips a client-response to a receipt', async () => {
  339. const seen: unknown[] = []
  340. const api = scriptedApi({
  341. respond: (message) => {
  342. seen.push(message)
  343. return Promise.resolve({ accepted: true as const })
  344. },
  345. })
  346. const receipt = await client(api).respond({ type: 'client-response', rpcId: RpcId('req-1'), result: { ok: true, value: { behavior: 'allow' } } })
  347. expect(receipt).toEqual({ accepted: true })
  348. expect(seen).toEqual([{ type: 'client-response', rpcId: 'req-1', result: { ok: true, value: { behavior: 'allow' } } }])
  349. })
  350. it('returns bad-response for a malformed client-response without reaching the impl', async () => {
  351. const respond = vi.fn()
  352. const handler = toFetchHandler(scriptedApi({ respond }))
  353. const response = await handler.fetch('http://dsh.internal/api/respond', { method: 'POST', body: JSON.stringify({ type: 'client-response' }) })
  354. expect(await response.json()).toEqual({ accepted: false, reason: 'bad-response' })
  355. expect(respond).not.toHaveBeenCalled()
  356. })
  357. })
  358. describe('envelope tap', () => {
  359. it('delivers one microtask batch of full forms per unary call', async () => {
  360. const api = scriptedApi()
  361. const tapped = client(api)
  362. const batches: (readonly RpcMessage[])[] = []
  363. tapped.subscribeEnvelopes(batch => batches.push(batch))
  364. await tapped.sessions.list({})
  365. await vi.waitFor(() => { expect(batches.length).toBeGreaterThan(0) })
  366. const all = batches.flat()
  367. expect(all.map(m => m.type)).toEqual(['client-request', 'server-response'])
  368. expect(all[0]?.rpcId).toBe(all[1]?.rpcId)
  369. })
  370. it('isolates a throwing listener and keeps serving the call', async () => {
  371. const api = scriptedApi()
  372. const tapped = client(api)
  373. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  374. try {
  375. const good: string[] = []
  376. tapped.subscribeEnvelopes(() => { throw new Error('listener bug') })
  377. tapped.subscribeEnvelopes(batch => good.push(...batch.map(m => m.type)))
  378. const response = await tapped.sessions.list({})
  379. expect(response.result.ok).toBe(true)
  380. await vi.waitFor(() => { expect(good).toContain('server-response') })
  381. } finally {
  382. errorSpy.mockRestore()
  383. }
  384. })
  385. it('buffers nothing with zero subscribers and unsubscribes cleanly', async () => {
  386. const api = scriptedApi()
  387. const tapped = client(api)
  388. await tapped.sessions.list({}) // no subscribers: must not accumulate
  389. const batches: (readonly RpcMessage[])[] = []
  390. const unsubscribe = tapped.subscribeEnvelopes(batch => batches.push(batch))
  391. unsubscribe()
  392. await tapped.sessions.list({})
  393. await new Promise(resolve => setTimeout(resolve, 0))
  394. expect(batches).toEqual([])
  395. })
  396. })