From 337180b40dac19f2e2c02a17b955dcebc3078fe1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sat, 21 Nov 2026 15:49:20 +0700 Subject: [PATCH 1/6] fix(server)!: encode batch-level refusals as standard error responses Batch refusals and failed subrequests answered bare strings with ad-hoc statuses, so an ORPCError thrown while the batch body is read, such as the Request Limit Plugin's, lost its code, status and data. - routing interceptors receive `encodeError`, and `StandardHandler` exposes it - `StandardHandlerCodec.encodeError` takes `procedure`, `path` and `options` as optional - batch refusals are BAD_REQUEST / PAYLOAD_TOO_LARGE errors, a thrown ORPCError is kept as is - unmatched subrequests and standard-peer requests share `createNoProcedureMatchedError` --- apps/content/docs/openapi/handler.mdx | 16 ++ apps/content/docs/plugins/batch.mdx | 8 +- apps/content/docs/rpc/handler.mdx | 16 ++ .../tmp-file-upload-handler-plugin.test.ts | 5 + .../src/adapters/standard-peer/utils.test.ts | 14 +- .../src/adapters/standard-peer/utils.ts | 7 +- .../server/src/adapters/standard/codec.ts | 10 +- .../src/adapters/standard/handler.test.ts | 1 + .../server/src/adapters/standard/handler.ts | 17 +- .../adapters/standard/rpc-handler-codec.ts | 6 +- .../server/src/adapters/standard/utils.ts | 8 + packages/server/src/plugins/batch.test.ts | 84 ++++++++-- packages/server/src/plugins/batch.ts | 151 ++++++++---------- tests/batch/batch-plugin.test.ts | 70 ++++++++ 14 files changed, 303 insertions(+), 110 deletions(-) diff --git a/apps/content/docs/openapi/handler.mdx b/apps/content/docs/openapi/handler.mdx index 3576c2f84..c3a1f8e73 100644 --- a/apps/content/docs/openapi/handler.mdx +++ b/apps/content/docs/openapi/handler.mdx @@ -92,6 +92,22 @@ const handler = new OpenAPIHandler(router, { }) ``` +To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the same way the handler encodes procedure errors: + +```ts +const handler = new OpenAPIHandler(router, { + routingInterceptors: [ + async ({ next, encodeError }) => { + if (condition) { + return { matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) } + } + + return next() + }, + ], +}) +``` + ### Interceptors These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure. diff --git a/apps/content/docs/plugins/batch.mdx b/apps/content/docs/plugins/batch.mdx index 0ab1cfc56..8bce9263c 100644 --- a/apps/content/docs/plugins/batch.mdx +++ b/apps/content/docs/plugins/batch.mdx @@ -49,7 +49,7 @@ const link = new RPCLink({ ## Max Size -Both plugins limit how many requests a batch holds with `maxSize`, and each side defaults to `DEFAULT_BATCH_MAX_SIZE` (10) independently. The client splits a larger group into several batches, while the server rejects a larger batch with a `413` for every request in it, so keep the client limit at or below the server's. +Both plugins limit how many requests a batch holds with `maxSize`, and each side defaults to `DEFAULT_BATCH_MAX_SIZE` (10) independently. The client splits a larger group into several batches, while the server rejects a larger batch with a `PAYLOAD_TOO_LARGE` error (`413`) for every request in it, so keep the client limit at or below the server's. @@ -82,6 +82,12 @@ const link = new RPCLink({ +## Refused Batches + +When the server refuses a whole batch, it answers with a regular error response instead of a batch response, and every call in the batch rejects with that `ORPCError`. A malformed batch is a `BAD_REQUEST`, a batch above `maxSize` is a `PAYLOAD_TOO_LARGE`, and an error another plugin throws while the batch body is read, such as the [Request Limit Plugin](/docs/plugins/request-limit)'s, keeps its code, status, message, and data. + +A subrequest that matches no procedure fails on its own with a `NOT_FOUND` error, without affecting the rest of the batch. + ## Response Modes In the default `buffered` mode, the server starts the batch response once every procedure has responded, so it can carry their [headers](#response-headers). The response streams only if one of them returned an [AsyncIteratorObject](/docs/async-iterator-object) or a [`ReadableStream`](/docs/binary-data). If your client cannot read streamed responses, keep these procedures out of the batch with [`filter`](#filtering-requests). diff --git a/apps/content/docs/rpc/handler.mdx b/apps/content/docs/rpc/handler.mdx index 3bb8845dc..6d0959a28 100644 --- a/apps/content/docs/rpc/handler.mdx +++ b/apps/content/docs/rpc/handler.mdx @@ -162,6 +162,22 @@ const handler = new RPCHandler(router, { }) ``` +To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the same way the handler encodes procedure errors: + +```ts +const handler = new RPCHandler(router, { + routingInterceptors: [ + async ({ next, encodeError }) => { + if (condition) { + return { matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) } + } + + return next() + }, + ], +}) +``` + ### Interceptors These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure. diff --git a/packages/node/src/tmp-file-upload-handler-plugin.test.ts b/packages/node/src/tmp-file-upload-handler-plugin.test.ts index c0cf97934..3d4e458b8 100644 --- a/packages/node/src/tmp-file-upload-handler-plugin.test.ts +++ b/packages/node/src/tmp-file-upload-handler-plugin.test.ts @@ -162,6 +162,7 @@ describe('tmpFileUploadHandlerPlugin', () => { await interceptor({ context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -589,6 +590,7 @@ describe('tmpFileUploadHandlerPlugin', () => { const result = await interceptor({ context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -1092,6 +1094,7 @@ describe('tmpFileUploadHandlerPlugin', () => { await plugin.init({}).routingInterceptors![0]!({ context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -1572,6 +1575,7 @@ describe('tmpFileUploadHandlerPlugin', () => { await interceptor({ context: options.context, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', @@ -1673,6 +1677,7 @@ describe('tmpFileUploadHandlerPlugin', () => { const interceptorOptions = { context: {}, prefix: undefined, + encodeError: vi.fn(), request: { method: 'POST', url: '/upload', diff --git a/packages/server/src/adapters/standard-peer/utils.test.ts b/packages/server/src/adapters/standard-peer/utils.test.ts index 3af1c485b..6aa68a30e 100644 --- a/packages/server/src/adapters/standard-peer/utils.test.ts +++ b/packages/server/src/adapters/standard-peer/utils.test.ts @@ -1,3 +1,4 @@ +import type { AnyORPCError } from '@orpc/client' import type { StandardLazyRequest } from '@standard-server/core' import { createStandardPeerRequestHandler } from './utils' @@ -41,6 +42,11 @@ describe('createStandardPeerRequestHandler', () => { it('returns 404 response when no procedure matched', async () => { const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), + encodeError: vi.fn((error: AnyORPCError) => ({ + status: 404, + headers: {}, + body: error.toJSON(), + })), } as any const handleRequest = createStandardPeerRequestHandler(handler, { context: { context: true } }) @@ -53,13 +59,18 @@ describe('createStandardPeerRequestHandler', () => { signal: new AbortController().signal, }) - expect(result).toEqual({ status: 404, headers: {}, body: 'No procedure matched' }) + expect(result).toEqual({ + status: 404, + headers: {}, + body: { defined: false, code: 'NOT_FOUND', message: 'No procedure matched' }, + }) expect(handler.handle).toHaveBeenCalledTimes(1) }) it('context fallback to empty object when it undefined', async () => { const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), + encodeError: vi.fn(), } as any const handleRequest = createStandardPeerRequestHandler(handler, {}) @@ -80,6 +91,7 @@ describe('createStandardPeerRequestHandler', () => { it('forwards a context function unresolved so the handler resolves it after its prefix check', async () => { const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), + encodeError: vi.fn(), } as any const context = vi.fn(() => ({ db: 'postgres' })) diff --git a/packages/server/src/adapters/standard-peer/utils.ts b/packages/server/src/adapters/standard-peer/utils.ts index 238c1ba18..9d9225802 100644 --- a/packages/server/src/adapters/standard-peer/utils.ts +++ b/packages/server/src/adapters/standard-peer/utils.ts @@ -2,7 +2,10 @@ import type { StandardLazyRequest, StandardResponse } from '@standard-server/cor import type { Context } from '../../context' import type { FriendlyStandardHandlerHandleOptions, StandardHandler } from '../standard/index' -import { resolveFriendlyStandardHandlerHandleOptions } from '../standard/index' +import { + createNoProcedureMatchedError, + resolveFriendlyStandardHandlerHandleOptions, +} from '../standard/index' export function createStandardPeerRequestHandler( handler: StandardHandler, @@ -13,6 +16,6 @@ export function createStandardPeerRequestHandler( request, resolveFriendlyStandardHandlerHandleOptions(options), ) - return response ?? { status: 404, headers: {}, body: 'No procedure matched' } + return response ?? handler.encodeError(createNoProcedureMatchedError()) } } diff --git a/packages/server/src/adapters/standard/codec.ts b/packages/server/src/adapters/standard/codec.ts index 61bdd8b01..3e64e0090 100644 --- a/packages/server/src/adapters/standard/codec.ts +++ b/packages/server/src/adapters/standard/codec.ts @@ -25,10 +25,14 @@ export interface StandardHandlerCodec { options: ResolvedStandardHandlerHandleOptions, ): Promisable + /** + * `procedure`, `path` and `options` are only given for an error of a matched procedure, + * and not for one raised outside it, such as a refusal by a routing interceptor. + */ encodeError( error: AnyORPCError, - procedure: AnyProcedure, - path: string[], - options: ResolvedStandardHandlerHandleOptions, + procedure?: AnyProcedure, + path?: string[], + options?: ResolvedStandardHandlerHandleOptions, ): Promisable } diff --git a/packages/server/src/adapters/standard/handler.test.ts b/packages/server/src/adapters/standard/handler.test.ts index 12a70fc63..0284beee1 100644 --- a/packages/server/src/adapters/standard/handler.test.ts +++ b/packages/server/src/adapters/standard/handler.test.ts @@ -116,6 +116,7 @@ describe('standardHandler', () => { expect(routingInterceptor).toHaveBeenCalledTimes(1) expect(routingInterceptor).toHaveBeenCalledWith({ next: expect.any(Function), + encodeError: expect.any(Function), request, context: OPTIONS.context, prefix: OPTIONS.prefix, diff --git a/packages/server/src/adapters/standard/handler.ts b/packages/server/src/adapters/standard/handler.ts index 5e83fc6c3..bec8d1750 100644 --- a/packages/server/src/adapters/standard/handler.ts +++ b/packages/server/src/adapters/standard/handler.ts @@ -1,3 +1,4 @@ +import type { AnyORPCError } from '@orpc/client' import { ORPCError, toORPCError } from '@orpc/client' import type { ErrorMap, Schema } from '@orpc/contract' import { reconcileORPCError } from '@orpc/contract' @@ -68,6 +69,12 @@ export interface StandardHandlerRoutingInterceptorOptions< T extends Context, > extends ResolvedStandardHandlerHandleOptions { request: StandardLazyRequest + + /** + * Encodes an error the way the handler encodes procedure errors, so a routing interceptor + * can refuse a request with the same error response a procedure would send. + */ + encodeError: (error: AnyORPCError) => Promisable } export type StandardHandlerRoutingInterceptor = Interceptor< StandardHandlerRoutingInterceptorOptions, @@ -120,6 +127,14 @@ export class StandardHandler { this.clientInterceptors = options.clientInterceptors } + /** + * Encodes an error raised outside a procedure, such as a request no procedure matched, + * the way the handler encodes procedure errors. + */ + encodeError(error: AnyORPCError): Promisable { + return this.codec.encodeError(error) + } + async handle( request: StandardLazyRequest, options: StandardHandlerHandleOptions, @@ -134,7 +149,7 @@ export class StandardHandler { return intercept( this.routingInterceptors, - { context, prefix, request }, + { context, prefix, request, encodeError: (error) => this.encodeError(error) }, async ({ context, prefix, request }) => { const span = getTracer()?.getActiveSpan() diff --git a/packages/server/src/adapters/standard/rpc-handler-codec.ts b/packages/server/src/adapters/standard/rpc-handler-codec.ts index 5aa227271..f4b18ba8d 100644 --- a/packages/server/src/adapters/standard/rpc-handler-codec.ts +++ b/packages/server/src/adapters/standard/rpc-handler-codec.ts @@ -106,9 +106,9 @@ export class RPCHandlerCodec implements StandardHandlerCodec< encodeError( error: AnyORPCError, - _procedure: AnyProcedure, - _path: string[], - _options: ResolvedStandardHandlerHandleOptions, + _procedure?: AnyProcedure, + _path?: string[], + _options?: ResolvedStandardHandlerHandleOptions, ): Promisable { const status = getOwn(this.errorStatusMap, error.code) ?? DEFAULT_ERROR_STATUS diff --git a/packages/server/src/adapters/standard/utils.ts b/packages/server/src/adapters/standard/utils.ts index afbfce86e..453c61500 100644 --- a/packages/server/src/adapters/standard/utils.ts +++ b/packages/server/src/adapters/standard/utils.ts @@ -1,3 +1,4 @@ +import { ORPCError } from '@orpc/client' import type { Promisable, Value } from '@orpc/shared' import type { StandardLazyRequest } from '@standard-server/core' @@ -20,3 +21,10 @@ export function resolveFriendlyStandardHandlerHandleOptions( context: options.context ?? ({} as T), // Context only optional if all fields are optional } } + +/** + * The error answered to a request no procedure matched, by transports that must always respond. + */ +export function createNoProcedureMatchedError(): ORPCError<'NOT_FOUND', undefined> { + return new ORPCError('NOT_FOUND', { message: 'No procedure matched' }) +} diff --git a/packages/server/src/plugins/batch.test.ts b/packages/server/src/plugins/batch.test.ts index 0d49f8898..c8c9c325a 100644 --- a/packages/server/src/plugins/batch.test.ts +++ b/packages/server/src/plugins/batch.test.ts @@ -243,6 +243,9 @@ describe('batchHandlerPlugin', () => { expect(body).toHaveLength(1) expect(body[0]).toMatchObject({ kind: 'response', id: '0' }) expect(body[0].json.status).toBe(404) + expect(body[0].json.body).toEqual({ + json: { defined: false, code: 'NOT_FOUND', message: 'No procedure matched' }, + }) }) it('returns 400 for invalid batch body', async () => { @@ -255,7 +258,9 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request body') + expect(await response!.json()).toEqual({ + json: { defined: false, code: 'BAD_REQUEST', message: 'Invalid batch request' }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) @@ -271,7 +276,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request body') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }, ) @@ -288,11 +293,11 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request body') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }) - it('returns the ORPCError message a body plugin throws while resolving the batch body', async () => { + it('returns the ORPCError a body plugin throws while resolving the batch body', async () => { const handler = new RPCHandler(router, { plugins: [new BatchHandlerPlugin(), new RequestCompressionHandlerPlugin()], }) @@ -309,12 +314,18 @@ describe('batchHandlerPlugin', () => { }), ) - expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Too many content encodings.') + expect(response!.status).toBe(415) + expect(await response!.json()).toEqual({ + json: { + defined: false, + code: 'UNSUPPORTED_MEDIA_TYPE', + message: 'Too many content encodings.', + }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) - it('returns the ORPCError message a body plugin raises while streaming the batch body', async () => { + it('returns the ORPCError a body plugin raises while streaming the batch body', async () => { const handler = new RPCHandler(router, { plugins: [new BatchHandlerPlugin(), new RequestLimitHandlerPlugin({ maxBodySize: 10 })], }) @@ -325,8 +336,42 @@ describe('batchHandlerPlugin', () => { }), ) - expect(response!.status).toBe(400) - expect(await response!.text()).toContain(new ORPCError('PAYLOAD_TOO_LARGE').message) + expect(response!.status).toBe(413) + expect(await response!.json()).toEqual({ + json: new ORPCError('PAYLOAD_TOO_LARGE').toJSON(), + }) + expect(handlerFn).toHaveBeenCalledTimes(0) + }) + + it('keeps the code, status, message and data of a custom error a body plugin raises', async () => { + const handler = new RPCHandler(router, { + plugins: [ + new BatchHandlerPlugin(), + new RequestLimitHandlerPlugin({ + maxBodySize: 10, + error: new ORPCError('TOO_MANY_REQUESTS', { + message: 'Slow down', + data: { limit: 10 }, + }), + }), + ], + }) + + const { response } = await handler.handle( + createBatchRequest({ + messages: [makePeerRequestMessage('0', '/ping')], + }), + ) + + expect(response!.status).toBe(429) + expect(await response!.json()).toEqual({ + json: { + defined: false, + code: 'TOO_MANY_REQUESTS', + message: 'Slow down', + data: { limit: 10 }, + }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) @@ -344,6 +389,13 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(413) + expect(await response!.json()).toEqual({ + json: { + defined: false, + code: 'PAYLOAD_TOO_LARGE', + message: 'Batch request size exceeds the maximum allowed size', + }, + }) expect(handlerFn).toHaveBeenCalledTimes(0) }) @@ -374,7 +426,9 @@ describe('batchHandlerPlugin', () => { const body = (await response!.json()) as any expect(body[0].json.status).toBe(500) - expect(body[0].json.body).toBe('Internal server error') + expect(body[0].json.body).toEqual({ + json: new ORPCError('INTERNAL_SERVER_ERROR').toJSON(), + }) expect(rejectSpy).toHaveBeenCalledTimes(1) }) @@ -405,7 +459,9 @@ describe('batchHandlerPlugin', () => { const body = (await response!.json()) as any expect(body[0].json.status).toBe(500) - expect(body[0].json.body).toBe('Internal server error') + expect(body[0].json.body).toEqual({ + json: new ORPCError('INTERNAL_SERVER_ERROR').toJSON(), + }) expect(rejectSpy).toHaveBeenCalledTimes(1) }) @@ -722,7 +778,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request data parameter') + expect(await response!.text()).toContain('Invalid batch request') }) it.each(INVALID_MESSAGE_IDS)( @@ -741,7 +797,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request data parameter') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }, ) @@ -760,7 +816,7 @@ describe('batchHandlerPlugin', () => { ) expect(response!.status).toBe(400) - expect(await response!.text()).toContain('Invalid batch request data parameter') + expect(await response!.text()).toContain('Invalid batch request') expect(handlerFn).toHaveBeenCalledTimes(0) }) diff --git a/packages/server/src/plugins/batch.ts b/packages/server/src/plugins/batch.ts index 306971d67..a282f4c88 100644 --- a/packages/server/src/plugins/batch.ts +++ b/packages/server/src/plugins/batch.ts @@ -18,6 +18,7 @@ import { ServerPeer, } from '@standard-server/peer' +import { createNoProcedureMatchedError } from '../adapters/standard/index' import type { StandardHandlerOptions, StandardHandlerPlugin, @@ -71,17 +72,6 @@ function isClientPeerSendMessages(maybe: unknown): maybe is ClientPeerSendMessag ) } -/** - * Errors should not occur at the routing interceptor level. - * Reject the promise so it can be handled by the unhandledRejection handler - * for global logging or error handling. - */ -function internalError(err: unknown): StandardResponse { - void Promise.reject(err) - - return { status: 500, headers: {}, body: 'Internal server error' } -} - /** * What the batch needs from a subresponse before it answers, without keeping its body alive. */ @@ -337,83 +327,28 @@ export class BatchHandlerPlugin implements StandardHandlerPlu let messages: ClientPeerSendMessage[] try { - if (interceptorOptions.request.method === 'GET') { - const [, search] = parseStandardUrl(interceptorOptions.request.url) - const params = new URLSearchParams(search) - const data = params.getAll('data').at(-1) - - if (!data) { - return { - matched: true, - response: { - status: 400, - headers: {}, - body: 'Missing data parameter for batch request', - }, - } - } - - const mightBeMessages: unknown = JSON.parse(data) - - if (!isClientPeerSendMessages(mightBeMessages)) { - return { - matched: true, - response: { status: 400, headers: {}, body: 'Invalid batch request data parameter' }, - } - } - - messages = mightBeMessages - } else { - const mightBeMessages = await interceptorOptions.request.resolveBody() - - if (!isClientPeerSendMessages(mightBeMessages)) { - return { - matched: true, - response: { status: 400, headers: {}, body: 'Invalid batch request body' }, - } - } - - messages = mightBeMessages - } + messages = await this.readMessages(interceptorOptions) } catch (error) { - return { - matched: true, - response: { - status: 400, - headers: {}, - body: error instanceof ORPCError ? error.message : 'Invalid batch request', - }, - } - } + /** + * A refusal thrown while the body is read, such as the Request Limit Plugin's, is kept as is. + */ + const refusal = + error instanceof ORPCError + ? error + : new ORPCError('BAD_REQUEST', { message: 'Invalid batch request', cause: error }) - const outerMethod = interceptorOptions.request.method - if ( - (outerMethod === 'GET' || outerMethod === 'QUERY') && - messages.some( - (message) => message.kind === 'request' && message.json.method !== outerMethod, - ) - ) { - return { - matched: true, - response: { - status: 400, - headers: {}, - body: `${outerMethod} batch requests only accept ${outerMethod} sub-requests`, - }, - } + return { matched: true, response: await interceptorOptions.encodeError(refusal) } } - const maxSize = await value(this.maxSize, interceptorOptions) + /** + * Errors should not occur at the routing interceptor level. + * Reject the promise so it can be handled by the unhandledRejection handler + * for global logging or error handling. + */ + const internalError = async (err: unknown): Promise => { + void Promise.reject(err) - if (messages.length > maxSize) { - return { - matched: true, - response: { - status: 413, - headers: {}, - body: 'Batch request size exceeds the maximum allowed size', - }, - } + return interceptorOptions.encodeError(new ORPCError('INTERNAL_SERVER_ERROR')) } const status = await value(this.successStatus, interceptorOptions) @@ -494,9 +429,9 @@ export class BatchHandlerPlugin implements StandardHandlerPlu const result = await interceptorOptions.next({ ...interceptorOptions, request }) response = result.matched ? result.response - : { status: 404, headers: {}, body: 'No procedure matched' } + : await interceptorOptions.encodeError(createNoProcedureMatchedError()) } catch (err) { - response = internalError(err) + response = await internalError(err) } markReady({ @@ -610,4 +545,50 @@ export class BatchHandlerPlugin implements StandardHandlerPlu routingInterceptors: [routingInterceptor, ...toArray(options.routingInterceptors)], } } + + /** + * Reads the subrequest messages of a batch request, throwing the error to refuse it with. + */ + private async readMessages( + options: StandardHandlerRoutingInterceptorOptions, + ): Promise { + const { request } = options + let messages: unknown + + if (request.method === 'GET') { + const [, search] = parseStandardUrl(request.url) + const data = new URLSearchParams(search).getAll('data').at(-1) + + if (!data) { + throw new ORPCError('BAD_REQUEST', { message: 'Missing data parameter for batch request' }) + } + + messages = JSON.parse(data) + } else { + messages = await request.resolveBody() + } + + if (!isClientPeerSendMessages(messages)) { + throw new ORPCError('BAD_REQUEST', { message: 'Invalid batch request' }) + } + + if ( + (request.method === 'GET' || request.method === 'QUERY') && + messages.some( + (message) => message.kind === 'request' && message.json.method !== request.method, + ) + ) { + throw new ORPCError('BAD_REQUEST', { + message: `${request.method} batch requests only accept ${request.method} sub-requests`, + }) + } + + if (messages.length > (await value(this.maxSize, options))) { + throw new ORPCError('PAYLOAD_TOO_LARGE', { + message: 'Batch request size exceeds the maximum allowed size', + }) + } + + return messages + } } diff --git a/tests/batch/batch-plugin.test.ts b/tests/batch/batch-plugin.test.ts index 97f9d6b67..a65063784 100644 --- a/tests/batch/batch-plugin.test.ts +++ b/tests/batch/batch-plugin.test.ts @@ -1,4 +1,11 @@ +import { createORPCClient } from '@orpc/client' +import { RPCLink } from '@orpc/client/fetch' +import { BatchLinkPlugin } from '@orpc/client/plugins' +import type { RouterClient } from '@orpc/server' import { ORPCError, os } from '@orpc/server' +import { RPCHandler } from '@orpc/server/fetch' +import { BatchHandlerPlugin, RequestLimitHandlerPlugin } from '@orpc/server/plugins' +import type { StandardHandlerPlugin } from '@orpc/server/standard' import { promiseWithResolvers } from '@orpc/shared' import { sleep } from '@standard-server/shared' import { z } from 'zod' @@ -268,3 +275,66 @@ describe('batch plugin: QUERY over node-http', () => { expect(fetchSpy.mock.calls[0]![1]).toEqual(expect.objectContaining({ method: 'QUERY' })) }) }) + +describe('batch plugin: batch-level refusals', () => { + function createClient(plugins: StandardHandlerPlugin<{}>[]) { + const ping = vi.fn(async (_options: unknown, input: string) => input) + const router = { ping: os.input(z.string()).handler(ping) } + const handler = new RPCHandler(router, { plugins }) + + const link = new RPCLink({ + url: '/rpc', + origin: 'http://localhost', + fetch: async (url, init) => { + const { response } = await handler.handle(new Request(url, init), { prefix: '/rpc' }) + + return response ?? new Response('Not Found', { status: 404 }) + }, + plugins: [new BatchLinkPlugin({ groups: [{ condition: () => true, context: {} }] })], + }) + + return { client: createORPCClient>(link), ping } + } + + it('rejects every call with the error a plugin refused the batch body with', async () => { + const { client, ping } = createClient([ + new BatchHandlerPlugin(), + new RequestLimitHandlerPlugin({ + maxBodySize: 10, + error: new ORPCError('PAYLOAD_TOO_LARGE', { message: 'Too big', data: { max: 10 } }), + }), + ]) + + const results = await Promise.allSettled([client.ping('alpha'), client.ping('beta')]) + + for (const result of results) { + expect(result).toMatchObject({ + status: 'rejected', + reason: expect.objectContaining({ + code: 'PAYLOAD_TOO_LARGE', + message: 'Too big', + data: { max: 10 }, + }), + }) + expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ORPCError) + } + + expect(ping).not.toHaveBeenCalled() + }) + + it('rejects every call with PAYLOAD_TOO_LARGE when the batch exceeds the server maxSize', async () => { + const { client, ping } = createClient([new BatchHandlerPlugin({ maxSize: 1 })]) + + const results = await Promise.allSettled([client.ping('alpha'), client.ping('beta')]) + + for (const result of results) { + expect(result).toMatchObject({ + status: 'rejected', + reason: expect.objectContaining({ code: 'PAYLOAD_TOO_LARGE' }), + }) + expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ORPCError) + } + + expect(ping).not.toHaveBeenCalled() + }) +}) From 456dbb17e8732387afe109c68c13223a6563e88e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Mon, 23 Nov 2026 14:58:37 +0700 Subject: [PATCH 2/6] refactor(server): trim comments and simplify batch refusal tests and docs --- apps/content/docs/openapi/handler.mdx | 16 +--- apps/content/docs/plugins/batch.mdx | 2 +- apps/content/docs/rpc/handler.mdx | 16 +--- .../src/adapters/standard-peer/utils.test.ts | 17 ++-- .../server/src/adapters/standard/codec.ts | 3 +- .../server/src/adapters/standard/handler.ts | 7 +- .../server/src/adapters/standard/utils.ts | 3 - packages/server/src/plugins/batch.ts | 6 -- tests/batch/batch-plugin.test.ts | 77 ++++++------------- 9 files changed, 35 insertions(+), 112 deletions(-) diff --git a/apps/content/docs/openapi/handler.mdx b/apps/content/docs/openapi/handler.mdx index c3a1f8e73..6052dec4d 100644 --- a/apps/content/docs/openapi/handler.mdx +++ b/apps/content/docs/openapi/handler.mdx @@ -92,21 +92,7 @@ const handler = new OpenAPIHandler(router, { }) ``` -To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the same way the handler encodes procedure errors: - -```ts -const handler = new OpenAPIHandler(router, { - routingInterceptors: [ - async ({ next, encodeError }) => { - if (condition) { - return { matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) } - } - - return next() - }, - ], -}) -``` +To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the way procedure errors are encoded: `{ matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) }`. ### Interceptors diff --git a/apps/content/docs/plugins/batch.mdx b/apps/content/docs/plugins/batch.mdx index 8bce9263c..e9634f8a5 100644 --- a/apps/content/docs/plugins/batch.mdx +++ b/apps/content/docs/plugins/batch.mdx @@ -49,7 +49,7 @@ const link = new RPCLink({ ## Max Size -Both plugins limit how many requests a batch holds with `maxSize`, and each side defaults to `DEFAULT_BATCH_MAX_SIZE` (10) independently. The client splits a larger group into several batches, while the server rejects a larger batch with a `PAYLOAD_TOO_LARGE` error (`413`) for every request in it, so keep the client limit at or below the server's. +Both plugins limit how many requests a batch holds with `maxSize`, and each side defaults to `DEFAULT_BATCH_MAX_SIZE` (10) independently. The client splits a larger group into several batches, while the server rejects a larger batch with a `413` for every request in it, so keep the client limit at or below the server's. diff --git a/apps/content/docs/rpc/handler.mdx b/apps/content/docs/rpc/handler.mdx index 6d0959a28..996b8ce8c 100644 --- a/apps/content/docs/rpc/handler.mdx +++ b/apps/content/docs/rpc/handler.mdx @@ -162,21 +162,7 @@ const handler = new RPCHandler(router, { }) ``` -To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the same way the handler encodes procedure errors: - -```ts -const handler = new RPCHandler(router, { - routingInterceptors: [ - async ({ next, encodeError }) => { - if (condition) { - return { matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) } - } - - return next() - }, - ], -}) -``` +To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the way procedure errors are encoded: `{ matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) }`. ### Interceptors diff --git a/packages/server/src/adapters/standard-peer/utils.test.ts b/packages/server/src/adapters/standard-peer/utils.test.ts index 6aa68a30e..da4677bb8 100644 --- a/packages/server/src/adapters/standard-peer/utils.test.ts +++ b/packages/server/src/adapters/standard-peer/utils.test.ts @@ -1,4 +1,3 @@ -import type { AnyORPCError } from '@orpc/client' import type { StandardLazyRequest } from '@standard-server/core' import { createStandardPeerRequestHandler } from './utils' @@ -40,13 +39,10 @@ describe('createStandardPeerRequestHandler', () => { }) it('returns 404 response when no procedure matched', async () => { + const notFound = { status: 404, headers: {}, body: 'encoded' } const handler = { handle: vi.fn(async () => ({ matched: false, response: undefined })), - encodeError: vi.fn((error: AnyORPCError) => ({ - status: 404, - headers: {}, - body: error.toJSON(), - })), + encodeError: vi.fn(() => notFound), } as any const handleRequest = createStandardPeerRequestHandler(handler, { context: { context: true } }) @@ -59,11 +55,10 @@ describe('createStandardPeerRequestHandler', () => { signal: new AbortController().signal, }) - expect(result).toEqual({ - status: 404, - headers: {}, - body: { defined: false, code: 'NOT_FOUND', message: 'No procedure matched' }, - }) + expect(result).toBe(notFound) + expect(handler.encodeError).toHaveBeenCalledWith( + expect.objectContaining({ code: 'NOT_FOUND', message: 'No procedure matched' }), + ) expect(handler.handle).toHaveBeenCalledTimes(1) }) diff --git a/packages/server/src/adapters/standard/codec.ts b/packages/server/src/adapters/standard/codec.ts index 3e64e0090..19c3c8b91 100644 --- a/packages/server/src/adapters/standard/codec.ts +++ b/packages/server/src/adapters/standard/codec.ts @@ -26,8 +26,7 @@ export interface StandardHandlerCodec { ): Promisable /** - * `procedure`, `path` and `options` are only given for an error of a matched procedure, - * and not for one raised outside it, such as a refusal by a routing interceptor. + * `procedure`, `path` and `options` are only given for an error of a matched procedure. */ encodeError( error: AnyORPCError, diff --git a/packages/server/src/adapters/standard/handler.ts b/packages/server/src/adapters/standard/handler.ts index bec8d1750..0f9185dd3 100644 --- a/packages/server/src/adapters/standard/handler.ts +++ b/packages/server/src/adapters/standard/handler.ts @@ -71,8 +71,7 @@ export interface StandardHandlerRoutingInterceptorOptions< request: StandardLazyRequest /** - * Encodes an error the way the handler encodes procedure errors, so a routing interceptor - * can refuse a request with the same error response a procedure would send. + * Encodes an error the way procedure errors are encoded, to refuse a request with it. */ encodeError: (error: AnyORPCError) => Promisable } @@ -127,10 +126,6 @@ export class StandardHandler { this.clientInterceptors = options.clientInterceptors } - /** - * Encodes an error raised outside a procedure, such as a request no procedure matched, - * the way the handler encodes procedure errors. - */ encodeError(error: AnyORPCError): Promisable { return this.codec.encodeError(error) } diff --git a/packages/server/src/adapters/standard/utils.ts b/packages/server/src/adapters/standard/utils.ts index 453c61500..2f63b101f 100644 --- a/packages/server/src/adapters/standard/utils.ts +++ b/packages/server/src/adapters/standard/utils.ts @@ -22,9 +22,6 @@ export function resolveFriendlyStandardHandlerHandleOptions( } } -/** - * The error answered to a request no procedure matched, by transports that must always respond. - */ export function createNoProcedureMatchedError(): ORPCError<'NOT_FOUND', undefined> { return new ORPCError('NOT_FOUND', { message: 'No procedure matched' }) } diff --git a/packages/server/src/plugins/batch.ts b/packages/server/src/plugins/batch.ts index a282f4c88..c2957379c 100644 --- a/packages/server/src/plugins/batch.ts +++ b/packages/server/src/plugins/batch.ts @@ -329,9 +329,6 @@ export class BatchHandlerPlugin implements StandardHandlerPlu try { messages = await this.readMessages(interceptorOptions) } catch (error) { - /** - * A refusal thrown while the body is read, such as the Request Limit Plugin's, is kept as is. - */ const refusal = error instanceof ORPCError ? error @@ -546,9 +543,6 @@ export class BatchHandlerPlugin implements StandardHandlerPlu } } - /** - * Reads the subrequest messages of a batch request, throwing the error to refuse it with. - */ private async readMessages( options: StandardHandlerRoutingInterceptorOptions, ): Promise { diff --git a/tests/batch/batch-plugin.test.ts b/tests/batch/batch-plugin.test.ts index a65063784..048312474 100644 --- a/tests/batch/batch-plugin.test.ts +++ b/tests/batch/batch-plugin.test.ts @@ -5,11 +5,11 @@ import type { RouterClient } from '@orpc/server' import { ORPCError, os } from '@orpc/server' import { RPCHandler } from '@orpc/server/fetch' import { BatchHandlerPlugin, RequestLimitHandlerPlugin } from '@orpc/server/plugins' -import type { StandardHandlerPlugin } from '@orpc/server/standard' import { promiseWithResolvers } from '@orpc/shared' import { sleep } from '@standard-server/shared' import { z } from 'zod' +import { defaultBatchGroup } from './__shared__/client-server' import { createCompressionHonoFetchBatchClientServerTest } from './__shared__/client-server.compression-hono-fetch' import { createCompressionNodeHttpBatchClientServerTest } from './__shared__/client-server.compression-node-http' import { createHonoFetchBatchClientServerTest } from './__shared__/client-server.hono-fetch' @@ -276,65 +276,36 @@ describe('batch plugin: QUERY over node-http', () => { }) }) -describe('batch plugin: batch-level refusals', () => { - function createClient(plugins: StandardHandlerPlugin<{}>[]) { - const ping = vi.fn(async (_options: unknown, input: string) => input) - const router = { ping: os.input(z.string()).handler(ping) } - const handler = new RPCHandler(router, { plugins }) - - const link = new RPCLink({ - url: '/rpc', - origin: 'http://localhost', - fetch: async (url, init) => { - const { response } = await handler.handle(new Request(url, init), { prefix: '/rpc' }) - - return response ?? new Response('Not Found', { status: 404 }) - }, - plugins: [new BatchLinkPlugin({ groups: [{ condition: () => true, context: {} }] })], - }) - - return { client: createORPCClient>(link), ping } - } - - it('rejects every call with the error a plugin refused the batch body with', async () => { - const { client, ping } = createClient([ +it('rejects every call with the error a plugin refused the batch body with', async () => { + const ping = vi.fn(async (_options: unknown, input: string) => input) + const router = { ping: os.input(z.string()).handler(ping) } + const handler = new RPCHandler(router, { + plugins: [ new BatchHandlerPlugin(), new RequestLimitHandlerPlugin({ maxBodySize: 10, error: new ORPCError('PAYLOAD_TOO_LARGE', { message: 'Too big', data: { max: 10 } }), }), - ]) - - const results = await Promise.allSettled([client.ping('alpha'), client.ping('beta')]) - - for (const result of results) { - expect(result).toMatchObject({ - status: 'rejected', - reason: expect.objectContaining({ - code: 'PAYLOAD_TOO_LARGE', - message: 'Too big', - data: { max: 10 }, - }), - }) - expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ORPCError) - } - - expect(ping).not.toHaveBeenCalled() + ], }) + const client: RouterClient = createORPCClient( + new RPCLink({ + url: '/rpc', + origin: 'http://localhost', + fetch: async (url, init) => (await handler.handle(new Request(url, init))).response!, + plugins: [new BatchLinkPlugin({ groups: [defaultBatchGroup] })], + }), + ) - it('rejects every call with PAYLOAD_TOO_LARGE when the batch exceeds the server maxSize', async () => { - const { client, ping } = createClient([new BatchHandlerPlugin({ maxSize: 1 })]) - - const results = await Promise.allSettled([client.ping('alpha'), client.ping('beta')]) + const results = await Promise.allSettled([client.ping('alpha'), client.ping('beta')]) - for (const result of results) { - expect(result).toMatchObject({ - status: 'rejected', - reason: expect.objectContaining({ code: 'PAYLOAD_TOO_LARGE' }), - }) - expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ORPCError) - } + for (const result of results) { + expect(result).toMatchObject({ + status: 'rejected', + reason: { code: 'PAYLOAD_TOO_LARGE', message: 'Too big', data: { max: 10 } }, + }) + expect((result as PromiseRejectedResult).reason).toBeInstanceOf(ORPCError) + } - expect(ping).not.toHaveBeenCalled() - }) + expect(ping).not.toHaveBeenCalled() }) From 45efc617bc88f0e53daf65b71a377e6b30f61277 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Mon, 23 Nov 2026 14:59:31 +0700 Subject: [PATCH 3/6] refactor(server)!: narrow StandardHandlerCodec.encodeError to the error No codec read `procedure`, `path` or `options`, and an error raised outside a procedure has none. --- .../server/src/adapters/standard/codec.ts | 10 +----- .../src/adapters/standard/handler.test.ts | 7 +--- .../server/src/adapters/standard/handler.ts | 5 +-- .../standard/rpc-handler-codec.test.ts | 34 ++++--------------- .../adapters/standard/rpc-handler-codec.ts | 7 +--- 5 files changed, 10 insertions(+), 53 deletions(-) diff --git a/packages/server/src/adapters/standard/codec.ts b/packages/server/src/adapters/standard/codec.ts index 19c3c8b91..49724dad6 100644 --- a/packages/server/src/adapters/standard/codec.ts +++ b/packages/server/src/adapters/standard/codec.ts @@ -25,13 +25,5 @@ export interface StandardHandlerCodec { options: ResolvedStandardHandlerHandleOptions, ): Promisable - /** - * `procedure`, `path` and `options` are only given for an error of a matched procedure. - */ - encodeError( - error: AnyORPCError, - procedure?: AnyProcedure, - path?: string[], - options?: ResolvedStandardHandlerHandleOptions, - ): Promisable + encodeError(error: AnyORPCError): Promisable } diff --git a/packages/server/src/adapters/standard/handler.test.ts b/packages/server/src/adapters/standard/handler.test.ts index 0284beee1..6b4e2dd43 100644 --- a/packages/server/src/adapters/standard/handler.test.ts +++ b/packages/server/src/adapters/standard/handler.test.ts @@ -434,12 +434,7 @@ describe('standardHandler', () => { matched: true, response: { status: 502, headers: {}, body: 'bad gateway' }, }) - expect(codec.encodeError).toHaveBeenCalledWith( - procedureError, - expect.anything(), - ['ping'], - OPTIONS, - ) + expect(codec.encodeError).toHaveBeenCalledWith(procedureError) }) it('reconciles errors thrown outside the procedure call with the procedure error map', async () => { diff --git a/packages/server/src/adapters/standard/handler.ts b/packages/server/src/adapters/standard/handler.ts index 0f9185dd3..f0f263090 100644 --- a/packages/server/src/adapters/standard/handler.ts +++ b/packages/server/src/adapters/standard/handler.ts @@ -252,10 +252,7 @@ export class StandardHandler { ? error : await reconcileORPCError(procedure['~orpc'].errorMap, error) - const response = await this.codec.encodeError(reconciled, procedure, path, { - context, - prefix, - }) + const response = await this.codec.encodeError(reconciled) return { matched: true, response } } diff --git a/packages/server/src/adapters/standard/rpc-handler-codec.test.ts b/packages/server/src/adapters/standard/rpc-handler-codec.test.ts index 6bfb1e881..3064ab64c 100644 --- a/packages/server/src/adapters/standard/rpc-handler-codec.test.ts +++ b/packages/server/src/adapters/standard/rpc-handler-codec.test.ts @@ -205,7 +205,7 @@ describe('rpcHandlerCodec', () => { const codec = new RPCHandlerCodec(router, { serializer }) const error = new ORPCError('BAD_GATEWAY') - const response = codec.encodeError(error, procedure as any, ['ping'], options as any) + const response = codec.encodeError(error) expect(response).toEqual({ headers: {}, @@ -222,9 +222,7 @@ describe('rpcHandlerCodec', () => { const codec = new RPCHandlerCodec(router, { serializer }) const error = new ORPCError('toString' as any) - expect( - (await codec.encodeError(error, procedure as any, ['ping'], options as any)).status, - ).toEqual(DEFAULT_ERROR_STATUS) + expect((await codec.encodeError(error)).status).toEqual(DEFAULT_ERROR_STATUS) }) it('custom status with errorStatusCodes option', () => { @@ -242,12 +240,7 @@ describe('rpcHandlerCodec', () => { }) const overriddenError = new ORPCError('BAD_GATEWAY') - const overriddenResponse = codec.encodeError( - overriddenError, - procedure as any, - ['ping'], - options as any, - ) + const overriddenResponse = codec.encodeError(overriddenError) expect(overriddenResponse).toEqual({ headers: {}, @@ -256,12 +249,7 @@ describe('rpcHandlerCodec', () => { }) const unknownError = new ORPCError('UNKNOWN_CODE' as any) - const fallbackResponse = codec.encodeError( - unknownError, - procedure as any, - ['ping'], - options as any, - ) + const fallbackResponse = codec.encodeError(unknownError) expect(fallbackResponse).toEqual({ headers: {}, @@ -288,12 +276,7 @@ describe('rpcHandlerCodec', () => { }) const customizedError = new ORPCError('BAD_GATEWAY') - const customizedResponse = codec.encodeError( - customizedError, - procedure as any, - ['ping'], - options as any, - ) + const customizedResponse = codec.encodeError(customizedError) expect(customizedResponse).toEqual({ headers: {}, @@ -302,12 +285,7 @@ describe('rpcHandlerCodec', () => { }) const fallbackError = new ORPCError('UNKNOWN_ERROR') - const fallbackResponse = codec.encodeError( - fallbackError, - procedure as any, - ['ping'], - options as any, - ) + const fallbackResponse = codec.encodeError(fallbackError) expect(fallbackResponse).toEqual({ headers: {}, diff --git a/packages/server/src/adapters/standard/rpc-handler-codec.ts b/packages/server/src/adapters/standard/rpc-handler-codec.ts index f4b18ba8d..dacc242af 100644 --- a/packages/server/src/adapters/standard/rpc-handler-codec.ts +++ b/packages/server/src/adapters/standard/rpc-handler-codec.ts @@ -104,12 +104,7 @@ export class RPCHandlerCodec implements StandardHandlerCodec< } } - encodeError( - error: AnyORPCError, - _procedure?: AnyProcedure, - _path?: string[], - _options?: ResolvedStandardHandlerHandleOptions, - ): Promisable { + encodeError(error: AnyORPCError): Promisable { const status = getOwn(this.errorStatusMap, error.code) ?? DEFAULT_ERROR_STATUS return { From 1348e2e15eb472774c8d49936326fd62305894aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Mon, 23 Nov 2026 15:02:07 +0700 Subject: [PATCH 4/6] docs(server): show encodeError in a tip with a not-found example --- apps/content/docs/openapi/handler.mdx | 17 ++++++++++++++++- apps/content/docs/rpc/handler.mdx | 17 ++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/apps/content/docs/openapi/handler.mdx b/apps/content/docs/openapi/handler.mdx index 6052dec4d..70b040274 100644 --- a/apps/content/docs/openapi/handler.mdx +++ b/apps/content/docs/openapi/handler.mdx @@ -92,7 +92,22 @@ const handler = new OpenAPIHandler(router, { }) ``` -To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the way procedure errors are encoded: `{ matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) }`. +:::tip +Use `encodeError` to respond with an `ORPCError`, encoded the way procedure errors are. For example, to answer unmatched requests with a `NOT_FOUND` error: + +```ts +;async ({ next, encodeError }) => { + const result = await next() + + if (!result.matched) { + return { matched: true, response: await encodeError(new ORPCError('NOT_FOUND')) } + } + + return result +} +``` + +::: ### Interceptors diff --git a/apps/content/docs/rpc/handler.mdx b/apps/content/docs/rpc/handler.mdx index 996b8ce8c..eac2322d8 100644 --- a/apps/content/docs/rpc/handler.mdx +++ b/apps/content/docs/rpc/handler.mdx @@ -162,7 +162,22 @@ const handler = new RPCHandler(router, { }) ``` -To refuse a request there, respond with `encodeError`, which encodes an `ORPCError` the way procedure errors are encoded: `{ matched: true, response: await encodeError(new ORPCError('FORBIDDEN')) }`. +:::tip +Use `encodeError` to respond with an `ORPCError`, encoded the way procedure errors are. For example, to answer unmatched requests with a `NOT_FOUND` error: + +```ts +;async ({ next, encodeError }) => { + const result = await next() + + if (!result.matched) { + return { matched: true, response: await encodeError(new ORPCError('NOT_FOUND')) } + } + + return result +} +``` + +::: ### Interceptors From 5e2c46f0e420af2f2c066218259b40dc860f0703 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Mon, 23 Nov 2026 15:03:07 +0700 Subject: [PATCH 5/6] docs(server): drop the refused batches section --- apps/content/docs/plugins/batch.mdx | 6 ------ 1 file changed, 6 deletions(-) diff --git a/apps/content/docs/plugins/batch.mdx b/apps/content/docs/plugins/batch.mdx index e9634f8a5..0ab1cfc56 100644 --- a/apps/content/docs/plugins/batch.mdx +++ b/apps/content/docs/plugins/batch.mdx @@ -82,12 +82,6 @@ const link = new RPCLink({ -## Refused Batches - -When the server refuses a whole batch, it answers with a regular error response instead of a batch response, and every call in the batch rejects with that `ORPCError`. A malformed batch is a `BAD_REQUEST`, a batch above `maxSize` is a `PAYLOAD_TOO_LARGE`, and an error another plugin throws while the batch body is read, such as the [Request Limit Plugin](/docs/plugins/request-limit)'s, keeps its code, status, message, and data. - -A subrequest that matches no procedure fails on its own with a `NOT_FOUND` error, without affecting the rest of the batch. - ## Response Modes In the default `buffered` mode, the server starts the batch response once every procedure has responded, so it can carry their [headers](#response-headers). The response streams only if one of them returned an [AsyncIteratorObject](/docs/async-iterator-object) or a [`ReadableStream`](/docs/binary-data). If your client cannot read streamed responses, keep these procedures out of the batch with [`filter`](#filtering-requests). From 0a616d9b35dc5b2080b61ae2708071251b31a52b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Mon, 23 Nov 2026 15:12:00 +0700 Subject: [PATCH 6/6] fix(server): keep a failing batch maxSize option from becoming a refusal --- packages/server/src/plugins/batch.test.ts | 15 +++++++++++++++ packages/server/src/plugins/batch.ts | 21 ++++++++++----------- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/packages/server/src/plugins/batch.test.ts b/packages/server/src/plugins/batch.test.ts index c8c9c325a..b368dc7e8 100644 --- a/packages/server/src/plugins/batch.test.ts +++ b/packages/server/src/plugins/batch.test.ts @@ -399,6 +399,21 @@ describe('batchHandlerPlugin', () => { expect(handlerFn).toHaveBeenCalledTimes(0) }) + it('does not turn a failing maxSize option into a refusal', async () => { + const error = new Error('boom') + const handler = createHandler( + new BatchHandlerPlugin({ + maxSize: () => { + throw error + }, + }), + ) + + await expect( + handler.handle(createBatchRequest({ messages: [makePeerRequestMessage('0', '/ping')] })), + ).rejects.toBe(error) + }) + it('returns 500 sub-response when mapSubrequest throws', async ({ onTestFinished }) => { const rejectSpy = vi .spyOn(Promise, 'reject') diff --git a/packages/server/src/plugins/batch.ts b/packages/server/src/plugins/batch.ts index c2957379c..078c98c18 100644 --- a/packages/server/src/plugins/batch.ts +++ b/packages/server/src/plugins/batch.ts @@ -327,7 +327,7 @@ export class BatchHandlerPlugin implements StandardHandlerPlu let messages: ClientPeerSendMessage[] try { - messages = await this.readMessages(interceptorOptions) + messages = await this.readMessages(interceptorOptions.request) } catch (error) { const refusal = error instanceof ORPCError @@ -337,6 +337,14 @@ export class BatchHandlerPlugin implements StandardHandlerPlu return { matched: true, response: await interceptorOptions.encodeError(refusal) } } + if (messages.length > (await value(this.maxSize, interceptorOptions))) { + const tooLarge = new ORPCError('PAYLOAD_TOO_LARGE', { + message: 'Batch request size exceeds the maximum allowed size', + }) + + return { matched: true, response: await interceptorOptions.encodeError(tooLarge) } + } + /** * Errors should not occur at the routing interceptor level. * Reject the promise so it can be handled by the unhandledRejection handler @@ -543,10 +551,7 @@ export class BatchHandlerPlugin implements StandardHandlerPlu } } - private async readMessages( - options: StandardHandlerRoutingInterceptorOptions, - ): Promise { - const { request } = options + private async readMessages(request: StandardLazyRequest): Promise { let messages: unknown if (request.method === 'GET') { @@ -577,12 +582,6 @@ export class BatchHandlerPlugin implements StandardHandlerPlu }) } - if (messages.length > (await value(this.maxSize, options))) { - throw new ORPCError('PAYLOAD_TOO_LARGE', { - message: 'Batch request size exceeds the maximum allowed size', - }) - } - return messages } }