Skip to content

Commit

Permalink
Revert "Separate routing code from render servers (#52492)"
Browse files Browse the repository at this point in the history
This reverts commit f57eecd.
  • Loading branch information
ijjk committed Jul 21, 2023
1 parent 1fefb4a commit c516ad4
Show file tree
Hide file tree
Showing 59 changed files with 4,692 additions and 5,217 deletions.
238 changes: 128 additions & 110 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import os from 'os'
import { Worker } from '../lib/worker'
import { defaultConfig } from '../server/config-shared'
import devalue from 'next/dist/compiled/devalue'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import findUp from 'next/dist/compiled/find-up'
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
Expand Down Expand Up @@ -140,12 +141,7 @@ import { createClientRouterFilter } from '../lib/create-client-router-filter'
import { createValidFileMatcher } from '../server/lib/find-page-file'
import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
import { buildDataRoute } from '../server/lib/router-utils/build-data-route'
import {
baseOverrides,
defaultOverrides,
experimentalOverrides,
} from '../server/require-hook'
import { baseOverrides, experimentalOverrides } from '../server/require-hook'

export type SsgRoute = {
initialRevalidateSeconds: number | false
Expand All @@ -170,66 +166,6 @@ export type PrerenderManifest = {
preview: __ApiPreviewProps
}

type CustomRoute = {
regex: string
statusCode?: number | undefined
permanent?: undefined
source: string
locale?: false | undefined
basePath?: false | undefined
destination?: string | undefined
}

export type RoutesManifest = {
version: number
pages404: boolean
basePath: string
redirects: Array<CustomRoute>
rewrites?:
| Array<CustomRoute>
| {
beforeFiles: Array<CustomRoute>
afterFiles: Array<CustomRoute>
fallback: Array<CustomRoute>
}
headers: Array<CustomRoute>
staticRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dataRoutes: Array<{
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}>
i18n?: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
localeDetection?: false
}
rsc: {
header: typeof RSC
varyHeader: typeof RSC_VARY_HEADER
}
skipMiddlewareUrlNormalize?: boolean
caseSensitive?: boolean
}

async function generateClientSsgManifest(
prerenderManifest: PrerenderManifest,
{
Expand Down Expand Up @@ -748,45 +684,89 @@ export default async function build(
}

const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
const routesManifest: RoutesManifest = nextBuildSpan
.traceChild('generate-routes-manifest')
.traceFn(() => {
const sortedRoutes = getSortedRoutes([
...pageKeys.pages,
...(pageKeys.app ?? []),
])
const dynamicRoutes: Array<ReturnType<typeof pageToRoute>> = []
const staticRoutes: typeof dynamicRoutes = []

for (const route of sortedRoutes) {
if (isDynamicRoute(route)) {
dynamicRoutes.push(pageToRoute(route))
} else if (!isReservedPage(route)) {
staticRoutes.push(pageToRoute(route))
const routesManifest: {
version: number
pages404: boolean
basePath: string
redirects: Array<ReturnType<typeof buildCustomRoute>>
rewrites?:
| Array<ReturnType<typeof buildCustomRoute>>
| {
beforeFiles: Array<ReturnType<typeof buildCustomRoute>>
afterFiles: Array<ReturnType<typeof buildCustomRoute>>
fallback: Array<ReturnType<typeof buildCustomRoute>>
}
headers: Array<ReturnType<typeof buildCustomRoute>>
staticRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dynamicRoutes: Array<{
page: string
regex: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}>
dataRoutes: Array<{
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}>
i18n?: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
localeDetection?: false
}
rsc: {
header: typeof RSC
varyHeader: typeof RSC_VARY_HEADER
}
skipMiddlewareUrlNormalize?: boolean
caseSensitive?: boolean
} = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => {
const sortedRoutes = getSortedRoutes([
...pageKeys.pages,
...(pageKeys.app ?? []),
])
const dynamicRoutes: Array<ReturnType<typeof pageToRoute>> = []
const staticRoutes: typeof dynamicRoutes = []

for (const route of sortedRoutes) {
if (isDynamicRoute(route)) {
dynamicRoutes.push(pageToRoute(route))
} else if (!isReservedPage(route)) {
staticRoutes.push(pageToRoute(route))
}
}

return {
version: 3,
pages404: true,
caseSensitive: !!config.experimental.caseSensitiveRoutes,
basePath: config.basePath,
redirects: redirects.map((r: any) =>
buildCustomRoute(r, 'redirect')
),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes,
staticRoutes,
dataRoutes: [],
i18n: config.i18n || undefined,
rsc: {
header: RSC,
varyHeader: RSC_VARY_HEADER,
contentTypeHeader: RSC_CONTENT_TYPE_HEADER,
},
skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize,
}
})
return {
version: 3,
pages404: true,
caseSensitive: !!config.experimental.caseSensitiveRoutes,
basePath: config.basePath,
redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
dynamicRoutes,
staticRoutes,
dataRoutes: [],
i18n: config.i18n || undefined,
rsc: {
header: RSC,
varyHeader: RSC_VARY_HEADER,
contentTypeHeader: RSC_CONTENT_TYPE_HEADER,
},
skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize,
}
})

if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
routesManifest.rewrites = rewrites.afterFiles.map((r: any) =>
Expand Down Expand Up @@ -923,7 +903,6 @@ export default async function build(
]
: []),
path.join(SERVER_DIRECTORY, APP_PATHS_MANIFEST),
path.join(APP_PATH_ROUTES_MANIFEST),
APP_BUILD_MANIFEST,
path.join(
SERVER_DIRECTORY,
Expand Down Expand Up @@ -1983,11 +1962,6 @@ export default async function build(
...Object.values(experimentalOverrides).map((override) =>
require.resolve(override)
),
...(config.experimental.turbotrace
? []
: Object.values(defaultOverrides).map((value) =>
require.resolve(value)
)),
]

// ensure we trace any dependencies needed for custom
Expand All @@ -2005,7 +1979,9 @@ export default async function build(
const vanillaServerEntries = [
...sharedEntriesSet,
isStandalone
? require.resolve('next/dist/server/lib/start-server')
? require.resolve(
'next/dist/server/lib/render-server-standalone'
)
: null,
require.resolve('next/dist/server/next-server'),
].filter(Boolean) as string[]
Expand Down Expand Up @@ -2182,7 +2158,49 @@ export default async function build(
...serverPropsPages,
...ssgPages,
]).map((page) => {
return buildDataRoute(page, buildId)
const pagePath = normalizePagePath(page)
const dataRoute = path.posix.join(
'/_next/data',
buildId,
`${pagePath}.json`
)

let dataRouteRegex: string
let namedDataRouteRegex: string | undefined
let routeKeys: { [named: string]: string } | undefined

if (isDynamicRoute(page)) {
const routeRegex = getNamedRouteRegex(
dataRoute.replace(/\.json$/, ''),
true
)

dataRouteRegex = normalizeRouteRegex(
routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, `\\.json$`)
)
namedDataRouteRegex = routeRegex.namedRegex!.replace(
/\(\?:\/\)\?\$$/,
`\\.json$`
)
routeKeys = routeRegex.routeKeys
} else {
dataRouteRegex = normalizeRouteRegex(
new RegExp(
`^${path.posix.join(
'/_next/data',
escapeStringRegexp(buildId),
`${pagePath}.json`
)}$`
).source
)
}

return {
page,
routeKeys,
dataRouteRegex,
namedDataRouteRegex,
}
})

await fs.writeFile(
Expand Down
67 changes: 41 additions & 26 deletions packages/next/src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1928,12 +1928,12 @@ export async function copyTracedFiles(
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
import { startServer } from 'next/dist/server/lib/start-server.js'
import { createServerHandler } from 'next/dist/server/lib/render-server-standalone.js'
`
: `
const http = require('http')
const path = require('path')
const { startServer } = require('next/dist/server/lib/start-server')`
const { createServerHandler } = require('next/dist/server/lib/render-server-standalone')`
}
const dir = path.join(__dirname)
Expand All @@ -1950,38 +1950,53 @@ if (!process.env.NEXT_MANUAL_SIG_HANDLE) {
const currentPort = parseInt(process.env.PORT, 10) || 3000
const hostname = process.env.HOSTNAME || 'localhost'
let keepAliveTimeout = parseInt(process.env.KEEP_ALIVE_TIMEOUT, 10);
const keepAliveTimeout = parseInt(process.env.KEEP_ALIVE_TIMEOUT, 10);
const isValidKeepAliveTimeout =
!Number.isNaN(keepAliveTimeout) &&
Number.isFinite(keepAliveTimeout) &&
keepAliveTimeout >= 0;
const nextConfig = ${JSON.stringify({
...serverConfig,
distDir: `./${path.relative(dir, distDir)}`,
})}
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(nextConfig)
if (
Number.isNaN(keepAliveTimeout) ||
!Number.isFinite(keepAliveTimeout) ||
keepAliveTimeout < 0
) {
keepAliveTimeout = undefined
}
startServer({
dir,
isDev: false,
config: nextConfig,
hostname: hostname === 'localhost' ? '0.0.0.0' : hostname,
createServerHandler({
port: currentPort,
allowRetry: false,
keepAliveTimeout,
useWorkers: !!nextConfig.experimental?.appDir,
}).then(() => {
console.log(
'Listening on port',
currentPort,
'url: http://' + hostname + ':' + currentPort
)
}).catch((err) => {
hostname,
dir,
conf: nextConfig,
keepAliveTimeout: isValidKeepAliveTimeout ? keepAliveTimeout : undefined,
}).then((nextHandler) => {
const server = http.createServer(async (req, res) => {
try {
await nextHandler(req, res)
} catch (err) {
console.error(err);
res.statusCode = 500
res.end('Internal Server Error')
}
})
if (isValidKeepAliveTimeout) {
server.keepAliveTimeout = keepAliveTimeout
}
server.listen(currentPort, async (err) => {
if (err) {
console.error("Failed to start server", err)
process.exit(1)
}
console.log(
'Listening on port',
currentPort,
'url: http://' + hostname + ':' + currentPort
)
});
}).catch(err => {
console.error(err);
process.exit(1);
});`
Expand Down

0 comments on commit c516ad4

Please sign in to comment.