Repository navigation
feat: add custom fetch option to newHttpBatchRpcSession #285
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 = <any>(() => { throw new Error("global fetch should not be called"); }); | ||
| try { | ||
| let cap = newHttpBatchRpcSession<TestTarget>(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 = <any>((input: any, init?: RequestInit) => { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. swapping |
||
| ++calls; | ||
| return originalFetch(input, init); | ||
| }); | ||
| try { | ||
| let cap = newHttpBatchRpcSession<TestTarget>(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); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
fetch?: (input: string | Request, init?: RequestInit) => Promise<Response> |
||
| }; | ||
|
|
||
| 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; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. called unbound, so |
||
| let response = await fetchFunc(urlOrRequest, { | ||
| method: "POST", | ||
| body: batch.join("\n"), | ||
| }); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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:<T extends RpcCompatible<T> = Empty> | |
| * The parameters to this method have exactly the same signature as `fetch()`, but the return | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit, pre-existing: this still says "exactly the same signature as |
||
| * 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:<T extends RpcCompatible<T>> | ||
| (urlOrRequest: string | Request, options?: RpcSessionOptions) => RpcStub<T> = | ||
| (urlOrRequest: string | Request, options?: HttpBatchRpcSessionOptions) => RpcStub<T> = | ||
| <any>newHttpBatchRpcSessionImpl; | ||
|
|
||
| /** | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
these only wrap global
fetch, the binding path isnt covered.workerd.test.tsalready hasenv.testServer(~L461) so a test there would be cheap