Unverified Commit 799a05ce authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Support preferredRegion and Support runtime/preferredRegion on layouts (#48959)

### What?

Implements resolving of `runtime` and `preferredRegion` in layouts. It
will resolve from the root layout down, each layout can override
`runtime` or `preferredRegion`.

```
app
├── layout.js -> export const runtime = 'edge'
├── page.js -> Edge runtime
└── dashboard
    ├── page.js -> Edge runtime
    └── settings
        ├── layout.js -> export const runtime = 'nodejs'
        └── page.js -> Node.js runtime
```

Adds support for `preferredRegion`. This is similar to `export const
config = { region: ['sfo1'] }` in `pages`.

However, there is a difference. It supports `export const
preferredRegion = 'home'` and `export const preferredRegion = 'edge'`.
`home` refers to the configured default region on your deployment
platform and `edge` refers to "all regions".

### How?

I've implemented a temporary resolving in `entries.ts`.
`preferredRegion` is tracked through the entry module in webpack which
is why it's added to all the loaders that create an entry module, this
prevents having to resolve/parse again later on.

Fixes NEXT-880
Fixes NEXT-1064
Fixes #48905
Closes #48933
parent 7bfd5829
......@@ -35,6 +35,7 @@ export interface MiddlewareMatcher {
export interface PageStaticInfo {
runtime?: ServerRuntime
preferredRegion?: string | string[]
ssg?: boolean
ssr?: boolean
rsc?: RSCModuleType
......@@ -81,10 +82,12 @@ function checkExports(swcAST: any): {
ssr: boolean
ssg: boolean
runtime?: string
preferredRegion?: string | string[]
} {
if (Array.isArray(swcAST?.body)) {
try {
let runtime: string | undefined
let preferredRegion: string | string[] | undefined
let ssr: boolean = false
let ssg: boolean = false
......@@ -97,6 +100,22 @@ function checkExports(swcAST: any): {
if (declaration.id.value === 'runtime') {
runtime = declaration.init.value
}
if (declaration.id.value === 'preferredRegion') {
if (declaration.init.type === 'ArrayExpression') {
const elements: string[] = []
for (const element of declaration.init.elements) {
const { expression } = element
if (expression.type !== 'StringLiteral') {
continue
}
elements.push(expression.value)
}
preferredRegion = elements
} else {
preferredRegion = declaration.init.value
}
}
}
}
......@@ -137,7 +156,7 @@ function checkExports(swcAST: any): {
}
}
return { ssr, ssg, runtime }
return { ssr, ssg, runtime, preferredRegion }
} catch (err) {}
}
......@@ -322,12 +341,12 @@ export async function getPageStaticInfo(params: {
const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || ''
if (
/runtime|getStaticProps|getServerSideProps|export const config/.test(
/runtime|preferredRegion|getStaticProps|getServerSideProps|export const config/.test(
fileContent
)
) {
const swcAST = await parseModule(pageFilePath, fileContent)
const { ssg, ssr, runtime } = checkExports(swcAST)
const { ssg, ssr, runtime, preferredRegion } = checkExports(swcAST)
const rsc = getRSCModuleInformation(fileContent).type
// default / failsafe value for config
......@@ -420,6 +439,7 @@ export async function getPageStaticInfo(params: {
rsc,
...(middlewareConfig && { middleware: middlewareConfig }),
...(resolvedRuntime && { runtime: resolvedRuntime }),
preferredRegion,
}
}
......
......@@ -7,12 +7,13 @@ import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type {
MiddlewareConfig,
MiddlewareMatcher,
PageStaticInfo,
} from './analysis/get-page-static-info'
import type { LoadedEnvFiles } from '@next/env'
import type { AppLoaderOptions } from './webpack/loaders/next-app-loader'
import chalk from 'next/dist/compiled/chalk'
import { posix, join } from 'path'
import { posix, join, dirname } from 'path'
import { stringify } from 'querystring'
import {
PAGES_DIR_ALIAS,
......@@ -50,6 +51,83 @@ import { encodeMatchers } from './webpack/loaders/next-middleware-loader'
import { EdgeFunctionLoaderOptions } from './webpack/loaders/next-edge-function-loader'
import { isAppRouteRoute } from '../lib/is-app-route-route'
import { normalizeMetadataRoute } from '../lib/metadata/get-metadata-route'
import { fileExists } from '../lib/file-exists'
export async function getStaticInfoIncludingLayouts({
isInsideAppDir,
pageExtensions,
pageFilePath,
appDir,
config,
isDev,
page,
}: {
isInsideAppDir: boolean
pageExtensions: string[]
pageFilePath: string
appDir: string | undefined
config: NextConfigComplete
isDev: boolean | undefined
page: string
}): Promise<PageStaticInfo> {
const pageStaticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath,
isDev,
page,
pageType: isInsideAppDir ? 'app' : 'pages',
})
const staticInfo: PageStaticInfo = isInsideAppDir
? {
// TODO-APP: Remove the rsc key altogether. It's no longer required.
rsc: 'server',
}
: pageStaticInfo
if (isInsideAppDir) {
const layoutFiles = []
const potentialLayoutFiles = pageExtensions.map((ext) => 'layout.' + ext)
let dir = dirname(pageFilePath)
while (dir !== appDir) {
for (const potentialLayoutFile of potentialLayoutFiles) {
const layoutFile = join(dir, potentialLayoutFile)
if (!(await fileExists(layoutFile))) {
continue
}
layoutFiles.unshift(layoutFile)
}
// Walk up the directory tree
dir = join(dir, '..')
}
for (const layoutFile of layoutFiles) {
const layoutStaticInfo = await getPageStaticInfo({
nextConfig: config,
pageFilePath: layoutFile,
isDev,
page,
pageType: isInsideAppDir ? 'app' : 'pages',
})
// Only runtime is relevant here.
if (layoutStaticInfo.runtime) {
staticInfo.runtime = layoutStaticInfo.runtime
}
if (layoutStaticInfo.preferredRegion) {
staticInfo.preferredRegion = layoutStaticInfo.preferredRegion
}
}
if (pageStaticInfo.runtime) {
staticInfo.runtime = pageStaticInfo.runtime
}
if (pageStaticInfo.preferredRegion) {
staticInfo.preferredRegion = pageStaticInfo.preferredRegion
}
}
return staticInfo
}
type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never
......@@ -204,6 +282,7 @@ export function getEdgeServerEntry(opts: {
pagesType: 'app' | 'pages' | 'root'
appDirLoader?: string
hasInstrumentationHook?: boolean
preferredRegion: string | string[] | undefined
}) {
if (
opts.pagesType === 'app' &&
......@@ -215,6 +294,7 @@ export function getEdgeServerEntry(opts: {
page: opts.page,
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
nextConfigOutput: opts.config.output,
preferredRegion: opts.preferredRegion,
}
return {
......@@ -240,6 +320,7 @@ export function getEdgeServerEntry(opts: {
absolutePagePath: opts.absolutePagePath,
page: opts.page,
rootDir: opts.rootDir,
preferredRegion: opts.preferredRegion,
}
return `next-edge-function-loader?${stringify(loaderParams)}!`
......@@ -268,6 +349,7 @@ export function getEdgeServerEntry(opts: {
sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm,
incrementalCacheHandlerPath:
opts.config.experimental.incrementalCacheHandlerPath,
preferredRegion: opts.preferredRegion,
}
return {
......@@ -426,12 +508,14 @@ export async function createEntrypoints(
(absolutePagePath.startsWith(APP_DIR_ALIAS) ||
absolutePagePath.startsWith(appDir))
const staticInfo = await getPageStaticInfo({
nextConfig: config,
const staticInfo: PageStaticInfo = await getStaticInfoIncludingLayouts({
isInsideAppDir,
pageExtensions,
pageFilePath,
appDir,
config,
isDev,
page,
pageType: isInsideAppDir ? 'app' : 'pages',
})
const isServerComponent =
......@@ -470,6 +554,7 @@ export async function createEntrypoints(
pageExtensions,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
preferredRegion: staticInfo.preferredRegion,
})
} else {
if (isInstrumentationHookFile(page) && pagesType === 'root') {
......@@ -496,6 +581,9 @@ export async function createEntrypoints(
pageExtensions,
assetPrefix: config.assetPrefix,
nextConfigOutput: config.output,
// This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead.
// Still passing it here for consistency.
preferredRegion: staticInfo.preferredRegion,
}).import
}
const normalizedServerBundlePath =
......@@ -513,6 +601,7 @@ export async function createEntrypoints(
middleware: staticInfo?.middleware,
pagesType,
appDirLoader,
preferredRegion: staticInfo.preferredRegion,
})
},
})
......
......@@ -36,6 +36,7 @@ export interface RSCMeta {
export interface RouteMeta {
page: string
absolutePagePath: string
preferredRegion: string | string[] | undefined
}
export interface EdgeMiddlewareMeta {
......
......@@ -27,6 +27,7 @@ export type AppLoaderOptions = {
pagePath: string
appDir: string
appPaths: readonly string[] | null
preferredRegion: string | string[] | undefined
pageExtensions: string[]
assetPrefix: string
rootDir?: string
......@@ -421,6 +422,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
tsconfigPath,
isDev,
nextConfigOutput,
preferredRegion,
} = loaderOptions
const buildInfo = getModuleBuildInfo((this as any)._module)
......@@ -428,6 +430,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
buildInfo.route = {
page,
absolutePagePath: createAbsolutePath(appDir, pagePath),
preferredRegion,
}
const extensions = pageExtensions.map((extension) => `.${extension}`)
......
......@@ -7,6 +7,7 @@ export type EdgeAppRouteLoaderQuery = {
absolutePagePath: string
page: string
appDirLoader: string
preferredRegion: string | string[] | undefined
nextConfigOutput: NextConfig['output']
}
......@@ -15,6 +16,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
const {
page,
absolutePagePath,
preferredRegion,
appDirLoader: appDirLoaderBase64 = '',
} = this.getOptions()
......@@ -33,6 +35,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
}
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
......
import type webpack from 'webpack'
import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request'
......@@ -5,19 +6,30 @@ export type EdgeFunctionLoaderOptions = {
absolutePagePath: string
page: string
rootDir: string
preferredRegion: string | string[] | undefined
}
export default function middlewareLoader(this: any) {
const { absolutePagePath, page, rootDir }: EdgeFunctionLoaderOptions =
this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeApiFunction = {
page: page || '/',
}
buildInfo.rootDir = rootDir
const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoaderOptions> =
function nextEdgeFunctionLoader(this) {
const {
absolutePagePath,
page,
rootDir,
preferredRegion,
}: EdgeFunctionLoaderOptions = this.getOptions()
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const buildInfo = getModuleBuildInfo(this._module as any)
buildInfo.route = {
page: page || '/',
absolutePagePath,
preferredRegion,
}
buildInfo.nextEdgeApiFunction = {
page: page || '/',
}
buildInfo.rootDir = rootDir
return `
return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache'
......@@ -39,4 +51,6 @@ export default function middlewareLoader(this: any) {
})
}
`
}
}
export default nextEdgeFunctionLoader
import type webpack from 'webpack'
import { getModuleBuildInfo } from '../get-module-build-info'
import { stringifyRequest } from '../../stringify-request'
......@@ -16,6 +17,7 @@ export type EdgeSSRLoaderQuery = {
pagesType: 'app' | 'pages' | 'root'
sriEnabled: boolean
incrementalCacheHandlerPath?: string
preferredRegion: string | string[] | undefined
}
/*
......@@ -30,64 +32,68 @@ function swapDistFolderWithEsmDistFolder(path: string) {
return path.replace('next/dist/pages', 'next/dist/esm/pages')
}
export default async function edgeSSRLoader(this: any) {
const {
dev,
page,
buildId,
absolutePagePath,
absoluteAppPath,
absoluteDocumentPath,
absolute500Path,
absoluteErrorPath,
isServerComponent,
stringifiedConfig,
appDirLoader: appDirLoaderBase64,
pagesType,
sriEnabled,
incrementalCacheHandlerPath,
} = this.getOptions()
const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
async function edgeSSRLoader(this) {
const {
dev,
page,
buildId,
absolutePagePath,
absoluteAppPath,
absoluteDocumentPath,
absolute500Path,
absoluteErrorPath,
isServerComponent,
stringifiedConfig,
appDirLoader: appDirLoaderBase64,
pagesType,
sriEnabled,
incrementalCacheHandlerPath,
preferredRegion,
} = this.getOptions()
const appDirLoader = Buffer.from(
appDirLoaderBase64 || '',
'base64'
).toString()
const isAppDir = pagesType === 'app'
const appDirLoader = Buffer.from(
appDirLoaderBase64 || '',
'base64'
).toString()
const isAppDir = pagesType === 'app'
const buildInfo = getModuleBuildInfo(this._module)
buildInfo.nextEdgeSSR = {
isServerComponent: isServerComponent === 'true',
page: page,
isAppDir,
}
buildInfo.route = {
page,
absolutePagePath,
}
const buildInfo = getModuleBuildInfo(this._module as any)
buildInfo.nextEdgeSSR = {
// @ts-expect-error === 'true' is correct because loader options are serialized as searchParams. Type needs to be fixed somehow.
isServerComponent: isServerComponent === 'true',
page: page,
isAppDir,
}
buildInfo.route = {
page,
absolutePagePath,
preferredRegion,
}
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteAppPath)
)
const stringifiedErrorPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteErrorPath)
)
const stringifiedDocumentPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteDocumentPath)
)
const stringified500Path = absolute500Path
? stringifyRequest(this, absolute500Path)
: null
const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteAppPath)
)
const stringifiedErrorPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteErrorPath)
)
const stringifiedDocumentPath = stringifyRequest(
this,
swapDistFolderWithEsmDistFolder(absoluteDocumentPath)
)
const stringified500Path = absolute500Path
? stringifyRequest(this, absolute500Path)
: null
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(
1,
stringifiedPagePath.length - 1
)}${isAppDir ? '?__edge_ssr_entry__' : ''}`
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(
1,
stringifiedPagePath.length - 1
)}${isAppDir ? '?__edge_ssr_entry__' : ''}`
const transformed = `
const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache'
......@@ -170,5 +176,6 @@ export default async function edgeSSRLoader(this: any) {
})
}`
return transformed
}
return transformed
}
export default edgeSSRLoader
......@@ -636,7 +636,7 @@ function getExtractMetadata(params: {
entryDependency,
resolver
)
const { rootDir } = getModuleBuildInfo(
const { rootDir, route } = getModuleBuildInfo(
compilation.moduleGraph.getResolvedModule(entryDependency)
)
......@@ -739,6 +739,15 @@ function getExtractMetadata(params: {
entryMetadata.regions = edgeFunctionConfig.config.regions
}
if (route?.preferredRegion) {
const preferredRegion = route.preferredRegion
entryMetadata.regions =
// Ensures preferredRegion is always an array in the manifest.
typeof preferredRegion === 'string'
? [preferredRegion]
: preferredRegion
}
/**
* The entry module has to be either a page or a middleware and hold
* the corresponding metadata.
......
......@@ -14,6 +14,7 @@ import {
getEdgeServerEntry,
getAppEntry,
runDependingOnPageType,
getStaticInfoIncludingLayouts,
} from '../../build/entries'
import { watchCompilers } from '../../build/output'
import * as Log from '../../build/output/log'
......@@ -47,7 +48,6 @@ import { Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws'
import { promises as fs } from 'fs'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { UnwrapPromise } from '../../lib/coalesced-function'
import { getRegistry } from '../../lib/helpers/get-registry'
import { RouteMatch } from '../future/route-matches/route-match'
......@@ -713,12 +713,14 @@ export default class HotReloader {
const hasAppDir = !!this.appDir
const isAppPath = hasAppDir && bundlePath.startsWith('app/')
const staticInfo = isEntry
? await getPageStaticInfo({
page,
? await getStaticInfoIncludingLayouts({
isInsideAppDir: isAppPath,
pageExtensions: this.config.pageExtensions,
pageFilePath: entryData.absolutePagePath,
nextConfig: this.config,
appDir: this.appDir,
config: this.config,
isDev: true,
pageType: isAppPath ? 'app' : 'pages',
page,
})
: {}
const isServerComponent =
......@@ -755,6 +757,7 @@ export default class HotReloader {
tsconfigPath: this.config.typescript.tsconfigPath,
assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion,
}).import
: undefined
......@@ -774,6 +777,7 @@ export default class HotReloader {
isServerComponent,
appDirLoader,
pagesType: isAppPath ? 'app' : 'pages',
preferredRegion: staticInfo.preferredRegion,
}),
hasAppDir,
})
......@@ -838,6 +842,7 @@ export default class HotReloader {
tsconfigPath: this.config.typescript.tsconfigPath,
assetPrefix: this.config.assetPrefix,
nextConfigOutput: this.config.output,
preferredRegion: staticInfo.preferredRegion,
})
: relativeRequest,
hasAppDir,
......
......@@ -7,3 +7,4 @@ export default function HelloPage(props) {
}
export const runtime = 'experimental-edge'
export const preferredRegion = ['iad1', 'sfo1']
......@@ -9,3 +9,5 @@ export default function DashboardLayout(props) {
</div>
)
}
export const preferredRegion = 'iad1'
......@@ -16,4 +16,4 @@ export default function DashboardPage(props) {
)
}
export const runtime = 'experimental-edge'
export const runtime = 'edge'
......@@ -14,3 +14,4 @@ export default function SlowPage(props) {
}
export const runtime = 'experimental-edge'
export const preferredRegion = 'edge'
export default function Page() {
return <p id="page">Page</p>
}
export const runtime = 'experimental-edge'
export const preferredRegion = 'home'
......@@ -10,6 +10,28 @@ createNextDescribe(
files: __dirname,
},
({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => {
if (isNextStart) {
it('should have correct preferredRegion values in manifest', async () => {
const middlewareManifest = JSON.parse(
await next.readFile('.next/server/middleware-manifest.json')
)
expect(
middlewareManifest.functions['/(rootonly)/dashboard/hello/page']
.regions
).toEqual(['iad1', 'sfo1'])
expect(middlewareManifest.functions['/dashboard/page'].regions).toEqual(
['iad1']
)
expect(
middlewareManifest.functions['/slow-page-no-loading/page'].regions
).toEqual(['edge'])
expect(middlewareManifest.functions['/test-page/page'].regions).toEqual(
['home']
)
})
}
it('should have correct searchParams and params (server)', async () => {
const html = await next.render('/dynamic/category-1/id-2?query1=value2')
const $ = cheerio.load(html)
......
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