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

Propagate fallback artifact base through hydration

parent 3713e8ac
......@@ -249,6 +249,7 @@ if (
}
let initialServerResponse: Promise<InitialRSCPayload>
let initialOutputExportFallbackBasePath: string | null = null
const decodeFallbackPrerenderPayload = async (
responsePromise: Promise<Response>,
renderedUrl?: URL
......@@ -294,6 +295,7 @@ if (instantTestStaticFetch) {
)
if (fallbackResult !== null) {
initialOutputExportFallbackBasePath = fallbackResult.fallbackUrl.pathname
return decodeFallbackPrerenderPayload(
Promise.resolve(fallbackResult.response),
renderedUrl
......@@ -454,6 +456,7 @@ export async function hydrate(
initialRSCPayload,
initialFlightStreamForCache,
location: window.location,
outputExportFallbackBasePath: initialOutputExportFallbackBasePath,
}),
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 {
initialRSCPayload: InitialRSCPayload
initialFlightStreamForCache?: ReadableStream<Uint8Array> | null
location: Location | null
outputExportFallbackBasePath?: string | null
}
export function createInitialRouterState({
......@@ -34,6 +35,7 @@ export function createInitialRouterState({
initialRSCPayload,
initialFlightStreamForCache,
location,
outputExportFallbackBasePath = null,
}: InitialRouterStateParameters): AppRouterState {
const {
c: initialCanonicalUrlParts,
......@@ -103,7 +105,7 @@ export function createInitialRouterState({
// route learning nor segment cache state persists from SSR to client.
if (location !== null && metadataVaryPath !== null) {
// Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute(
const initialRouteEntry = discoverKnownRoute(
Date.now(),
location.pathname,
null, // nextUrl — initial render is never an interception
......@@ -115,6 +117,10 @@ export function createInitialRouterState({
initialSupportsPerSegmentPrefetching,
false // hasDynamicRewrite
)
if (outputExportFallbackBasePath !== null) {
initialRouteEntry.outputExportFallbackBasePath =
outputExportFallbackBasePath
}
// Write the initial seed data into the segment cache so subsequent
// navigations to the initial page can serve cached segments instantly.
......
......@@ -125,6 +125,7 @@ describe('fetchServerResponse output export fallback', () => {
expect(typeof result).not.toBe('string')
if (typeof result !== 'string') {
expect(result.canonicalUrl.href).toBe(`${origin}/another/third`)
expect(result.outputExportFallbackBasePath).toBe('/another/__fallback')
}
expect(global.fetch).toHaveBeenCalledTimes(1)
expect(mockFetchOutputExportFallbackResponse).toHaveBeenCalledTimes(1)
......
......@@ -86,6 +86,7 @@ type SpaFetchServerResponseResult = {
flightData: NormalizedFlightData[]
canonicalUrl: URL
renderedSearch: NormalizedSearch
outputExportFallbackBasePath: string | null
couldBeIntercepted: boolean
supportsPerSegmentPrefetching: boolean
postponed: boolean
......@@ -172,6 +173,7 @@ export async function fetchServerResponse(
try {
let usedCachedOutputExportFallback = false
let outputExportFallbackBasePath: string | null = null
if (process.env.NODE_ENV === 'production') {
if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {
// In "output: export" mode, we can't rely on headers to distinguish
......@@ -244,6 +246,7 @@ export async function fetchServerResponse(
if (fallbackResult !== null) {
usedOutputExportFallback = true
outputExportFallbackBasePath = fallbackResult.fallbackUrl.pathname
const { response: processed, cacheData } = await processFetch(
fallbackResult.response
)
......@@ -352,6 +355,7 @@ export async function fetchServerResponse(
// header alone. So we need to investigate why the header is sometimes
// wrong for interception routes.
renderedSearch: flightResponse.q as NormalizedSearch,
outputExportFallbackBasePath,
couldBeIntercepted: interception,
supportsPerSegmentPrefetching: flightResponse.S,
postponed,
......
......@@ -407,6 +407,7 @@ async function navigateToUnknownRoute(
flightData,
canonicalUrl,
renderedSearch,
outputExportFallbackBasePath,
couldBeIntercepted,
supportsPerSegmentPrefetching,
dynamicStaleTime,
......@@ -434,7 +435,7 @@ async function navigateToUnknownRoute(
// retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).
const metadataVaryPath = navigationSeed.metadataVaryPath
if (metadataVaryPath !== null) {
discoverKnownRoute(
const discoveredRoute = discoverKnownRoute(
now,
url.pathname,
nextUrl,
......@@ -446,6 +447,10 @@ async function navigateToUnknownRoute(
supportsPerSegmentPrefetching,
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
)
if (outputExportFallbackBasePath !== null) {
discoveredRoute.outputExportFallbackBasePath =
outputExportFallbackBasePath
}
if (staticStageData !== null) {
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) {
}
})
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 () => {
const outDir = join(next.testDir, 'out')
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