Unverified Commit bbeaf081 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update to leverage AsyncLocalStorage for app static handling (#40727)

Leverages `AsyncLocalStorage` when available for handling static generation context and falls back to requiring render to be isolated when `AsyncLocalStorage` is not available. 

Note: most changes are spacing so toggling to ignore spacing may make reviewing easier
parent 47195173
......@@ -33,7 +33,6 @@ export const CONTEXT_NAMES = {
HeadersContext: 'HeadersContext',
PreviewDataContext: 'PreviewDataContext',
CookiesContext: 'CookiesContext',
StaticGenerationContext: 'StaticGenerationContext',
FetchRevalidateContext: 'FetchRevalidateContext',
} as const
......@@ -42,7 +41,3 @@ export const PreviewDataContext = createContext(
CONTEXT_NAMES.PreviewDataContext
)
export const CookiesContext = createContext(CONTEXT_NAMES.CookiesContext)
export const StaticGenerationContext = createContext(
CONTEXT_NAMES.StaticGenerationContext,
{ isStaticGeneration: false }
)
import type { AsyncLocalStorage } from 'async_hooks'
import { useContext } from 'react'
import {
HeadersContext,
PreviewDataContext,
CookiesContext,
DynamicServerError,
StaticGenerationContext,
} from './hooks-server-context'
export function useTrackStaticGeneration() {
return useContext<
typeof import('./hooks-server-context').StaticGenerationContext
>(StaticGenerationContext)
export interface StaticGenerationStore {
inUse?: boolean
pathname?: string
revalidate?: number
fetchRevalidate?: number
isStaticGeneration?: boolean
}
export let staticGenerationAsyncStorage:
| AsyncLocalStorage<StaticGenerationStore>
| StaticGenerationStore = {}
if (process.env.NEXT_RUNTIME !== 'edge' && typeof window === 'undefined') {
staticGenerationAsyncStorage =
new (require('async_hooks').AsyncLocalStorage)()
}
function useStaticGenerationBailout(reason: string) {
const staticGenerationContext = useTrackStaticGeneration()
const staticGenerationStore =
staticGenerationAsyncStorage && 'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage?.getStore()
: staticGenerationAsyncStorage
if (staticGenerationContext.isStaticGeneration) {
if (staticGenerationStore?.isStaticGeneration) {
// TODO: honor the dynamic: 'force-static'
staticGenerationContext.revalidate = 0
if (staticGenerationStore) {
staticGenerationStore.revalidate = 0
}
throw new DynamicServerError(reason)
}
}
......
......@@ -28,6 +28,7 @@ import RenderResult from '../server/render-result'
import isError from '../lib/is-error'
import { addRequestMeta } from '../server/request-meta'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { REDIRECT_ERROR_CODE } from '../client/components/redirect'
loadRequireHook()
const envConfig = require('../shared/lib/runtime-config')
......@@ -419,7 +420,10 @@ export default async function exportPage({
)
}
} catch (err) {
if (!(err instanceof DynamicServerError)) {
if (
!(err instanceof DynamicServerError) &&
(err as any).code !== REDIRECT_ERROR_CODE
) {
throw err
}
}
......
......@@ -27,6 +27,7 @@ import {
import { FlushEffectsContext } from '../shared/lib/flush-effects'
import { stripInternalQueries } from './internal-utils'
import type { ComponentsType } from '../build/webpack/loaders/next-app-loader'
import type { UnwrapPromise } from '../lib/coalesced-function'
import { REDIRECT_ERROR_CODE } from '../client/components/redirect'
// this needs to be required lazily so that `next-server` can set
......@@ -109,26 +110,24 @@ function patchFetch() {
const { DynamicServerError } =
require('../client/components/hooks-server-context') as typeof import('../client/components/hooks-server-context')
const { useTrackStaticGeneration } =
const { staticGenerationAsyncStorage } =
require('../client/components/hooks-server') as typeof import('../client/components/hooks-server')
const origFetch = (global as any).fetch
;(global as any).fetch = async (init: any, opts: any) => {
let staticGenerationContext: ReturnType<typeof useTrackStaticGeneration> =
{}
try {
// eslint-disable-next-line react-hooks/rules-of-hooks
staticGenerationContext = useTrackStaticGeneration() || {}
} catch (_) {}
const staticGenerationStore =
'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage.getStore()
: staticGenerationAsyncStorage
const { isStaticGeneration, fetchRevalidate, pathname } =
staticGenerationContext
staticGenerationStore || {}
if (isStaticGeneration) {
if (staticGenerationStore && isStaticGeneration) {
if (opts && typeof opts === 'object') {
if (opts.cache === 'no-store') {
staticGenerationContext.revalidate = 0
staticGenerationStore.revalidate = 0
// TODO: ensure this error isn't logged to the user
// seems it's slipping through currently
throw new DynamicServerError(
......@@ -141,7 +140,7 @@ function patchFetch() {
(typeof fetchRevalidate === 'undefined' ||
opts.revalidate < fetchRevalidate)
) {
staticGenerationContext.fetchRevalidate = opts.revalidate
staticGenerationStore.fetchRevalidate = opts.revalidate
}
}
}
......@@ -505,6 +504,25 @@ export async function renderToHTMLOrFlight(
): Promise<RenderResult | null> {
patchFetch()
const { staticGenerationAsyncStorage } =
require('../client/components/hooks-server') as typeof import('../client/components/hooks-server')
if (
!('getStore' in staticGenerationAsyncStorage) &&
staticGenerationAsyncStorage.inUse
) {
throw new Error(
`Invariant: A separate worker must be used for each render when AsyncLocalStorage is not available`
)
}
// we wrap the render in an AsyncLocalStorage context
const wrappedRender = async () => {
const staticGenerationStore =
'getStore' in staticGenerationAsyncStorage
? staticGenerationAsyncStorage.getStore()
: staticGenerationAsyncStorage
const { CONTEXT_NAMES } =
require('../client/components/hooks-server-context') as typeof import('../client/components/hooks-server-context')
......@@ -594,18 +612,12 @@ export async function renderToHTMLOrFlight(
* It has to hold values that can't change while rendering from the common layout down.
* An example of this would be that `headers` are available but `searchParams` are not because that'd mean we have to render from the root layout down on all requests.
*/
const staticGenerationContext: {
revalidate?: undefined | number
isStaticGeneration: boolean
pathname: string
} = { isStaticGeneration, pathname }
const serverContexts: Array<[string, any]> = [
['WORKAROUND', null], // TODO-APP: First value has a bug currently where the value is not set on the second request: https://github.com/facebook/react/issues/24849
[CONTEXT_NAMES.HeadersContext, headers],
[CONTEXT_NAMES.CookiesContext, cookies],
[CONTEXT_NAMES.PreviewDataContext, previewData],
[CONTEXT_NAMES.StaticGenerationContext, staticGenerationContext],
]
type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath
......@@ -657,7 +669,11 @@ export async function renderToHTMLOrFlight(
// The value that is passed to user code.
value: value,
// The value that is rendered in the router tree.
treeSegment: [key, Array.isArray(value) ? value.join('/') : value, type],
treeSegment: [
key,
Array.isArray(value) ? value.join('/') : value,
type,
],
type: type,
}
}
......@@ -1212,9 +1228,9 @@ export async function renderToHTMLOrFlight(
serverComponentsRenderOpts.rscChunks
).toString()
;(renderOpts as any).revalidate =
typeof staticGenerationContext.revalidate === 'undefined'
typeof staticGenerationStore?.revalidate === 'undefined'
? defaultRevalidate
: staticGenerationContext.revalidate
: staticGenerationStore?.revalidate
return new RenderResult(staticHtml)
}
......@@ -1234,4 +1250,26 @@ export async function renderToHTMLOrFlight(
}
throw err
}
}
const initialStaticGenerationStore = {
isStaticGeneration,
inUse: true,
pathname,
}
if ('getStore' in staticGenerationAsyncStorage) {
return new Promise<UnwrapPromise<ReturnType<typeof renderToHTMLOrFlight>>>(
(resolve, reject) => {
staticGenerationAsyncStorage.run(initialStaticGenerationStore, () => {
wrappedRender().then(resolve).catch(reject)
})
}
)
} else {
Object.assign(staticGenerationAsyncStorage, initialStaticGenerationStore)
return wrappedRender().finally(() => {
staticGenerationAsyncStorage.inUse = false
})
}
}
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