Unverified Commit 201f98e8 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Per-page runtime (#35011)

Partially implements #31317 and #31506. There're also some trade-offs made with this PR: since we can't know if a certain runtime will be used or not beforehand, we have to start both runtime compilers (Node.js and Edge) and then generate entrypoints correspondingly.

Note that with this PR, the global runtime is still required to use the per-page runtime.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent 9e4724de
This diff is collapsed.
......@@ -104,6 +104,7 @@ import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import { recursiveCopy } from '../lib/recursive-copy'
import { shouldUseReactRoot } from '../server/config'
export type SsgRoute = {
initialRevalidateSeconds: number | false
......@@ -154,10 +155,11 @@ export default async function build(
// Currently, when the runtime option is set (either `nodejs` or `edge`),
// we enable concurrent features (Fizz-related rendering architecture).
const runtime = config.experimental.runtime
const hasReactRoot = shouldUseReactRoot()
const hasConcurrentFeatures = !!runtime
const hasServerComponents =
hasConcurrentFeatures && !!config.experimental.serverComponents
hasReactRoot && !!config.experimental.serverComponents
const { target } = config
const buildId: string = await nextBuildSpan
......@@ -296,20 +298,21 @@ export default async function build(
createPagesMapping(pagePaths, config.pageExtensions, {
isDev: false,
hasServerComponents,
runtime,
globalRuntime: runtime,
})
)
const entrypoints = nextBuildSpan
const entrypoints = await nextBuildSpan
.traceChild('create-entrypoints')
.traceFn(() =>
.traceAsyncFn(() =>
createEntrypoints(
mappedPages,
target,
buildId,
previewProps,
config,
loadedEnvFiles
loadedEnvFiles,
pagesDir
)
)
const pageKeys = Object.keys(mappedPages)
......@@ -576,13 +579,15 @@ export default async function build(
BUILD_MANIFEST,
PRERENDER_MANIFEST,
path.join(SERVER_DIRECTORY, MIDDLEWARE_MANIFEST),
hasServerComponents
? path.join(
SERVER_DIRECTORY,
MIDDLEWARE_FLIGHT_MANIFEST +
(runtime === 'edge' ? '.js' : '.json')
)
: null,
...(hasServerComponents
? [
path.join(SERVER_DIRECTORY, MIDDLEWARE_FLIGHT_MANIFEST + '.js'),
path.join(
SERVER_DIRECTORY,
MIDDLEWARE_FLIGHT_MANIFEST + '.json'
),
]
: []),
REACT_LOADABLE_MANIFEST,
config.optimizeFonts
? path.join(
......@@ -629,7 +634,7 @@ export default async function build(
rewrites,
runWebpackSpan,
}),
runtime === 'edge'
hasReactRoot
? getBaseWebpackConfig(dir, {
buildId,
reactProductionProfiling,
......
......@@ -1113,12 +1113,7 @@ export function isFlightPage(
nextConfig: NextConfigComplete,
filePath: string
): boolean {
if (
!(
nextConfig.experimental.serverComponents &&
nextConfig.experimental.runtime
)
) {
if (!nextConfig.experimental.serverComponents) {
return false
}
......
......@@ -1173,44 +1173,41 @@ export default async function getBaseWebpackConfig(
} as any,
]
: []),
// Loaders for the client compilation when RSC is enabled.
...(hasServerComponents && !isServer
? [
{
...codeCondition,
test: serverComponentsRegex,
use: {
loader: 'next-flight-server-loader',
options: {
client: 1,
pageExtensions: rawPageExtensions,
...(hasServerComponents
? isServer
? [
// RSC server compilation loaders
{
...codeCondition,
use: {
loader: 'next-flight-server-loader',
options: {
pageExtensions: rawPageExtensions,
},
},
},
},
]
: []),
// Loaders for the server compilation when RSC is enabled.
...(hasServerComponents &&
((runtime === 'edge' && isEdgeRuntime) ||
(runtime === 'nodejs' && isServer))
? [
{
...codeCondition,
use: {
loader: 'next-flight-server-loader',
options: {
pageExtensions: rawPageExtensions,
{
test: codeCondition.test,
resourceQuery: /__sc_client__/,
use: {
loader: 'next-flight-client-loader',
},
},
},
{
test: codeCondition.test,
resourceQuery: /__sc_client__/,
use: {
loader: 'next-flight-client-loader',
]
: [
// RSC client compilation loaders
{
...codeCondition,
test: serverComponentsRegex,
use: {
loader: 'next-flight-server-loader',
options: {
client: 1,
pageExtensions: rawPageExtensions,
},
},
},
},
]
]
: []),
{
test: /\.(js|cjs|mjs)$/,
......@@ -1493,7 +1490,7 @@ export default async function getBaseWebpackConfig(
}),
hasServerComponents &&
!isServer &&
new FlightManifestPlugin({ dev, clientComponentsRegex, runtime }),
new FlightManifestPlugin({ dev, clientComponentsRegex }),
!dev &&
!isServer &&
new TelemetryPlugin(
......
......@@ -18,14 +18,12 @@ import { MIDDLEWARE_FLIGHT_MANIFEST } from '../../../shared/lib/constants'
type Options = {
dev: boolean
clientComponentsRegex: RegExp
runtime?: 'nodejs' | 'edge'
}
const PLUGIN_NAME = 'FlightManifestPlugin'
export class FlightManifestPlugin {
dev: boolean = false
runtime?: 'nodejs' | 'edge'
clientComponentsRegex: RegExp
constructor(options: Options) {
......@@ -33,7 +31,6 @@ export class FlightManifestPlugin {
this.dev = options.dev
}
this.clientComponentsRegex = options.clientComponentsRegex
this.runtime = options.runtime
}
apply(compiler: any) {
......@@ -65,7 +62,7 @@ export class FlightManifestPlugin {
}
createAsset(assets: any, compilation: any) {
const json: any = {}
const manifest: any = {}
const { clientComponentsRegex } = this
compilation.chunkGroups.forEach((chunkGroup: any) => {
function recordModule(id: string, _chunk: any, mod: any) {
......@@ -79,7 +76,7 @@ export class FlightManifestPlugin {
return
}
const moduleExports: any = json[resource] || {}
const moduleExports: any = manifest[resource] || {}
const exportsInfo = compilation.moduleGraph.getExportsInfo(mod)
const moduleExportedKeys = ['', '*'].concat(
......@@ -102,7 +99,7 @@ export class FlightManifestPlugin {
}
}
})
json[resource] = moduleExports
manifest[resource] = moduleExports
}
chunkGroup.chunks.forEach((chunk: any) => {
......@@ -126,13 +123,12 @@ export class FlightManifestPlugin {
})
})
const output =
(this.runtime === 'edge' ? 'self.__RSC_MANIFEST=' : '') +
JSON.stringify(json)
assets[
`server/${MIDDLEWARE_FLIGHT_MANIFEST}${
this.runtime === 'edge' ? '.js' : '.json'
}`
] = new sources.RawSource(output)
// With switchable runtime, we need to emit the manifest files for both
// runtimes.
const file = `server/${MIDDLEWARE_FLIGHT_MANIFEST}`
const json = JSON.stringify(manifest)
assets[file + '.js'] = new sources.RawSource('self.__RSC_MANIFEST=' + json)
assets[file + '.json'] = new sources.RawSource(json)
}
}
......@@ -42,6 +42,8 @@ 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 { getPageRuntime } from '../../build/entries'
import { shouldUseReactRoot } from '../config'
const wsServer = new ws.Server({ noServer: true })
......@@ -195,9 +197,7 @@ export default class HotReloader {
this.config = config
this.runtime = config.experimental.runtime
this.hasServerComponents = !!(
this.runtime && config.experimental.serverComponents
)
this.hasServerComponents = !!config.experimental.serverComponents
this.previewProps = previewProps
this.rewrites = rewrites
this.hotReloaderSpan = trace('hot-reloader', undefined, {
......@@ -321,26 +321,27 @@ export default class HotReloader {
this.config.pageExtensions,
{
isDev: true,
runtime: this.config.experimental.runtime,
globalRuntime: this.runtime,
hasServerComponents: this.hasServerComponents,
}
)
)
const entrypoints = webpackConfigSpan
const entrypoints = await webpackConfigSpan
.traceChild('create-entrypoints')
.traceFn(() =>
.traceAsyncFn(() =>
createEntrypoints(
this.pagesMapping,
'server',
this.buildId,
this.previewProps,
this.config,
[]
[],
this.pagesDir
)
)
const hasEdgeRuntimePages = this.runtime === 'edge'
const hasReactRoot = shouldUseReactRoot()
return webpackConfigSpan
.traceChild('generate-webpack-config')
......@@ -367,9 +368,8 @@ export default class HotReloader {
entrypoints: entrypoints.server,
runWebpackSpan: this.hotReloaderSpan,
}),
// For the edge runtime, we need an extra compiler to generate the
// web-targeted server bundle for now.
hasEdgeRuntimePages
// The edge runtime is only supported with React root.
hasReactRoot
? getBaseWebpackConfig(this.dir, {
dev: true,
isServer: true,
......@@ -404,16 +404,19 @@ export default class HotReloader {
fallback: [],
},
isDevFallback: true,
entrypoints: createEntrypoints(
{
'/_app': 'next/dist/pages/_app',
'/_error': 'next/dist/pages/_error',
},
'server',
this.buildId,
this.previewProps,
this.config,
[]
entrypoints: (
await createEntrypoints(
{
'/_app': 'next/dist/pages/_app',
'/_error': 'next/dist/pages/_error',
},
'server',
this.buildId,
this.previewProps,
this.config,
[],
this.pagesDir
)
).client,
})
const fallbackCompiler = webpack(fallbackConfig)
......@@ -499,11 +502,19 @@ export default class HotReloader {
const isServerComponent =
this.hasServerComponents &&
isFlightPage(this.config, absolutePagePath)
const isEdgeSSRPage = this.runtime === 'edge' && !isApiRoute
const pageRuntimeConfig = await getPageRuntime(
absolutePagePath,
this.runtime
)
const isEdgeSSRPage = pageRuntimeConfig === 'edge' && !isApiRoute
if (isNodeServerCompilation && isEdgeSSRPage && !isCustomError) {
return
}
if (isEdgeServerCompilation && !isEdgeSSRPage) {
return
}
entries[pageKey].status = BUILDING
const pageLoaderOpts: ClientPagesLoaderOptions = {
......
......@@ -60,6 +60,7 @@ import isError, { getProperError } from '../../lib/is-error'
import { getMiddlewareRegex } from '../../shared/lib/router/utils/get-middleware-regex'
import { isCustomErrorPage, isReservedPage } from '../../build/utils'
import { NodeNextResponse, NodeNextRequest } from '../base-http/node'
import { getPageRuntime, invalidatePageRuntimeCache } from '../../build/entries'
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: React.FunctionComponent
......@@ -254,17 +255,13 @@ export default class DevServer extends Server {
let wp = (this.webpackWatcher = new Watchpack())
wp.watch([], [pagesDir!], 0)
wp.on('aggregated', () => {
wp.on('aggregated', async () => {
const routedMiddleware = []
const routedPages = []
const knownFiles = wp.getTimeInfoEntries()
const ssrMiddleware = new Set<string>()
const runtime = this.nextConfig.experimental.runtime
const isEdgeRuntime = runtime === 'edge'
const hasServerComponents =
runtime && this.nextConfig.experimental.serverComponents
for (const [fileName, { accuracy }] of knownFiles) {
for (const [fileName, { accuracy, safeTime }] of knownFiles) {
if (accuracy === undefined || !regexPageExtension.test(fileName)) {
continue
}
......@@ -283,10 +280,14 @@ export default class DevServer extends Server {
pageName = pageName.replace(regexPageExtension, '')
pageName = pageName.replace(/\/index$/, '') || '/'
if (hasServerComponents && pageName.endsWith('.server')) {
routedMiddleware.push(pageName)
ssrMiddleware.add(pageName)
} else if (
invalidatePageRuntimeCache(fileName, safeTime)
const pageRuntimeConfig = await getPageRuntime(
fileName,
this.nextConfig.experimental.runtime
)
const isEdgeRuntime = pageRuntimeConfig === 'edge'
if (
isEdgeRuntime &&
!(isReservedPage(pageName) || isCustomErrorPage(pageName))
) {
......
......@@ -10,6 +10,7 @@ import { reportTrigger } from '../../build/output'
import type ws from 'ws'
import { NextConfigComplete } from '../config-shared'
import { isCustomErrorPage } from '../../build/utils'
import { getPageRuntime } from '../../build/entries'
export const ADDED = Symbol('added')
export const BUILDING = Symbol('building')
......@@ -204,7 +205,12 @@ export default function onDemandEntryHandler(
const isMiddleware = normalizedPage.match(MIDDLEWARE_ROUTE)
const isApiRoute = normalizedPage.match(API_ROUTE) && !isMiddleware
const isEdgeServer = nextConfig.experimental.runtime === 'edge'
const pageRuntimeConfig = await getPageRuntime(
absolutePagePath,
nextConfig.experimental.runtime
)
const isEdgeServer = pageRuntimeConfig === 'edge'
const isCustomError = isCustomErrorPage(page)
let entriesChanged = false
......
......@@ -690,7 +690,7 @@ export default class NextNodeServer extends BaseServer {
}
protected getServerComponentManifest() {
if (this.nextConfig.experimental.runtime !== 'nodejs') return undefined
if (!this.nextConfig.experimental.runtime) return undefined
return require(join(
this.distDir,
'server',
......
......@@ -359,22 +359,16 @@ function createServerComponentRenderer(
cachePrefix,
transformStream,
serverComponentManifest,
runtime,
}: {
cachePrefix: string
transformStream: TransformStream<Uint8Array, Uint8Array>
serverComponentManifest: NonNullable<RenderOpts['serverComponentManifest']>
runtime: 'nodejs' | 'edge'
}
) {
if (runtime === 'nodejs') {
// For the nodejs runtime, we need to expose the `__webpack_require__` API
// globally for react-server-dom-webpack.
// This is a hack until we find a better way.
// @ts-ignore
globalThis.__webpack_require__ =
ComponentMod.__next_rsc__.__webpack_require__
}
// We need to expose the `__webpack_require__` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
// @ts-ignore
globalThis.__webpack_require__ = ComponentMod.__next_rsc__.__webpack_require__
const writable = transformStream.writable
const ServerComponentWrapper = (props: any) => {
......@@ -490,7 +484,6 @@ export async function renderToHTML(
cachePrefix: pathname + (search ? `?${search}` : ''),
transformStream: serverComponentsInlinedTransformStream,
serverComponentManifest,
runtime,
}
)
}
......
......@@ -20,6 +20,6 @@ export default function Index() {
)
}
export const config = {
runtime: 'edge',
}
// export const config = {
// runtime: 'edge',
// }
......@@ -31,9 +31,3 @@ export function getServerSideProps({ req }) {
},
}
}
export const config = {
amp: false,
unstable_runtimeJS: false,
runtime: 'nodejs',
}
......@@ -26,12 +26,9 @@ function Data() {
export default function () {
return (
<>
Current Runtime:{' '}
{typeof window === 'undefined'
? typeof ReadableStream === 'undefined'
? 'node-server'
: 'edge-server'
: 'browser'}
{process.version
? `Runtime: Node.js ${process.version}`
: 'Runtime: Edge/Browser'}
<br />
<div className="suspense">
<Suspense fallback="next_streaming_fallback">
......
export default function () {
return process.version
? `Runtime: Node.js ${process.version}`
: 'Runtime: Edge/Browser'
}
export const config = {
runtime: 'nodejs',
}
export default function () {
return process.version
? `Runtime: Node.js ${process.version}`
: 'Runtime: Edge/Browser'
}
export const config = {
runtime: 'nodejs',
}
......@@ -31,12 +31,20 @@ export default function (context) {
const { pages } = content
const pageNames = Object.keys(pages)
const paths = ['/', '/next-api/link', '/routes/[dynamic]']
const paths = [
'/',
'/next-api/link',
'/routes/[dynamic]',
// @TODO: Implement per-page runtime in functions-manifest.
// '/runtime'
]
paths.forEach((path) => {
const { runtime, files } = pages[path]
expect(pageNames).toContain(path)
// Runtime of page `/` is undefined since it's configured as nodejs.
expect(runtime).toBe(path === '/' ? undefined : 'web')
// Runtime of page `/runtime` is configured as `nodejs`.
expect(runtime).toBe(path === '/runtime' ? 'nodejs' : 'web')
expect(files.every((f) => f.startsWith('server/'))).toBe(true)
})
......
......@@ -25,6 +25,7 @@ import rsc from './rsc'
import streaming from './streaming'
import basic from './basic'
import functions from './functions'
import runtime from './runtime'
const documentWithGip = `
import { Html, Head, Main, NextScript } from 'next/document'
......@@ -105,8 +106,9 @@ describe('Edge runtime - prod', () => {
const distServerDir = join(distDir, 'server')
const files = [
'middleware-build-manifest.js',
'middleware-flight-manifest.js',
'middleware-ssr-runtime.js',
'middleware-flight-manifest.js',
'middleware-flight-manifest.json',
'middleware-manifest.json',
]
......@@ -154,6 +156,7 @@ describe('Edge runtime - prod', () => {
basic(context, options)
streaming(context, options)
rsc(context, options)
runtime(context, options)
})
describe('Edge runtime - dev', () => {
......@@ -188,6 +191,7 @@ describe('Edge runtime - dev', () => {
basic(context, options)
streaming(context, options)
rsc(context, options)
runtime(context, options)
})
const nodejsRuntimeBasicSuite = {
......
import { renderViaHTTP } from 'next-test-utils'
export default async function runtime(context, { runtime }) {
if (runtime === 'edge') {
it('should support per-page runtime configuration', async () => {
const html1 = await renderViaHTTP(context.appPort, '/runtime')
expect(html1).toContain('Runtime: Node.js')
const html2 = await renderViaHTTP(context.appPort, '/runtime-rsc')
expect(html2).toContain('Runtime: Node.js')
})
}
}
export default function Fallback() {
return null
}
export async function getStaticProps() {
return {
props: {},
}
}
......@@ -24,4 +24,12 @@ describe('parse page runtime config', () => {
)
expect(runtime).toBe(undefined)
})
it('should fallback to the global runtime configuration if a runtime is needed', async () => {
const runtime = await getPageRuntime(
join(fixtureDir, 'page-runtime/fallback.js'),
'edge'
)
expect(runtime).toBe('edge')
})
})
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