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

Refactor Server Router (#39902)

<!--
Thanks for opening a PR! Your contribution is much appreciated.
In order 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 that you're making:
-->

This is intended to refactor the router code to reduce the overhead of executing routes. This is related to #32314 that may help reduce the memory overhead as this also replaced the `Set` with a `WeakMap`.
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent c89e25eb
......@@ -222,7 +222,6 @@ export default class DevServer extends Server {
for (const path in exportPathMap) {
const { page, query = {} } = exportPathMap[path]
// We use unshift so that we're sure the routes is defined before Next's default routes
this.router.addFsRoute({
match: getPathMatch(path),
type: 'route',
......
......@@ -40,7 +40,7 @@ export type Route = {
res: BaseNextResponse,
params: Params,
parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: any
upgradeHead?: Buffer
) => Promise<RouteResult> | RouteResult
}
......@@ -49,21 +49,37 @@ export type DynamicRoutes = Array<{ page: string; match: RouteMatch }>
export type PageChecker = (pathname: string) => Promise<boolean>
export default class Router {
headers: Route[]
fsRoutes: Route[]
redirects: Route[]
rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
public catchAllMiddleware: ReadonlyArray<Route>
private readonly headers: ReadonlyArray<Route>
private readonly fsRoutes: Route[]
private readonly redirects: ReadonlyArray<Route>
private readonly rewrites: {
beforeFiles: ReadonlyArray<Route>
afterFiles: ReadonlyArray<Route>
fallback: ReadonlyArray<Route>
}
private readonly catchAllRoute: Route
private readonly pageChecker: PageChecker
private dynamicRoutes: DynamicRoutes
private readonly useFileSystemPublicRoutes: boolean
private readonly nextConfig: NextConfig
private compiledRoutes: ReadonlyArray<Route>
private needsRecompilation: boolean
/**
* context stores information used by the router.
*/
private readonly context = new WeakMap<
BaseNextRequest,
{
/**
* pageChecks is the memoized record of all checks made against pages to
* help de-duplicate work.
*/
pageChecks: Record<string, boolean>
}
catchAllRoute: Route
catchAllMiddleware: Route[]
pageChecker: PageChecker
dynamicRoutes: DynamicRoutes
useFileSystemPublicRoutes: boolean
seenRequests: Set<any>
nextConfig: NextConfig
>()
constructor({
headers = [],
......@@ -81,16 +97,16 @@ export default class Router {
useFileSystemPublicRoutes,
nextConfig,
}: {
headers: Route[]
fsRoutes: Route[]
headers: ReadonlyArray<Route>
fsRoutes: ReadonlyArray<Route>
rewrites: {
beforeFiles: Route[]
afterFiles: Route[]
fallback: Route[]
beforeFiles: ReadonlyArray<Route>
afterFiles: ReadonlyArray<Route>
fallback: ReadonlyArray<Route>
}
redirects: Route[]
redirects: ReadonlyArray<Route>
catchAllRoute: Route
catchAllMiddleware: Route[]
catchAllMiddleware: ReadonlyArray<Route>
dynamicRoutes: DynamicRoutes | undefined
pageChecker: PageChecker
useFileSystemPublicRoutes: boolean
......@@ -98,7 +114,7 @@ export default class Router {
}) {
this.nextConfig = nextConfig
this.headers = headers
this.fsRoutes = fsRoutes
this.fsRoutes = [...fsRoutes]
this.rewrites = rewrites
this.redirects = redirects
this.pageChecker = pageChecker
......@@ -106,112 +122,59 @@ export default class Router {
this.catchAllMiddleware = catchAllMiddleware
this.dynamicRoutes = dynamicRoutes
this.useFileSystemPublicRoutes = useFileSystemPublicRoutes
this.seenRequests = new Set()
}
get locales() {
return this.nextConfig.i18n?.locales || []
}
get basePath() {
return this.nextConfig.basePath || ''
// Perform the initial route compilation.
this.compiledRoutes = this.compileRoutes()
this.needsRecompilation = false
}
setDynamicRoutes(routes: DynamicRoutes = []) {
this.dynamicRoutes = routes
}
setCatchallMiddleware(route?: Route[]) {
this.catchAllMiddleware = route || []
}
addFsRoute(fsRoute: Route) {
this.fsRoutes.unshift(fsRoute)
}
async execute(
private async checkPage(
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: any
pathname: string
): Promise<boolean> {
if (this.seenRequests.has(req)) {
pathname = normalizeLocalePath(pathname, this.locales).pathname
const context = this.context.get(req)
if (!context) {
throw new Error(
`Invariant: request has already been processed: ${req.url}, this is an internal error please open an issue.`
'Invariant: request is not available inside the context, this is an internal error please open an issue.'
)
}
this.seenRequests.add(req)
try {
// memoize page check calls so we don't duplicate checks for pages
const pageChecks: { [name: string]: Promise<boolean> } = {}
const memoizedPageChecker = async (p: string): Promise<boolean> => {
p = normalizeLocalePath(p, this.locales).pathname
if (pageChecks[p] !== undefined) {
return pageChecks[p]
if (context.pageChecks[pathname] !== undefined) {
return context.pageChecks[pathname]
}
const result = this.pageChecker(p)
pageChecks[p] = result
const result = await this.pageChecker(pathname)
context.pageChecks[pathname] = result
return result
}
let parsedUrlUpdated = parsedUrl
const applyCheckTrue = async (checkParsedUrl: NextUrlWithParsedQuery) => {
const originalFsPathname = checkParsedUrl.pathname
const fsPathname = removePathPrefix(originalFsPathname!, this.basePath)
for (const fsRoute of this.fsRoutes) {
const fsParams = fsRoute.match(fsPathname)
if (fsParams) {
checkParsedUrl.pathname = fsPathname
const fsResult = await fsRoute.fn(
req,
res,
fsParams,
checkParsedUrl
)
if (fsResult.finished) {
return true
get locales() {
return this.nextConfig.i18n?.locales || []
}
checkParsedUrl.pathname = originalFsPathname
}
get basePath() {
return this.nextConfig.basePath || ''
}
let matchedPage = await memoizedPageChecker(fsPathname)
// If we didn't match a page check dynamic routes
if (!matchedPage) {
const normalizedFsPathname = normalizeLocalePath(
fsPathname,
this.locales
).pathname
for (const dynamicRoute of this.dynamicRoutes) {
if (dynamicRoute.match(normalizedFsPathname)) {
matchedPage = true
}
public setDynamicRoutes(dynamicRoutes: DynamicRoutes) {
this.dynamicRoutes = dynamicRoutes
this.needsRecompilation = true
}
public setCatchallMiddleware(catchAllMiddleware: ReadonlyArray<Route>) {
this.catchAllMiddleware = catchAllMiddleware
this.needsRecompilation = true
}
// Matched a page or dynamic route so render it using catchAllRoute
if (matchedPage) {
const pageParams = this.catchAllRoute.match(checkParsedUrl.pathname)
checkParsedUrl.pathname = fsPathname
checkParsedUrl.query._nextBubbleNoFallback = '1'
const result = await this.catchAllRoute.fn(
req,
res,
pageParams as Params,
checkParsedUrl
)
return result.finished
}
public addFsRoute(fsRoute: Route) {
// We use unshift so that we're sure the routes is defined before Next's
// default routes.
this.fsRoutes.unshift(fsRoute)
this.needsRecompilation = true
}
private compileRoutes(): ReadonlyArray<Route> {
/*
Desired routes order
- headers
......@@ -221,16 +184,12 @@ export default class Router {
*/
const [middlewareCatchAllRoute] = this.catchAllMiddleware
const allRoutes = [
return [
...(middlewareCatchAllRoute
? this.fsRoutes
.filter((r) => r.name === '_next/data catchall')
.map((r) => {
return {
...r,
check: false,
}
})
.filter((route) => route.name === '_next/data catchall')
.map((route) => ({ ...route, check: false }))
: []),
...this.headers,
...this.redirects,
......@@ -247,27 +206,22 @@ export default class Router {
type: 'route',
name: 'page checker',
match: getPathMatch('/:path*'),
fn: async (
checkerReq,
checkerRes,
params,
parsedCheckerUrl
) => {
let { pathname } = parsedCheckerUrl
pathname = removeTrailingSlash(pathname || '/')
fn: async (req, res, params, parsedUrl, upgradeHead) => {
const pathname = removeTrailingSlash(parsedUrl.pathname || '/')
if (!pathname) {
return { finished: false }
}
if (await memoizedPageChecker(pathname)) {
if (await this.checkPage(req, pathname)) {
return this.catchAllRoute.fn(
checkerReq,
checkerRes,
req,
res,
params,
parsedCheckerUrl
parsedUrl,
upgradeHead
)
}
return { finished: false }
},
} as Route,
......@@ -280,14 +234,14 @@ export default class Router {
type: 'route',
name: 'dynamic route/page check',
match: getPathMatch('/:path*'),
fn: async (
_checkerReq,
_checkerRes,
_params,
parsedCheckerUrl
) => {
fn: async (req, res, _params, parsedCheckerUrl, upgradeHead) => {
return {
finished: await applyCheckTrue(parsedCheckerUrl),
finished: await this.checkFsRoutes(
req,
res,
parsedCheckerUrl,
upgradeHead
),
}
},
} as Route,
......@@ -299,10 +253,106 @@ export default class Router {
// disabled
...(this.useFileSystemPublicRoutes ? [this.catchAllRoute] : []),
]
}
private async checkFsRoutes(
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: Buffer
) {
const originalFsPathname = parsedUrl.pathname
const fsPathname = removePathPrefix(originalFsPathname!, this.basePath)
for (const route of this.fsRoutes) {
const params = route.match(fsPathname)
if (params) {
parsedUrl.pathname = fsPathname
const { finished } = await route.fn(req, res, params, parsedUrl)
if (finished) {
return true
}
parsedUrl.pathname = originalFsPathname
}
}
let matchedPage = await this.checkPage(req, fsPathname)
// If we didn't match a page check dynamic routes
if (!matchedPage) {
const normalizedFsPathname = normalizeLocalePath(
fsPathname,
this.locales
).pathname
for (const dynamicRoute of this.dynamicRoutes) {
if (dynamicRoute.match(normalizedFsPathname)) {
matchedPage = true
}
}
}
// Matched a page or dynamic route so render it using catchAllRoute
if (matchedPage) {
const params = this.catchAllRoute.match(parsedUrl.pathname)
if (!params) {
throw new Error(
`Invariant: could not match params, this is an internal error please open an issue.`
)
}
parsedUrl.pathname = fsPathname
parsedUrl.query._nextBubbleNoFallback = '1'
for (const testRoute of allRoutes) {
const { finished } = await this.catchAllRoute.fn(
req,
res,
params,
parsedUrl,
upgradeHead
)
return finished
}
return false
}
async execute(
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl: NextUrlWithParsedQuery,
upgradeHead?: Buffer
): Promise<boolean> {
// Only recompile if the routes need to be recompiled, this should only
// happen in development.
if (this.needsRecompilation) {
this.compiledRoutes = this.compileRoutes()
this.needsRecompilation = false
}
if (this.context.has(req)) {
throw new Error(
`Invariant: request has already been processed: ${req.url}, this is an internal error please open an issue.`
)
}
this.context.set(req, { pageChecks: {} })
try {
// Create a deep copy of the parsed URL.
const parsedUrlUpdated = {
...parsedUrl,
query: {
...parsedUrl.query,
},
}
for (const route of this.compiledRoutes) {
// only process rewrites for upgrade request
if (upgradeHead && testRoute.type !== 'rewrite') {
if (upgradeHead && route.type !== 'rewrite') {
continue
}
......@@ -314,7 +364,7 @@ export default class Router {
if (
pathnameInfo.locale &&
!testRoute.matchesLocaleAPIRoutes &&
!route.matchesLocaleAPIRoutes &&
pathnameInfo.pathname.match(/^\/api(?:\/|$)/)
) {
continue
......@@ -325,20 +375,20 @@ export default class Router {
}
const basePath = pathnameInfo.basePath
if (!testRoute.matchesBasePath) {
if (!route.matchesBasePath) {
pathnameInfo.basePath = ''
}
if (
testRoute.matchesLocale &&
parsedUrl.query.__nextLocale &&
route.matchesLocale &&
parsedUrlUpdated.query.__nextLocale &&
!pathnameInfo.locale
) {
pathnameInfo.locale = parsedUrl.query.__nextLocale
pathnameInfo.locale = parsedUrlUpdated.query.__nextLocale
}
if (
!testRoute.matchesLocale &&
!route.matchesLocale &&
pathnameInfo.locale === this.nextConfig.i18n?.defaultLocale &&
pathnameInfo.locale
) {
......@@ -346,7 +396,7 @@ export default class Router {
}
if (
testRoute.matchesTrailingSlash &&
route.matchesTrailingSlash &&
getRequestMeta(req, '__nextHadTrailingSlash')
) {
pathnameInfo.trailingSlash = true
......@@ -357,13 +407,13 @@ export default class Router {
...pathnameInfo,
})
let newParams = testRoute.match(matchPathname)
if (testRoute.has && newParams) {
const hasParams = matchHas(req, testRoute.has, parsedUrlUpdated.query)
let params = route.match(matchPathname)
if (route.has && params) {
const hasParams = matchHas(req, route.has, parsedUrlUpdated.query)
if (hasParams) {
Object.assign(newParams, hasParams)
Object.assign(params, hasParams)
} else {
newParams = false
params = false
}
}
......@@ -373,35 +423,34 @@ export default class Router {
* never there, we consider this an invalid match and keep routing.
*/
if (
newParams &&
params &&
this.basePath &&
!testRoute.matchesBasePath &&
!route.matchesBasePath &&
!getRequestMeta(req, '_nextDidRewrite') &&
!basePath
) {
continue
}
if (newParams) {
if (params) {
parsedUrlUpdated.pathname = matchPathname
const result = await testRoute.fn(
const result = await route.fn(
req,
res,
newParams,
params,
parsedUrlUpdated,
upgradeHead
)
if (result.finished) {
return true
}
if (result.pathname) {
parsedUrlUpdated.pathname = result.pathname
} else {
// since the fs route didn't finish routing we need to re-add the
// basePath to continue checking with the basePath present
parsedUrlUpdated.pathname = originalPathname
if (result.pathname) {
parsedUrlUpdated.pathname = result.pathname
}
if (result.query) {
......@@ -412,16 +461,19 @@ export default class Router {
}
// check filesystem
if (testRoute.check === true) {
if (await applyCheckTrue(parsedUrlUpdated)) {
if (
route.check &&
(await this.checkFsRoutes(req, res, parsedUrlUpdated))
) {
return true
}
}
}
}
// All routes were tested, none were found.
return false
} finally {
this.seenRequests.delete(req)
this.context.delete(req)
}
}
}
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