Unverified Commit 0c923c33 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Async Storage Cleanup (#46586)

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
-->

Cleaned up duplicate code around async storage. Also fixed some types:

- Changed `supportsDynamicHTML: boolean`
- Changed `revalidate: false | number | undefined`
parent 9fdddb36
...@@ -30,7 +30,7 @@ export function getHandle({ page, mod }: any) { ...@@ -30,7 +30,7 @@ export function getHandle({ page, mod }: any) {
extendedReq, extendedReq,
extendedRes, extendedRes,
// TODO: pass incrementalCache here // TODO: pass incrementalCache here
{}, { supportsDynamicHTML: true },
request request
) )
......
...@@ -8,7 +8,7 @@ export interface StaticGenerationStore { ...@@ -8,7 +8,7 @@ export interface StaticGenerationStore {
readonly isRevalidate?: boolean readonly isRevalidate?: boolean
forceDynamic?: boolean forceDynamic?: boolean
revalidate?: boolean | number revalidate?: false | number
forceStatic?: boolean forceStatic?: boolean
dynamicShouldError?: boolean dynamicShouldError?: boolean
pendingRevalidates?: Promise<any>[] pendingRevalidates?: Promise<any>[]
......
...@@ -45,8 +45,8 @@ import type { StaticGenerationAsyncStorage } from '../client/components/static-g ...@@ -45,8 +45,8 @@ import type { StaticGenerationAsyncStorage } from '../client/components/static-g
import type { RequestAsyncStorage } from '../client/components/request-async-storage' import type { RequestAsyncStorage } from '../client/components/request-async-storage'
import { formatServerError } from '../lib/format-server-error' import { formatServerError } from '../lib/format-server-error'
import { MetadataTree } from '../lib/metadata/metadata' import { MetadataTree } from '../lib/metadata/metadata'
import { runWithRequestAsyncStorage } from './run-with-request-async-storage' import { RequestAsyncStorageWrapper } from './async-storage/request-async-storage-wrapper'
import { runWithStaticGenerationAsyncStorage } from './run-with-static-generation-async-storage' import { StaticGenerationAsyncStorageWrapper } from './async-storage/static-generation-async-storage-wrapper'
import { collectMetadata } from '../lib/metadata/resolve-metadata' import { collectMetadata } from '../lib/metadata/resolve-metadata'
import type { MetadataItems } from '../lib/metadata/resolve-metadata' import type { MetadataItems } from '../lib/metadata/resolve-metadata'
import { isClientReference } from '../build/is-client-reference' import { isClientReference } from '../build/is-client-reference'
...@@ -184,7 +184,7 @@ export type RenderOptsPartial = { ...@@ -184,7 +184,7 @@ export type RenderOptsPartial = {
dev?: boolean dev?: boolean
serverComponentManifest?: FlightManifest serverComponentManifest?: FlightManifest
serverCSSManifest?: FlightCSSManifest serverCSSManifest?: FlightCSSManifest
supportsDynamicHTML?: boolean supportsDynamicHTML: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
assetPrefix?: string assetPrefix?: string
...@@ -2001,11 +2001,11 @@ export async function renderToHTMLOrFlight( ...@@ -2001,11 +2001,11 @@ export async function renderToHTMLOrFlight(
return renderResult return renderResult
} }
return runWithRequestAsyncStorage( return RequestAsyncStorageWrapper.wrap(
requestAsyncStorage, requestAsyncStorage,
{ req, res, renderOpts }, { req, res, renderOpts },
() => () =>
runWithStaticGenerationAsyncStorage( StaticGenerationAsyncStorageWrapper.wrap(
staticGenerationAsyncStorage, staticGenerationAsyncStorage,
{ pathname, renderOpts }, { pathname, renderOpts },
() => wrappedRender() () => wrappedRender()
......
...@@ -7,7 +7,7 @@ export type RequestContext = { ...@@ -7,7 +7,7 @@ export type RequestContext = {
pathname: string pathname: string
renderOpts: { renderOpts: {
incrementalCache?: IncrementalCache incrementalCache?: IncrementalCache
supportsDynamicHTML?: boolean supportsDynamicHTML: boolean
isRevalidate?: boolean isRevalidate?: boolean
isBot?: boolean isBot?: boolean
} }
...@@ -45,11 +45,8 @@ export class StaticGenerationAsyncStorageWrapper ...@@ -45,11 +45,8 @@ export class StaticGenerationAsyncStorageWrapper
* These rules help ensure that other existing features like request caching, * These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended. * coalescing, and ISR continue working as intended.
*/ */
const supportsDynamicHTML = const isStaticGeneration =
typeof renderOpts.supportsDynamicHTML !== 'boolean' || !renderOpts.supportsDynamicHTML && !renderOpts.isBot
renderOpts.supportsDynamicHTML
const isStaticGeneration = !supportsDynamicHTML && !renderOpts.isBot
const store: StaticGenerationStore = { const store: StaticGenerationStore = {
isStaticGeneration, isStaticGeneration,
......
...@@ -93,7 +93,7 @@ export type AppRouteModule = { ...@@ -93,7 +93,7 @@ export type AppRouteModule = {
export type StaticGenerationContext = { export type StaticGenerationContext = {
incrementalCache?: IncrementalCache incrementalCache?: IncrementalCache
supportsDynamicHTML?: boolean supportsDynamicHTML: boolean
} }
/** /**
...@@ -309,7 +309,9 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -309,7 +309,9 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
staticGenerationAsyncStorage, staticGenerationAsyncStorage,
{ {
pathname: definition.pathname, pathname: definition.pathname,
renderOpts: context || {}, renderOpts: context ?? {
supportsDynamicHTML: false,
},
}, },
() => { () => {
const _req = (request ? request : wrapRequest(req)) as NextRequest const _req = (request ? request : wrapRequest(req)) as NextRequest
...@@ -317,7 +319,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -317,7 +319,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
// We can currently only statically optimize if only GET/HEAD // We can currently only statically optimize if only GET/HEAD
// are used as a Prerender can't be used conditionally based // are used as a Prerender can't be used conditionally based
// on the method currently // on the method currently
const nonStaticHandlers = [ const nonStaticHandlers: ReadonlyArray<HTTP_METHOD> = [
'OPTIONS', 'OPTIONS',
'POST', 'POST',
'PUT', 'PUT',
...@@ -325,7 +327,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -325,7 +327,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
'PATCH', 'PATCH',
] ]
const usedNonStaticHandlers = nonStaticHandlers.filter( const usedNonStaticHandlers = nonStaticHandlers.filter(
(name) => !!(module.handlers as any)[name] (name) => name in module.handlers
) )
if (usedNonStaticHandlers.length > 0) { if (usedNonStaticHandlers.length > 0) {
......
...@@ -254,7 +254,7 @@ export type RenderOptsPartial = { ...@@ -254,7 +254,7 @@ export type RenderOptsPartial = {
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: DomainLocale[]
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
supportsDynamicHTML?: boolean supportsDynamicHTML: boolean
isBot?: boolean isBot?: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
......
import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'
import type { PreviewData } from 'next/types'
import { FLIGHT_PARAMETERS } from '../client/components/app-router-headers'
import type {
RequestStore,
RequestAsyncStorage,
} from '../client/components/request-async-storage'
import {
ReadonlyHeaders,
ReadonlyRequestCookies,
type RenderOpts,
} from './app-render'
function headersWithoutFlight(headers: IncomingHttpHeaders) {
const newHeaders = { ...headers }
for (const param of FLIGHT_PARAMETERS) {
delete newHeaders[param.toString().toLowerCase()]
}
return newHeaders
}
type RunWithRequestAsyncStorageContext = {
req: IncomingMessage
res: ServerResponse
renderOpts?: RenderOpts
}
export function runWithRequestAsyncStorage<Result>(
requestAsyncStorage: RequestAsyncStorage,
{ req, res, renderOpts }: RunWithRequestAsyncStorageContext,
callback: () => Promise<Result>
): Promise<Result> {
const tryGetPreviewData =
process.env.NEXT_RUNTIME === 'edge'
? () => false
: require('./api-utils/node').tryGetPreviewData
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
const previewData: PreviewData = renderOpts
? // TODO: investigate why previewProps isn't on RenderOpts
tryGetPreviewData(req, res, (renderOpts as any).previewProps)
: false
let cachedHeadersInstance: ReadonlyHeaders
let cachedCookiesInstance: ReadonlyRequestCookies
const store: RequestStore = {
get headers() {
if (!cachedHeadersInstance) {
cachedHeadersInstance = new ReadonlyHeaders(
headersWithoutFlight(req.headers)
)
}
return cachedHeadersInstance
},
get cookies() {
if (!cachedCookiesInstance) {
cachedCookiesInstance = new ReadonlyRequestCookies({
headers: {
get: (key) => {
if (key !== 'cookie') {
throw new Error('Only cookie header is supported')
}
return req.headers.cookie
},
},
})
}
return cachedCookiesInstance
},
previewData,
}
return requestAsyncStorage.run(store, callback)
}
import type {
StaticGenerationStore,
StaticGenerationAsyncStorage,
} from '../client/components/static-generation-async-storage'
import type { RenderOpts } from './app-render'
type RunWithStaticGenerationAsyncStorageContext = {
pathname: string
renderOpts: RenderOpts
}
export function runWithStaticGenerationAsyncStorage<Result>(
staticGenerationAsyncStorage: StaticGenerationAsyncStorage,
{ pathname, renderOpts }: RunWithStaticGenerationAsyncStorageContext,
callback: () => Promise<Result>
): Promise<Result> {
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const isStaticGeneration =
renderOpts.supportsDynamicHTML !== true && !renderOpts.isBot
const store: StaticGenerationStore = {
isStaticGeneration,
pathname,
incrementalCache: renderOpts.incrementalCache,
isRevalidate: renderOpts.isRevalidate,
}
return staticGenerationAsyncStorage.run(store, callback)
}
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