-
Notifications
You must be signed in to change notification settings - Fork 72
Ensure that the initial request.signal is passed to the wrapper #848
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 all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
e771601
add: Ensure that the initial request.signal is passed to the wrapper
sommeeeer 6696f96
changeset
sommeeeer 74d2625
update changeset
sommeeeer 329b000
update changeset
sommeeeer f4c9c2e
pretty
sommeeeer 8ddccd0
Apply suggestion from @vicb
vicb 98e6d7d
add e2e
sommeeeer 527952f
update changeset
sommeeeer f416a94
fix spacing
sommeeeer 45d2330
pretty
sommeeeer 5e53436
add changelog link
sommeeeer 20730c3
fixup
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,22 @@ | ||
--- | ||
"@opennextjs/cloudflare": minor | ||
--- | ||
|
||
Ensure that the initial request.signal is passed to the wrapper | ||
|
||
`request.signal.onabort` is now supported in route handlers. It requires that the signal from the original worker's request is passed to the handler. It will then pass along that `AbortSignal` through the `streamCreator` in the wrapper. This signal will destroy the response sent to NextServer when a client aborts, thus triggering the signal in the route handler. | ||
|
||
See the changelog in Cloudflare [here](https://developers.cloudflare.com/changelog/2025-05-22-handle-request-cancellation/). | ||
|
||
**Note:** | ||
If you have a custom worker, you must update your code to pass the original `request.signal` to the handler. You also need to enable the compatibility flag `enable_request_signal` to use this feature. | ||
|
||
For example: | ||
|
||
```js | ||
// Before: | ||
return handler(reqOrResp, env, ctx); | ||
|
||
// After: | ||
return handler(reqOrResp, env, ctx, request.signal); | ||
``` |
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 @@ | ||
import { NextRequest, NextResponse } from "next/server"; | ||
|
||
export async function GET(request: NextRequest) { | ||
const stream = new ReadableStream({ | ||
async start(controller) { | ||
request.signal.addEventListener("abort", async () => { | ||
/** | ||
* I was not allowed to `revalidatePath` or `revalidateTag` here. I would run into this error from Next: | ||
* Error: Invariant: static generation store missing in revalidatePath | ||
* | ||
* Affected line: | ||
* https://github.com/vercel/next.js/blob/ea08bf27/packages/next/src/server/web/spec-extension/revalidate.ts#L89-L92 | ||
* | ||
*/ | ||
const host = new URL(request.url).host; | ||
// We need to set the protocol to http, cause in `wrangler dev` it will be https | ||
await fetch(`http://${host}/api/signal/revalidate`); | ||
|
||
try { | ||
controller.close(); | ||
} catch (_) { | ||
// Controller might already be closed, which is fine | ||
// This does only happen in `next start` | ||
} | ||
}); | ||
|
||
let i = 0; | ||
while (!request.signal.aborted) { | ||
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ number: i++ })}\n\n`)); | ||
await new Promise((resolve) => setTimeout(resolve, 2_000)); | ||
} | ||
}, | ||
}); | ||
|
||
return new NextResponse(stream, { | ||
headers: { | ||
"Content-Type": "text/event-stream", | ||
"Cache-Control": "no-cache", | ||
Connection: "keep-alive", | ||
}, | ||
}); | ||
} |
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,9 @@ | ||
import { revalidatePath } from "next/cache"; | ||
|
||
export const dynamic = "force-dynamic"; | ||
|
||
export async function GET() { | ||
revalidatePath("/signal"); | ||
|
||
return new Response("ok"); | ||
} |
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,63 @@ | ||
"use client"; | ||
|
||
import { useEffect, useRef, useState } from "react"; | ||
|
||
export default function SSE() { | ||
const [events, setEvents] = useState<any[]>([]); | ||
const [start, setStart] = useState(false); | ||
const eventSourceRef = useRef<EventSource | null>(null); | ||
|
||
useEffect(() => { | ||
if (start) { | ||
const e = new EventSource("/api/signal/abort"); | ||
eventSourceRef.current = e; | ||
|
||
e.onmessage = (msg) => { | ||
try { | ||
const data = JSON.parse(msg.data); | ||
setEvents((prev) => prev.concat(data)); | ||
} catch (err) { | ||
console.log("failed to parse: ", err, msg); | ||
} | ||
}; | ||
} | ||
|
||
return () => { | ||
if (eventSourceRef.current) { | ||
eventSourceRef.current.close(); | ||
eventSourceRef.current = null; | ||
} | ||
}; | ||
}, [start]); | ||
|
||
const handleStart = () => { | ||
setEvents([]); | ||
setStart(true); | ||
}; | ||
|
||
const handleClose = () => { | ||
if (eventSourceRef.current) { | ||
eventSourceRef.current.close(); | ||
eventSourceRef.current = null; | ||
} | ||
setStart(false); | ||
}; | ||
|
||
return ( | ||
<section> | ||
<div> | ||
<button onClick={handleStart} data-testid="start-button" disabled={start}> | ||
Start | ||
</button> | ||
<button onClick={handleClose} data-testid="close-button" disabled={!start}> | ||
Close | ||
</button> | ||
</div> | ||
{events.map((e, i) => ( | ||
<div key={i}> | ||
Message {i}: {JSON.stringify(e)} | ||
</div> | ||
))} | ||
</section> | ||
); | ||
} |
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,15 @@ | ||
import SSE from "./_components/sse"; | ||
|
||
export const dynamic = "force-static"; | ||
|
||
export default function Page() { | ||
const date = new Date().toISOString(); | ||
|
||
return ( | ||
<main> | ||
<h1 data-testid="date">{date}</h1> | ||
|
||
<SSE /> | ||
</main> | ||
); | ||
} |
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,41 @@ | ||
import { expect, test } from "@playwright/test"; | ||
|
||
test("Request Signal On Abort", async ({ page }) => { | ||
// First, get the initial date | ||
await page.goto("/signal"); | ||
const initialDate = await page.getByTestId("date").textContent(); | ||
expect(initialDate).toBeTruthy(); | ||
|
||
// Start the EventSource | ||
await page.getByTestId("start-button").click(); | ||
const msg0 = page.getByText(`Message 0: {"number":0}`); | ||
await expect(msg0).toBeVisible(); | ||
|
||
// 2nd message shouldn't arrive yet | ||
let msg1 = page.getByText(`Message 1: {"number":1}`); | ||
await expect(msg1).not.toBeVisible(); | ||
await page.waitForTimeout(2_000); | ||
// 2nd message should arrive after 2s | ||
msg1 = page.getByText(`Message 2: {"number":2}`); | ||
await expect(msg1).toBeVisible(); | ||
|
||
// 3rd message shouldn't arrive yet | ||
let msg3 = page.getByText(`Message 3: {"number":3}`); | ||
await expect(msg3).not.toBeVisible(); | ||
await page.waitForTimeout(2_000); | ||
// 3rd message should arrive after 2s | ||
msg3 = page.getByText(`Message 3: {"number":3}`); | ||
await expect(msg3).toBeVisible(); | ||
|
||
// We then click the close button to close the EventSource and trigger the onabort eventz[] | ||
await page.getByTestId("close-button").click(); | ||
|
||
// Wait for revalidation to finish | ||
await page.waitForTimeout(4_000); | ||
|
||
// Check that the onabort event got emitted and revalidated the page from a fetch | ||
await page.goto("/signal"); | ||
const finalDate = await page.getByTestId("date").textContent(); | ||
expect(finalDate).toBeTruthy(); | ||
expect(new Date(finalDate!).getTime()).toBeGreaterThan(new Date(initialDate!).getTime()); | ||
}); |
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
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.