Repository navigation
fix: expose the buffered body as a readable request stream on non-node presets #58
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,87 @@ | ||
| import { Readable } from "node:stream"; | ||
|
|
||
| // Keep in sync with h3's `PayloadMethods` (PATCH, POST, PUT, DELETE) so that | ||
| // presets attach the body for every method `readRawBody`/`readBody` accepts. | ||
| const METHOD_WITH_BODY_RE = /post|put|patch|delete/i; | ||
|
|
||
| /** | ||
| * Whether a request's method can carry a body, matching the methods h3 reads | ||
| * the payload of. Misclassifying `DELETE` here made presets drop its body, so | ||
| * h3 fell back to reading the (stubbed) request stream. | ||
| */ | ||
| export function requestHasBody(request: globalThis.Request): boolean { | ||
| return METHOD_WITH_BODY_RE.test(request.method); | ||
| } | ||
|
|
||
| // `node-mock-http` (used by `localFetch` / `localCall`) builds a mock | ||
| // `IncomingMessage` whose readable side is a non-functional stub: it never | ||
| // emits `data`/`end`, reports `readableEnded = true` from the start and throws | ||
| // when iterated. When a buffered `body` is attached (by presets such as `bun` | ||
| // and `cloudflare`), expose it through a real `node:stream` Readable so that | ||
| // reading `event.node.req` as a stream behaves like it does on `node-server`. | ||
|
|
||
| // Request properties carried over from the mock to the readable request | ||
| const requestKeys = [ | ||
| "httpVersion", | ||
| "httpVersionMajor", | ||
| "httpVersionMinor", | ||
| "complete", | ||
| "aborted", | ||
| "method", | ||
| "url", | ||
| "headers", | ||
| "trailers", | ||
| "socket", | ||
| "connection", | ||
| "body", // keeps h3 `readRawBody` fast path working | ||
| "__unenv__", // platform context | ||
| ] as const; | ||
|
|
||
| // Minimal shape of the `node-mock-http` request, kept structural so this helper | ||
| // works for both its mock and the real `node:http` `IncomingMessage`. | ||
| type MockRequest = Record<string, any> & { | ||
| __unenv__?: unknown; | ||
| body?: unknown; | ||
| rawHeaders?: string[]; | ||
| }; | ||
|
|
||
| /** | ||
| * Replace the `node-mock-http` request with a real `node:stream` Readable when | ||
| * a buffered body is attached. Real requests (node presets, no `__unenv__` | ||
| * marker) and requests without a body are returned unchanged. | ||
| */ | ||
| export function normalizeNodeRequest<T extends object>(req: T): T { | ||
| const mockReq = req as MockRequest; | ||
| if (!("__unenv__" in mockReq)) { | ||
| return req; | ||
| } | ||
| const body = toNodeBuffer(mockReq.body); | ||
| if (!body || body.byteLength === 0) { | ||
|
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. Normalize attached zero-length buffers too. For
|
||
| return req; | ||
| } | ||
| const readable = new Readable({ | ||
| read() { | ||
| this.push(body); | ||
| this.push(null); | ||
| }, | ||
| }); | ||
| for (const key of requestKeys) { | ||
| (readable as any)[key] = mockReq[key]; | ||
| } | ||
|
Comment on lines
+68
to
+70
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. Keep For a nonempty buffered body, Forward those members to the original request. Keep the stream methods on the replacement. Suggested fix
|
||
| Object.defineProperty(readable, "rawHeaders", { | ||
| get: () => mockReq.rawHeaders, | ||
| }); | ||
| return readable as unknown as T; | ||
| } | ||
|
|
||
| function toNodeBuffer(body: unknown): Buffer | undefined { | ||
| if (typeof body === "string") { | ||
| return Buffer.from(body); | ||
| } | ||
| if (body instanceof ArrayBuffer) { | ||
| return Buffer.from(body); | ||
| } | ||
| if (ArrayBuffer.isView(body)) { | ||
| return Buffer.from(body.buffer, body.byteOffset, body.byteLength); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import { Readable } from "node:stream"; | ||
| import { describe, expect, it } from "vitest"; | ||
| import { type IncomingMessage, fetchNodeRequestHandler } from "node-mock-http"; | ||
| import { | ||
| normalizeNodeRequest, | ||
| requestHasBody, | ||
| } from "../../src/runtime/internal/node-request"; | ||
|
|
||
| // Reads the request as a Node.js readable stream, the same way raw body | ||
| // pass-through (`fetch(url, { body: event.node.req })`) and h3's `readRawBody` | ||
| // stream fallback do. | ||
| async function readStream(req: AsyncIterable<Buffer>): Promise<string> { | ||
| const chunks: Buffer[] = []; | ||
| for await (const chunk of req) { | ||
| chunks.push(chunk); | ||
| } | ||
| return Buffer.concat(chunks).toString("utf8"); | ||
| } | ||
|
|
||
| // Reproduces the request that `localFetch` builds on non-Node presets: | ||
| // `node-mock-http` wraps the buffered body in a mock `IncomingMessage` whose | ||
| // readable side is a stub. | ||
| async function createMockRequest( | ||
| init: { method?: string; body?: any; headers?: Record<string, string> } = {} | ||
| ): Promise<IncomingMessage> { | ||
| let request: IncomingMessage | undefined; | ||
| await fetchNodeRequestHandler( | ||
| async (req) => { | ||
| request = req; | ||
| }, | ||
| "/", | ||
| init | ||
| ); | ||
| return request!; | ||
| } | ||
|
|
||
| describe("normalizeNodeRequest", () => { | ||
| it("exposes the buffered body through a readable `event.node.req` stream", async () => { | ||
| const req = await createMockRequest({ | ||
| method: "POST", | ||
| body: "hello-from-mock", | ||
| headers: { "content-type": "text/plain" }, | ||
| }); | ||
| // The mock request is not a usable stream (this is what the bug reported). | ||
| await expect(readStream(req)).rejects.toThrow(/not implemented/); | ||
|
|
||
| const normalized = normalizeNodeRequest(req); | ||
| await expect(readStream(normalized)).resolves.toBe("hello-from-mock"); | ||
| }); | ||
|
|
||
| it("reports readableEnded as false and preserves request properties", async () => { | ||
| const req = await createMockRequest({ | ||
| method: "POST", | ||
| body: "hello", | ||
| headers: { "content-type": "text/plain" }, | ||
| }); | ||
| const normalized = normalizeNodeRequest(req); | ||
| expect(normalized.readableEnded).toBe(false); | ||
| // Body is kept so h3's `readRawBody` fast path keeps working. | ||
| expect((normalized as any).body).toBe("hello"); | ||
| expect(normalized.method).toBe("POST"); | ||
| expect(normalized.headers).toBe(req.headers); | ||
| expect(normalized.rawHeaders).toEqual(req.rawHeaders); | ||
| expect((normalized as any).__unenv__).toBe((req as any).__unenv__); | ||
| }); | ||
|
|
||
| it("returns the original request when there is no attached body", () => { | ||
| const req = Object.assign(Readable.from([]) as any, { | ||
| __unenv__: {}, | ||
| body: null, | ||
| headers: {}, | ||
| method: "DELETE", | ||
| }) as IncomingMessage; | ||
| expect(normalizeNodeRequest(req)).toBe(req); | ||
| }); | ||
|
|
||
| it("returns real (non-mock) requests unchanged", () => { | ||
| const req = Readable.from([Buffer.from("x")]) as unknown as IncomingMessage; | ||
| expect(normalizeNodeRequest(req)).toBe(req); | ||
| }); | ||
| }); | ||
|
|
||
| describe("requestHasBody", () => { | ||
| const makeRequest = (method: string) => | ||
| ({ method }) as unknown as globalThis.Request; | ||
|
|
||
| it.each(["POST", "PUT", "PATCH", "DELETE"])( | ||
| "reports %s requests as carrying a body", | ||
| (method) => { | ||
| expect(requestHasBody(makeRequest(method))).toBe(true); | ||
| } | ||
| ); | ||
|
|
||
| it.each(["GET", "HEAD", "OPTIONS"])( | ||
| "reports %s requests as not carrying a body", | ||
| (method) => { | ||
| expect(requestHasBody(makeRequest(method))).toBe(false); | ||
| } | ||
| ); | ||
| }); |
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.
The default
cloudflare-workerbuild cannot read the buffered request body.Without
nodejs_compat,node:streaminsrc/runtime/internal/node-request.tsresolves to unenv's_Readablefallback. Its constructor ignores thereadcallback, andpushdoes nothing. Async iteration throws. The newReadablecreated bynormalizeNodeRequesttherefore cannot yield a nonempty body on this path. The change swaps one unreadable stub for another. The PR's readable-body objective is not met for default Cloudflare builds. Make the shared request stream functional on nodeless targets. Either bundle an implementation that honorsreadand async iteration, or mapnode:streamto the native module on targets that provide it. The choice between these two options is a design decision.