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 {
ResolvedMetadata,
ResolvedViewport,
} from './types/metadata-interface'
import {
createDefaultMetadata,
createDefaultViewport,
} from './default-metadata'
import { isNotFoundError } from '../../client/components/not-found'
import type { MetadataContext } from './types/resolvers'
......@@ -70,96 +66,142 @@ export function createMetadataComponents({
createDynamicallyTrackedSearchParams: (
searchParams: ParsedUrlQuery
) => ParsedUrlQuery
}): [React.ComponentType, React.ComponentType] {
let resolve: (value: Error | undefined) => void | undefined
// Only use promise.resolve here to avoid unhandled rejections
const metadataErrorResolving = new Promise<Error | undefined>((res) => {
resolve = res
})
}): [React.ComponentType, () => Promise<void>] {
let currentMetadataReady:
| null
| (Promise<void> & {
status?: string
value?: unknown
}) = null
async function MetadataTree() {
const defaultMetadata = createDefaultMetadata()
const defaultViewport = createDefaultViewport()
let metadata: ResolvedMetadata | undefined = defaultMetadata
let viewport: ResolvedViewport | undefined = defaultViewport
let error: any
const errorMetadataItem: [null, null, null] = [null, null, null]
const errorConvention = errorType === 'redirect' ? undefined : 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 pendingMetadata = getResolvedMetadata(
tree,
query,
getDynamicParamFromSegment,
metadataContext,
createDynamicallyTrackedSearchParams,
errorType
)
const elements = 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 }),
])
// We construct this instrumented promise to allow React.use to synchronously unwrap
// it if it has already settled.
const metadataReady: Promise<void> & { status: string; value: unknown } =
pendingMetadata.then(
([error]) => {
if (error) {
metadataReady.status = 'rejected'
metadataReady.value = error
throw error
}
metadataReady.status = 'fulfilled'
metadataReady.value = undefined
},
(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 (
<>
{elements.map((el, index) => {
return React.cloneElement(el as React.ReactElement, { key: index })
})}
{appUsingSizeAdjustment ? <meta name="next-size-adjust" /> : null}
</>
)
}
async function MetadataOutlet() {
const error = await metadataErrorResolving
if (error) {
throw error
function getMetadataReady() {
return Promise.resolve().then(() => {
if (currentMetadataReady) {
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(
if (!options?.skipFlight) {
const preloadCallbacks: PreloadCallbacks = []
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree: loaderTree,
query,
metadataContext: createMetadataContext(url.pathname, ctx.renderOpts),
......@@ -379,7 +379,7 @@ async function generateDynamicRSCPayload(
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
asNotFound: ctx.isNotFoundPath || options?.asNotFound,
metadataOutlet: <MetadataOutlet />,
getMetadataReady,
preloadCallbacks,
})
).map((path) => path.slice(1)) // remove the '' (root) segment
......@@ -486,7 +486,7 @@ async function getRSCPayload(
query
)
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree,
errorType: asNotFound ? 'not-found' : undefined,
query,
......@@ -509,7 +509,7 @@ async function getRSCPayload(
injectedFontPreloadTags,
rootLayoutIncluded: false,
asNotFound: asNotFound,
metadataOutlet: <MetadataOutlet />,
getMetadataReady,
missingSlots,
preloadCallbacks,
})
......
......@@ -37,7 +37,7 @@ export function createComponentTree(props: {
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
asNotFound?: boolean
metadataOutlet?: React.ReactNode
getMetadataReady: () => Promise<void>
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
......@@ -67,7 +67,7 @@ async function createComponentTreeInternal({
injectedJS,
injectedFontPreloadTags,
asNotFound,
metadataOutlet,
getMetadataReady,
ctx,
missingSlots,
preloadCallbacks,
......@@ -81,7 +81,7 @@ async function createComponentTreeInternal({
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
asNotFound?: boolean
metadataOutlet?: React.ReactNode
getMetadataReady: () => Promise<void>
ctx: AppRenderContext
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
......@@ -439,10 +439,12 @@ async function createComponentTreeInternal({
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
asNotFound,
// The metadataOutlet is responsible for throwing 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
// The metadataReady is used to trigger any errors that were caught during metadata resolution.
// We only want to throw once per segment, as otherwise the error will be triggered
// multiple times causing an uncaught error.
metadataOutlet: isChildrenRouteKey ? metadataOutlet : undefined,
getMetadataReady: isChildrenRouteKey
? getMetadataReady
: () => Promise.resolve(),
ctx,
missingSlots,
preloadCallbacks,
......@@ -590,7 +592,7 @@ async function createComponentTreeInternal({
props.searchParams = createUntrackedSearchParams(query)
segmentElement = (
<>
{metadataOutlet}
<MetadataOutlet getReady={getMetadataReady} />
<ClientPageRoot props={props} Component={Component} />
{layerAssets}
</>
......@@ -601,7 +603,7 @@ async function createComponentTreeInternal({
props.searchParams = createDynamicallyTrackedSearchParams(query)
segmentElement = (
<>
{metadataOutlet}
<MetadataOutlet getReady={getMetadataReady} />
<Component {...props} />
{layerAssets}
</>
......@@ -635,3 +637,21 @@ async function createComponentTreeInternal({
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({
injectedFontPreloadTags,
rootLayoutIncluded,
asNotFound,
metadataOutlet,
getMetadataReady,
ctx,
preloadCallbacks,
}: {
......@@ -54,7 +54,7 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean
asNotFound?: boolean
metadataOutlet: React.ReactNode
getMetadataReady: () => Promise<void>
ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks
}): Promise<FlightDataPath[]> {
......@@ -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.
rootLayoutIncluded,
asNotFound,
metadataOutlet,
getMetadataReady,
preloadCallbacks,
}
)
......@@ -215,7 +215,7 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
asNotFound,
metadataOutlet,
getMetadataReady,
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