Commit 45ccb41b authored by Jimmy Lai's avatar Jimmy Lai

Propagate fallback artifact base through hydration

parent 3713e8ac
...@@ -249,6 +249,7 @@ if ( ...@@ -249,6 +249,7 @@ if (
} }
let initialServerResponse: Promise<InitialRSCPayload> let initialServerResponse: Promise<InitialRSCPayload>
let initialOutputExportFallbackBasePath: string | null = null
const decodeFallbackPrerenderPayload = async ( const decodeFallbackPrerenderPayload = async (
responsePromise: Promise<Response>, responsePromise: Promise<Response>,
renderedUrl?: URL renderedUrl?: URL
...@@ -294,6 +295,7 @@ if (instantTestStaticFetch) { ...@@ -294,6 +295,7 @@ if (instantTestStaticFetch) {
) )
if (fallbackResult !== null) { if (fallbackResult !== null) {
initialOutputExportFallbackBasePath = fallbackResult.fallbackUrl.pathname
return decodeFallbackPrerenderPayload( return decodeFallbackPrerenderPayload(
Promise.resolve(fallbackResult.response), Promise.resolve(fallbackResult.response),
renderedUrl renderedUrl
...@@ -454,6 +456,7 @@ export async function hydrate( ...@@ -454,6 +456,7 @@ export async function hydrate(
initialRSCPayload, initialRSCPayload,
initialFlightStreamForCache, initialFlightStreamForCache,
location: window.location, location: window.location,
outputExportFallbackBasePath: initialOutputExportFallbackBasePath,
}), }),
instrumentationHooks instrumentationHooks
) )
......
import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'
import { createInitialRouterState } from './create-initial-router-state'
const mockGetFlightDataPartsFromPath = jest.fn()
const mockCreateInitialCacheNodeForHydration = jest.fn()
const mockConvertRootFlightRouterStateToRouteTree = jest.fn()
const mockDiscoverKnownRoute = jest.fn()
jest.mock('../../flight-data-helpers', () => ({
getFlightDataPartsFromPath: (...args: Array<unknown>) =>
mockGetFlightDataPartsFromPath(...args),
}))
jest.mock('./ppr-navigations', () => ({
createInitialCacheNodeForHydration: (...args: Array<unknown>) =>
mockCreateInitialCacheNodeForHydration(...args),
}))
jest.mock('../segment-cache/cache', () => ({
convertRootFlightRouterStateToRouteTree: (...args: Array<unknown>) =>
mockConvertRootFlightRouterStateToRouteTree(...args),
getStaleTimeMs: jest.fn((staleTime: number) => staleTime),
getStaleAt: jest.fn(),
processRuntimePrefetchStream: jest.fn(),
writeDynamicRenderResponseIntoCache: jest.fn(),
writeStaticStageResponseIntoCache: jest.fn(),
}))
jest.mock('../segment-cache/optimistic-routes', () => ({
discoverKnownRoute: (...args: Array<unknown>) =>
mockDiscoverKnownRoute(...args),
}))
describe('createInitialRouterState output export fallback', () => {
const discoveredRouteEntry = {
outputExportFallbackBasePath: null as string | null,
}
const initialRSCPayload: InitialRSCPayload = {
c: ['', 'hydrated', 'first'],
q: '',
i: false,
f: [[] as any],
m: new Set(),
G: [(() => null) as any, undefined],
S: false,
h: null,
}
beforeEach(() => {
mockGetFlightDataPartsFromPath.mockReset()
mockCreateInitialCacheNodeForHydration.mockReset()
mockConvertRootFlightRouterStateToRouteTree.mockReset()
mockDiscoverKnownRoute.mockReset()
discoveredRouteEntry.outputExportFallbackBasePath = null
mockGetFlightDataPartsFromPath.mockReturnValue({
tree: ['', {}],
seedData: null,
head: null,
})
mockCreateInitialCacheNodeForHydration.mockReturnValue({
rsc: null,
prefetchRsc: null,
prefetchHead: null,
head: null,
slots: null,
scrollRef: null,
})
mockConvertRootFlightRouterStateToRouteTree.mockImplementation(
(_tree, _renderedSearch, acc) => {
acc.metadataVaryPath = '__PAGE__'
return { path: '/hydrated/[thread]' }
}
)
mockDiscoverKnownRoute.mockReturnValue(discoveredRouteEntry)
})
it('stores the learned fallback artifact base path on the hydrated route entry', () => {
createInitialRouterState({
navigatedAt: Date.now(),
initialRSCPayload,
location: new URL('https://example.com/hydrated/first/') as Location,
outputExportFallbackBasePath: '/hydrated/__fallback',
})
expect(discoveredRouteEntry.outputExportFallbackBasePath).toBe(
'/hydrated/__fallback'
)
})
})
...@@ -27,6 +27,7 @@ export interface InitialRouterStateParameters { ...@@ -27,6 +27,7 @@ export interface InitialRouterStateParameters {
initialRSCPayload: InitialRSCPayload initialRSCPayload: InitialRSCPayload
initialFlightStreamForCache?: ReadableStream<Uint8Array> | null initialFlightStreamForCache?: ReadableStream<Uint8Array> | null
location: Location | null location: Location | null
outputExportFallbackBasePath?: string | null
} }
export function createInitialRouterState({ export function createInitialRouterState({
...@@ -34,6 +35,7 @@ export function createInitialRouterState({ ...@@ -34,6 +35,7 @@ export function createInitialRouterState({
initialRSCPayload, initialRSCPayload,
initialFlightStreamForCache, initialFlightStreamForCache,
location, location,
outputExportFallbackBasePath = null,
}: InitialRouterStateParameters): AppRouterState { }: InitialRouterStateParameters): AppRouterState {
const { const {
c: initialCanonicalUrlParts, c: initialCanonicalUrlParts,
...@@ -103,7 +105,7 @@ export function createInitialRouterState({ ...@@ -103,7 +105,7 @@ export function createInitialRouterState({
// route learning nor segment cache state persists from SSR to client. // route learning nor segment cache state persists from SSR to client.
if (location !== null && metadataVaryPath !== null) { if (location !== null && metadataVaryPath !== null) {
// Learn the route pattern so we can predict it for future navigations. // Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute( const initialRouteEntry = discoverKnownRoute(
Date.now(), Date.now(),
location.pathname, location.pathname,
null, // nextUrl — initial render is never an interception null, // nextUrl — initial render is never an interception
...@@ -115,6 +117,10 @@ export function createInitialRouterState({ ...@@ -115,6 +117,10 @@ export function createInitialRouterState({
initialSupportsPerSegmentPrefetching, initialSupportsPerSegmentPrefetching,
false // hasDynamicRewrite false // hasDynamicRewrite
) )
if (outputExportFallbackBasePath !== null) {
initialRouteEntry.outputExportFallbackBasePath =
outputExportFallbackBasePath
}
// Write the initial seed data into the segment cache so subsequent // Write the initial seed data into the segment cache so subsequent
// navigations to the initial page can serve cached segments instantly. // navigations to the initial page can serve cached segments instantly.
......
...@@ -125,6 +125,7 @@ describe('fetchServerResponse output export fallback', () => { ...@@ -125,6 +125,7 @@ describe('fetchServerResponse output export fallback', () => {
expect(typeof result).not.toBe('string') expect(typeof result).not.toBe('string')
if (typeof result !== 'string') { if (typeof result !== 'string') {
expect(result.canonicalUrl.href).toBe(`${origin}/another/third`) expect(result.canonicalUrl.href).toBe(`${origin}/another/third`)
expect(result.outputExportFallbackBasePath).toBe('/another/__fallback')
} }
expect(global.fetch).toHaveBeenCalledTimes(1) expect(global.fetch).toHaveBeenCalledTimes(1)
expect(mockFetchOutputExportFallbackResponse).toHaveBeenCalledTimes(1) expect(mockFetchOutputExportFallbackResponse).toHaveBeenCalledTimes(1)
......
...@@ -86,6 +86,7 @@ type SpaFetchServerResponseResult = { ...@@ -86,6 +86,7 @@ type SpaFetchServerResponseResult = {
flightData: NormalizedFlightData[] flightData: NormalizedFlightData[]
canonicalUrl: URL canonicalUrl: URL
renderedSearch: NormalizedSearch renderedSearch: NormalizedSearch
outputExportFallbackBasePath: string | null
couldBeIntercepted: boolean couldBeIntercepted: boolean
supportsPerSegmentPrefetching: boolean supportsPerSegmentPrefetching: boolean
postponed: boolean postponed: boolean
...@@ -172,6 +173,7 @@ export async function fetchServerResponse( ...@@ -172,6 +173,7 @@ export async function fetchServerResponse(
try { try {
let usedCachedOutputExportFallback = false let usedCachedOutputExportFallback = false
let outputExportFallbackBasePath: string | null = null
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') { if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
// In "output: export" mode, we can't rely on headers to distinguish // In "output: export" mode, we can't rely on headers to distinguish
...@@ -244,6 +246,7 @@ export async function fetchServerResponse( ...@@ -244,6 +246,7 @@ export async function fetchServerResponse(
if (fallbackResult !== null) { if (fallbackResult !== null) {
usedOutputExportFallback = true usedOutputExportFallback = true
outputExportFallbackBasePath = fallbackResult.fallbackUrl.pathname
const { response: processed, cacheData } = await processFetch( const { response: processed, cacheData } = await processFetch(
fallbackResult.response fallbackResult.response
) )
...@@ -352,6 +355,7 @@ export async function fetchServerResponse( ...@@ -352,6 +355,7 @@ export async function fetchServerResponse(
// header alone. So we need to investigate why the header is sometimes // header alone. So we need to investigate why the header is sometimes
// wrong for interception routes. // wrong for interception routes.
renderedSearch: flightResponse.q as NormalizedSearch, renderedSearch: flightResponse.q as NormalizedSearch,
outputExportFallbackBasePath,
couldBeIntercepted: interception, couldBeIntercepted: interception,
supportsPerSegmentPrefetching: flightResponse.S, supportsPerSegmentPrefetching: flightResponse.S,
postponed, postponed,
......
...@@ -407,6 +407,7 @@ async function navigateToUnknownRoute( ...@@ -407,6 +407,7 @@ async function navigateToUnknownRoute(
flightData, flightData,
canonicalUrl, canonicalUrl,
renderedSearch, renderedSearch,
outputExportFallbackBasePath,
couldBeIntercepted, couldBeIntercepted,
supportsPerSegmentPrefetching, supportsPerSegmentPrefetching,
dynamicStaleTime, dynamicStaleTime,
...@@ -434,7 +435,7 @@ async function navigateToUnknownRoute( ...@@ -434,7 +435,7 @@ async function navigateToUnknownRoute(
// retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch). // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).
const metadataVaryPath = navigationSeed.metadataVaryPath const metadataVaryPath = navigationSeed.metadataVaryPath
if (metadataVaryPath !== null) { if (metadataVaryPath !== null) {
discoverKnownRoute( const discoveredRoute = discoverKnownRoute(
now, now,
url.pathname, url.pathname,
nextUrl, nextUrl,
...@@ -446,6 +447,10 @@ async function navigateToUnknownRoute( ...@@ -446,6 +447,10 @@ async function navigateToUnknownRoute(
supportsPerSegmentPrefetching, supportsPerSegmentPrefetching,
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
) )
if (outputExportFallbackBasePath !== null) {
discoveredRoute.outputExportFallbackBasePath =
outputExportFallbackBasePath
}
if (staticStageData !== null) { if (staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } = const { response: staticStageResponse, isResponsePartial } =
......
import { Suspense } from 'react'
import { LinkAccordion } from '../../components/link-accordion'
import HydratedThreadClient from './thread-client'
export default function HydratedThreadPage() {
return (
<>
<Suspense fallback={<h1>Loading hydrated thread...</h1>}>
<HydratedThreadClient />
</Suspense>
<ul>
<li>
<LinkAccordion href="/hydrated/second">
Visit hydrated thread second
</LinkAccordion>
</li>
</ul>
</>
)
}
'use client'
import { useParams } from 'next/navigation'
export default function HydratedThreadClient() {
const params = useParams()
return <h1>{params.thread}</h1>
}
...@@ -410,6 +410,55 @@ if (skipped) { ...@@ -410,6 +410,55 @@ if (skipped) {
} }
}) })
it('reuses the hydrated fallback artifact base for sibling segment prefetches', async () => {
let act!: ReturnType<typeof createRouterAct>
const browser = await webdriver(port, '/hydrated/first/', {
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
},
})
try {
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('first')
})
clearRequests()
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/hydrated/second"]')
.click()
})
const prefetchRequests = getRequests()
expect(prefetchRequests.length).toBeGreaterThan(0)
expect(
prefetchRequests.some((requestPath) =>
requestPath.startsWith('/hydrated/second/?_rsc=')
)
).toBe(false)
expect(
prefetchRequests.some((requestPath) =>
requestPath.startsWith('/hydrated/second/index.txt')
)
).toBe(false)
expect(
prefetchRequests.some((requestPath) =>
requestPath.startsWith('/hydrated/second/__next.')
)
).toBe(false)
expect(
prefetchRequests.some((requestPath) =>
requestPath.startsWith('/hydrated/__fallback')
)
).toBe(true)
} finally {
await browser.close()
}
})
it('generates a hidden _fallback.html bootstrap document', async () => { it('generates a hidden _fallback.html bootstrap document', async () => {
const outDir = join(next.testDir, 'out') const outDir = join(next.testDir, 'out')
const fallbackHtml = await fs.readFile( const fallbackHtml = await fs.readFile(
......
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