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) {
extendedReq,
extendedRes,
// TODO: pass incrementalCache here
{},
{ supportsDynamicHTML: true },
request
)
......
......@@ -8,7 +8,7 @@ export interface StaticGenerationStore {
readonly isRevalidate?: boolean
forceDynamic?: boolean
revalidate?: boolean | number
revalidate?: false | number
forceStatic?: boolean
dynamicShouldError?: boolean
pendingRevalidates?: Promise<any>[]
......
......@@ -45,8 +45,8 @@ import type { StaticGenerationAsyncStorage } from '../client/components/static-g
import type { RequestAsyncStorage } from '../client/components/request-async-storage'
import { formatServerError } from '../lib/format-server-error'
import { MetadataTree } from '../lib/metadata/metadata'
import { runWithRequestAsyncStorage } from './run-with-request-async-storage'
import { runWithStaticGenerationAsyncStorage } from './run-with-static-generation-async-storage'
import { RequestAsyncStorageWrapper } from './async-storage/request-async-storage-wrapper'
import { StaticGenerationAsyncStorageWrapper } from './async-storage/static-generation-async-storage-wrapper'
import { collectMetadata } from '../lib/metadata/resolve-metadata'
import type { MetadataItems } from '../lib/metadata/resolve-metadata'
import { isClientReference } from '../build/is-client-reference'
......@@ -184,7 +184,7 @@ export type RenderOptsPartial = {
dev?: boolean
serverComponentManifest?: FlightManifest
serverCSSManifest?: FlightCSSManifest
supportsDynamicHTML?: boolean
supportsDynamicHTML: boolean
runtime?: ServerRuntime
serverComponents?: boolean
assetPrefix?: string
......@@ -2001,11 +2001,11 @@ export async function renderToHTMLOrFlight(
return renderResult
}
return runWithRequestAsyncStorage(
return RequestAsyncStorageWrapper.wrap(
requestAsyncStorage,
{ req, res, renderOpts },
() =>
runWithStaticGenerationAsyncStorage(
StaticGenerationAsyncStorageWrapper.wrap(
staticGenerationAsyncStorage,
{ pathname, renderOpts },
() => wrappedRender()
......
......@@ -7,7 +7,7 @@ export type RequestContext = {
pathname: string
renderOpts: {
incrementalCache?: IncrementalCache
supportsDynamicHTML?: boolean
supportsDynamicHTML: boolean
isRevalidate?: boolean
isBot?: boolean
}
......@@ -45,11 +45,8 @@ export class StaticGenerationAsyncStorageWrapper
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const supportsDynamicHTML =
typeof renderOpts.supportsDynamicHTML !== 'boolean' ||
renderOpts.supportsDynamicHTML
const isStaticGeneration = !supportsDynamicHTML && !renderOpts.isBot
const isStaticGeneration =
!renderOpts.supportsDynamicHTML && !renderOpts.isBot
const store: StaticGenerationStore = {
isStaticGeneration,
......
......@@ -93,7 +93,7 @@ export type AppRouteModule = {
export type StaticGenerationContext = {
incrementalCache?: IncrementalCache
supportsDynamicHTML?: boolean
supportsDynamicHTML: boolean
}
/**
......@@ -309,7 +309,9 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
staticGenerationAsyncStorage,
{
pathname: definition.pathname,
renderOpts: context || {},
renderOpts: context ?? {
supportsDynamicHTML: false,
},
},
() => {
const _req = (request ? request : wrapRequest(req)) as NextRequest
......@@ -317,7 +319,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
// We can currently only statically optimize if only GET/HEAD
// are used as a Prerender can't be used conditionally based
// on the method currently
const nonStaticHandlers = [
const nonStaticHandlers: ReadonlyArray<HTTP_METHOD> = [
'OPTIONS',
'POST',
'PUT',
......@@ -325,7 +327,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
'PATCH',
]
const usedNonStaticHandlers = nonStaticHandlers.filter(
(name) => !!(module.handlers as any)[name]
(name) => name in module.handlers
)
if (usedNonStaticHandlers.length > 0) {
......
......@@ -254,7 +254,7 @@ export type RenderOptsPartial = {
defaultLocale?: string
domainLocales?: DomainLocale[]
disableOptimizedLoading?: boolean
supportsDynamicHTML?: boolean
supportsDynamicHTML: boolean
isBot?: boolean
runtime?: ServerRuntime
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