diff --git a/apps/content/docs/plugins/dedupe.mdx b/apps/content/docs/plugins/dedupe.mdx index 28ae014a0..c16889d2a 100644 --- a/apps/content/docs/plugins/dedupe.mdx +++ b/apps/content/docs/plugins/dedupe.mdx @@ -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. diff --git a/packages/client/src/plugins/dedupe.test.ts b/packages/client/src/plugins/dedupe.test.ts index c5bc4392b..0e830af4b 100644 --- a/packages/client/src/plugins/dedupe.test.ts +++ b/packages/client/src/plugins/dedupe.test.ts @@ -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' @@ -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).id}-01` + headers.tracestate = `vendor=${(span as ReturnType).id}` + + if (extraHeader) { + headers[extraHeader] = `${(span as ReturnType).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() diff --git a/packages/client/src/plugins/dedupe.ts b/packages/client/src/plugins/dedupe.ts index 929e05df6..d45b45683 100644 --- a/packages/client/src/plugins/dedupe.ts +++ b/packages/client/src/plugins/dedupe.ts @@ -68,6 +68,14 @@ export interface DedupeLinkPluginOptions { */ scope?: ((options: StandardLinkTransportInterceptorOptions) => 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. @@ -95,6 +103,7 @@ export class DedupeLinkPlugin implements StandardLinkPl private readonly groups: DedupeLinkPluginOptions['groups'] private readonly filter: Exclude['filter'], undefined> private readonly scope: Exclude['scope'], undefined> + private readonly ignoredHeaders: Exclude['ignoredHeaders'], undefined> private readonly wait: Exclude['wait'], undefined> private readonly queue: Map< @@ -107,6 +116,7 @@ export class DedupeLinkPlugin 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 } @@ -167,7 +177,11 @@ export class DedupeLinkPlugin 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) { @@ -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 & { path: string[] })