From 9a5dd40f52327267465f03f8a301755d3134efbf Mon Sep 17 00:00:00 2001 From: Harsh Bhanushali Date: Tue, 20 Oct 2026 12:46:40 +0000 Subject: [PATCH 1/2] feat: add custom fetch option to newHttpBatchRpcSession Lets callers pass a fetch function in the options, used instead of the global fetch to send the batch (e.g. a VPC or service binding). --- .changeset/http-batch-custom-fetch.md | 7 ++++ __tests__/index.test.ts | 42 +++++++++++++++++++ .../content/docs/transports/http-batch.mdx | 12 ++++++ src/batch.ts | 17 +++++++- src/index.ts | 10 +++-- 5 files changed, 83 insertions(+), 5 deletions(-) create mode 100644 .changeset/http-batch-custom-fetch.md diff --git a/.changeset/http-batch-custom-fetch.md b/.changeset/http-batch-custom-fetch.md new file mode 100644 index 00000000..bdb5ab53 --- /dev/null +++ b/.changeset/http-batch-custom-fetch.md @@ -0,0 +1,7 @@ +--- +"capnweb": minor +--- + +`newHttpBatchRpcSession()` now accepts an optional `fetch` function in its options, used instead +of the global `fetch()` to send the batch. This makes it possible to send batches through a VPC or +service binding without overriding `globalThis.fetch`. diff --git a/__tests__/index.test.ts b/__tests__/index.test.ts index 8e358c4f..98dc0ca5 100644 --- a/__tests__/index.test.ts +++ b/__tests__/index.test.ts @@ -3316,6 +3316,48 @@ describe("HTTP requests", () => { .toStrictEqual([36, 5, 9]); }); + it("sends the batch using a custom fetch function from options", async () => { + let url = `http://${inject("testServerHost")}`; + let calls: { input: string | Request, init?: RequestInit }[] = []; + let originalFetch = globalThis.fetch; + let customFetch: typeof fetch = (input: any, init?: RequestInit) => { + calls.push({ input, init }); + return originalFetch(input, init); + }; + + // Make sure the global fetch is NOT used when a custom one is provided. + globalThis.fetch = (() => { throw new Error("global fetch should not be called"); }); + try { + let cap = newHttpBatchRpcSession(url, { fetch: customFetch }); + let promise1 = cap.square(6); + let promise2 = cap.square(7); + expect(await Promise.all([promise1, promise2])).toStrictEqual([36, 49]); + } finally { + globalThis.fetch = originalFetch; + } + + expect(calls.length).toBe(1); + expect(calls[0].input).toBe(url); + expect(calls[0].init?.method).toBe("POST"); + }); + + it("uses the global fetch when no custom fetch is given", async () => { + let url = `http://${inject("testServerHost")}`; + let originalFetch = globalThis.fetch; + let calls = 0; + globalThis.fetch = ((input: any, init?: RequestInit) => { + ++calls; + return originalFetch(input, init); + }); + try { + let cap = newHttpBatchRpcSession(url); + expect(await cap.square(5)).toBe(25); + } finally { + globalThis.fetch = originalFetch; + } + expect(calls).toBe(1); + }); + it("rejects non-POST requests with 405", async () => { let response = await fetch(`http://${inject("testServerHost")}`, { method: "GET" }); expect(response.status).toBe(405); diff --git a/packages/docs/src/content/docs/transports/http-batch.mdx b/packages/docs/src/content/docs/transports/http-batch.mdx index 73c056d2..837fdcf1 100644 --- a/packages/docs/src/content/docs/transports/http-batch.mdx +++ b/packages/docs/src/content/docs/transports/http-batch.mdx @@ -62,6 +62,18 @@ console.log(greeting2); console.log(greeting3); ``` +### Custom `fetch` + +By default the batch is sent with the global `fetch()`. To use a different function, such as a +VPC or service binding on Cloudflare Workers, pass it as the `fetch` option. It must have the same +signature as `fetch()`: + +```ts +using stub = newHttpBatchRpcSession('https://example.com/api', { + fetch: (input, init) => env.VPC.fetch(input, init), +}); +``` + ## When the batch is sent The batch is dispatched on the next I/O tick. Everything you queue synchronously ends up in the same diff --git a/src/batch.ts b/src/batch.ts index 1a8b3ddb..8415ea4e 100644 --- a/src/batch.ts +++ b/src/batch.ts @@ -73,10 +73,23 @@ class BatchClientTransport implements RpcTransport { } } +export type HttpBatchRpcSessionOptions = RpcSessionOptions & { + /** + * Function used to send the batch request. Must have the same signature as the global `fetch()`. + * Defaults to the global `fetch`. Useful for runtimes where requests must go through a special + * fetch function, such as a VPC or service binding (pass e.g. + * `(input, init) => env.VPC.fetch(input, init)`), or for instrumenting requests. + */ + fetch?: typeof fetch; +}; + export function newHttpBatchRpcSession( - urlOrRequest: string | Request, options?: RpcSessionOptions): RpcStub { + urlOrRequest: string | Request, options?: HttpBatchRpcSessionOptions): RpcStub { let sendBatch: SendBatchFunc = async (batch: string[]) => { - let response = await fetch(urlOrRequest, { + // Look up the global `fetch` at send time (not at session creation) so that it behaves as it + // did before this option existed. + let fetchFunc = options?.fetch ?? fetch; + let response = await fetchFunc(urlOrRequest, { method: "POST", body: batch.join("\n"), }); diff --git a/src/index.ts b/src/index.ts index 0a45747c..0dfd73da 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,7 +11,8 @@ import { RpcTargetBranded, RpcCompatible, Stub, ElideStub, PayloadOrStub, import { newWebSocketRpcSession as newWebSocketRpcSessionImpl, newWorkersWebSocketRpcResponse, WebSocketTransport } from "./websocket.js"; import { newHttpBatchRpcSession as newHttpBatchRpcSessionImpl, - newHttpBatchRpcResponse, nodeHttpBatchRpcResponse } from "./batch.js"; + newHttpBatchRpcResponse, nodeHttpBatchRpcResponse, + type HttpBatchRpcSessionOptions } from "./batch.js"; import { newMessagePortRpcSession as newMessagePortRpcSessionImpl } from "./messageport.js"; import { forceInitMap } from "./map.js"; import { forceInitStreams } from "./streams.js"; @@ -23,7 +24,7 @@ forceInitStreams(); export { serialize, deserialize, newWorkersWebSocketRpcResponse, newHttpBatchRpcResponse, nodeHttpBatchRpcResponse, WebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH }; export type { RpcTransport, RpcTransportWithCustomEncoding, AnyRpcTransport, - RpcSessionOptions, RpcCompatible, EncodingLevel, RpcLimits }; + RpcSessionOptions, HttpBatchRpcSessionOptions, RpcCompatible, EncodingLevel, RpcLimits }; // Hack the type system to make RpcStub's types work nicely! /** @@ -142,9 +143,12 @@ export let newWebSocketRpcSession: = Empty> * The parameters to this method have exactly the same signature as `fetch()`, but the return * value is an RpcStub. You can customize anything about the request except for the method * (it will always be set to POST) and the body (which the RPC system will fill in). + * + * To send the request with something other than the global `fetch()`, pass a `fetch` function in + * `options`. */ export let newHttpBatchRpcSession:> - (urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub = + (urlOrRequest: string | Request, options?: HttpBatchRpcSessionOptions) => RpcStub = newHttpBatchRpcSessionImpl; /** From e0310068fdc0253f7b09a32434edd474f02e5be6 Mon Sep 17 00:00:00 2001 From: Harsh Bhanushali Date: Fri, 27 Nov 2026 21:44:58 +0000 Subject: [PATCH 2/2] address review: type the fetch option as a plain function, cover bound-call and binding paths, docs nits --- __tests__/index.test.ts | 32 ++++++------------- __tests__/workerd.test.ts | 15 +++++++++ .../docs/src/content/docs/reference/api.mdx | 3 ++ .../content/docs/transports/http-batch.mdx | 4 +-- src/batch.ts | 10 +++--- src/index.ts | 7 ++-- 6 files changed, 40 insertions(+), 31 deletions(-) diff --git a/__tests__/index.test.ts b/__tests__/index.test.ts index 98dc0ca5..f4cda534 100644 --- a/__tests__/index.test.ts +++ b/__tests__/index.test.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license found in the LICENSE.txt file or at: // https://opensource.org/license/mit -import { expect, it, describe, inject } from "vitest" +import { expect, it, describe, inject, vi } from "vitest" import { deserialize, serialize, RpcSession, type RpcSessionOptions, RpcTransport, type RpcTransportWithCustomEncoding, RpcTarget, RpcStub, RpcPromise, newWebSocketRpcSession, newMessagePortRpcSession, @@ -3319,22 +3319,15 @@ describe("HTTP requests", () => { it("sends the batch using a custom fetch function from options", async () => { let url = `http://${inject("testServerHost")}`; let calls: { input: string | Request, init?: RequestInit }[] = []; - let originalFetch = globalThis.fetch; - let customFetch: typeof fetch = (input: any, init?: RequestInit) => { + let customFetch = (input: string | Request, init?: RequestInit) => { calls.push({ input, init }); - return originalFetch(input, init); + return fetch(input, init); }; - // Make sure the global fetch is NOT used when a custom one is provided. - globalThis.fetch = (() => { throw new Error("global fetch should not be called"); }); - try { - let cap = newHttpBatchRpcSession(url, { fetch: customFetch }); - let promise1 = cap.square(6); - let promise2 = cap.square(7); - expect(await Promise.all([promise1, promise2])).toStrictEqual([36, 49]); - } finally { - globalThis.fetch = originalFetch; - } + let cap = newHttpBatchRpcSession(url, { fetch: customFetch }); + let promise1 = cap.square(6); + let promise2 = cap.square(7); + expect(await Promise.all([promise1, promise2])).toStrictEqual([36, 49]); expect(calls.length).toBe(1); expect(calls[0].input).toBe(url); @@ -3343,19 +3336,14 @@ describe("HTTP requests", () => { it("uses the global fetch when no custom fetch is given", async () => { let url = `http://${inject("testServerHost")}`; - let originalFetch = globalThis.fetch; - let calls = 0; - globalThis.fetch = ((input: any, init?: RequestInit) => { - ++calls; - return originalFetch(input, init); - }); + let spy = vi.spyOn(globalThis, "fetch"); try { let cap = newHttpBatchRpcSession(url); expect(await cap.square(5)).toBe(25); + expect(spy.mock.calls.filter(c => c[0] === url).length).toBe(1); } finally { - globalThis.fetch = originalFetch; + spy.mockRestore(); } - expect(calls).toBe(1); }); it("rejects non-POST requests with 405", async () => { diff --git a/__tests__/workerd.test.ts b/__tests__/workerd.test.ts index 68b77380..c7d59606 100644 --- a/__tests__/workerd.test.ts +++ b/__tests__/workerd.test.ts @@ -471,4 +471,19 @@ describe("workerd RPC server", () => { expect(await Promise.all([promise1, promise2, promise3])) .toStrictEqual([36, 5, 9]); }) + + it("can send an HTTP batch through a custom fetch function", async () => { + let calls = 0; + let cap = newHttpBatchRpcSession("http://foo", { + fetch: (input, init) => { + ++calls; + return (env).testServer.fetch(input, init); + }, + }); + + let promise1 = cap.square(6); + let promise2 = cap.square(7); + expect(await Promise.all([promise1, promise2])).toStrictEqual([36, 49]); + expect(calls).toBe(1); + }) }); diff --git a/packages/docs/src/content/docs/reference/api.mdx b/packages/docs/src/content/docs/reference/api.mdx index 5153ac5b..2c6cc377 100644 --- a/packages/docs/src/content/docs/reference/api.mdx +++ b/packages/docs/src/content/docs/reference/api.mdx @@ -86,6 +86,9 @@ interface RpcTransport { Passed as the last argument to the session and response helpers. Commonly used for response `headers` (e.g. CORS) on the HTTP batch helpers. +`newHttpBatchRpcSession()` also accepts a `fetch` option (`HttpBatchRpcSessionOptions`), used +instead of the global `fetch()` to send the batch. [Docs](/transports/http-batch/#custom-fetch) + ## Disposal at a glance | You have | You must | diff --git a/packages/docs/src/content/docs/transports/http-batch.mdx b/packages/docs/src/content/docs/transports/http-batch.mdx index 837fdcf1..022e2e37 100644 --- a/packages/docs/src/content/docs/transports/http-batch.mdx +++ b/packages/docs/src/content/docs/transports/http-batch.mdx @@ -65,8 +65,8 @@ console.log(greeting3); ### Custom `fetch` By default the batch is sent with the global `fetch()`. To use a different function, such as a -VPC or service binding on Cloudflare Workers, pass it as the `fetch` option. It must have the same -signature as `fetch()`: +VPC or service binding on Cloudflare Workers, pass it as the `fetch` option. It is called unbound, +so wrap a method that needs its receiver: ```ts using stub = newHttpBatchRpcSession('https://example.com/api', { diff --git a/src/batch.ts b/src/batch.ts index 8415ea4e..258a12ca 100644 --- a/src/batch.ts +++ b/src/batch.ts @@ -75,12 +75,14 @@ class BatchClientTransport implements RpcTransport { export type HttpBatchRpcSessionOptions = RpcSessionOptions & { /** - * Function used to send the batch request. Must have the same signature as the global `fetch()`. + * Function used to send the batch request, taking the same arguments as the global `fetch()`. * Defaults to the global `fetch`. Useful for runtimes where requests must go through a special - * fetch function, such as a VPC or service binding (pass e.g. - * `(input, init) => env.VPC.fetch(input, init)`), or for instrumenting requests. + * fetch function, such as a VPC or service binding, or for instrumenting requests. + * + * The function is called unbound, so wrap a method that needs its receiver, e.g. + * `(input, init) => env.VPC.fetch(input, init)` rather than `env.VPC.fetch`. */ - fetch?: typeof fetch; + fetch?: (input: string | Request, init?: RequestInit) => Promise; }; export function newHttpBatchRpcSession( diff --git a/src/index.ts b/src/index.ts index 0dfd73da..eeffff17 100644 --- a/src/index.ts +++ b/src/index.ts @@ -140,9 +140,10 @@ export let newWebSocketRpcSession: = Empty> /** * Initiate an HTTP batch session from the client side. * - * The parameters to this method have exactly the same signature as `fetch()`, but the return - * value is an RpcStub. You can customize anything about the request except for the method - * (it will always be set to POST) and the body (which the RPC system will fill in). + * The first parameter is the same as the first parameter of `fetch()` (a URL or a Request), but the + * return value is an RpcStub. You can customize anything about the request except for the method + * (it will always be set to POST) and the body (which the RPC system will fill in). The second + * parameter is session options, not `RequestInit`. * * To send the request with something other than the global `fetch()`, pass a `fetch` function in * `options`.