Repository navigation
feat(server): max batch size - #7191
Conversation
|
π Deployed to the trpc-pr-7191 environment in trpc-sse-and-websockets
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. π βΉοΈ Recent review infoβοΈ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: π Files selected for processing (3)
π§ Files skipped from review as they are similar to previous changes (2)
WalkthroughAdds a server-side Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant HTTP_Handler as "HTTP Handler\n(fetchRequestHandler)"
participant Parser as "getRequestInfo / jsonContentTypeHandler"
participant Router
Client->>HTTP_Handler: POST/GET ?batch=1 with N operations
HTTP_Handler->>Parser: parse request (includes opts.maxBatchSize)
alt N > maxBatchSize
Parser-->>HTTP_Handler: 400 BAD_REQUEST ("Batch call exceeds maximum size")
HTTP_Handler-->>Client: 400 Bad Request
else N β€ maxBatchSize
Parser->>Router: resolve procedures (info.calls)
Router-->>HTTP_Handler: responses
HTTP_Handler-->>Client: 200 OK with batch results
end
Estimated code review effortπ― 3 (Moderate) | β±οΈ ~20 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
π₯ Pre-merge checks | β 3 | β 2β Failed checks (1 warning, 1 inconclusive)
β Passed checks (3 passed)
βοΈ Tip: You can configure your own custom pre-merge checks in the settings. β¨ Finishing Touchesπ Generate docstrings
π§ͺ Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
packages/tests/server/adapters/standalone.test.ts (1)
283-283: Remove redundant shadowed variable.This line creates a local
tthat shadows the module-leveltdefined at line 14. Both are identical (initTRPC.create()), so this declaration is unnecessary and could cause confusion.β»οΈ Suggested fix
test('recipe: max batch size on the server', async () => { const MAX_BATCH_SIZE = 10; - const t = initTRPC.create(); - const appRouter = t.router({π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/tests/server/adapters/standalone.test.ts` at line 283, The test declares a redundant local variable `const t = initTRPC.create();` that shadows the module-level `t` (also created via `initTRPC.create()`); remove the local declaration so the test uses the existing module-level `t` (ensure any references in the test continue to use `t` without re-declaring it).
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/tests/server/adapters/standalone.test.ts`:
- Line 283: The test declares a redundant local variable `const t =
initTRPC.create();` that shadows the module-level `t` (also created via
`initTRPC.create()`); remove the local declaration so the test uses the existing
module-level `t` (ensure any references in the test continue to use `t` without
re-declaring it).
βΉοΈ Review info
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
π Files selected for processing (5)
packages/server/src/unstable-core-do-not-import/http/contentType.tspackages/server/src/unstable-core-do-not-import/http/resolveResponse.tspackages/server/src/unstable-core-do-not-import/http/types.tspackages/tests/server/adapters/standalone.test.tswww/docs/server/context.md
π€ Files with no reviewable changes (1)
- www/docs/server/context.md
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
There was a problem hiding this comment.
Pull request overview
Adds a first-class server-side maxBatchSize option to tRPC HTTP handlers/adapters to reject oversized batch calls early (during request info parsing), addressing a DoS/bypass vector where createContext-based limits can be skipped.
Changes:
- Introduces
maxBatchSizeon server HTTP handler options (BaseHandlerOptions) and wires it into request parsing. - Enforces the limit in the JSON content-type request parser before input deserialization.
- Updates the standalone adapter test to use the new
maxBatchSizeoption and adjusts expected error details; removes the old docs recipe snippet.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| www/docs/server/context.md | Removes the prior βlimit batch size via contextβ recipe (currently without replacement docs for maxBatchSize). |
| packages/tests/server/adapters/standalone.test.ts | Updates the batch-size βrecipeβ test to configure maxBatchSize on the server and assert the new error behavior. |
| packages/server/src/unstable-core-do-not-import/http/types.ts | Adds maxBatchSize?: number to base handler options with JSDoc guidance. |
| packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts | Plumbs maxBatchSize through to getRequestInfo. |
| packages/server/src/unstable-core-do-not-import/http/contentType.ts | Enforces maxBatchSize during JSON request parsing (before reading/parsing the body). |
π‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
π§Ή Nitpick comments (1)
www/docs/client/links/httpBatchLink.md (1)
105-105: Consider using American English spelling for consistency.The word "organisations" uses British spelling. Most open-source projects and technical documentation use American English ("organizations") for consistency.
π Suggested spelling change
-Some organisations are concerned that request batching may increase the service impact of abuse such as DDoS attacks. While this is typically best addressed with proper rate limiting and WAF policies, you can also cap the number of operations allowed in a batch if desired. +Some organizations are concerned that request batching may increase the service impact of abuse such as DDoS attacks. While this is typically best addressed with proper rate limiting and WAF policies, you can also cap the number of operations allowed in a batch if desired.π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@www/docs/client/links/httpBatchLink.md` at line 105, Update the British spelling "organisations" to American English "organizations" in the sentence starting "Some organisations are concerned..." (and search the same document for any other occurrences of "organisations"/"organisation" to change to "organizations"/"organization"); keep the rest of the sentence unchanged and ensure consistency across the markdown file.
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@www/docs/client/links/httpBatchLink.md`:
- Line 105: Update the British spelling "organisations" to American English
"organizations" in the sentence starting "Some organisations are concerned..."
(and search the same document for any other occurrences of
"organisations"/"organisation" to change to "organizations"/"organization");
keep the rest of the sentence unchanged and ensure consistency across the
markdown file.
564d3e7 to
52c76ba
Compare
52c76ba to
ad53da0
Compare
f086a04 to
7aca182
Compare
There was a problem hiding this comment.
π§Ή Nitpick comments (2)
packages/tests/server/adapters/standalone.test.ts (2)
316-331: Test logic is correct but assertion pattern is unconventional.The test correctly validates that exactly
MAX_BATCH_SIZErequests succeed. However, nestingexpect()inside.every()is unusual - if the innerexpectfails, it throws before.every()completes. Consider using.forEach()for assertions and.every()only for filtering:β»οΈ Alternative assertion pattern
- expect( - results1.every((res) => { - if (res.status !== 'fulfilled') { - return false; - } - - expect(res.value).toBe('hello test'); - - return true; - }), - ).toBe(true); + expect(results1.every((res) => res.status === 'fulfilled')).toBe(true); + for (const res of results1) { + if (res.status === 'fulfilled') { + expect(res.value).toBe('hello test'); + } + }π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/tests/server/adapters/standalone.test.ts` around lines 316 - 331, The current test uses expect() inside results1.every(), which can throw during iteration; change the assertion pattern: first assert that results1.length === MAX_BATCH_SIZE and that results1.every(r => r.status === 'fulfilled') (using results1 and MAX_BATCH_SIZE), then iterate over results1 with a forEach to call expect(res.value).toBe('hello test') for each fulfilled result (referring to promises1, results1, and client.hello.query) so assertions run directly and failures report clearly.
283-283: Variable shadowing is intentional but consider removing redundant declaration.The
tvariable at line 283 shadows the module-leveltdeclared at line 14. Both are created identically viainitTRPC.create(). Since this test doesn't need different tRPC configuration, consider reusing the module-leveltfor consistency.β»οΈ Proposed simplification
test('recipe: max batch size on the server', async () => { const MAX_BATCH_SIZE = 10; - const t = initTRPC.create(); - const appRouter = t.router({π€ Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/tests/server/adapters/standalone.test.ts` at line 283, The local test-level declaration "const t = initTRPC.create();" shadows the module-level "t" (both created identically); remove the local declaration and reuse the existing module-level variable "t" throughout the test to avoid redundancy and shadowing (update any references in the test to use the module-level "t" and delete the duplicated initialization).
π€ Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/tests/server/adapters/standalone.test.ts`:
- Around line 316-331: The current test uses expect() inside results1.every(),
which can throw during iteration; change the assertion pattern: first assert
that results1.length === MAX_BATCH_SIZE and that results1.every(r => r.status
=== 'fulfilled') (using results1 and MAX_BATCH_SIZE), then iterate over results1
with a forEach to call expect(res.value).toBe('hello test') for each fulfilled
result (referring to promises1, results1, and client.hello.query) so assertions
run directly and failures report clearly.
- Line 283: The local test-level declaration "const t = initTRPC.create();"
shadows the module-level "t" (both created identically); remove the local
declaration and reuse the existing module-level variable "t" throughout the test
to avoid redundancy and shadowing (update any references in the test to use the
module-level "t" and delete the duplicated initialization).
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 13f8541c-823f-42f2-9c06-23c86c3216a6
π Files selected for processing (6)
packages/server/src/unstable-core-do-not-import/http/contentType.tspackages/server/src/unstable-core-do-not-import/http/resolveResponse.tspackages/server/src/unstable-core-do-not-import/http/types.tspackages/tests/server/adapters/standalone.test.tswww/docs/client/links/httpBatchLink.mdwww/docs/server/context.md
π€ Files with no reviewable changes (1)
- www/docs/server/context.md
π§ Files skipped from review as they are similar to previous changes (3)
- packages/server/src/unstable-core-do-not-import/http/contentType.ts
- www/docs/client/links/httpBatchLink.md
- packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts
themavik
left a comment
There was a problem hiding this comment.
maxBatchSize runs on comma-split paths inside jsonContentTypeHandler.parse, which matches httpBatchLink batch URLs. Custom adapters that batch without that shape will not hit this guardβfine, just know the limit is tied to that parser.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.
π‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const paths = isBatchCall ? opts.path.split(',') : [opts.path]; | ||
| if ( | ||
| isBatchCall && | ||
| typeof maxBatchSize === 'number' && | ||
| paths.length > maxBatchSize | ||
| ) { | ||
| throw new TRPCError({ | ||
| code: 'BAD_REQUEST', | ||
| message: `Batch call exceeds maximum size`, | ||
| }); |
There was a problem hiding this comment.
opts.path.split(',') allocates an array with one entry per comma before the size check. With a long path containing many commas, this can create a large allocation even when maxBatchSize is small. Consider counting segments up to maxBatchSize + 1 (e.g., scan the string for commas and early-exit) and only performing a full split when within the limit.
| const paths = isBatchCall ? opts.path.split(',') : [opts.path]; | |
| if ( | |
| isBatchCall && | |
| typeof maxBatchSize === 'number' && | |
| paths.length > maxBatchSize | |
| ) { | |
| throw new TRPCError({ | |
| code: 'BAD_REQUEST', | |
| message: `Batch call exceeds maximum size`, | |
| }); | |
| let paths: string[]; | |
| if (isBatchCall) { | |
| if (typeof maxBatchSize === 'number') { | |
| // Count segments up to maxBatchSize + 1 without allocating an array. | |
| let segments = 1; | |
| const path = opts.path; | |
| for (let i = 0; i < path.length && segments <= maxBatchSize; i++) { | |
| if (path[i] === ',') { | |
| segments++; | |
| } | |
| } | |
| if (segments > maxBatchSize) { | |
| throw new TRPCError({ | |
| code: 'BAD_REQUEST', | |
| message: `Batch call exceeds maximum size`, | |
| }); | |
| } | |
| } | |
| paths = opts.path.split(','); | |
| } else { | |
| paths = [opts.path]; |
| const paths = isBatchCall ? opts.path.split(',') : [opts.path]; | ||
| if ( | ||
| isBatchCall && | ||
| typeof maxBatchSize === 'number' && |
There was a problem hiding this comment.
typeof maxBatchSize === 'number' will treat NaN/Infinity as valid, but the comparison can then fail to enforce the limit (e.g., paths.length > NaN is always false). Validate maxBatchSize as a finite, positive integer (e.g., Number.isSafeInteger(maxBatchSize) && maxBatchSize > 0) or explicitly document/handle these edge values.
| typeof maxBatchSize === 'number' && | |
| Number.isSafeInteger(maxBatchSize) && | |
| maxBatchSize > 0 && |
| ```ts title="server.ts" | ||
| import { createHTTPServer } from '@trpc/server/adapters/standalone'; | ||
|
|
||
| createHTTPServer({ |
There was a problem hiding this comment.
The createHTTPServer snippet is missing required options (at least router). As written, it wonβt work if copied verbatim. Consider including router: appRouter (and any other required fields) or using an ellipsis to indicate omitted options.
| createHTTPServer({ | |
| createHTTPServer({ | |
| router: appRouter, |
| ```ts title='pages/api/trpc/[trpc].ts' | ||
| export default trpcNext.createNextApiHandler({ |
There was a problem hiding this comment.
The Next.js example calls createNextApiHandler with only maxBatchSize, but the handler also requires router (and typically createContext). Consider expanding the snippet so itβs runnable when copied.
| ```ts title='pages/api/trpc/[trpc].ts' | |
| export default trpcNext.createNextApiHandler({ | |
| ```ts title='pages/api/trpc/[trpc].ts' | |
| import * as trpcNext from '@trpc/server/adapters/next'; | |
| import { appRouter, createContext } from '../../../server'; | |
| export default trpcNext.createNextApiHandler({ | |
| router: appRouter, | |
| createContext, |
|
|
||
| ### 1. Set a maximum batch size on your server: | ||
|
|
||
| `maxBatchSize` limits how many operations may be sent in a single batch request. Requests exceeding this limit will be rejected with a `400 Bad Request` error. This can be passed to any tRPC adapter. |
There was a problem hiding this comment.
The docs say maxBatchSize βcan be passed to any tRPC adapterβ, but this option is specific to the HTTP request handlers (it wonβt apply to non-HTTP adapters like WS). Consider rewording to βany HTTP adapterβ to avoid confusion.
| `maxBatchSize` limits how many operations may be sent in a single batch request. Requests exceeding this limit will be rejected with a `400 Bad Request` error. This can be passed to any tRPC adapter. | |
| `maxBatchSize` limits how many operations may be sent in a single batch request. Requests exceeding this limit will be rejected with a `400 Bad Request` error. This can be passed to any HTTP adapter. |
|
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you. |
Closes #7153
π― Changes
Adds maxBatchSize to server adapters, validating at the earliest point possible during batch deserialisation
β Checklist
Summary by CodeRabbit
New Features
Documentation
Tests