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..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, @@ -3316,6 +3316,36 @@ 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 customFetch = (input: string | Request, init?: RequestInit) => { + calls.push({ input, init }); + return fetch(input, init); + }; + + 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); + 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 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 { + spy.mockRestore(); + } + }); + 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/__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 73c056d2..022e2e37 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 is called unbound, +so wrap a method that needs its receiver: + +```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..258a12ca 100644 --- a/src/batch.ts +++ b/src/batch.ts @@ -73,10 +73,25 @@ class BatchClientTransport implements RpcTransport { } } +export type HttpBatchRpcSessionOptions = RpcSessionOptions & { + /** + * 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, 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?: (input: string | Request, init?: RequestInit) => Promise; +}; + 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..eeffff17 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! /** @@ -139,12 +140,16 @@ 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`. */ export let newHttpBatchRpcSession:> - (urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub = + (urlOrRequest: string | Request, options?: HttpBatchRpcSessionOptions) => RpcStub = newHttpBatchRpcSessionImpl; /**