Unverified Commit 0027c842 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: fixed dedupe response cloning (#73274)

Based on our testing, we've observed a bug with undici that presents as
the `Body has already been consumed` error while trying to call
`Response#clone()`. The problem was resolved using a custom cloning
implementation.

Rather than relying on the existing `Response#clone()`, we call
`ReadableStream#tee()` on the body and re-create the `Response` object.
This has the same underlying behaviour as `Response#clone()` (admittedly
with more steps), but explicitly manages the stream management correctly
during response cloning.
parent ab59e37a
/**
* Clones a response by teeing the body so we can return two independent
* ReadableStreams from it. This avoids the bug in the undici library around
* response cloning.
*
* After cloning, the original response's body will be consumed and closed.
*
* @see https://github.com/vercel/next.js/pull/73274
*
* @param original - The original response to clone.
* @returns A tuple containing two independent clones of the original response.
*/
export function cloneResponse(original: Response): [Response, Response] {
// If the response has no body, then we can just return the original response
// twice because it's immutable.
if (!original.body) {
return [original, original]
}
const [body1, body2] = original.body.tee()
const cloned1 = new Response(body1, {
status: original.status,
statusText: original.statusText,
headers: original.headers,
})
Object.defineProperty(cloned1, 'url', {
value: original.url,
})
const cloned2 = new Response(body2, {
status: original.status,
statusText: original.statusText,
headers: original.headers,
})
Object.defineProperty(cloned2, 'url', {
value: original.url,
})
return [cloned1, cloned2]
}
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
* Based on https://github.com/facebook/react/blob/d4e78c42a94be027b4dc7ed2659a5fddfbf9bd4e/packages/react/src/ReactFetch.js * Based on https://github.com/facebook/react/blob/d4e78c42a94be027b4dc7ed2659a5fddfbf9bd4e/packages/react/src/ReactFetch.js
*/ */
import * as React from 'react' import * as React from 'react'
import { cloneResponse } from './clone-response'
import { InvariantError } from '../../shared/lib/invariant-error'
const simpleCacheKey = '["GET",[],null,"follow",null,null,null,null]' // generateCacheKey(new Request('https://blank')); const simpleCacheKey = '["GET",[],null,"follow",null,null,null,null]' // generateCacheKey(new Request('https://blank'));
...@@ -24,14 +26,22 @@ function generateCacheKey(request: Request): string { ...@@ -24,14 +26,22 @@ function generateCacheKey(request: Request): string {
]) ])
} }
type CacheEntry = [
key: string,
promise: Promise<Response>,
response: Response | null,
]
export function createDedupeFetch(originalFetch: typeof fetch) { export function createDedupeFetch(originalFetch: typeof fetch) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- url is the cache key const getCacheEntries = React.cache(
const getCacheEntries = React.cache((url: string): Array<any> => []) // eslint-disable-next-line @typescript-eslint/no-unused-vars -- url is the cache key
(url: string): CacheEntry[] => []
)
return function dedupeFetch( return function dedupeFetch(
resource: URL | RequestInfo, resource: URL | RequestInfo,
options?: RequestInit options?: RequestInit
) { ): Promise<Response> {
if (options && options.signal) { if (options && options.signal) {
// If we're passed a signal, then we assume that // If we're passed a signal, then we assume that
// someone else controls the lifetime of this object and opts out of // someone else controls the lifetime of this object and opts out of
...@@ -60,7 +70,6 @@ export function createDedupeFetch(originalFetch: typeof fetch) { ...@@ -60,7 +70,6 @@ export function createDedupeFetch(originalFetch: typeof fetch) {
: resource : resource
if ( if (
(request.method !== 'GET' && request.method !== 'HEAD') || (request.method !== 'GET' && request.method !== 'HEAD') ||
// $FlowFixMe[prop-missing]: keepalive is real
request.keepalive request.keepalive
) { ) {
// We currently don't dedupe requests that might have side-effects. Those // We currently don't dedupe requests that might have side-effects. Those
...@@ -74,29 +83,38 @@ export function createDedupeFetch(originalFetch: typeof fetch) { ...@@ -74,29 +83,38 @@ export function createDedupeFetch(originalFetch: typeof fetch) {
} }
const cacheEntries = getCacheEntries(url) const cacheEntries = getCacheEntries(url)
let match for (let i = 0, j = cacheEntries.length; i < j; i += 1) {
if (cacheEntries.length === 0) { const [key, promise] = cacheEntries[i]
// We pass the original arguments here in case normalizing the Request if (key === cacheKey) {
// doesn't include all the options in this environment. return promise.then(() => {
match = originalFetch(resource, options) const response = cacheEntries[i][2]
cacheEntries.push(cacheKey, match) if (!response) throw new InvariantError('No cached response')
} else {
// We use an array as the inner data structure since it's lighter and // We're cloning the response using this utility because there exists
// we typically only expect to see one or two entries here. // a bug in the undici library around response cloning. See the
for (let i = 0, l = cacheEntries.length; i < l; i += 2) { // following pull request for more details:
const key = cacheEntries[i] // https://github.com/vercel/next.js/pull/73274
const value = cacheEntries[i + 1] const [cloned1, cloned2] = cloneResponse(response)
if (key === cacheKey) { cacheEntries[i][2] = cloned2
match = value return cloned1
// I would've preferred a labelled break but lint says no. })
return match.then((response: Response) => response.clone())
}
} }
match = originalFetch(resource, options)
cacheEntries.push(cacheKey, match)
} }
// We clone the response so that each time you call this you get a new read
// of the body so that it can be read multiple times. // We pass the original arguments here in case normalizing the Request
return match.then((response) => response.clone()) // doesn't include all the options in this environment.
const promise = originalFetch(resource, options)
const entry: CacheEntry = [cacheKey, promise, null]
cacheEntries.push(entry)
return promise.then((response) => {
// 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 for more details:
// https://github.com/vercel/next.js/pull/73274
const [cloned1, cloned2] = cloneResponse(response)
entry[2] = cloned2
return cloned1
})
} }
} }
...@@ -25,6 +25,7 @@ import { ...@@ -25,6 +25,7 @@ import {
type CachedFetchData, type CachedFetchData,
} from '../response-cache' } from '../response-cache'
import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler' import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'
import { cloneResponse } from './clone-response'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -676,20 +677,25 @@ export function createPatchedFetcher( ...@@ -676,20 +677,25 @@ export function createPatchedFetcher(
statusText: res.statusText, statusText: res.statusText,
}) })
} else { } else {
// 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 for more details:
// https://github.com/vercel/next.js/pull/73274
const [cloned1, cloned2] = cloneResponse(res)
// We are dynamically rendering including dev mode. We want to return // We are dynamically rendering including dev mode. We want to return
// the response to the caller as soon as possible because it might stream // the response to the caller as soon as possible because it might stream
// over a very long time. // over a very long time.
res cloned1
.clone()
.arrayBuffer() .arrayBuffer()
.then(async (arrayBuffer) => { .then(async (arrayBuffer) => {
const bodyBuffer = Buffer.from(arrayBuffer) const bodyBuffer = Buffer.from(arrayBuffer)
const fetchedData = { const fetchedData = {
headers: Object.fromEntries(res.headers.entries()), headers: Object.fromEntries(cloned1.headers.entries()),
body: bodyBuffer.toString('base64'), body: bodyBuffer.toString('base64'),
status: res.status, status: cloned1.status,
url: res.url, url: cloned1.url,
} }
requestStore?.serverComponentsHmrCache?.set( requestStore?.serverComponentsHmrCache?.set(
...@@ -720,7 +726,7 @@ export function createPatchedFetcher( ...@@ -720,7 +726,7 @@ export function createPatchedFetcher(
) )
.finally(handleUnlock) .finally(handleUnlock)
return res return cloned2
} }
} }
...@@ -788,14 +794,23 @@ export function createPatchedFetcher( ...@@ -788,14 +794,23 @@ export function createPatchedFetcher(
if (entry.isStale) { if (entry.isStale) {
workStore.pendingRevalidates ??= {} workStore.pendingRevalidates ??= {}
if (!workStore.pendingRevalidates[cacheKey]) { if (!workStore.pendingRevalidates[cacheKey]) {
workStore.pendingRevalidates[cacheKey] = doOriginalFetch( const pendingRevalidate = doOriginalFetch(true)
true .then(async (response) => ({
) body: await response.arrayBuffer(),
.catch(console.error) headers: response.headers,
status: response.status,
statusText: response.statusText,
}))
.finally(() => { .finally(() => {
workStore.pendingRevalidates ??= {} workStore.pendingRevalidates ??= {}
delete workStore.pendingRevalidates[cacheKey || ''] delete workStore.pendingRevalidates[cacheKey || '']
}) })
// Attach the empty catch here so we don't get a "unhandled
// promise rejection" warning.
pendingRevalidate.catch(console.error)
workStore.pendingRevalidates[cacheKey] = pendingRevalidate
} }
} }
...@@ -895,7 +910,7 @@ export function createPatchedFetcher( ...@@ -895,7 +910,7 @@ export function createPatchedFetcher(
if (cacheKey && isForegroundRevalidate) { if (cacheKey && isForegroundRevalidate) {
const pendingRevalidateKey = cacheKey const pendingRevalidateKey = cacheKey
workStore.pendingRevalidates ??= {} workStore.pendingRevalidates ??= {}
const pendingRevalidate = let pendingRevalidate =
workStore.pendingRevalidates[pendingRevalidateKey] workStore.pendingRevalidates[pendingRevalidateKey]
if (pendingRevalidate) { if (pendingRevalidate) {
...@@ -914,27 +929,27 @@ export function createPatchedFetcher( ...@@ -914,27 +929,27 @@ export function createPatchedFetcher(
// We used to just resolve the Response and clone it however for // We used to just resolve the Response and clone it however for
// static generation with dynamicIO we need the response to be able to // static generation with dynamicIO we need the response to be able to
// be resolved in a microtask and Response#clone() will never have a // be resolved in a microtask and cloning the response will never have
// body that can resolve in a microtask in node (as observed through // a body that can resolve in a microtask in node (as observed through
// experimentation) So instead we await the body and then when it is // experimentation) So instead we await the body and then when it is
// available we construct manually cloned Response objects with the // available we construct manually cloned Response objects with the
// body as an ArrayBuffer. This will be resolvable in a microtask // body as an ArrayBuffer. This will be resolvable in a microtask
// making it compatible with dynamicIO. // making it compatible with dynamicIO.
const pendingResponse = doOriginalFetch(true, cacheReasonOverride) const pendingResponse = doOriginalFetch(true, cacheReasonOverride)
// We're cloning the response using this utility because there
const nextRevalidate = pendingResponse // exists a bug in the undici library around response cloning.
.then(async (response) => { // See the following pull request for more details:
// Clone the response here. It'll run first because we attached // https://github.com/vercel/next.js/pull/73274
// the resolve before we returned below. We have to clone it .then(cloneResponse)
// because the original response is going to be consumed by
// at a later point in time. pendingRevalidate = pendingResponse
const clonedResponse = response.clone() .then(async (responses) => {
const response = responses[0]
return { return {
body: await clonedResponse.arrayBuffer(), body: await response.arrayBuffer(),
headers: clonedResponse.headers, headers: response.headers,
status: clonedResponse.status, status: response.status,
statusText: clonedResponse.statusText, statusText: response.statusText,
} }
}) })
.finally(() => { .finally(() => {
...@@ -949,11 +964,11 @@ export function createPatchedFetcher( ...@@ -949,11 +964,11 @@ export function createPatchedFetcher(
// Attach the empty catch here so we don't get a "unhandled promise // Attach the empty catch here so we don't get a "unhandled promise
// rejection" warning // rejection" warning
nextRevalidate.catch(() => {}) pendingRevalidate.catch(() => {})
workStore.pendingRevalidates[pendingRevalidateKey] = nextRevalidate workStore.pendingRevalidates[pendingRevalidateKey] = pendingRevalidate
return pendingResponse return pendingResponse.then((responses) => responses[1])
} else { } else {
return doOriginalFetch(false, cacheReasonOverride) return doOriginalFetch(false, cacheReasonOverride)
} }
......
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