Unverified Commit 852092f2 authored by Josh Story's avatar Josh Story Committed by GitHub

Update metadata ready tracking (#67929)

Refactors the `createMetadataComponents` function to convey readiness
via a promise `metadataReady` rather than a renderable component
`<MetadataOutlet>`.

I also moved the resolution out of the render and into the factory
function because we generally only want to do this resolution once and
later we may retry the RSC render and it is wasteful to recompute the
resolved value.

I am instrumenting the ready promise with `status` and `value` so that
in a future update React can unrwap the value synchronously. This isn't
very important right now but in the future we will want to take
advantage of it.
parent b4ec5acb
...@@ -28,10 +28,6 @@ import type { ...@@ -28,10 +28,6 @@ import type {
ResolvedMetadata, ResolvedMetadata,
ResolvedViewport, ResolvedViewport,
} from './types/metadata-interface' } from './types/metadata-interface'
import {
createDefaultMetadata,
createDefaultViewport,
} from './default-metadata'
import { isNotFoundError } from '../../client/components/not-found' import { isNotFoundError } from '../../client/components/not-found'
import type { MetadataContext } from './types/resolvers' import type { MetadataContext } from './types/resolvers'
...@@ -70,96 +66,142 @@ export function createMetadataComponents({ ...@@ -70,96 +66,142 @@ export function createMetadataComponents({
createDynamicallyTrackedSearchParams: ( createDynamicallyTrackedSearchParams: (
searchParams: ParsedUrlQuery searchParams: ParsedUrlQuery
) => ParsedUrlQuery ) => ParsedUrlQuery
}): [React.ComponentType, React.ComponentType] { }): [React.ComponentType, () => Promise<void>] {
let resolve: (value: Error | undefined) => void | undefined let currentMetadataReady:
// Only use promise.resolve here to avoid unhandled rejections | null
const metadataErrorResolving = new Promise<Error | undefined>((res) => { | (Promise<void> & {
resolve = res status?: string
}) value?: unknown
}) = null
async function MetadataTree() { async function MetadataTree() {
const defaultMetadata = createDefaultMetadata() const pendingMetadata = getResolvedMetadata(
const defaultViewport = createDefaultViewport() tree,
let metadata: ResolvedMetadata | undefined = defaultMetadata query,
let viewport: ResolvedViewport | undefined = defaultViewport getDynamicParamFromSegment,
let error: any metadataContext,
const errorMetadataItem: [null, null, null] = [null, null, null] createDynamicallyTrackedSearchParams,
const errorConvention = errorType === 'redirect' ? undefined : errorType errorType
const searchParams = createDynamicallyTrackedSearchParams(query) )
const [resolvedError, resolvedMetadata, resolvedViewport] =
await resolveMetadata({
tree,
parentParams: {},
metadataItems: [],
errorMetadataItem,
searchParams,
getDynamicParamFromSegment,
errorConvention,
metadataContext,
})
if (!resolvedError) {
viewport = resolvedViewport
metadata = resolvedMetadata
resolve(undefined)
} else {
error = resolvedError
// If a not-found error is triggered during metadata resolution, we want to capture the metadata
// for the not-found route instead of whatever triggered the error. For all error types, we resolve an
// error, which will cause the outlet to throw it so it'll be handled by an error boundary
// (either an actual error, or an internal error that renders UI such as the NotFoundBoundary).
if (!errorType && isNotFoundError(resolvedError)) {
const [notFoundMetadataError, notFoundMetadata, notFoundViewport] =
await resolveMetadata({
tree,
parentParams: {},
metadataItems: [],
errorMetadataItem,
searchParams,
getDynamicParamFromSegment,
errorConvention: 'not-found',
metadataContext,
})
viewport = notFoundViewport
metadata = notFoundMetadata
error = notFoundMetadataError || error
}
resolve(error)
}
const elements = MetaFilter([ // We construct this instrumented promise to allow React.use to synchronously unwrap
ViewportMeta({ viewport: viewport }), // it if it has already settled.
BasicMeta({ metadata }), const metadataReady: Promise<void> & { status: string; value: unknown } =
AlternatesMetadata({ alternates: metadata.alternates }), pendingMetadata.then(
ItunesMeta({ itunes: metadata.itunes }), ([error]) => {
FacebookMeta({ facebook: metadata.facebook }), if (error) {
FormatDetectionMeta({ formatDetection: metadata.formatDetection }), metadataReady.status = 'rejected'
VerificationMeta({ verification: metadata.verification }), metadataReady.value = error
AppleWebAppMeta({ appleWebApp: metadata.appleWebApp }), throw error
OpenGraphMetadata({ openGraph: metadata.openGraph }), }
TwitterMetadata({ twitter: metadata.twitter }), metadataReady.status = 'fulfilled'
AppLinksMeta({ appLinks: metadata.appLinks }), metadataReady.value = undefined
IconsMetadata({ icons: metadata.icons }), },
]) (error) => {
metadataReady.status = 'rejected'
metadataReady.value = error
throw error
}
) as Promise<void> & { status: string; value: unknown }
metadataReady.status = 'pending'
currentMetadataReady = metadataReady
if (appUsingSizeAdjustment) elements.push(<meta name="next-size-adjust" />) // We ignore any error from metadata here because it needs to be thrown from within the Page
// not where the metadata itself is actually rendered
const [, elements] = await pendingMetadata
return ( return (
<> <>
{elements.map((el, index) => { {elements.map((el, index) => {
return React.cloneElement(el as React.ReactElement, { key: index }) return React.cloneElement(el as React.ReactElement, { key: index })
})} })}
{appUsingSizeAdjustment ? <meta name="next-size-adjust" /> : null}
</> </>
) )
} }
async function MetadataOutlet() { function getMetadataReady() {
const error = await metadataErrorResolving return Promise.resolve().then(() => {
if (error) { if (currentMetadataReady) {
throw error return currentMetadataReady
}
throw new Error(
'getMetadataReady was called before MetadataTree rendered'
)
})
}
return [MetadataTree, getMetadataReady]
}
async function getResolvedMetadata(
tree: LoaderTree,
query: ParsedUrlQuery,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext,
createDynamicallyTrackedSearchParams: (
searchParams: ParsedUrlQuery
) => ParsedUrlQuery,
errorType?: 'not-found' | 'redirect'
): Promise<[any, Array<React.ReactNode>]> {
const errorMetadataItem: [null, null, null] = [null, null, null]
const errorConvention = errorType === 'redirect' ? undefined : errorType
const searchParams = createDynamicallyTrackedSearchParams(query)
const [error, metadata, viewport] = await resolveMetadata({
tree,
parentParams: {},
metadataItems: [],
errorMetadataItem,
searchParams,
getDynamicParamFromSegment,
errorConvention,
metadataContext,
})
if (!error) {
return [null, createMetadataElements(metadata, viewport)]
} else {
// If a not-found error is triggered during metadata resolution, we want to capture the metadata
// for the not-found route instead of whatever triggered the error. For all error types, we resolve an
// error, which will cause the outlet to throw it so it'll be handled by an error boundary
// (either an actual error, or an internal error that renders UI such as the NotFoundBoundary).
if (!errorType && isNotFoundError(error)) {
const [notFoundMetadataError, notFoundMetadata, notFoundViewport] =
await resolveMetadata({
tree,
parentParams: {},
metadataItems: [],
errorMetadataItem,
searchParams,
getDynamicParamFromSegment,
errorConvention: 'not-found',
metadataContext,
})
return [
notFoundMetadataError || error,
createMetadataElements(notFoundMetadata, notFoundViewport),
]
} }
return null return [error, []]
} }
}
return [MetadataTree, MetadataOutlet] function createMetadataElements(
metadata: ResolvedMetadata,
viewport: ResolvedViewport
) {
return MetaFilter([
ViewportMeta({ viewport: viewport }),
BasicMeta({ metadata }),
AlternatesMetadata({ alternates: metadata.alternates }),
ItunesMeta({ itunes: metadata.itunes }),
FacebookMeta({ facebook: metadata.facebook }),
FormatDetectionMeta({ formatDetection: metadata.formatDetection }),
VerificationMeta({ verification: metadata.verification }),
AppleWebAppMeta({ appleWebApp: metadata.appleWebApp }),
OpenGraphMetadata({ openGraph: metadata.openGraph }),
TwitterMetadata({ twitter: metadata.twitter }),
AppLinksMeta({ appLinks: metadata.appLinks }),
IconsMetadata({ icons: metadata.icons }),
])
} }
...@@ -350,7 +350,7 @@ async function generateDynamicRSCPayload( ...@@ -350,7 +350,7 @@ async function generateDynamicRSCPayload(
if (!options?.skipFlight) { if (!options?.skipFlight) {
const preloadCallbacks: PreloadCallbacks = [] const preloadCallbacks: PreloadCallbacks = []
const [MetadataTree, MetadataOutlet] = createMetadataComponents({ const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree: loaderTree, tree: loaderTree,
query, query,
metadataContext: createMetadataContext(url.pathname, ctx.renderOpts), metadataContext: createMetadataContext(url.pathname, ctx.renderOpts),
...@@ -379,7 +379,7 @@ async function generateDynamicRSCPayload( ...@@ -379,7 +379,7 @@ async function generateDynamicRSCPayload(
injectedFontPreloadTags: new Set(), injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: ctx.isNotFoundPath || options?.asNotFound, asNotFound: ctx.isNotFoundPath || options?.asNotFound,
metadataOutlet: <MetadataOutlet />, getMetadataReady,
preloadCallbacks, preloadCallbacks,
}) })
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
...@@ -486,7 +486,7 @@ async function getRSCPayload( ...@@ -486,7 +486,7 @@ async function getRSCPayload(
query query
) )
const [MetadataTree, MetadataOutlet] = createMetadataComponents({ const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree, tree,
errorType: asNotFound ? 'not-found' : undefined, errorType: asNotFound ? 'not-found' : undefined,
query, query,
...@@ -509,7 +509,7 @@ async function getRSCPayload( ...@@ -509,7 +509,7 @@ async function getRSCPayload(
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: asNotFound, asNotFound: asNotFound,
metadataOutlet: <MetadataOutlet />, getMetadataReady,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
}) })
......
...@@ -37,7 +37,7 @@ export function createComponentTree(props: { ...@@ -37,7 +37,7 @@ export function createComponentTree(props: {
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean asNotFound?: boolean
metadataOutlet?: React.ReactNode getMetadataReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
...@@ -67,7 +67,7 @@ async function createComponentTreeInternal({ ...@@ -67,7 +67,7 @@ async function createComponentTreeInternal({
injectedJS, injectedJS,
injectedFontPreloadTags, injectedFontPreloadTags,
asNotFound, asNotFound,
metadataOutlet, getMetadataReady,
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
...@@ -81,7 +81,7 @@ async function createComponentTreeInternal({ ...@@ -81,7 +81,7 @@ async function createComponentTreeInternal({
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean asNotFound?: boolean
metadataOutlet?: React.ReactNode getMetadataReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
...@@ -439,10 +439,12 @@ async function createComponentTreeInternal({ ...@@ -439,10 +439,12 @@ async function createComponentTreeInternal({
injectedJS: injectedJSWithCurrentLayout, injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
asNotFound, asNotFound,
// The metadataOutlet is responsible for throwing any errors that were caught during metadata resolution. // The metadataReady is used to trigger any errors that were caught during metadata resolution.
// We only want to render an outlet once per segment, as otherwise the error will be triggered // We only want to throw once per segment, as otherwise the error will be triggered
// multiple times causing an uncaught error. // multiple times causing an uncaught error.
metadataOutlet: isChildrenRouteKey ? metadataOutlet : undefined, getMetadataReady: isChildrenRouteKey
? getMetadataReady
: () => Promise.resolve(),
ctx, ctx,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
...@@ -590,7 +592,7 @@ async function createComponentTreeInternal({ ...@@ -590,7 +592,7 @@ async function createComponentTreeInternal({
props.searchParams = createUntrackedSearchParams(query) props.searchParams = createUntrackedSearchParams(query)
segmentElement = ( segmentElement = (
<> <>
{metadataOutlet} <MetadataOutlet getReady={getMetadataReady} />
<ClientPageRoot props={props} Component={Component} /> <ClientPageRoot props={props} Component={Component} />
{layerAssets} {layerAssets}
</> </>
...@@ -601,7 +603,7 @@ async function createComponentTreeInternal({ ...@@ -601,7 +603,7 @@ async function createComponentTreeInternal({
props.searchParams = createDynamicallyTrackedSearchParams(query) props.searchParams = createDynamicallyTrackedSearchParams(query)
segmentElement = ( segmentElement = (
<> <>
{metadataOutlet} <MetadataOutlet getReady={getMetadataReady} />
<Component {...props} /> <Component {...props} />
{layerAssets} {layerAssets}
</> </>
...@@ -635,3 +637,21 @@ async function createComponentTreeInternal({ ...@@ -635,3 +637,21 @@ async function createComponentTreeInternal({
loadingData, loadingData,
] ]
} }
async function MetadataOutlet({
getReady,
}: {
getReady: () => Promise<void> & { status?: string; value?: unknown }
}) {
const ready = getReady()
// We actually expect this to be an instrumented promise and once this file is properly
// moved to the RSC module graph we can switch to using React.use for this synchronous unwrapping.
// The synchronous unwrapping will become important with dynamic IO since we want to resolve metadata
// before anything dynamic can be triggered
if (ready.status === 'rejected') {
throw ready.value
} else if (ready.status !== 'fulfilled') {
await ready
}
return null
}
...@@ -38,7 +38,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -38,7 +38,7 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded, rootLayoutIncluded,
asNotFound, asNotFound,
metadataOutlet, getMetadataReady,
ctx, ctx,
preloadCallbacks, preloadCallbacks,
}: { }: {
...@@ -54,7 +54,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -54,7 +54,7 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
asNotFound?: boolean asNotFound?: boolean
metadataOutlet: React.ReactNode getMetadataReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
}): Promise<FlightDataPath[]> { }): Promise<FlightDataPath[]> {
...@@ -154,7 +154,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -154,7 +154,7 @@ export async function walkTreeWithFlightRouterState({
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too. // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded, rootLayoutIncluded,
asNotFound, asNotFound,
metadataOutlet, getMetadataReady,
preloadCallbacks, preloadCallbacks,
} }
) )
...@@ -215,7 +215,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -215,7 +215,7 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
asNotFound, asNotFound,
metadataOutlet, getMetadataReady,
preloadCallbacks, preloadCallbacks,
}) })
......
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