-
Notifications
You must be signed in to change notification settings - Fork 217
fix: Cloudflare streaming response backpressure #1186
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
Open
Cooperrr
wants to merge
8
commits into
opennextjs:main
Choose a base branch
from
Cooperrr:cloudflare-streaming-response-backpressure
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d2a3438
apply backpressure
Cooperrr beecf15
avoid tee copy of response when not required
Cooperrr 63f6a8c
add tests
Cooperrr 0f7dfd9
add changeset
Cooperrr a5188ac
fix node compatability issue on node < 20
Cooperrr 3cdee23
remove timing flakiness from added tests
Cooperrr fc546c2
preserve routed response body while applying stream backpressure
Cooperrr 961a03b
additional comments for clarity
Cooperrr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@opennextjs/aws": patch | ||
| --- | ||
|
|
||
| Bound Cloudflare Node response streaming with backpressure. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| import { Writable } from "node:stream"; | ||
| import { ReadableStream } from "node:stream/web"; | ||
|
|
||
| import { openNextHandler } from "@opennextjs/aws/core/requestHandler.js"; | ||
| import routingHandler from "@opennextjs/aws/core/routingHandler.js"; | ||
| import type { | ||
| InternalEvent, | ||
| InternalResult, | ||
| StreamCreator, | ||
| } from "@opennextjs/aws/types/open-next.js"; | ||
| import { beforeEach, vi } from "vitest"; | ||
|
|
||
| vi.mock("@opennextjs/aws/adapters/config/index.js", () => ({ | ||
| BuildId: "build-id", | ||
| HtmlPages: [], | ||
| NextConfig: {}, | ||
| })); | ||
|
|
||
| vi.mock("@opennextjs/aws/core/routingHandler.js", () => ({ | ||
| default: vi.fn(), | ||
| INTERNAL_EVENT_REQUEST_ID: "x-opennext-request-id", | ||
| INTERNAL_HEADER_INITIAL_URL: "x-opennext-initial-url", | ||
| INTERNAL_HEADER_RESOLVED_ROUTES: "x-opennext-resolved-routes", | ||
| INTERNAL_HEADER_REWRITE_STATUS_CODE: "x-opennext-rewrite-status-code", | ||
| MIDDLEWARE_HEADER_PREFIX: "x-middleware-response-", | ||
| MIDDLEWARE_HEADER_PREFIX_LEN: "x-middleware-response-".length, | ||
| })); | ||
|
|
||
| vi.mock("@opennextjs/aws/core/util.js", () => ({ | ||
| requestHandler: vi.fn(), | ||
| setNextjsPrebundledReact: vi.fn(), | ||
| })); | ||
|
|
||
| const mockedRoutingHandler = vi.mocked(routingHandler); | ||
| const event: InternalEvent = { | ||
| type: "core", | ||
| method: "GET", | ||
| rawPath: "/", | ||
| url: "https://example.com/", | ||
| body: Buffer.alloc(0), | ||
| headers: {}, | ||
| query: {}, | ||
| cookies: {}, | ||
| remoteAddress: "::1", | ||
| }; | ||
|
|
||
| function nextTurn() { | ||
| return new Promise<void>((resolve) => setImmediate(resolve)); | ||
| } | ||
|
|
||
| async function waitFor(predicate: () => boolean) { | ||
| for (let attempt = 0; attempt < 100; attempt++) { | ||
| if (predicate()) { | ||
| return; | ||
| } | ||
| await nextTurn(); | ||
| } | ||
| throw new Error("Timed out waiting for condition"); | ||
| } | ||
|
|
||
| function createBody(total: number) { | ||
| let produced = 0; | ||
| const body = new ReadableStream<Uint8Array>({ | ||
| pull(controller) { | ||
| if (produced >= total) { | ||
| controller.close(); | ||
| return; | ||
| } | ||
| const chunk = new Uint8Array(64 * 1024); | ||
| chunk[0] = produced++; | ||
| controller.enqueue(chunk); | ||
| }, | ||
| }); | ||
|
|
||
| return { | ||
| body, | ||
| get produced() { | ||
| return produced; | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| function createResult(body: ReadableStream<Uint8Array>): InternalResult { | ||
| return { | ||
| type: "core", | ||
| statusCode: 200, | ||
| headers: {}, | ||
| body, | ||
| isBase64Encoded: false, | ||
| }; | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| globalThis.openNextConfig = {}; | ||
| globalThis.__next_route_preloader = vi.fn(async () => {}); | ||
| }); | ||
|
|
||
| describe("requestHandler streaming", () => { | ||
| it("retains a tee branch and remains bounded when chunks do not need retaining", async () => { | ||
| const source = createBody(20); | ||
| const tee = vi.spyOn(source.body, "tee"); | ||
| const result = createResult(source.body); | ||
| mockedRoutingHandler.mockResolvedValue(result); | ||
|
|
||
| const writeCallbacks: Array<() => void> = []; | ||
| const received: number[] = []; | ||
| const streamCreator: StreamCreator = { | ||
| retainChunks: false, | ||
| writeHeaders: () => | ||
| new Writable({ | ||
| highWaterMark: 1, | ||
| write(chunk: Buffer, _encoding, callback) { | ||
| received.push(chunk[0]); | ||
| writeCallbacks.push(callback); | ||
| }, | ||
| }), | ||
| }; | ||
|
|
||
| const handlerPromise = openNextHandler(event, { streamCreator }); | ||
| await waitFor(() => writeCallbacks.length > 0); | ||
| await nextTurn(); | ||
| const producedWhileStalled = source.produced; | ||
| for (let i = 0; i < 25; i++) { | ||
| await nextTurn(); | ||
| } | ||
|
|
||
| expect(source.produced).toBe(producedWhileStalled); | ||
| expect(source.produced).toBeLessThan(20); | ||
| expect(tee).toHaveBeenCalledOnce(); | ||
|
|
||
| while (received.length < 20) { | ||
| await waitFor(() => writeCallbacks.length > 0); | ||
| writeCallbacks.shift()!(); | ||
| } | ||
|
|
||
| const returned = await handlerPromise; | ||
| expect(returned).toBe(result); | ||
| expect(received).toEqual(Array.from({ length: 20 }, (_, index) => index)); | ||
| expect(returned.body).not.toBe(source.body); | ||
| expect((await new Response(returned.body).arrayBuffer()).byteLength).toBe( | ||
| 20 * 64 * 1024, | ||
| ); | ||
| expect(source.body.locked).toBe(true); | ||
| }); | ||
|
|
||
| it("retains a tee branch by default", async () => { | ||
| const source = createBody(3); | ||
| const tee = vi.spyOn(source.body, "tee"); | ||
| const result = createResult(source.body); | ||
| mockedRoutingHandler.mockResolvedValue(result); | ||
|
|
||
| const streamed: Buffer[] = []; | ||
| const streamCreator: StreamCreator = { | ||
| writeHeaders: () => | ||
| new Writable({ | ||
| write(chunk, _encoding, callback) { | ||
| streamed.push(chunk); | ||
| callback(); | ||
| }, | ||
| }), | ||
| }; | ||
|
|
||
| const returned = await openNextHandler(event, { streamCreator }); | ||
|
|
||
| expect(tee).toHaveBeenCalledOnce(); | ||
| expect(returned.body).not.toBe(source.body); | ||
| expect(Buffer.concat(streamed).length).toBe(3 * 64 * 1024); | ||
| expect((await new Response(returned.body).arrayBuffer()).byteLength).toBe( | ||
| 3 * 64 * 1024, | ||
| ); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Add more comment on your change please, this is quite hard to review and follow what's going on
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.
I've tried to better explain what's going on with 961a03b