Commit 3f821ad3 authored by Jimmy Lai's avatar Jimmy Lai

Collapse output export fallback critical path

parent 4abd51e4
...@@ -11,9 +11,11 @@ import { ...@@ -11,9 +11,11 @@ import {
describe('output export fallback helpers', () => { describe('output export fallback helpers', () => {
const originalFetch = global.fetch const originalFetch = global.fetch
const originalTrailingSlash = process.env.__NEXT_TRAILING_SLASH
afterEach(() => { afterEach(() => {
global.fetch = originalFetch global.fetch = originalFetch
process.env.__NEXT_TRAILING_SLASH = originalTrailingSlash
clearOutputExportFallbackManifestCache() clearOutputExportFallbackManifestCache()
jest.restoreAllMocks() jest.restoreAllMocks()
}) })
...@@ -91,7 +93,8 @@ describe('output export fallback helpers', () => { ...@@ -91,7 +93,8 @@ describe('output export fallback helpers', () => {
]) ])
}) })
it('walks prefixes from the root until a fallback payload is found', async () => { it('tries the direct fallback artifact before manifest lookups', async () => {
process.env.__NEXT_TRAILING_SLASH = 'false'
const fetchMock = jest.fn(async (input: RequestInfo | URL) => { const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input) const url = String(input)
...@@ -102,10 +105,34 @@ describe('output export fallback helpers', () => { ...@@ -102,10 +105,34 @@ describe('output export fallback helpers', () => {
}) })
} }
return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
})
global.fetch = fetchMock as typeof fetch
const renderedUrl = new URL('https://example.com/org/acme/chat/123')
const result = await fetchOutputExportFallbackResponse(renderedUrl)
expect(result).not.toBeNull()
expect(result?.renderedUrl.href).toBe(renderedUrl.href)
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/org/__fallback.txt',
])
})
it('prefers the trailing-slash fallback artifact when the request URL ends with /', async () => {
delete process.env.__NEXT_TRAILING_SLASH
const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input)
if (url.endsWith('/org/__fallback/index.txt')) { if (url.endsWith('/org/__fallback/index.txt')) {
return new Response('not found', { return new Response('flight', {
status: 404, status: 200,
headers: { 'content-type': 'text/html' }, headers: { 'content-type': 'text/x-component' },
}) })
} }
...@@ -117,21 +144,30 @@ describe('output export fallback helpers', () => { ...@@ -117,21 +144,30 @@ describe('output export fallback helpers', () => {
global.fetch = fetchMock as typeof fetch global.fetch = fetchMock as typeof fetch
const renderedUrl = new URL('https://example.com/org/acme/chat/123') const renderedUrl = new URL(
'https://example.com/org/umbrella/chat/thread-789/'
)
const result = await fetchOutputExportFallbackResponse(renderedUrl) const result = await fetchOutputExportFallbackResponse(renderedUrl)
expect(result).not.toBeNull() expect(result).not.toBeNull()
expect(result?.renderedUrl.href).toBe(renderedUrl.href) expect(result?.renderedUrl.href).toBe(renderedUrl.href)
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/org/__fallback.meta.json', 'https://example.com/org/__fallback/index.txt',
'https://example.com/org/__fallback.txt',
]) ])
}) })
it('uses fallback metadata to select the most specific conflicting route', async () => { it('uses fallback metadata to select the most specific conflicting route', async () => {
process.env.__NEXT_TRAILING_SLASH = 'false'
const fetchMock = jest.fn(async (input: RequestInfo | URL) => { const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input) const url = String(input)
if (url.endsWith('/docs/__fallback.txt')) {
return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
}
if (url.endsWith('/docs/__fallback.meta.json')) { if (url.endsWith('/docs/__fallback.meta.json')) {
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
...@@ -175,12 +211,14 @@ describe('output export fallback helpers', () => { ...@@ -175,12 +211,14 @@ describe('output export fallback helpers', () => {
expect(result).not.toBeNull() expect(result).not.toBeNull()
expect(result?.fallbackUrl.pathname).toBe('/docs/__fallback/__route_0') expect(result?.fallbackUrl.pathname).toBe('/docs/__fallback/__route_0')
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/docs/__fallback.txt',
'https://example.com/docs/__fallback.meta.json', 'https://example.com/docs/__fallback.meta.json',
'https://example.com/docs/__fallback/__route_0.txt', 'https://example.com/docs/__fallback/__route_0.txt',
]) ])
}) })
it('caches the resolved fallback data URL for later RSC fetches', async () => { it('caches the resolved fallback data URL for later RSC fetches', async () => {
process.env.__NEXT_TRAILING_SLASH = 'false'
const fetchMock = jest.fn(async (input: RequestInfo | URL) => { const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input) const url = String(input)
...@@ -247,9 +285,17 @@ describe('output export fallback helpers', () => { ...@@ -247,9 +285,17 @@ describe('output export fallback helpers', () => {
}) })
it('dedupes fallback artifact fetches across sibling routes', async () => { it('dedupes fallback artifact fetches across sibling routes', async () => {
process.env.__NEXT_TRAILING_SLASH = 'false'
const fetchMock = jest.fn(async (input: RequestInfo | URL) => { const fetchMock = jest.fn(async (input: RequestInfo | URL) => {
const url = String(input) const url = String(input)
if (url.endsWith('/docs/__fallback.txt')) {
return new Response('not found', {
status: 404,
headers: { 'content-type': 'text/html' },
})
}
if (url.endsWith('/docs/__fallback.meta.json')) { if (url.endsWith('/docs/__fallback.meta.json')) {
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
...@@ -295,6 +341,7 @@ describe('output export fallback helpers', () => { ...@@ -295,6 +341,7 @@ describe('output export fallback helpers', () => {
) )
expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
'https://example.com/docs/__fallback.txt',
'https://example.com/docs/__fallback.meta.json', 'https://example.com/docs/__fallback.meta.json',
'https://example.com/docs/__fallback/__route_0.txt', 'https://example.com/docs/__fallback/__route_0.txt',
]) ])
......
...@@ -163,6 +163,22 @@ function getOutputExportDataCandidates(url: URL): URL[] { ...@@ -163,6 +163,22 @@ function getOutputExportDataCandidates(url: URL): URL[] {
return [direct, trailingSlash] return [direct, trailingSlash]
} }
function getConfiguredOutputExportDataUrl(
url: URL,
prefersTrailingSlash: boolean
): URL {
const trailingSlash = process.env.__NEXT_TRAILING_SLASH
const configuredUrl = new URL(url)
const useTrailingSlash =
trailingSlash == null
? prefersTrailingSlash
: String(trailingSlash) === 'true'
if (useTrailingSlash && !configuredUrl.pathname.endsWith('/')) {
configuredUrl.pathname = `${configuredUrl.pathname}/`
}
return addOutputExportDataSuffix(configuredUrl)
}
function normalizeOutputExportRouteDirectory(pathname: string): string { function normalizeOutputExportRouteDirectory(pathname: string): string {
if (pathname === '/') { if (pathname === '/') {
return '' return ''
...@@ -229,6 +245,30 @@ async function fetchOutputExportDataResult( ...@@ -229,6 +245,30 @@ async function fetchOutputExportDataResult(
return null return null
} }
async function fetchConfiguredOutputExportDataResult(
renderedUrl: URL,
prefersTrailingSlash: boolean,
init?: RequestInit
): Promise<{ response: Response; dataUrl: URL } | null> {
const configuredDataUrl = getConfiguredOutputExportDataUrl(
renderedUrl,
prefersTrailingSlash
)
const response = await fetchOutputExportDataResponseByUrl(
configuredDataUrl,
init
)
if (response === null) {
return null
}
return {
response,
dataUrl: configuredDataUrl,
}
}
async function fetchOutputExportDataResponseByUrl( async function fetchOutputExportDataResponseByUrl(
dataUrl: URL, dataUrl: URL,
init?: RequestInit init?: RequestInit
...@@ -287,12 +327,32 @@ export async function fetchOutputExportFallbackResponse( ...@@ -287,12 +327,32 @@ export async function fetchOutputExportFallbackResponse(
renderedUrl: URL, renderedUrl: URL,
init?: RequestInit init?: RequestInit
): Promise<{ response: Response; renderedUrl: URL; fallbackUrl: URL } | null> { ): Promise<{ response: Response; renderedUrl: URL; fallbackUrl: URL } | null> {
const prefersTrailingSlash = renderedUrl.pathname.endsWith('/')
for (const candidate of getOutputExportFallbackCandidates( for (const candidate of getOutputExportFallbackCandidates(
renderedUrl.pathname renderedUrl.pathname
)) { )) {
const candidateUrl = new URL(renderedUrl) const candidateUrl = new URL(renderedUrl)
candidateUrl.pathname = candidate candidateUrl.pathname = candidate
const directResult = await fetchConfiguredOutputExportDataResult(
candidateUrl,
prefersTrailingSlash,
init
)
if (directResult) {
cacheOutputExportFallbackDataUrl(
renderedUrl,
candidateUrl,
directResult.dataUrl
)
return {
response: directResult.response,
renderedUrl,
fallbackUrl: candidateUrl,
}
}
const fallbackManifest = await fetchOutputExportFallbackManifest( const fallbackManifest = await fetchOutputExportFallbackManifest(
candidateUrl, candidateUrl,
init init
...@@ -308,8 +368,9 @@ export async function fetchOutputExportFallbackResponse( ...@@ -308,8 +368,9 @@ export async function fetchOutputExportFallbackResponse(
const branchFallbackUrl = new URL(renderedUrl) const branchFallbackUrl = new URL(renderedUrl)
branchFallbackUrl.pathname = entry.fallbackPath branchFallbackUrl.pathname = entry.fallbackPath
const result = await fetchOutputExportDataResult( const result = await fetchConfiguredOutputExportDataResult(
branchFallbackUrl, branchFallbackUrl,
prefersTrailingSlash,
init init
) )
if (result) { if (result) {
...@@ -326,20 +387,6 @@ export async function fetchOutputExportFallbackResponse( ...@@ -326,20 +387,6 @@ export async function fetchOutputExportFallbackResponse(
} }
} }
} }
const result = await fetchOutputExportDataResult(candidateUrl, init)
if (result) {
cacheOutputExportFallbackDataUrl(
renderedUrl,
candidateUrl,
result.dataUrl
)
return {
response: result.response,
renderedUrl,
fallbackUrl: candidateUrl,
}
}
} }
return null return null
......
...@@ -286,9 +286,11 @@ export async function writeOutputExportFallbackHtml( ...@@ -286,9 +286,11 @@ export async function writeOutputExportFallbackHtml(
'<style id="__next-export-fallback-style">#__next{visibility:hidden}</style>' '<style id="__next-export-fallback-style">#__next{visibility:hidden}</style>'
const injection = `${exportFallbackStyle}${exportFallbackScript}` const injection = `${exportFallbackStyle}${exportFallbackScript}`
const patchedFallbackHtml = fallbackHtml.includes('</head>') const patchedFallbackHtml = fallbackHtml.includes('<head>')
? fallbackHtml.replace('</head>', `${injection}</head>`) ? fallbackHtml.replace('<head>', `<head>${injection}`)
: injection + fallbackHtml : fallbackHtml.includes('</head>')
? fallbackHtml.replace('</head>', `${injection}</head>`)
: injection + fallbackHtml
await fs.writeFile(join(outDir, '_fallback.html'), patchedFallbackHtml) await fs.writeFile(join(outDir, '_fallback.html'), patchedFallbackHtml)
} }
......
...@@ -535,7 +535,7 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream< ...@@ -535,7 +535,7 @@ function createClientResumeScriptInsertionTransformStream(): TransformStream<
undefined // headers[NEXT_URL] undefined // headers[NEXT_URL]
) )
const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}` const searchStr = `${NEXT_RSC_UNION_QUERY}=${cacheBustingHeader}`
const NEXT_CLIENT_RESUME_SCRIPT = `<script>try{var u=sessionStorage.getItem('${originalUrlSessionKey}');var r=location.pathname;if(u){r=r.endsWith('.html')?r.slice(0,-5)+'.txt':r.endsWith('/')?r+'index.txt':r+'.txt'}__NEXT_CLIENT_RESUME=fetch(r+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}': '1','${NEXT_ROUTER_PREFETCH_HEADER}': '1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}': '${segmentPath}'}});if(u){window.${originalUrlGlobalKey}=u;history.replaceState(null,'',u);sessionStorage.removeItem('${originalUrlSessionKey}')}}catch{}</script>` const NEXT_CLIENT_RESUME_SCRIPT = `<script>try{var u=sessionStorage.getItem('${originalUrlSessionKey}');var r=location.pathname;if(u){r=r.endsWith('.html')?r.slice(0,-5)+'.txt':r.endsWith('/')?r+'index.txt':r+'.txt'}if(!self.__NEXT_EXPORT_FALLBACK){__NEXT_CLIENT_RESUME=fetch(r+'?${searchStr}',{credentials:'same-origin',headers:{'${RSC_HEADER}': '1','${NEXT_ROUTER_PREFETCH_HEADER}': '1','${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}': '${segmentPath}'}})}if(u){window.${originalUrlGlobalKey}=u;history.replaceState(null,'',u);sessionStorage.removeItem('${originalUrlSessionKey}')}}catch{}</script>`
let didAlreadyInsert = false let didAlreadyInsert = false
return new TransformStream({ return new TransformStream({
......
...@@ -369,6 +369,47 @@ if (skipped) { ...@@ -369,6 +369,47 @@ if (skipped) {
} }
}) })
it('loads nested fallback routes without concrete retries or extra probes', async () => {
clearRequests()
const browser = await webdriver(port, '/org/umbrella/chat/thread-789/')
try {
await retry(async () => {
expect(await browser.elementByCss('#org-name').text()).toBe(
'Org umbrella'
)
expect(await browser.elementByCss('h1').text()).toBe(
'umbrella:thread-789'
)
})
const requests = getRequests()
expect(
requests.some((requestPath) =>
requestPath.startsWith('/org/umbrella/chat/thread-789/?_rsc=')
)
).toBe(false)
expect(
requests.some((requestPath) =>
requestPath.startsWith('/org/__fallback.meta.json')
)
).toBe(false)
expect(
requests.some((requestPath) =>
requestPath.startsWith('/org/__fallback.txt')
)
).toBe(false)
expect(
requests.filter((requestPath) =>
requestPath.startsWith('/org/__fallback/index.txt')
)
).toHaveLength(1)
} 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