Unverified Commit 3853a7ff authored by Josh Story's avatar Josh Story Committed by GitHub

Separate the rendering of viewport from metadata (#70685)

viewport will never be streaming because is necessarily blocks important
shell time rendering with things like themeColor and viewport size. Most
other metadata can be streamed in if we're not serving an agent which
doesn't construct a DOM. This change doesn't actually make metadata
streaming but it does further separate the two so we can more easily
alter the rendering characteristics of metadata without affecting
viewport.

The approach is to ensure the metadata component creation is in the
react-server layer in the server module graph so it can access
`React.cache`. then we construct a pair of functions that can produce
the resolved metadata and viewport values, throwing if there is an
encountered error. We suppress these errors in our top level metadata
component (MetadataRoot) and and simultaneously expose a ready function
which calls these (`React.cache()`'d) functions in the Metadata outlet
where any errors will throw.

This cleans up the layering quite a bit and makes some runtime error
checks unecessary such as ensuring you rendered the MetadataRoot before
attempting to determine if the metadata was resolved.

The key thing achieved here though is that Metadata and Viewport now
resolve in parallel but separately. We avoid double walking the module
graph by again making use of `React.cache()`. In the future we can
render each of these components differently without affecting each
other.

This work is motivated more immediately by some error tracking work I
will land after this that needs to determine whether viewport or
metadata were dynamic independently.

There is one semantic difference worth calling out. Previously if you
called `notFound()` in `generateMetadata()` or `generateViewport()` both
would render the appropriate not found metadata/viewport. In this latest
update only the one that called notFound will update to reflect the
notFound metadata/viewport. I think fundamentally the approach to
handling notFound needs to change here. Really we should be abandoning
the render and starting over. This will be doubly important once
metadata is streaming. I'm ok with the edge case as is given customizing
viewport is not very common and calling notFound from within
generateViewport is expected to be an edge case of an edge case. The
workaround for now is to call notFound simultaneously from both
generateViewport and generateMetadata
parent 60dfe735
import type { AppRenderContext } from '../../server/app-render/app-render'
import type { MetadataContext } from './types/resolvers'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering'
export function createMetadataContext(
pathname: string,
renderOpts: AppRenderContext['renderOpts']
): MetadataContext {
return {
pathname,
trailingSlash: renderOpts.trailingSlash,
isStandaloneMode: renderOpts.nextConfigOutput === 'standalone',
}
}
export function createTrackedMetadataContext(
pathname: string,
renderOpts: AppRenderContext['renderOpts'],
staticGenerationStore: StaticGenerationStore | null
): MetadataContext {
return {
// Use the regular metadata context, but we trap the pathname access.
...createMetadataContext(pathname, renderOpts),
// Setup the trap around the pathname access so we can track when the
// pathname is accessed while resolving metadata which would indicate it's
// being used to resolve a relative URL. If that's the case, we don't want
// to provide it, and instead we should error.
get pathname() {
if (
staticGenerationStore &&
staticGenerationStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0
) {
trackFallbackParamAccessed(
staticGenerationStore,
'metadata relative url resolving'
)
}
return pathname
},
}
}
This diff is collapsed.
...@@ -21,6 +21,10 @@ import type { ...@@ -21,6 +21,10 @@ import type {
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { StaticMetadata } from './types/icons' import type { StaticMetadata } from './types/icons'
// eslint-disable-next-line import/no-extraneous-dependencies
import 'server-only'
import { cache } from 'react'
import { import {
createDefaultMetadata, createDefaultMetadata,
createDefaultViewport, createDefaultViewport,
...@@ -417,7 +421,7 @@ async function resolveStaticMetadata( ...@@ -417,7 +421,7 @@ async function resolveStaticMetadata(
} }
// [layout.metadata, static files metadata] -> ... -> [page.metadata, static files metadata] // [layout.metadata, static files metadata] -> ... -> [page.metadata, static files metadata]
export async function collectMetadata({ async function collectMetadata({
tree, tree,
metadataItems, metadataItems,
errorMetadataItem, errorMetadataItem,
...@@ -477,32 +481,50 @@ export async function collectMetadata({ ...@@ -477,32 +481,50 @@ export async function collectMetadata({
} }
} }
export async function resolveMetadataItems({ const cachedResolveMetadataItems = cache(resolveMetadataItems)
tree, export { cachedResolveMetadataItems as resolveMetadataItems }
parentParams, async function resolveMetadataItems(
metadataItems, tree: LoaderTree,
errorMetadataItem, searchParams: Promise<ParsedUrlQuery>,
treePrefix = [], errorConvention: 'not-found' | undefined,
getDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams, createServerParamsForMetadata: CreateServerParamsForMetadata,
errorConvention, staticGenerationStore: StaticGenerationStore
createServerParamsForMetadata, ) {
staticGenerationStore, const parentParams = {}
}: { const metadataItems: MetadataItems = []
tree: LoaderTree const errorMetadataItem: MetadataItems[number] = [null, null, null]
parentParams: Params const treePrefix = undefined
metadataItems: MetadataItems return resolveMetadataItemsImpl(
errorMetadataItem: MetadataItems[number] metadataItems,
tree,
treePrefix,
parentParams,
searchParams,
errorConvention,
errorMetadataItem,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
)
}
async function resolveMetadataItemsImpl(
metadataItems: MetadataItems,
tree: LoaderTree,
/** Provided tree can be nested subtree, this argument says what is the path of such subtree */ /** Provided tree can be nested subtree, this argument says what is the path of such subtree */
treePrefix?: string[] treePrefix: undefined | string[],
getDynamicParamFromSegment: GetDynamicParamFromSegment parentParams: Params,
searchParams: ParsedUrlQuery searchParams: Promise<ParsedUrlQuery>,
errorConvention: 'not-found' | undefined errorConvention: 'not-found' | undefined,
createServerParamsForMetadata: CreateServerParamsForMetadata errorMetadataItem: MetadataItems[number],
getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore staticGenerationStore: StaticGenerationStore
}): Promise<MetadataItems> { ): Promise<MetadataItems> {
const [segment, parallelRoutes, { page }] = tree const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix = [...treePrefix, segment] const currentTreePrefix =
treePrefix && treePrefix.length ? [...treePrefix, segment] : [segment]
const isPage = typeof page !== 'undefined' const isPage = typeof page !== 'undefined'
// Handle dynamic segment params. // Handle dynamic segment params.
...@@ -549,18 +571,18 @@ export async function resolveMetadataItems({ ...@@ -549,18 +571,18 @@ export async function resolveMetadataItems({
for (const key in parallelRoutes) { for (const key in parallelRoutes) {
const childTree = parallelRoutes[key] const childTree = parallelRoutes[key]
await resolveMetadataItems({ await resolveMetadataItemsImpl(
tree: childTree,
metadataItems, metadataItems,
errorMetadataItem, childTree,
parentParams: currentParams, currentTreePrefix,
treePrefix: currentTreePrefix, currentParams,
searchParams, searchParams,
getDynamicParamFromSegment,
errorConvention, errorConvention,
errorMetadataItem,
getDynamicParamFromSegment,
createServerParamsForMetadata, createServerParamsForMetadata,
staticGenerationStore, staticGenerationStore
}) )
} }
if (Object.keys(parallelRoutes).length === 0 && errorConvention) { if (Object.keys(parallelRoutes).length === 0 && errorConvention) {
...@@ -892,51 +914,3 @@ export async function accumulateViewport( ...@@ -892,51 +914,3 @@ export async function accumulateViewport(
} }
return resolvedViewport return resolvedViewport
} }
export async function resolveMetadata({
tree,
parentParams,
metadataItems,
errorMetadataItem,
getDynamicParamFromSegment,
searchParams,
errorConvention,
metadataContext,
createServerParamsForMetadata,
staticGenerationStore,
}: {
tree: LoaderTree
parentParams: Params
metadataItems: MetadataItems
errorMetadataItem: MetadataItems[number]
/** Provided tree can be nested subtree, this argument says what is the path of such subtree */
treePrefix?: string[]
getDynamicParamFromSegment: GetDynamicParamFromSegment
searchParams: { [key: string]: any }
errorConvention: 'not-found' | undefined
metadataContext: MetadataContext
createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
}): Promise<[any, ResolvedMetadata, ResolvedViewport]> {
const resolvedMetadataItems = await resolveMetadataItems({
tree,
parentParams,
metadataItems,
errorMetadataItem,
getDynamicParamFromSegment,
searchParams,
errorConvention,
createServerParamsForMetadata,
staticGenerationStore,
})
let error
let metadata: ResolvedMetadata = createDefaultMetadata()
let viewport: ResolvedViewport = createDefaultViewport()
try {
viewport = await accumulateViewport(resolvedMetadataItems)
metadata = await accumulateMetadata(resolvedMetadataItems, metadataContext)
} catch (err: any) {
error = err
}
return [error, metadata, viewport]
}
...@@ -48,10 +48,9 @@ import { ...@@ -48,10 +48,9 @@ import {
RSC_HEADER, RSC_HEADER,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { import {
createMetadataComponents,
createTrackedMetadataContext, createTrackedMetadataContext,
createMetadataContext, createMetadataContext,
} from '../../lib/metadata/metadata' } from '../../lib/metadata/metadata-context'
import { withRequestStore } from '../async-storage/with-request-store' import { withRequestStore } from '../async-storage/with-request-store'
import { withStaticGenerationStore } from '../async-storage/with-static-generation-store' import { withStaticGenerationStore } from '../async-storage/with-static-generation-store'
import { isNotFoundError } from '../../client/components/not-found' import { isNotFoundError } from '../../client/components/not-found'
...@@ -389,6 +388,7 @@ async function generateDynamicRSCPayload( ...@@ -389,6 +388,7 @@ async function generateDynamicRSCPayload(
tree: loaderTree, tree: loaderTree,
createServerSearchParamsForMetadata, createServerSearchParamsForMetadata,
createServerParamsForMetadata, createServerParamsForMetadata,
createMetadataComponents,
}, },
getDynamicParamFromSegment, getDynamicParamFromSegment,
appUsingSizeAdjustment, appUsingSizeAdjustment,
...@@ -571,6 +571,7 @@ async function getRSCPayload( ...@@ -571,6 +571,7 @@ async function getRSCPayload(
GlobalError, GlobalError,
createServerSearchParamsForMetadata, createServerSearchParamsForMetadata,
createServerParamsForMetadata, createServerParamsForMetadata,
createMetadataComponents,
}, },
requestStore: { url }, requestStore: { url },
staticGenerationStore, staticGenerationStore,
...@@ -672,6 +673,7 @@ async function getErrorRSCPayload( ...@@ -672,6 +673,7 @@ async function getErrorRSCPayload(
GlobalError, GlobalError,
createServerSearchParamsForMetadata, createServerSearchParamsForMetadata,
createServerParamsForMetadata, createServerParamsForMetadata,
createMetadataComponents,
}, },
requestStore: { url }, requestStore: { url },
requestId, requestId,
......
...@@ -29,6 +29,7 @@ import { ...@@ -29,6 +29,7 @@ import {
} from '../request/params' } from '../request/params'
import * as serverHooks from '../../client/components/hooks-server-context' import * as serverHooks from '../../client/components/hooks-server-context'
import { NotFoundBoundary } from '../../client/components/not-found-boundary' import { NotFoundBoundary } from '../../client/components/not-found-boundary'
import { createMetadataComponents } from '../../lib/metadata/metadata'
import { patchFetch as _patchFetch } from '../lib/patch-fetch' import { patchFetch as _patchFetch } from '../lib/patch-fetch'
// not being used but needs to be included in the client manifest for /_not-found // not being used but needs to be included in the client manifest for /_not-found
import '../../client/components/error-boundary' import '../../client/components/error-boundary'
...@@ -69,4 +70,5 @@ export { ...@@ -69,4 +70,5 @@ export {
ClientSegmentRoot, ClientSegmentRoot,
NotFoundBoundary, NotFoundBoundary,
patchFetch, patchFetch,
createMetadataComponents,
} }
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