Skip to content

Commit 4bdb6f5

Browse files
dinwwwhclaude
andauthored
fix(contract): reconcile mid-stream errors in response validation plugin (#2380)
## Problem `ResponseValidationLinkPlugin` reconciles `ORPCError`s against the contract's `errorMap` with a `try { return await next() } catch { ... }`. That only catches errors thrown before `next()` resolves. When the output is an async iterator, `next()` resolves as soon as the stream opens, so errors thrown while the stream is being read never go through `reconcileORPCError`. This applies even when the stream has an output schema. The `asyncIteratorObject` schema wraps the stream, but only to validate yielded values. Errors pass through it unchanged. Example: a contract with `outputSchemas: [asyncIteratorObject(z.number())]` and error map `NOT_FOUND: { data: z.object({ value: z.string().transform(v => parseInt(v)) }) }`. The stream yields `1`, then throws `NOT_FOUND { value: '123' }`: | | `defined` | `data` | |-----------------------|-----------|--------------------| | Error returned directly | `true` | `{ value: 123 }` | | Error thrown mid-stream (before this PR) | `false` | `{ value: '123' }` | So `isDefinedError` / `safe()` treat an error the contract defines as undefined, and `error.data` doesn't match its static type. ## Fix When `next()` returns an async iterator, the plugin now wraps it with `wrapAsyncIteratorPreservingEventMeta(output, { mapError: reconcileError })`, inside `override(...)`. This is the same pattern `packages/server/src/procedure-client.ts` already uses for server-side outputs. Errors thrown before the stream starts are reconciled through the same `reconcileError` helper as before. ## Tests Added to `packages/contract/src/plugins/response-validation.test.ts`: - A mid-stream `ORPCError` is reconciled against the procedure's error map, and only when that item is read. - The error's event meta (`id`, `retry`) is kept after reconciliation. - Errors that aren't `ORPCError` pass through without reconciliation. - With the real `reconcileORPCError`, a mid-stream error comes out with `defined === true` and transformed `data`. The first, second and fourth tests fail without the fix. The existing tests in this file now share a `mockResponse` helper for their mock setup. `pnpm vitest run packages/contract`, `pnpm type:check` and `pnpm lint` pass. --- _Generated by [Claude Code](https://claude.ai/code/session_01VVaw7PzHC3szJidv5pjRfn)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0e38bd8 commit 4bdb6f5

2 files changed

Lines changed: 134 additions & 79 deletions

File tree

Lines changed: 106 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import { ORPCError } from '@orpc/client'
1+
import { getEventMeta, ORPCError, withEventMeta } from '@orpc/client'
22
import { StandardLink } from '@orpc/client/standard'
33
import * as z from 'zod'
44
import { ValidationError } from '../error'
55
import { reconcileORPCError } from '../error-utils'
66
import { ProcedureContract } from '../procedure'
7+
import { asyncIteratorObject } from '../schema-built-in'
78
import { ResponseValidationLinkPlugin } from './response-validation'
89

910
vi.mock('../error-utils', async original => ({
@@ -40,12 +41,19 @@ describe('responseValidationLinkPlugin', () => {
4041
meta: {},
4142
})
4243

44+
const streamProcedure = new ProcedureContract({
45+
outputSchemas: [asyncIteratorObject(z.number())],
46+
errorMap: procedure['~orpc'].errorMap,
47+
meta: {},
48+
})
49+
4350
const contract = {
4451
procedure,
4552
nested: {
4653
procedure,
4754
},
4855
withoutOutputSchema: withoutOutputSchemaProcedure,
56+
stream: streamProcedure,
4957
}
5058

5159
const codec = {
@@ -66,22 +74,14 @@ describe('responseValidationLinkPlugin', () => {
6674
interceptors: [interceptor],
6775
})
6876

77+
function mockResponse(url: string, decoded: unknown, status = 200) {
78+
codec.encodeInput.mockResolvedValueOnce({ method: 'POST', url, headers: {}, body: '__encoded__' })
79+
transport.send.mockResolvedValueOnce({ status, headers: {}, resolveBody: () => Promise.resolve('__body__') })
80+
codec.decodeResponse.mockResolvedValueOnce(decoded)
81+
}
82+
6983
it('validates output using the output schema pipeline', async () => {
70-
codec.encodeInput.mockResolvedValueOnce({
71-
method: 'POST',
72-
url: '/procedure',
73-
headers: {},
74-
body: '__encoded__',
75-
})
76-
transport.send.mockResolvedValueOnce({
77-
status: 200,
78-
headers: {},
79-
resolveBody: () => Promise.resolve('__body__'),
80-
})
81-
codec.decodeResponse.mockResolvedValueOnce({
82-
kind: 'output',
83-
output: { value: '123' },
84-
})
84+
mockResponse('/procedure', { kind: 'output', output: { value: '123' } })
8585

8686
const output = await link.call(['procedure'], {}, { context: {} })
8787

@@ -90,21 +90,7 @@ describe('responseValidationLinkPlugin', () => {
9090
})
9191

9292
it('skips validation when the procedure has no output schemas', async () => {
93-
codec.encodeInput.mockResolvedValueOnce({
94-
method: 'POST',
95-
url: '/withoutOutputSchema',
96-
headers: {},
97-
body: '__encoded__',
98-
})
99-
transport.send.mockResolvedValueOnce({
100-
status: 200,
101-
headers: {},
102-
resolveBody: () => Promise.resolve('__body__'),
103-
})
104-
codec.decodeResponse.mockResolvedValueOnce({
105-
kind: 'output',
106-
output: 'anything',
107-
})
93+
mockResponse('/withoutOutputSchema', { kind: 'output', output: 'anything' })
10894

10995
const output = await link.call(['withoutOutputSchema'], {}, { context: {} })
11096

@@ -113,21 +99,7 @@ describe('responseValidationLinkPlugin', () => {
11399
})
114100

115101
it('throws INTERNAL_SERVER_ERROR when output validation fails', async () => {
116-
codec.encodeInput.mockResolvedValueOnce({
117-
method: 'POST',
118-
url: '/procedure',
119-
headers: {},
120-
body: '__encoded__',
121-
})
122-
transport.send.mockResolvedValueOnce({
123-
status: 200,
124-
headers: {},
125-
resolveBody: () => Promise.resolve('__body__'),
126-
})
127-
codec.decodeResponse.mockResolvedValueOnce({
128-
kind: 'output',
129-
output: 'invalid',
130-
})
102+
mockResponse('/procedure', { kind: 'output', output: 'invalid' })
131103

132104
const expectedError = new ORPCError('INTERNAL_SERVER_ERROR', {
133105
message: 'Output validation failed',
@@ -150,22 +122,10 @@ describe('responseValidationLinkPlugin', () => {
150122
})
151123

152124
it('reconciles thrown ORPCError instances against the contract', async () => {
153-
codec.encodeInput.mockResolvedValueOnce({
154-
method: 'POST',
155-
url: '/nested/procedure',
156-
headers: {},
157-
body: '__encoded__',
158-
})
159-
transport.send.mockResolvedValueOnce({
160-
status: 400,
161-
headers: {},
162-
resolveBody: () => Promise.resolve('__body__'),
163-
})
164-
165125
const error = new ORPCError('TEST', { message: 'test', data: { value: '123' } })
166126
const reconciled = new ORPCError('TEST', { message: 'test', data: { value: 123 } })
167127

168-
codec.decodeResponse.mockResolvedValueOnce({ kind: 'error', error })
128+
mockResponse('/nested/procedure', { kind: 'error', error }, 400)
169129
vi.mocked(reconcileORPCError).mockResolvedValueOnce(reconciled)
170130

171131
await expect(link.call(['nested', 'procedure'], {}, { context: {} })).rejects.toBe(reconciled)
@@ -175,25 +135,100 @@ describe('responseValidationLinkPlugin', () => {
175135
})
176136

177137
it('rethrows non-ORPCError failures without reconciliation', async () => {
178-
codec.encodeInput.mockResolvedValueOnce({
179-
method: 'POST',
180-
url: '/nested/procedure',
181-
headers: {},
182-
body: '__encoded__',
183-
})
184-
transport.send.mockResolvedValueOnce({
185-
status: 500,
186-
headers: {},
187-
resolveBody: () => Promise.resolve('__body__'),
188-
})
189-
190138
const error = new Error('plain failure')
191139

140+
codec.encodeInput.mockResolvedValueOnce({ method: 'POST', url: '/nested/procedure', headers: {}, body: '__encoded__' })
141+
transport.send.mockResolvedValueOnce({ status: 500, headers: {}, resolveBody: () => Promise.resolve('__body__') })
192142
codec.decodeResponse.mockRejectedValueOnce(error)
193143

194144
await expect(link.call(['nested', 'procedure'], {}, { context: {} })).rejects.toBe(error)
195145
await expect(interceptor.mock.results[0]?.value).rejects.toBe(error)
196146

197147
expect(reconcileORPCError).not.toHaveBeenCalled()
198148
})
149+
150+
describe('async iterator output', () => {
151+
it('reconciles ORPCError thrown while consuming the iterator', async () => {
152+
const error = new ORPCError('TEST', { data: { value: '123' } })
153+
const reconciled = new ORPCError('TEST', { data: { value: 123 } })
154+
155+
mockResponse('/stream', {
156+
kind: 'output',
157+
output: (async function* () {
158+
yield 1
159+
throw error
160+
})(),
161+
})
162+
vi.mocked(reconcileORPCError).mockResolvedValueOnce(reconciled)
163+
164+
const output = await link.call(['stream'], {}, { context: {} }) as AsyncIteratorObject<number>
165+
166+
expect(reconcileORPCError).not.toHaveBeenCalled()
167+
await expect(output.next()).resolves.toEqual({ done: false, value: 1 })
168+
await expect(output.next()).rejects.toBe(reconciled)
169+
170+
expect(reconcileORPCError).toHaveBeenCalledTimes(1)
171+
expect(reconcileORPCError).toHaveBeenCalledWith(contract.stream['~orpc'].errorMap, error)
172+
})
173+
174+
it('preserves event meta of reconciled mid-stream errors', async () => {
175+
const error = withEventMeta(new ORPCError('TEST', { data: { value: '123' } }), { id: 'id-1', retry: 1000 })
176+
const reconciled = new ORPCError('TEST', { data: { value: 123 } })
177+
178+
mockResponse('/stream', {
179+
kind: 'output',
180+
output: (async function* () {
181+
throw error
182+
})(),
183+
})
184+
vi.mocked(reconcileORPCError).mockResolvedValueOnce(reconciled)
185+
186+
const output = await link.call(['stream'], {}, { context: {} }) as AsyncIteratorObject<number>
187+
188+
const thrown = await output.next().catch(e => e)
189+
190+
expect(thrown).toBeInstanceOf(ORPCError)
191+
expect(thrown.data).toEqual({ value: 123 })
192+
expect(getEventMeta(thrown)).toEqual({ id: 'id-1', retry: 1000 })
193+
})
194+
195+
it('rethrows non-ORPCError mid-stream failures without reconciliation', async () => {
196+
const error = new Error('plain failure')
197+
198+
mockResponse('/stream', {
199+
kind: 'output',
200+
output: (async function* () {
201+
throw error
202+
})(),
203+
})
204+
205+
const output = await link.call(['stream'], {}, { context: {} }) as AsyncIteratorObject<number>
206+
207+
await expect(output.next()).rejects.toBe(error)
208+
expect(reconcileORPCError).not.toHaveBeenCalled()
209+
})
210+
211+
it('marks mid-stream errors as defined and applies the error data schema', async () => {
212+
const { reconcileORPCError: actualReconcileORPCError } = await vi.importActual<typeof import('../error-utils')>('../error-utils')
213+
vi.mocked(reconcileORPCError).mockImplementation(actualReconcileORPCError)
214+
onTestFinished(() => {
215+
vi.mocked(reconcileORPCError).mockReset()
216+
})
217+
218+
mockResponse('/stream', {
219+
kind: 'output',
220+
output: (async function* () {
221+
yield 1
222+
throw new ORPCError('TEST', { data: { value: '123' } })
223+
})(),
224+
})
225+
226+
const output = await link.call(['stream'], {}, { context: {} }) as AsyncIteratorObject<number>
227+
228+
await expect(output.next()).resolves.toEqual({ done: false, value: 1 })
229+
await expect(output.next()).rejects.toSatisfy((error: any) =>
230+
error instanceof ORPCError && error.defined === true && error.data.value === 123,
231+
)
232+
})
233+
})
199234
})

‎packages/contract/src/plugins/response-validation.ts‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import type { ClientContext } from '@orpc/client'
22
import type { StandardLinkOptions, StandardLinkPlugin } from '@orpc/client/standard'
3+
import type { ThrowableError } from '@orpc/shared'
34
import type { RouterContract } from '../router'
4-
import { ORPCError } from '@orpc/client'
5-
import { toArray } from '@orpc/shared'
5+
import { ORPCError, wrapAsyncIteratorPreservingEventMeta } from '@orpc/client'
6+
import { isAsyncIteratorObject, override, toArray } from '@orpc/shared'
67
import { ValidationError } from '../error'
78
import { reconcileORPCError } from '../error-utils'
89
import { getProcedureContractOrThrow } from '../router-utils'
@@ -28,15 +29,34 @@ export class ResponseValidationLinkPlugin<T extends ClientContext> implements St
2829
async ({ next, path }) => {
2930
const procedure = getProcedureContractOrThrow(this.contract, path)
3031

31-
try {
32-
return await next()
33-
}
34-
catch (error) {
32+
const reconcileError = async (error: ThrowableError) => {
3533
if (error instanceof ORPCError) {
36-
throw await reconcileORPCError(procedure['~orpc'].errorMap, error)
34+
return await reconcileORPCError(procedure['~orpc'].errorMap, error)
3735
}
3836

39-
throw error
37+
return error
38+
}
39+
40+
try {
41+
const output = await next()
42+
43+
if (isAsyncIteratorObject(output)) {
44+
/**
45+
* Errors thrown while consuming the iterator must be reconciled too.
46+
*
47+
* @warning
48+
* Remember use `override` for AsyncIteratorObject to remain other special properties
49+
*/
50+
return override(output, wrapAsyncIteratorPreservingEventMeta(
51+
output,
52+
{ mapError: reconcileError },
53+
)) as typeof output
54+
}
55+
56+
return output
57+
}
58+
catch (error) {
59+
throw await reconcileError(error as ThrowableError)
4060
}
4161
},
4262
...toArray(options.interceptors),

0 commit comments

Comments
 (0)