Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/content/docs/plugins/dedupe.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ const link = new RPCLink({
The `link` can be any supported oRPC link, such as [RPCLink](/docs/rpc/link), [OpenAPILink](/docs/openapi/link), or a custom one.
:::

Requests are identical when their path, method, URL, body, and headers match. Headers listed in `ignoredHeaders` (default `traceparent` and `tracestate`) are not compared, and the shared request carries those of the first request.

## Filter

By default, the plugin deduplicates `GET` and `QUERY` requests. You can customize this behavior by providing a `filter` function.
Expand Down
104 changes: 104 additions & 0 deletions packages/client/src/plugins/dedupe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import * as SharedExperimentalV2Module from '@orpc/shared'
import {
AsyncIteratorClass,
asyncIteratorToStream,
getTracer,
promiseWithResolvers,
setTracer,
sleep,
} from '@orpc/shared'
import type { StandardBody, StandardLazyResponse, StandardRequest } from '@standard-server/core'
Expand Down Expand Up @@ -159,6 +161,108 @@ describe('dedupeLinkPlugin', () => {
expect(transport.send).toHaveBeenCalledTimes(1)
})

describe('with a tracer injecting per-call headers', () => {
function useTracer(extraHeader?: string) {
const original = getTracer()
onTestFinished(() => setTracer(original))

let spanId = 0
const makeSpan = () => ({
id: ++spanId,
setAttribute() {},
updateName() {},
addEvent() {},
recordException() {},
end() {},
})

setTracer({
startSpan: makeSpan,
startActiveSpan: (_name, _parent, fn) => fn(makeSpan()),
getActiveSpan: () => undefined,
withActiveSpan: (_span, fn) => fn(),
inject(span, headers) {
headers.traceparent = `00-trace-${(span as ReturnType<typeof makeSpan>).id}-01`
headers.tracestate = `vendor=${(span as ReturnType<typeof makeSpan>).id}`

if (extraHeader) {
headers[extraHeader] = `${(span as ReturnType<typeof makeSpan>).id}`
}
},
})
}

it('dedupes identical requests and sends the first one', async () => {
useTracer()
const codec = makeCodec()
const transport = makeTransport()

const link = new StandardLink(codec, transport, {
plugins: [
new DedupeLinkPlugin({
groups: [{ condition: () => true, context: { group: true } }],
}),
],
})

const [output1, output2] = await Promise.all([
link.call(['GET', 'planet'], undefined, { context: {} }),
link.call(['GET', 'planet'], undefined, { context: {} }),
])

expect(output1).toBe(output2)
expect(transport.send).toHaveBeenCalledTimes(1)
expect(vi.mocked(transport.send).mock.calls[0]![0].headers).toMatchObject({
traceparent: '00-trace-1-01',
tracestate: 'vendor=1',
})
})

it('dedupes requests differing only in custom `ignoredHeaders`', async () => {
useTracer('b3')
const codec = makeCodec()
const transport = makeTransport()

const link = new StandardLink(codec, transport, {
plugins: [
new DedupeLinkPlugin({
ignoredHeaders: ['traceparent', 'tracestate', 'b3'],
groups: [{ condition: () => true, context: { group: true } }],
}),
],
})

await Promise.all([
link.call(['GET', 'planet'], undefined, { context: {} }),
link.call(['GET', 'planet'], undefined, { context: {} }),
])

expect(transport.send).toHaveBeenCalledTimes(1)
})

it('does not dedupe requests differing in headers left out of `ignoredHeaders`', async () => {
useTracer()
const codec = makeCodec()
const transport = makeTransport()

const link = new StandardLink(codec, transport, {
plugins: [
new DedupeLinkPlugin({
ignoredHeaders: ['traceparent'],
groups: [{ condition: () => true, context: { group: true } }],
}),
],
})

await Promise.all([
link.call(['GET', 'planet'], undefined, { context: {} }),
link.call(['GET', 'planet'], undefined, { context: {} }),
])

expect(transport.send).toHaveBeenCalledTimes(2)
})
})

it('does not dedupe QUERY requests with different bodies', async () => {
const codec = makeCodec()
const transport = makeTransport()
Expand Down
30 changes: 27 additions & 3 deletions packages/client/src/plugins/dedupe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ export interface DedupeLinkPluginOptions<T extends ClientContext> {
*/
scope?: ((options: StandardLinkTransportInterceptorOptions<T>) => unknown) | undefined

/**
* Lowercase names of headers left out of the deduplication key.
* The shared request carries the first request's values.
*
* @default ['traceparent', 'tracestate']
*/
ignoredHeaders?: readonly string[] | undefined

/**
* How long (in ms) to wait for more identical requests before sending,
* counted from the first queued request.
Expand Down Expand Up @@ -95,6 +103,7 @@ export class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPl
private readonly groups: DedupeLinkPluginOptions<T>['groups']
private readonly filter: Exclude<DedupeLinkPluginOptions<T>['filter'], undefined>
private readonly scope: Exclude<DedupeLinkPluginOptions<T>['scope'], undefined>
private readonly ignoredHeaders: Exclude<DedupeLinkPluginOptions<T>['ignoredHeaders'], undefined>
private readonly wait: Exclude<DedupeLinkPluginOptions<T>['wait'], undefined>

private readonly queue: Map<
Expand All @@ -107,6 +116,7 @@ export class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPl
this.filter =
options.filter ?? (({ request }) => request.method === 'GET' || request.method === 'QUERY')
this.scope = options.scope ?? (() => undefined)
this.ignoredHeaders = options.ignoredHeaders ?? ['traceparent', 'tracestate']
this.wait = options.wait ?? 0
}

Expand Down Expand Up @@ -167,7 +177,11 @@ export class DedupeLinkPlugin<T extends ClientContext> implements StandardLinkPl
groups.set(group, queue)
}

const requestKey = createRequestKey(caller.options.path, caller.options.request)
const requestKey = createRequestKey(
caller.options.path,
caller.options.request,
this.ignoredHeaders,
)
const matched = queue.get(requestKey)

if (matched) {
Expand Down Expand Up @@ -270,11 +284,21 @@ function canDedupeRequest(request: StandardRequest): boolean {
)
}

function createRequestKey(path: string[], request: StandardRequest): string {
function createRequestKey(
path: string[],
request: StandardRequest,
ignoredHeaders: readonly string[],
): string {
const headers = { ...request.headers }

for (const name of ignoredHeaders) {
delete headers[name]
}

return stringifyJSON({
path,
body: request.body,
headers: request.headers,
headers,
method: request.method,
url: request.url,
} satisfies Omit<StandardRequest, 'signal'> & { path: string[] })
Expand Down
Loading