Unverified Commit f92a4cee authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add failing case for location throw (#40445)

Found that the cause was that `React.useId()` returns the same value across requests whereas it was being used to create a unique key. On further inspection that code could be removed altogether as `id` was not used client-side and the `rscCache` map is no longer needed as the flight instance is already being created per request so it can live in the context of the request execution.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent 3851d906
...@@ -56,7 +56,9 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined = ...@@ -56,7 +56,9 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false let initialServerDataLoaded = false
let initialServerDataFlushed = false let initialServerDataFlushed = false
function nextServerDataCallback(seg: [number, string, string]) { function nextServerDataCallback(
seg: [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string]
): void {
if (seg[0] === 0) { if (seg[0] === 0) {
initialServerDataBuffer = [] initialServerDataBuffer = []
} else { } else {
...@@ -64,9 +66,9 @@ function nextServerDataCallback(seg: [number, string, string]) { ...@@ -64,9 +66,9 @@ function nextServerDataCallback(seg: [number, string, string]) {
throw new Error('Unexpected server data: missing bootstrap script.') throw new Error('Unexpected server data: missing bootstrap script.')
if (initialServerDataWriter) { if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[2])) initialServerDataWriter.enqueue(encoder.encode(seg[1]))
} else { } else {
initialServerDataBuffer.push(seg[2]) initialServerDataBuffer.push(seg[1])
} }
} }
} }
......
...@@ -54,8 +54,6 @@ function interopDefault(mod: any) { ...@@ -54,8 +54,6 @@ function interopDefault(mod: any) {
return mod.default || mod return mod.default || mod
} }
const rscCache = new Map()
// Shadowing check does not work with TypeScript enums // Shadowing check does not work with TypeScript enums
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
const enum RecordStatus { const enum RecordStatus {
...@@ -134,57 +132,59 @@ function preloadDataFetchingRecord( ...@@ -134,57 +132,59 @@ function preloadDataFetchingRecord(
*/ */
function useFlightResponse( function useFlightResponse(
writable: WritableStream<Uint8Array>, writable: WritableStream<Uint8Array>,
cachePrefix: string,
req: ReadableStream<Uint8Array>, req: ReadableStream<Uint8Array>,
serverComponentManifest: any, serverComponentManifest: any,
flightResponseRef: {
current: ReturnType<typeof createFromReadableStream> | null
},
nonce?: string nonce?: string
) { ) {
const id = cachePrefix + ',' + (React as any).useId() if (flightResponseRef.current) {
let entry = rscCache.get(id) return flightResponseRef.current
if (!entry) { }
const [renderStream, forwardStream] = readableStreamTee(req)
entry = createFromReadableStream(renderStream, { const [renderStream, forwardStream] = readableStreamTee(req)
moduleMap: serverComponentManifest.__ssr_module_mapping__, flightResponseRef.current = createFromReadableStream(renderStream, {
}) moduleMap: serverComponentManifest.__ssr_module_mapping__,
rscCache.set(id, entry) })
let bootstrapped = false let bootstrapped = false
// We only attach CSS chunks to the inlined data. // We only attach CSS chunks to the inlined data.
const forwardReader = forwardStream.getReader() const forwardReader = forwardStream.getReader()
const writer = writable.getWriter() const writer = writable.getWriter()
const startScriptTag = nonce const startScriptTag = nonce
? `<script nonce=${JSON.stringify(nonce)}>` ? `<script nonce=${JSON.stringify(nonce)}>`
: '<script>' : '<script>'
function process() { function process() {
forwardReader.read().then(({ done, value }) => { forwardReader.read().then(({ done, value }) => {
if (!bootstrapped) { if (!bootstrapped) {
bootstrapped = true bootstrapped = true
writer.write( writer.write(
encodeText( encodeText(
`${startScriptTag}(self.__next_s=self.__next_s||[]).push(${htmlEscapeJsonString( `${startScriptTag}(self.__next_s=self.__next_s||[]).push(${htmlEscapeJsonString(
JSON.stringify([0, id]) JSON.stringify([0])
)})</script>` )})</script>`
)
) )
} )
if (done) { }
rscCache.delete(id) if (done) {
writer.close() flightResponseRef.current = null
} else { writer.close()
const responsePartial = decodeText(value) } else {
const scripts = `${startScriptTag}(self.__next_s=self.__next_s||[]).push(${htmlEscapeJsonString( const responsePartial = decodeText(value)
JSON.stringify([1, id, responsePartial]) const scripts = `${startScriptTag}(self.__next_s=self.__next_s||[]).push(${htmlEscapeJsonString(
)})</script>` JSON.stringify([1, responsePartial])
)})</script>`
writer.write(encodeText(scripts))
process() writer.write(encodeText(scripts))
} process()
}) }
} })
process()
} }
return entry process()
return flightResponseRef.current
} }
/** /**
...@@ -200,12 +200,10 @@ function createServerComponentRenderer( ...@@ -200,12 +200,10 @@ function createServerComponentRenderer(
} }
}, },
{ {
cachePrefix,
transformStream, transformStream,
serverComponentManifest, serverComponentManifest,
serverContexts, serverContexts,
}: { }: {
cachePrefix: string
transformStream: TransformStream<Uint8Array, Uint8Array> transformStream: TransformStream<Uint8Array, Uint8Array>
serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']> serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']>
serverContexts: Array< serverContexts: Array<
...@@ -240,14 +238,16 @@ function createServerComponentRenderer( ...@@ -240,14 +238,16 @@ function createServerComponentRenderer(
return RSCStream return RSCStream
} }
const flightResponseRef = { current: null }
const writable = transformStream.writable const writable = transformStream.writable
return function ServerComponentWrapper() { return function ServerComponentWrapper() {
const reqStream = createRSCStream() const reqStream = createRSCStream()
const response = useFlightResponse( const response = useFlightResponse(
writable, writable,
cachePrefix,
reqStream, reqStream,
serverComponentManifest, serverComponentManifest,
flightResponseRef,
nonce nonce
) )
return response.readRoot() return response.readRoot()
...@@ -1110,7 +1110,6 @@ export async function renderToHTMLOrFlight( ...@@ -1110,7 +1110,6 @@ export async function renderToHTMLOrFlight(
}, },
ComponentMod, ComponentMod,
{ {
cachePrefix: initialCanonicalUrl,
transformStream: serverComponentsInlinedTransformStream, transformStream: serverComponentsInlinedTransformStream,
serverComponentManifest, serverComponentManifest,
serverContexts, serverContexts,
......
export default function Loading() {
return <h2>Loading...</h2>
}
// @ts-ignore
import { experimental_use as use } from 'react'
const fetchCategory = async (categorySlug) => {
// artificial delay
await new Promise((resolve) => setTimeout(resolve, 3000))
return categorySlug + 'abc'
}
export default function Page({ params }) {
const category = use(fetchCategory(params.categorySlug))
return <div id="category-id">{category}</div>
}
...@@ -1419,6 +1419,21 @@ describe('app dir', () => { ...@@ -1419,6 +1419,21 @@ describe('app dir', () => {
expect(errors).toInclude('Error during SSR') expect(errors).toInclude('Error during SSR')
}) })
}) })
describe('known bugs', () => {
it('should not share flight data between requests', async () => {
const fetches = await Promise.all(
[...new Array(5)].map(() =>
renderViaHTTP(next.url, '/loading-bug/electronics')
)
)
for (const text of fetches) {
const $ = cheerio.load(text)
expect($('#category-id').text()).toBe('electronicsabc')
}
})
})
} }
describe('without assetPrefix', () => { describe('without assetPrefix', () => {
......
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