Registry Mirror
Skip to content

File tree

‎apps/content/docs/plugins/batch.mdx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,14 @@ const link = new RPCLink({
269269
Per-request data passed through the link's [`headers` option](/docs/rpc/link#url-and-header-options) is resolved for each request, so it is safe without `scope`.
270270
:::
271271

272+
## Request Headers
273+
274+
Headers shared by every request in a batch are sent on the batch request. Other headers stay on each subrequest.
275+
276+
A `GET` batch puts only the headers listed in `allowedUrlHeaders` in its URL, by default `traceparent` and `tracestate`. After `mapSubrequest`, `GET` requests with other headers are batched only with requests that have the same headers, once the `headers` option moves them to the batch request. The rest are sent individually.
277+
278+
Requests sent individually skip the `headers` and `mapSubrequest` options.
279+
272280
## Response Headers
273281

274282
In `buffered` mode, the batch response carries the cookies and `Vary` fields of its subresponses, and the headers they all share. In `streaming` mode, it carries only the cookies of the first subresponse to respond. Other headers stay on their subresponse. To change what stays on each subresponse, set the server plugin's `mapSubresponse` option.

‎packages/client/src/plugins/batch.test.ts‎

Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { encodePeerMessage } from '@standard-server/peer'
66

77
import type { StandardLinkCodec, StandardLinkTransport } from '../adapters/standard/index'
88
import { StandardLink } from '../adapters/standard/index'
9+
import type { BatchLinkPluginOptions } from './batch'
910
import { BatchLinkPlugin } from './batch'
1011

1112
interface TestContext {
@@ -1868,6 +1869,262 @@ describe('batchLinkPlugin', () => {
18681869
})
18691870
})
18701871

1872+
describe('method GET subrequest headers', () => {
1873+
function makeHeadersLink(
1874+
headersByPath: Record<string, Record<string, string>>,
1875+
options: Partial<BatchLinkPluginOptions<TestContext>> = {},
1876+
method: 'GET' | 'POST' = 'GET',
1877+
) {
1878+
const codec = makeCodec()
1879+
const transport = makeTransport()
1880+
1881+
vi.mocked(codec.encodeInput).mockImplementation(async (_input, path) => ({
1882+
method,
1883+
url: `/${path.join('/')}` as `/${string}`,
1884+
headers: headersByPath[path[0]!] ?? {},
1885+
body: undefined,
1886+
}))
1887+
1888+
const link = new StandardLink(codec, transport, {
1889+
plugins: [new BatchLinkPlugin({ groups: [defaultGroup], ...options })],
1890+
})
1891+
1892+
const sent = () => vi.mocked(transport.send).mock.calls.map(([request]) => request)
1893+
1894+
return {
1895+
callAll: (...paths: string[]) =>
1896+
Promise.all(paths.map((path) => link.call([path], {}, { context: {} }))),
1897+
urls: () =>
1898+
sent()
1899+
.map((request) => decodeURIComponent(request.url))
1900+
.join('\n'),
1901+
sent,
1902+
batches: () => sent().filter((request) => request.headers['orpc-batch']),
1903+
singles: () => sent().filter((request) => !request.headers['orpc-batch']),
1904+
}
1905+
}
1906+
1907+
it('sends calls with different headers individually instead of writing them to the URL', async () => {
1908+
const { callAll, urls, batches, singles } = makeHeadersLink({
1909+
a: { authorization: 'Bearer USER_A_TOKEN' },
1910+
b: { authorization: 'Bearer USER_B_TOKEN' },
1911+
})
1912+
1913+
await expect(callAll('a', 'b')).resolves.toEqual(['not-batched', 'not-batched'])
1914+
1915+
expect(urls()).not.toContain('USER_')
1916+
expect(batches()).toHaveLength(0)
1917+
expect(singles().map(({ url, headers }) => [url, headers.authorization])).toEqual([
1918+
['/a', 'Bearer USER_A_TOKEN'],
1919+
['/b', 'Bearer USER_B_TOKEN'],
1920+
])
1921+
})
1922+
1923+
it('keeps the header of an authenticated call out of the URL when batched with a public call', async () => {
1924+
const { callAll, urls, batches, singles } = makeHeadersLink({
1925+
private: { authorization: 'Bearer USER_A_TOKEN' },
1926+
})
1927+
1928+
await expect(callAll('private', 'public')).resolves.toEqual(['not-batched', 'not-batched'])
1929+
1930+
expect(urls()).not.toContain('USER_A_TOKEN')
1931+
expect(batches()).toHaveLength(0)
1932+
expect(singles().map(({ url, headers }) => [url, headers.authorization])).toEqual([
1933+
['/private', 'Bearer USER_A_TOKEN'],
1934+
['/public', undefined],
1935+
])
1936+
})
1937+
1938+
it('keeps both shared and differing headers on a call that cannot join the batch', async () => {
1939+
const { callAll, urls, singles } = makeHeadersLink({
1940+
a: { 'x-shared': 'SHARED', 'cookie': 'session=COOKIE_A' },
1941+
b: { 'x-shared': 'SHARED', 'cookie': 'session=COOKIE_B' },
1942+
})
1943+
1944+
await callAll('a', 'b')
1945+
1946+
expect(urls()).not.toContain('COOKIE_')
1947+
expect(singles().map(({ headers }) => headers)).toEqual([
1948+
{ 'x-shared': 'SHARED', 'cookie': 'session=COOKIE_A' },
1949+
{ 'x-shared': 'SHARED', 'cookie': 'session=COOKIE_B' },
1950+
])
1951+
})
1952+
1953+
it('still batches the calls that share identical headers', async () => {
1954+
const { callAll, urls, sent, batches, singles } = makeHeadersLink({
1955+
a1: { 'authorization': 'Bearer USER_A_TOKEN', 'x-tenant': 'ACME' },
1956+
// Same headers in a different order
1957+
a2: { 'x-tenant': 'ACME', 'authorization': 'Bearer USER_A_TOKEN' },
1958+
b: { authorization: 'Bearer USER_B_TOKEN' },
1959+
public1: {},
1960+
public2: {},
1961+
})
1962+
1963+
await expect(callAll('a1', 'a2', 'b', 'public1', 'public2')).resolves.toHaveLength(5)
1964+
1965+
expect(urls()).not.toContain('USER_')
1966+
expect(urls()).not.toContain('ACME')
1967+
expect(sent()).toHaveLength(3)
1968+
1969+
expect(
1970+
batches()
1971+
.map((request) => extractBatchMessagesFromRequest(request).map((m) => m.json.url))
1972+
.toSorted((a, b) => a[0].localeCompare(b[0])),
1973+
).toEqual([
1974+
['/a1', '/a2'],
1975+
['/public1', '/public2'],
1976+
])
1977+
expect(batches().find((r) => r.headers.authorization)?.headers).toEqual({
1978+
'authorization': 'Bearer USER_A_TOKEN',
1979+
'x-tenant': 'ACME',
1980+
'orpc-batch': 'buffered',
1981+
})
1982+
expect(singles().map(({ url, headers }) => [url, headers.authorization])).toEqual([
1983+
['/b', 'Bearer USER_B_TOKEN'],
1984+
])
1985+
})
1986+
1987+
it('batches every call when all of them share identical headers', async () => {
1988+
const shared = { authorization: 'Bearer USER_A_TOKEN' }
1989+
const { callAll, urls, sent, batches } = makeHeadersLink({ a: shared, b: shared })
1990+
1991+
await expect(callAll('a', 'b')).resolves.toEqual(['result-0', 'result-1'])
1992+
1993+
expect(sent()).toHaveLength(1)
1994+
expect(batches()[0]!.headers.authorization).toBe('Bearer USER_A_TOKEN')
1995+
expect(urls()).not.toContain('USER_A_TOKEN')
1996+
})
1997+
1998+
it('keeps headers out of the URL when a batch of identical headers is split by maxUrlLength', async () => {
1999+
const shared = { authorization: 'Bearer USER_A_TOKEN' }
2000+
const { callAll, urls, singles } = makeHeadersLink(
2001+
{ a: shared, b: shared },
2002+
{ maxUrlLength: 1 },
2003+
)
2004+
2005+
await expect(callAll('a', 'b')).resolves.toEqual(['not-batched', 'not-batched'])
2006+
2007+
expect(urls()).not.toContain('USER_A_TOKEN')
2008+
expect(singles().map(({ headers }) => headers.authorization)).toEqual([
2009+
'Bearer USER_A_TOKEN',
2010+
'Bearer USER_A_TOKEN',
2011+
])
2012+
})
2013+
2014+
it('sends a call individually when a custom mapSubrequest adds a header to it', async () => {
2015+
const { callAll, urls, batches, singles } = makeHeadersLink(
2016+
{},
2017+
{
2018+
mapSubrequest: ({ request }) =>
2019+
request.url === '/secret'
2020+
? { ...request, headers: { ...request.headers, 'x-secret': 'MAPPED_SECRET' } }
2021+
: request,
2022+
},
2023+
)
2024+
2025+
await expect(callAll('secret', 'a', 'b')).resolves.toEqual([
2026+
'not-batched',
2027+
'result-0',
2028+
'result-1',
2029+
])
2030+
2031+
expect(urls()).not.toContain('MAPPED_SECRET')
2032+
expect(batches()).toHaveLength(1)
2033+
expect(singles().map(({ url, headers }) => [url, headers['x-secret']])).toEqual([
2034+
['/secret', undefined],
2035+
])
2036+
})
2037+
2038+
it.each([
2039+
['a custom mapSubrequest keeps them', { mapSubrequest: ({ request }) => request }],
2040+
['a custom headers option lifts none of them', { headers: () => ({}) }],
2041+
] satisfies [string, Partial<BatchLinkPluginOptions<TestContext>>][])(
2042+
'sends calls with identical headers individually when %s',
2043+
async (_, options) => {
2044+
const shared = { authorization: 'Bearer USER_A_TOKEN' }
2045+
const { callAll, urls, batches, singles } = makeHeadersLink(
2046+
{ a: shared, b: shared },
2047+
options,
2048+
)
2049+
2050+
await expect(callAll('a', 'b')).resolves.toEqual(['not-batched', 'not-batched'])
2051+
2052+
expect(urls()).not.toContain('USER_A_TOKEN')
2053+
expect(batches()).toHaveLength(0)
2054+
expect(singles().map(({ headers }) => headers.authorization)).toEqual([
2055+
'Bearer USER_A_TOKEN',
2056+
'Bearer USER_A_TOKEN',
2057+
])
2058+
},
2059+
)
2060+
2061+
it('batches calls whose differing headers a custom mapSubrequest removes', async () => {
2062+
const { callAll, urls, sent, batches } = makeHeadersLink(
2063+
{
2064+
a: { 'x-request-id': 'REQUEST_A' },
2065+
b: { 'x-request-id': 'REQUEST_B' },
2066+
},
2067+
{ mapSubrequest: ({ request }) => ({ ...request, headers: {} }) },
2068+
)
2069+
2070+
await expect(callAll('a', 'b')).resolves.toEqual(['result-0', 'result-1'])
2071+
2072+
expect(sent()).toHaveLength(1)
2073+
expect(batches()).toHaveLength(1)
2074+
expect(urls()).not.toContain('REQUEST_')
2075+
})
2076+
2077+
it('batches calls whose differing headers are allowed in the URL', async () => {
2078+
const { callAll, urls, sent, batches } = makeHeadersLink({
2079+
a: { authorization: 'Bearer USER_A_TOKEN', traceparent: 'TRACE_A' },
2080+
b: { authorization: 'Bearer USER_A_TOKEN', traceparent: 'TRACE_B' },
2081+
})
2082+
2083+
await expect(callAll('a', 'b')).resolves.toEqual(['result-0', 'result-1'])
2084+
2085+
expect(sent()).toHaveLength(1)
2086+
expect(batches()[0]!.headers.authorization).toBe('Bearer USER_A_TOKEN')
2087+
expect(urls()).not.toContain('USER_A_TOKEN')
2088+
expect(urls()).toContain('TRACE_A')
2089+
expect(urls()).toContain('TRACE_B')
2090+
})
2091+
2092+
it.each([
2093+
['an empty allowedUrlHeaders', { allowedUrlHeaders: [] }, 'traceparent', 2],
2094+
['a custom allowedUrlHeaders', { allowedUrlHeaders: ['x-request-id'] }, 'x-request-id', 1],
2095+
] satisfies [string, Partial<BatchLinkPluginOptions<TestContext>>, string, number][])(
2096+
'follows %s',
2097+
async (_, options, header, requests) => {
2098+
const { callAll, sent } = makeHeadersLink(
2099+
{ a: { [header]: 'VALUE_A' }, b: { [header]: 'VALUE_B' } },
2100+
options,
2101+
)
2102+
2103+
await callAll('a', 'b')
2104+
2105+
expect(sent()).toHaveLength(requests)
2106+
},
2107+
)
2108+
2109+
it('keeps batching POST calls with different headers in the body', async () => {
2110+
const { callAll, sent, batches } = makeHeadersLink(
2111+
{
2112+
a: { authorization: 'Bearer USER_A_TOKEN' },
2113+
b: { authorization: 'Bearer USER_B_TOKEN' },
2114+
},
2115+
{},
2116+
'POST',
2117+
)
2118+
2119+
await expect(callAll('a', 'b')).resolves.toEqual(['result-0', 'result-1'])
2120+
2121+
expect(sent()).toHaveLength(1)
2122+
expect(
2123+
extractBatchMessagesFromRequest(batches()[0]!).map((m) => m.json.headers.authorization),
2124+
).toEqual(['Bearer USER_A_TOKEN', 'Bearer USER_B_TOKEN'])
2125+
})
2126+
})
2127+
18712128
describe('async context', () => {
18722129
const storage = new AsyncLocalStorage<string>()
18732130

@@ -1912,6 +2169,30 @@ describe('batchLinkPlugin', () => {
19122169
expect(transport.send).toHaveBeenCalledTimes(2)
19132170
})
19142171

2172+
it("sends a GET request left out of the batch for its headers in its caller's async context", async () => {
2173+
const codec = makeCodec()
2174+
vi.mocked(codec.encodeInput).mockImplementation(async (_input, path) => ({
2175+
method: 'GET',
2176+
url: `/${path.join('/')}` as `/${string}`,
2177+
headers: { 'x-user': path[0]! },
2178+
body: undefined,
2179+
}))
2180+
2181+
const transport = makeUserTransport()
2182+
const link = new StandardLink(codec, transport, {
2183+
plugins: [new BatchLinkPlugin({ groups: [defaultGroup] })],
2184+
})
2185+
2186+
await expect(
2187+
Promise.all([
2188+
storage.run('alice', () => link.call(['alice'], {}, { context: {} })),
2189+
storage.run('bob', () => link.call(['bob'], {}, { context: {} })),
2190+
]),
2191+
).resolves.toEqual(['alice', 'bob'])
2192+
2193+
expect(transport.send).toHaveBeenCalledTimes(2)
2194+
})
2195+
19152196
it.each([
19162197
['maxSize', { maxSize: 1 }],
19172198
['maxUrlLength', { maxUrlLength: 1 }],

0 commit comments

Comments
 (0)