Unverified Commit 3db90632 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[backport] [Cache Components] Prevent streaming fetch calls from hanging in dev (#89194)

Backports:

- #89171
parent a9686b34
...@@ -184,7 +184,8 @@ async function createCachedDynamicResponse( ...@@ -184,7 +184,8 @@ async function createCachedDynamicResponse(
serverComponentsHmrCache: ServerComponentsHmrCache | undefined, serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
revalidate: number, revalidate: number,
input: RequestInfo | URL, input: RequestInfo | URL,
handleUnlock: () => Promise<void> | void handleUnlock: () => Promise<void> | void,
signal: AbortSignal | null
): Promise<Response> { ): Promise<Response> {
// We're cloning the response using this utility because there exists a bug in // We're cloning the response using this utility because there exists a bug in
// the undici library around response cloning. See the following pull request // the undici library around response cloning. See the following pull request
...@@ -216,7 +217,12 @@ async function createCachedDynamicResponse( ...@@ -216,7 +217,12 @@ async function createCachedDynamicResponse(
) )
} }
}) })
.catch((error) => console.warn(`Failed to set fetch cache`, input, error)) .catch((error) => {
// Don't warn if the request was aborted intentionally.
if (!signal?.aborted) {
console.warn(`Failed to set fetch cache`, input, error)
}
})
.finally(handleUnlock) .finally(handleUnlock)
const pendingRevalidateKey = `cache-set-${cacheKey}` const pendingRevalidateKey = `cache-set-${cacheKey}`
...@@ -871,10 +877,15 @@ export function createPatchedFetcher( ...@@ -871,10 +877,15 @@ export function createPatchedFetcher(
if ( if (
process.env.NODE_ENV === 'development' && process.env.NODE_ENV === 'development' &&
workUnitStore.stagedRendering && workUnitStore.stagedRendering &&
workUnitStore.cacheSignal workUnitStore.cacheSignal &&
isCacheableRevalidate
) { ) {
// We're filling caches for a staged render, // We're filling caches for a staged render with an
// so we need to wait for the response to finish instead of streaming. // explicit cache config, so we need to wait for the
// response to finish instead of streaming. For HMR-only
// caching (no explicit revalidate), we fall through to
// createCachedDynamicResponse which handles streaming
// and abort gracefully.
return createCachedPrerenderResponse( return createCachedPrerenderResponse(
res, res,
cacheKey, cacheKey,
...@@ -900,7 +911,8 @@ export function createPatchedFetcher( ...@@ -900,7 +911,8 @@ export function createPatchedFetcher(
serverComponentsHmrCache, serverComponentsHmrCache,
normalizedRevalidate, normalizedRevalidate,
input, input,
handleUnlock handleUnlock,
getRequestMeta('signal')
) )
default: default:
workUnitStore satisfies never workUnitStore satisfies never
......
...@@ -87,7 +87,6 @@ ...@@ -87,7 +87,6 @@
"test/development/app-dir/segment-explorer/segment-explorer.test.ts", "test/development/app-dir/segment-explorer/segment-explorer.test.ts",
"test/development/app-dir/serialize-circular-error/serialize-circular-error.test.ts", "test/development/app-dir/serialize-circular-error/serialize-circular-error.test.ts",
"test/development/app-dir/serialize-circular-error/serialize-circular-error.test.ts", "test/development/app-dir/serialize-circular-error/serialize-circular-error.test.ts",
"test/development/app-dir/server-components-hmr-cache/server-components-hmr-cache.test.ts",
"test/development/app-dir/ssr-in-rsc/ssr-in-rsc.test.ts", "test/development/app-dir/ssr-in-rsc/ssr-in-rsc.test.ts",
"test/development/app-dir/ssr-only-error/ssr-only-error.test.ts", "test/development/app-dir/ssr-only-error/ssr-only-error.test.ts",
"test/development/app-hmr/hmr-env.test.ts", "test/development/app-hmr/hmr-env.test.ts",
......
...@@ -40,11 +40,10 @@ describe('react-performance-track', () => { ...@@ -40,11 +40,10 @@ describe('react-performance-track', () => {
{ {
// React might decide to display the shorthand in round brackets differently. // React might decide to display the shorthand in round brackets differently.
// Double check with React changes if a shorthand change is intended. // Double check with React changes if a shorthand change is intended.
// TODO: Should include short name "(…/random)" and URL name: '\u200bfetch (…/random)',
name: '\u200bfetch',
properties: expect.arrayContaining([ properties: expect.arrayContaining([
['status', '200'], ['status', '200'],
['url', '""'], ['url', '"https://next-data-api-endpoint.vercel.app/api/random"'],
]), ]),
}, },
]) ])
......
import { setTimeout } from 'timers/promises'
export async function GET() {
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
let i = 1
while (true) {
controller.enqueue(encoder.encode(`data: chunk-${i++}\n\n`))
await setTimeout(300)
}
},
})
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream' },
})
}
async function fetchChunk() {
const controller = new AbortController()
const response = await fetch(`http://localhost:${process.env.PORT}/api/sse`, {
signal: controller.signal,
})
const reader = response.body!.getReader()
const { value } = await reader.read()
controller.abort()
return new TextDecoder().decode(value)
}
export default async function Page() {
const chunk = await fetchChunk()
return <p>{chunk}</p>
}
import React from 'react' import { Suspense } from 'react'
export default function Root({ children }) { export default function Root({ children }) {
return ( return (
<html> <html>
<body>{children}</body> <body>
<Suspense>{children}</Suspense>
</body>
</html> </html>
) )
} }
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
describe('server-components-hmr-cache', () => { describe('server-components-hmr-cache', () => {
const { next } = nextTestSetup({ files: __dirname, patchFileDelay: 1000 }) const { next } = nextTestSetup({ files: __dirname, patchFileDelay: 1000 })
const loggedAfterValueRegexp = /After: (\d\.\d+)/ const loggedAfterValueRegexp = /After: (\d\.\d+)/
...@@ -17,7 +19,14 @@ describe('server-components-hmr-cache', () => { ...@@ -17,7 +19,14 @@ describe('server-components-hmr-cache', () => {
return match[1] return match[1]
} }
describe.each(['edge', 'node'])('%s runtime', (runtime) => { // Edge runtime is not supported with Cache Components.
const runtimes = isCacheComponentsEnabled ? ['node'] : ['edge', 'node']
beforeEach(() => {
cliOutputLength = next.cliOutput.length
})
describe.each(runtimes)('%s runtime', (runtime) => {
it('should use cached fetch calls for fast refresh requests', async () => { it('should use cached fetch calls for fast refresh requests', async () => {
const browser = await next.browser(`/${runtime}`) const browser = await next.browser(`/${runtime}`)
const valueBeforePatch = await browser.elementById('value').text() const valueBeforePatch = await browser.elementById('value').text()
...@@ -51,10 +60,6 @@ describe('server-components-hmr-cache', () => { ...@@ -51,10 +60,6 @@ describe('server-components-hmr-cache', () => {
}) })
describe('in after()', () => { describe('in after()', () => {
beforeEach(() => {
cliOutputLength = next.cliOutput.length
})
it('should use cached fetch calls for fast refresh requests', async () => { it('should use cached fetch calls for fast refresh requests', async () => {
const browser = await next.browser(`/${runtime}`) const browser = await next.browser(`/${runtime}`)
const valueBeforePatch = getLoggedAfterValue() const valueBeforePatch = getLoggedAfterValue()
...@@ -215,4 +220,16 @@ describe('server-components-hmr-cache', () => { ...@@ -215,4 +220,16 @@ describe('server-components-hmr-cache', () => {
}) })
}) })
}) })
it('should support reading from an infinite streaming fetch', async () => {
const browser = await next.browser('/infinite-stream')
const text = await browser.elementByCss('p').text()
expect(text).toBe('data: chunk-1')
// The fetch is aborted after reading the first chunk, which is intentional,
// so we shouldn't warn about failing to cache it.
expect(next.cliOutput.slice(cliOutputLength)).not.toContain(
'Failed to set fetch cache'
)
}, 10_000) // fail fast
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment