-
Notifications
You must be signed in to change notification settings - Fork 176
add e2e for streaming in pages-router #792
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8788ed7
add routehandler and api route
sommeeeer 02e6d04
add streaming to pages-router
sommeeeer a078d07
add e2e for both
sommeeeer cfe323e
fix e2e
sommeeeer 6e659b3
make typescript happy
sommeeeer ada149c
rm from app router
sommeeeer 9d1fad8
add comment
sommeeeer 68a0c5e
review fix
sommeeeer 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,42 @@ | ||
// https://developer.mozilla.org/docs/Web/API/ReadableStream#convert_async_iterator_to_stream | ||
function iteratorToStream(iterator: any) { | ||
return new ReadableStream({ | ||
async pull(controller) { | ||
const { value, done } = await iterator.next(); | ||
|
||
if (done) { | ||
controller.close(); | ||
} else { | ||
controller.enqueue(value); | ||
} | ||
}, | ||
}); | ||
} | ||
|
||
function sleep(time: number) { | ||
return new Promise((resolve) => { | ||
setTimeout(resolve, time); | ||
}); | ||
} | ||
|
||
const encoder = new TextEncoder(); | ||
|
||
async function* makeIterator() { | ||
for (let i = 1; i <= 10; i++) { | ||
yield encoder.encode(`<p data-testid="iteratorCount">${i}</p>`); | ||
await sleep(1000); | ||
} | ||
} | ||
|
||
export async function GET() { | ||
const iterator = makeIterator(); | ||
const stream = iteratorToStream(iterator); | ||
|
||
return new Response(stream, { | ||
headers: { | ||
"Content-Type": "text/html; charset=utf-8", | ||
Connection: "keep-alive", | ||
"Cache-Control": "no-cache, no-transform", | ||
}, | ||
}); | ||
} |
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,52 @@ | ||
import { Readable } from "node:stream"; | ||
import { ReadableStream } from "node:stream/web"; | ||
import type { NextApiRequest, NextApiResponse } from "next"; | ||
|
||
function iteratorToStream(iterator: AsyncIterator<Uint8Array>) { | ||
return new ReadableStream({ | ||
async pull(controller) { | ||
const { value, done } = await iterator.next(); | ||
|
||
if (done) { | ||
controller.close(); | ||
} else { | ||
controller.enqueue(value); | ||
} | ||
}, | ||
}); | ||
} | ||
|
||
function sleep(time: number) { | ||
return new Promise((resolve) => { | ||
setTimeout(resolve, time); | ||
}); | ||
} | ||
|
||
const encoder = new TextEncoder(); | ||
|
||
async function* makeIterator() { | ||
for (let i = 1; i <= 10; i++) { | ||
yield encoder.encode(`<p data-testid="iteratorCount">${i}</p>`); | ||
await sleep(1000); | ||
} | ||
} | ||
|
||
export default async function handler( | ||
req: NextApiRequest, | ||
res: NextApiResponse, | ||
) { | ||
if (req.method !== "GET") { | ||
return res.status(405).json({ message: "Method not allowed" }); | ||
} | ||
|
||
res.setHeader("Content-Type", "text/html; charset=utf-8"); | ||
sommeeeer marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
res.setHeader("Connection", "keep-alive"); | ||
res.setHeader("Cache-Control", "no-cache, no-transform"); | ||
|
||
// create and pipe the stream | ||
const iterator = makeIterator(); | ||
const stream = iteratorToStream(iterator); | ||
sommeeeer marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
// we need to import ReadableStream from `node:stream/web` to make TypeScript happy | ||
return Readable.fromWeb(stream).pipe(res); | ||
} |
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,54 @@ | ||
import { expect, test } from "@playwright/test"; | ||
|
||
test("streaming should work in route handler", async ({ page }) => { | ||
const ITERATOR_LENGTH = 10; | ||
|
||
const res = await page.goto("/streaming", { | ||
// we set waitUntil: "commit" to ensure that the response is streamed | ||
// without this option, the response would be buffered and sent all at once | ||
// we could also drop the `await` aswell, but then we can't see the headers first. | ||
waitUntil: "commit", | ||
}); | ||
|
||
expect(res?.headers()["content-type"]).toBe("text/html; charset=utf-8"); | ||
expect(res?.headers()["cache-control"]).toBe("no-cache, no-transform"); | ||
// AWS API Gateway remaps the connection header to `x-amzn-remapped-connection` | ||
expect(res?.headers()["x-amzn-remapped-connection"]).toBe("keep-alive"); | ||
|
||
// wait for first number to be present | ||
await page.getByTestId("iteratorCount").first().waitFor(); | ||
|
||
const seenNumbers: Array<{ number: string; time: number }> = []; | ||
const startTime = Date.now(); | ||
|
||
const initialParagraphs = await page.getByTestId("iteratorCount").count(); | ||
// fail if all paragraphs appear at once | ||
// this is a safeguard to ensure that the response is streamed and not buffered all at once | ||
expect(initialParagraphs).toBe(1); | ||
|
||
while ( | ||
seenNumbers.length < ITERATOR_LENGTH && | ||
Date.now() - startTime < 11000 | ||
) { | ||
const elements = await page.getByTestId("iteratorCount").all(); | ||
if (elements.length > seenNumbers.length) { | ||
expect(elements.length).toBe(seenNumbers.length + 1); | ||
const newElement = elements[elements.length - 1]; | ||
seenNumbers.push({ | ||
number: await newElement.innerText(), | ||
time: Date.now() - startTime, | ||
}); | ||
} | ||
await page.waitForTimeout(100); | ||
} | ||
|
||
expect(seenNumbers.map((n) => n.number)).toEqual( | ||
[...Array(ITERATOR_LENGTH)].map((_, i) => String(i + 1)), | ||
); | ||
|
||
// verify streaming timing | ||
for (let i = 1; i < seenNumbers.length; i++) { | ||
const timeDiff = seenNumbers[i].time - seenNumbers[i - 1].time; | ||
expect(timeDiff).toBeGreaterThanOrEqual(100); | ||
} | ||
}); |
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,54 @@ | ||
import { expect, test } from "@playwright/test"; | ||
|
||
test("streaming should work in api route", async ({ page }) => { | ||
const ITERATOR_LENGTH = 10; | ||
|
||
const res = await page.goto("/api/streaming", { | ||
// we set waitUntil: "commit" to ensure that the response is streamed | ||
// without this option, the response would be buffered and sent all at once | ||
// we could also drop the `await` aswell, but then we can't see the headers first. | ||
waitUntil: "commit", | ||
}); | ||
|
||
expect(res?.headers()["content-type"]).toBe("text/html; charset=utf-8"); | ||
expect(res?.headers()["cache-control"]).toBe("no-cache, no-transform"); | ||
// AWS API Gateway remaps the connection header to `x-amzn-remapped-connection` | ||
expect(res?.headers()["x-amzn-remapped-connection"]).toBe("keep-alive"); | ||
sommeeeer marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
// wait for first number to be present | ||
await page.getByTestId("iteratorCount").first().waitFor(); | ||
|
||
const seenNumbers: Array<{ number: string; time: number }> = []; | ||
const startTime = Date.now(); | ||
|
||
const initialParagraphs = await page.getByTestId("iteratorCount").count(); | ||
// fail if all paragraphs appear at once | ||
// this is a safeguard to ensure that the response is streamed and not buffered all at once | ||
expect(initialParagraphs).toBe(1); | ||
|
||
while ( | ||
seenNumbers.length < ITERATOR_LENGTH && | ||
Date.now() - startTime < 11000 | ||
) { | ||
const elements = await page.getByTestId("iteratorCount").all(); | ||
if (elements.length > seenNumbers.length) { | ||
expect(elements.length).toBe(seenNumbers.length + 1); | ||
const newElement = elements[elements.length - 1]; | ||
seenNumbers.push({ | ||
number: await newElement.innerText(), | ||
time: Date.now() - startTime, | ||
}); | ||
} | ||
await page.waitForTimeout(100); | ||
} | ||
|
||
expect(seenNumbers.map((n) => n.number)).toEqual( | ||
[...Array(ITERATOR_LENGTH)].map((_, i) => String(i + 1)), | ||
); | ||
|
||
// verify streaming timing | ||
for (let i = 1; i < seenNumbers.length; i++) { | ||
const timeDiff = seenNumbers[i].time - seenNumbers[i - 1].time; | ||
expect(timeDiff).toBeGreaterThanOrEqual(100); | ||
} | ||
}); |
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.
Uh oh!
There was an error while loading. Please reload this page.