Unverified Commit 2e327560 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Include server latency in debug info (#84580)

The debug info of the promise created by the Flight client represents
the latency between when the navigation starts and when it's passed to
React. Most importantly, it should include the time it takes for the
client to start receiving data from the server.

Before this PR, the timing was too late because we did not call into the
Flight client until after we started receiving data.

To fix this, we switch from using `createFromReadableStream` to
`createFromFetch`. This allows us to call into the Flight client
immediately without waiting for the `fetch` promise to resolve.

The `_debugInfo` field contains the profiling information. Promises that
are created by Flight already have this info added by React; for any
derived promise created by the router, we need to transfer the Flight
debug info onto the derived promise.

Concretely, we create a derived promise for each route segment contained
in a response. Any nested promises contained with that segment are
passed directly from Flight to React and don't require special
processing.
parent 32476071
...@@ -139,6 +139,7 @@ describe('createInitialRouterState', () => { ...@@ -139,6 +139,7 @@ describe('createInitialRouterState', () => {
cache: expectedCache, cache: expectedCache,
nextUrl: '/linking', nextUrl: '/linking',
previousNextUrl: null, previousNextUrl: null,
debugInfo: null,
} }
expect(state).toMatchObject(expected) expect(state).toMatchObject(expected)
......
...@@ -111,6 +111,7 @@ export function createInitialRouterState({ ...@@ -111,6 +111,7 @@ export function createInitialRouterState({
(extractPathFromFlightRouterState(initialTree) || location?.pathname) ?? (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??
null, null,
previousNextUrl: null, previousNextUrl: null,
debugInfo: null,
} }
if (process.env.NODE_ENV !== 'development' && location) { if (process.env.NODE_ENV !== 'development' && location) {
...@@ -146,6 +147,7 @@ export function createInitialRouterState({ ...@@ -146,6 +147,7 @@ export function createInitialRouterState({
prerendered && !process.env.__NEXT_CLIENT_SEGMENT_CACHE prerendered && !process.env.__NEXT_CLIENT_SEGMENT_CACHE
? STATIC_STALETIME_MS ? STATIC_STALETIME_MS
: -1, : -1,
debugInfo: null,
}, },
tree: initialState.tree, tree: initialState.tree,
prefetchCache: initialState.prefetchCache, prefetchCache: initialState.prefetchCache,
......
...@@ -2,7 +2,10 @@ ...@@ -2,7 +2,10 @@
// TODO: Explicitly import from client.browser // TODO: Explicitly import from client.browser
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { createFromReadableStream as createFromReadableStreamBrowser } from 'react-server-dom-webpack/client' import {
createFromReadableStream as createFromReadableStreamBrowser,
createFromFetch as createFromFetchBrowser,
} from 'react-server-dom-webpack/client'
import type { import type {
FlightRouterState, FlightRouterState,
...@@ -37,6 +40,8 @@ import { urlToUrlWithoutFlightMarker } from '../../route-params' ...@@ -37,6 +40,8 @@ import { urlToUrlWithoutFlightMarker } from '../../route-params'
const createFromReadableStream = const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream'] createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
let createDebugChannel: let createDebugChannel:
| typeof import('../../dev/debug-channel').createDebugChannel | typeof import('../../dev/debug-channel').createDebugChannel
...@@ -65,6 +70,7 @@ export type FetchServerResponseResult = { ...@@ -65,6 +70,7 @@ export type FetchServerResponseResult = {
prerendered: boolean prerendered: boolean
postponed: boolean postponed: boolean
staleTime: number staleTime: number
debugInfo: Array<any> | null
} }
export type RequestHeaders = { export type RequestHeaders = {
...@@ -91,6 +97,7 @@ function doMpaNavigation(url: string): FetchServerResponseResult { ...@@ -91,6 +97,7 @@ function doMpaNavigation(url: string): FetchServerResponseResult {
prerendered: false, prerendered: false,
postponed: false, postponed: false,
staleTime: -1, staleTime: -1,
debugInfo: null,
} }
} }
...@@ -175,10 +182,17 @@ export async function fetchServerResponse( ...@@ -175,10 +182,17 @@ export async function fetchServerResponse(
} }
} }
const res = await createFetch( // Typically, during a navigation, we decode the response using Flight's
// `createFromFetch` API, which accepts a `fetch` promise.
// TODO: Remove this check once the old PPR flag is removed
const isLegacyPPR =
process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS
const shouldImmediatelyDecode = !isLegacyPPR
const res = await createFetch<NavigationFlightResponse>(
url, url,
headers, headers,
fetchPriority, fetchPriority,
shouldImmediatelyDecode,
abortController.signal abortController.signal
) )
...@@ -226,26 +240,37 @@ export async function fetchServerResponse( ...@@ -226,26 +240,37 @@ export async function fetchServerResponse(
).waitForWebpackRuntimeHotUpdate() ).waitForWebpackRuntimeHotUpdate()
} }
// Handle the `fetch` readable stream that can be unwrapped by `React.use`. let flightResponsePromise = res.flightResponse
const flightStream = postponed if (flightResponsePromise === null) {
? createUnclosingPrefetchStream(res.body) // Typically, `createFetch` would have already started decoding the
: res.body // Flight response. If it hasn't, though, we need to decode it now.
const response = await (createFromNextReadableStream( // TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR
flightStream, // without Cache Components). Remove this branch once legacy PPR
headers // is deleted.
) as Promise<NavigationFlightResponse>) const flightStream = postponed
? createUnclosingPrefetchStream(res.body)
: res.body
flightResponsePromise =
createFromNextReadableStream<NavigationFlightResponse>(
flightStream,
headers
)
}
const flightResponse = await flightResponsePromise
if (getAppBuildId() !== response.b) { if (getAppBuildId() !== flightResponse.b) {
return doMpaNavigation(res.url) return doMpaNavigation(res.url)
} }
return { return {
flightData: normalizeFlightData(response.f), flightData: normalizeFlightData(flightResponse.f),
canonicalUrl: canonicalUrl, canonicalUrl: canonicalUrl,
couldBeIntercepted: interception, couldBeIntercepted: interception,
prerendered: response.S, prerendered: flightResponse.S,
postponed, postponed,
staleTime, staleTime,
debugInfo: flightResponsePromise._debugInfo ?? null,
} }
} catch (err) { } catch (err) {
if (!abortController.signal.aborted) { if (!abortController.signal.aborted) {
...@@ -265,6 +290,7 @@ export async function fetchServerResponse( ...@@ -265,6 +290,7 @@ export async function fetchServerResponse(
prerendered: false, prerendered: false,
postponed: false, postponed: false,
staleTime: -1, staleTime: -1,
debugInfo: null,
} }
} }
} }
...@@ -274,21 +300,23 @@ export async function fetchServerResponse( ...@@ -274,21 +300,23 @@ export async function fetchServerResponse(
// the codebase. For example, there's some custom logic for manually following // the codebase. For example, there's some custom logic for manually following
// redirects, so "redirected" in this type could be a composite of multiple // redirects, so "redirected" in this type could be a composite of multiple
// browser fetch calls; however, this fact should not leak to the caller. // browser fetch calls; however, this fact should not leak to the caller.
export type RSCResponse = { export type RSCResponse<T> = {
ok: boolean ok: boolean
redirected: boolean redirected: boolean
headers: Headers headers: Headers
body: ReadableStream<Uint8Array> | null body: ReadableStream<Uint8Array> | null
status: number status: number
url: string url: string
flightResponse: (Promise<T> & { _debugInfo?: Array<any> }) | null
} }
export async function createFetch( export async function createFetch<T>(
url: URL, url: URL,
headers: RequestHeaders, headers: RequestHeaders,
fetchPriority: 'auto' | 'high' | 'low' | null, fetchPriority: 'auto' | 'high' | 'low' | null,
shouldImmediatelyDecode: boolean,
signal?: AbortSignal signal?: AbortSignal
): Promise<RSCResponse> { ): Promise<RSCResponse<T>> {
// TODO: In output: "export" mode, the headers do nothing. Omit them (and the // TODO: In output: "export" mode, the headers do nothing. Omit them (and the
// cache busting search param) from the request so they're // cache busting search param) from the request so they're
// maximally cacheable. // maximally cacheable.
...@@ -326,7 +354,21 @@ export async function createFetch( ...@@ -326,7 +354,21 @@ export async function createFetch(
// track them separately. // track them separately.
let fetchUrl = new URL(url) let fetchUrl = new URL(url)
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
let browserResponse = await fetch(fetchUrl, fetchOptions) let fetchPromise = fetch(fetchUrl, fetchOptions)
// Immediately pass the fetch promise to the Flight client so that the debug
// info includes the latency from the client to the server. The internal timer
// in React starts as soon as `createFromFetch` is called.
//
// The only case where we don't do this is during a prefetch, because we have
// to do some extra processing of the response stream (see
// `createUnclosingPrefetchStream`). But this is fine, because a top-level
// prefetch response never blocks a navigation; if it hasn't already been
// written into the cache by the time the navigation happens, the router will
// go straight to a dynamic request.
let flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers)
: null
let browserResponse = await fetchPromise
// If the server responds with a redirect (e.g. 307), and the redirected // If the server responds with a redirect (e.g. 307), and the redirected
// location does not contain the cache busting search param set in the // location does not contain the cache busting search param set in the
...@@ -379,9 +421,14 @@ export async function createFetch( ...@@ -379,9 +421,14 @@ export async function createFetch(
// //
// Append the cache busting search param to the redirected URL and // Append the cache busting search param to the redirected URL and
// fetch again. // fetch again.
// TODO: We should abort the previous request.
fetchUrl = new URL(responseUrl) fetchUrl = new URL(responseUrl)
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
browserResponse = await fetch(fetchUrl, fetchOptions) fetchPromise = fetch(fetchUrl, fetchOptions)
flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers)
: null
browserResponse = await fetchPromise
// We just performed a manual redirect, so this is now true. // We just performed a manual redirect, so this is now true.
redirected = true redirected = true
} }
...@@ -392,7 +439,7 @@ export async function createFetch( ...@@ -392,7 +439,7 @@ export async function createFetch(
const responseUrl = new URL(browserResponse.url, fetchUrl) const responseUrl = new URL(browserResponse.url, fetchUrl)
responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY) responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)
const rscResponse: RSCResponse = { const rscResponse: RSCResponse<T> = {
url: responseUrl.href, url: responseUrl.href,
// This is true if any redirects occurred, either automatically by the // This is true if any redirects occurred, either automatically by the
...@@ -408,15 +455,20 @@ export async function createFetch( ...@@ -408,15 +455,20 @@ export async function createFetch(
headers: browserResponse.headers, headers: browserResponse.headers,
body: browserResponse.body, body: browserResponse.body,
status: browserResponse.status, status: browserResponse.status,
// This is the exact promise returned by `createFromFetch`. It contains
// debug information that we need to transfer to any derived promises that
// are later rendered by React.
flightResponse: flightResponsePromise,
} }
return rscResponse return rscResponse
} }
export function createFromNextReadableStream( export function createFromNextReadableStream<T>(
flightStream: ReadableStream<Uint8Array>, flightStream: ReadableStream<Uint8Array>,
requestHeaders: RequestHeaders requestHeaders: RequestHeaders
): Promise<unknown> { ): Promise<T> {
return createFromReadableStream(flightStream, { return createFromReadableStream(flightStream, {
callServer, callServer,
findSourceMapURL, findSourceMapURL,
...@@ -424,6 +476,17 @@ export function createFromNextReadableStream( ...@@ -424,6 +476,17 @@ export function createFromNextReadableStream(
}) })
} }
function createFromNextFetch<T>(
promiseForResponse: Promise<Response>,
requestHeaders: RequestHeaders
): Promise<T> & { _debugInfo?: Array<any> } {
return createFromFetch(promiseForResponse, {
callServer,
findSourceMapURL,
debugChannel: createDebugChannel && createDebugChannel(requestHeaders),
})
}
function createUnclosingPrefetchStream( function createUnclosingPrefetchStream(
originalFlightStream: ReadableStream<Uint8Array> originalFlightStream: ReadableStream<Uint8Array>
): ReadableStream<Uint8Array> { ): ReadableStream<Uint8Array> {
......
...@@ -87,5 +87,6 @@ export function handleMutable( ...@@ -87,5 +87,6 @@ export function handleMutable(
: state.tree, : state.tree,
nextUrl, nextUrl,
previousNextUrl: previousNextUrl, previousNextUrl: previousNextUrl,
debugInfo: mutable.collectedDebugInfo ?? null,
} }
} }
...@@ -210,7 +210,8 @@ export function navigateReducer( ...@@ -210,7 +210,8 @@ export function navigateReducer(
state.cache, state.cache,
state.tree, state.tree,
state.nextUrl, state.nextUrl,
shouldScroll shouldScroll,
mutable
) )
return handleNavigationResult(url, state, mutable, pendingPush, result) return handleNavigationResult(url, state, mutable, pendingPush, result)
} }
......
...@@ -46,5 +46,6 @@ export function restoreReducer( ...@@ -46,5 +46,6 @@ export function restoreReducer(
tree: treeToRestore, tree: treeToRestore,
nextUrl: extractPathFromFlightRouterState(treeToRestore) ?? url.pathname, nextUrl: extractPathFromFlightRouterState(treeToRestore) ?? url.pathname,
previousNextUrl: null, previousNextUrl: null,
debugInfo: null,
} }
} }
...@@ -439,6 +439,7 @@ export function serverActionReducer( ...@@ -439,6 +439,7 @@ export function serverActionReducer(
// TODO: We should be able to set this if the server action // TODO: We should be able to set this if the server action
// returned a fully static response. // returned a fully static response.
staleTime: -1, staleTime: -1,
debugInfo: null,
}, },
tree: state.tree, tree: state.tree,
prefetchCache: state.prefetchCache, prefetchCache: state.prefetchCache,
......
...@@ -35,6 +35,7 @@ export interface Mutable { ...@@ -35,6 +35,7 @@ export interface Mutable {
shouldScroll?: boolean shouldScroll?: boolean
preserveCustomHistoryState?: boolean preserveCustomHistoryState?: boolean
onlyHashChange?: boolean onlyHashChange?: boolean
collectedDebugInfo?: Array<unknown>
} }
export interface ServerActionMutable extends Mutable { export interface ServerActionMutable extends Mutable {
...@@ -259,10 +260,14 @@ export type AppRouterState = { ...@@ -259,10 +260,14 @@ export type AppRouterState = {
* The previous next-url that was used previous to a dynamic navigation. * The previous next-url that was used previous to a dynamic navigation.
*/ */
previousNextUrl: string | null previousNextUrl: string | null
debugInfo: Array<unknown> | null
} }
export type ReadonlyReducerState = Readonly<AppRouterState> export type ReadonlyReducerState = Readonly<AppRouterState>
export type ReducerState = Promise<AppRouterState> | AppRouterState export type ReducerState =
| (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })
| AppRouterState
export type ReducerActions = Readonly< export type ReducerActions = Readonly<
| RefreshAction | RefreshAction
| NavigateAction | NavigateAction
......
...@@ -1450,10 +1450,10 @@ export async function fetchRouteOnCacheMiss( ...@@ -1450,10 +1450,10 @@ export async function fetchRouteOnCacheMiss(
routeCacheLru.updateSize(entry, size) routeCacheLru.updateSize(entry, size)
} }
) )
const serverData = await (createFromNextReadableStream( const serverData = await createFromNextReadableStream<RootTreePrefetch>(
prefetchStream, prefetchStream,
headers headers
) as Promise<RootTreePrefetch>) )
if (serverData.buildId !== getAppBuildId()) { if (serverData.buildId !== getAppBuildId()) {
// The server build does not match the client. Treat as a 404. During // The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation. // an actual navigation, the router will trigger an MPA navigation.
...@@ -1502,10 +1502,11 @@ export async function fetchRouteOnCacheMiss( ...@@ -1502,10 +1502,11 @@ export async function fetchRouteOnCacheMiss(
routeCacheLru.updateSize(entry, size) routeCacheLru.updateSize(entry, size)
} }
) )
const serverData = await (createFromNextReadableStream( const serverData =
prefetchStream, await createFromNextReadableStream<NavigationFlightResponse>(
headers prefetchStream,
) as Promise<NavigationFlightResponse>) headers
)
if (serverData.b !== getAppBuildId()) { if (serverData.b !== getAppBuildId()) {
// The server build does not match the client. Treat as a 404. During // The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation. // an actual navigation, the router will trigger an MPA navigation.
...@@ -1523,7 +1524,7 @@ export async function fetchRouteOnCacheMiss( ...@@ -1523,7 +1524,7 @@ export async function fetchRouteOnCacheMiss(
// The non-PPR response format is what we'd get if we prefetched these segments // The non-PPR response format is what we'd get if we prefetched these segments
// using the LoadingBoundary fetch strategy, so mark their cache entries accordingly. // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.
FetchStrategy.LoadingBoundary, FetchStrategy.LoadingBoundary,
response, response as RSCResponse<NavigationFlightResponse>,
serverData, serverData,
entry, entry,
couldBeIntercepted, couldBeIntercepted,
...@@ -1787,7 +1788,7 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -1787,7 +1788,7 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
Date.now(), Date.now(),
task, task,
fetchStrategy, fetchStrategy,
response, response as RSCResponse<NavigationFlightResponse>,
serverData, serverData,
isResponsePartial, isResponsePartial,
route, route,
...@@ -1810,7 +1811,7 @@ function writeDynamicTreeResponseIntoCache( ...@@ -1810,7 +1811,7 @@ function writeDynamicTreeResponseIntoCache(
| FetchStrategy.LoadingBoundary | FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.Full, | FetchStrategy.Full,
response: RSCResponse, response: RSCResponse<NavigationFlightResponse>,
serverData: NavigationFlightResponse, serverData: NavigationFlightResponse,
entry: PendingRouteCacheEntry, entry: PendingRouteCacheEntry,
couldBeIntercepted: boolean, couldBeIntercepted: boolean,
...@@ -1915,7 +1916,7 @@ function writeDynamicRenderResponseIntoCache( ...@@ -1915,7 +1916,7 @@ function writeDynamicRenderResponseIntoCache(
| FetchStrategy.LoadingBoundary | FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.Full, | FetchStrategy.Full,
response: RSCResponse, response: RSCResponse<NavigationFlightResponse>,
serverData: NavigationFlightResponse, serverData: NavigationFlightResponse,
isResponsePartial: boolean, isResponsePartial: boolean,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
...@@ -2139,12 +2140,22 @@ function writeSeedDataIntoCache( ...@@ -2139,12 +2140,22 @@ function writeSeedDataIntoCache(
} }
} }
async function fetchPrefetchResponse( async function fetchPrefetchResponse<T>(
url: URL, url: URL,
headers: RequestHeaders headers: RequestHeaders
): Promise<RSCResponse | null> { ): Promise<RSCResponse<T> | null> {
const fetchPriority = 'low' const fetchPriority = 'low'
const response = await createFetch(url, headers, fetchPriority) // When issuing a prefetch request, don't immediately decode the response; we
// use the lower level `createFromResponse` API instead because we need to do
// some extra processing of the response stream. See
// `createPrefetchResponseStream` for more details.
const shouldImmediatelyDecode = false
const response = await createFetch<T>(
url,
headers,
fetchPriority,
shouldImmediatelyDecode
)
if (!response.ok) { if (!response.ok) {
return null return null
} }
......
...@@ -81,7 +81,8 @@ export function navigate( ...@@ -81,7 +81,8 @@ export function navigate(
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null, nextUrl: string | null,
shouldScroll: boolean shouldScroll: boolean,
accumulation: { collectedDebugInfo?: Array<unknown> }
): NavigationResult { ): NavigationResult {
const now = Date.now() const now = Date.now()
const href = url.href const href = url.href
...@@ -183,6 +184,10 @@ export function navigate( ...@@ -183,6 +184,10 @@ export function navigate(
} }
// There's no matching prefetch for this route in the cache. // There's no matching prefetch for this route in the cache.
let collectedDebugInfo = accumulation.collectedDebugInfo ?? []
if (accumulation.collectedDebugInfo === undefined) {
collectedDebugInfo = accumulation.collectedDebugInfo = []
}
return { return {
tag: NavigationResultTag.Async, tag: NavigationResultTag.Async,
data: navigateDynamicallyWithNoPrefetch( data: navigateDynamicallyWithNoPrefetch(
...@@ -194,7 +199,8 @@ export function navigate( ...@@ -194,7 +199,8 @@ export function navigate(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
shouldScroll, shouldScroll,
url.hash url.hash,
collectedDebugInfo
), ),
} }
} }
...@@ -404,7 +410,8 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -404,7 +410,8 @@ async function navigateDynamicallyWithNoPrefetch(
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
shouldScroll: boolean, shouldScroll: boolean,
hash: string hash: string,
collectedDebugInfo: Array<unknown>
): Promise< ): Promise<
MPANavigationResult | SuccessfulNavigationResult | NoOpNavigationResult MPANavigationResult | SuccessfulNavigationResult | NoOpNavigationResult
> { > {
...@@ -424,8 +431,15 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -424,8 +431,15 @@ async function navigateDynamicallyWithNoPrefetch(
flightRouterState: currentFlightRouterState, flightRouterState: currentFlightRouterState,
nextUrl, nextUrl,
}) })
const { flightData, canonicalUrl: canonicalUrlOverride } = const {
await promiseForDynamicServerResponse flightData,
canonicalUrl: canonicalUrlOverride,
debugInfo: debugInfoFromResponse,
} = await promiseForDynamicServerResponse
if (debugInfoFromResponse !== null) {
collectedDebugInfo.push(...debugInfoFromResponse)
}
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
// This is an MPA navigation. // This is an MPA navigation.
......
import type { Dispatch } from 'react' import type { Dispatch } from 'react'
import React, { use } from 'react' import React, { use, useMemo } from 'react'
import { isThenable } from '../../shared/lib/is-thenable' import { isThenable } from '../../shared/lib/is-thenable'
import type { AppRouterActionQueue } from './app-router-instance' import type { AppRouterActionQueue } from './app-router-instance'
import type { import type {
...@@ -50,5 +50,27 @@ export function useActionQueue( ...@@ -50,5 +50,27 @@ export function useActionQueue(
actionQueue.dispatch(action, setState) actionQueue.dispatch(action, setState)
} }
return isThenable(state) ? use(state) : state // When navigating to a non-prefetched route, then App Router state will be
// blocked until the server responds. We need to transfer the `_debugInfo`
// from the underlying Flight response onto the top-level promise that is
// passed to React (via `use`) so that the latency is accurately represented
// in the React DevTools.
const stateWithDebugInfo = useMemo(() => {
if (isThenable(state)) {
const debugInfo: Array<unknown> = []
const promiseWithDebugInfo = Promise.resolve(state).then((asyncState) => {
if (asyncState.debugInfo !== null) {
debugInfo.push(...asyncState.debugInfo)
}
return asyncState
}) as Promise<AppRouterState> & { _debugInfo?: Array<unknown> }
promiseWithDebugInfo._debugInfo = debugInfo
return promiseWithDebugInfo
}
return state
}, [state])
return isThenable(stateWithDebugInfo)
? use(stateWithDebugInfo)
: stateWithDebugInfo
} }
...@@ -21,7 +21,9 @@ export type RouteParam = { ...@@ -21,7 +21,9 @@ export type RouteParam = {
type: DynamicParamTypesShort type: DynamicParamTypesShort
} }
export function getRenderedSearch(response: RSCResponse): NormalizedSearch { export function getRenderedSearch(
response: RSCResponse<unknown>
): NormalizedSearch {
// If the server performed a rewrite, the search params used to render the // If the server performed a rewrite, the search params used to render the
// page will be different from the params in the request URL. In this case, // page will be different from the params in the request URL. In this case,
// the response will include a header that gives the rewritten search query. // the response will include a header that gives the rewritten search query.
...@@ -37,7 +39,7 @@ export function getRenderedSearch(response: RSCResponse): NormalizedSearch { ...@@ -37,7 +39,7 @@ export function getRenderedSearch(response: RSCResponse): NormalizedSearch {
.search as NormalizedSearch .search as NormalizedSearch
} }
export function getRenderedPathname(response: RSCResponse): string { export function getRenderedPathname(response: RSCResponse<unknown>): string {
// If the server performed a rewrite, the pathname used to render the // If the server performed a rewrite, the pathname used to render the
// page will be different from the pathname in the request URL. In this case, // page will be different from the pathname in the request URL. In this case,
// the response will include a header that gives the rewritten pathname. // the response will include a header that gives the rewritten pathname.
......
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