Unverified Commit 765744e3 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Change App Route Route Handler signature (#47268)

In preparation for improvements for the runtime support, this changes
the handle signature to _always_ return a response object.
fix NEXT-679 ([link](https://linear.app/vercel/issue/NEXT-679))
parent 2a8961b3
...@@ -19,8 +19,12 @@ type HandleProps = { ...@@ -19,8 +19,12 @@ type HandleProps = {
} }
export function getHandle({ page, mod, nextConfigOutput }: HandleProps) { export function getHandle({ page, mod, nextConfigOutput }: HandleProps) {
const appRouteRouteHandler = new AppRouteRouteHandler(nextConfigOutput) const handler = new AppRouteRouteHandler(nextConfigOutput)
const appRouteRouteMatcher = new AppRouteRouteMatcher({
// Set the module on the handler so it can be used when we handle the request.
handler.module = mod
const matcher = new AppRouteRouteMatcher({
kind: RouteKind.APP_ROUTE, kind: RouteKind.APP_ROUTE,
pathname: normalizeAppPath(page), pathname: normalizeAppPath(page),
page: '', page: '',
...@@ -31,17 +35,16 @@ export function getHandle({ page, mod, nextConfigOutput }: HandleProps) { ...@@ -31,17 +35,16 @@ export function getHandle({ page, mod, nextConfigOutput }: HandleProps) {
return async function handle(request: Request) { return async function handle(request: Request) {
const extendedReq = new WebNextRequest(request) const extendedReq = new WebNextRequest(request)
const extendedRes = new WebNextResponse() const extendedRes = new WebNextResponse()
const match = appRouteRouteMatcher.match( const match = matcher.match(
removeTrailingSlash(new URL(request.url).pathname) removeTrailingSlash(new URL(request.url).pathname)
)! )!
const response = await appRouteRouteHandler.execute(
const response = await handler.handle(
match, match,
mod,
extendedReq, extendedReq,
extendedRes, extendedRes,
// TODO: pass incrementalCache here // TODO: pass incrementalCache here
{ supportsDynamicHTML: true }, { supportsDynamicHTML: true }
request
) )
return response return response
......
...@@ -41,6 +41,7 @@ import { RouteKind } from '../server/future/route-kind' ...@@ -41,6 +41,7 @@ import { RouteKind } from '../server/future/route-kind'
import { NodeNextRequest, NodeNextResponse } from '../server/base-http/node' import { NodeNextRequest, NodeNextResponse } from '../server/base-http/node'
import { StaticGenerationContext } from '../server/future/route-handlers/app-route-route-handler' import { StaticGenerationContext } from '../server/future/route-handlers/app-route-route-handler'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { AppRouteRouteMatch } from '../server/future/route-matches/app-route-route-match'
loadRequireHook() loadRequireHook()
...@@ -393,24 +394,26 @@ export default async function exportPage({ ...@@ -393,24 +394,26 @@ export default async function exportPage({
incrementalCache: curRenderOpts.incrementalCache, incrementalCache: curRenderOpts.incrementalCache,
} }
const match: AppRouteRouteMatch = {
params: query,
definition: {
filename: posix.join(distDir, 'server', 'app', page),
bundlePath: posix.join('app', page),
kind: RouteKind.APP_ROUTE,
page,
pathname: path,
},
}
try { try {
const routeHandler = new AppRouteRouteHandler(nextConfigOuput) const handler = new AppRouteRouteHandler(nextConfigOuput)
const response: Response = await routeHandler.handle( const response = await handler.handle(
{ match,
params: query,
definition: {
filename: posix.join(distDir, 'server', 'app', page),
bundlePath: posix.join('app', page),
kind: RouteKind.APP_ROUTE,
page,
pathname: path,
},
},
nodeReq, nodeReq,
nodeRes, nodeRes,
staticContext, staticContext
true
) )
// we don't consider error status for static generation // we don't consider error status for static generation
// except for 404 // except for 404
// TODO: do we want to cache other status codes? // TODO: do we want to cache other status codes?
......
...@@ -92,8 +92,10 @@ import { PagesRouteMatcherProvider } from './future/route-matcher-providers/page ...@@ -92,8 +92,10 @@ import { PagesRouteMatcherProvider } from './future/route-matcher-providers/page
import { ServerManifestLoader } from './future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader' import { ServerManifestLoader } from './future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'
import { getTracer, SpanKind } from './lib/trace/tracer' import { getTracer, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants' import { BaseServerSpan } from './lib/trace/constants'
import { sendResponse } from './future/route-handlers/app-route-route-handler'
import { I18NProvider } from './future/helpers/i18n-provider' import { I18NProvider } from './future/helpers/i18n-provider'
import { sendResponse } from './send-response'
import { RouteKind } from './future/route-kind'
import { handleInternalServerErrorResponse } from './future/helpers/response-handlers'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -1456,37 +1458,56 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1456,37 +1458,56 @@ export default abstract class Server<ServerOptions extends Options = Options> {
supportsDynamicHTML, supportsDynamicHTML,
incrementalCache, incrementalCache,
} }
let response: Response | undefined = (await this.handlers.handle(
match, try {
req, // Handle the match and collect the response if it's a static response.
res, const response = await this.handlers.handle(match, req, res, context)
context, if (response) {
isSSG // If the request is for a static response, we can cache it so long
)) as any // as it's not edge.
if (isSSG && process.env.NEXT_RUNTIME !== 'edge') {
if (response) { const blob = await response.blob()
if (isSSG && process.env.NEXT_RUNTIME !== 'edge') {
const blob = await response.blob() // Copy the headers from the response.
const headers = Object.fromEntries(response.headers) const headers = Object.fromEntries(response.headers)
if (!headers['content-type'] && blob.type) { if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type headers['content-type'] = blob.type
} }
const cacheEntry: ResponseCacheEntry = {
value: { // Create the cache entry for the response.
kind: 'ROUTE', const cacheEntry: ResponseCacheEntry = {
status: response.status, value: {
body: Buffer.from(await blob.arrayBuffer()), kind: 'ROUTE',
headers, status: response.status,
}, body: Buffer.from(await blob.arrayBuffer()),
revalidate: headers,
((context as any).store as any as { revalidate?: number }) },
.revalidate || false, revalidate:
((context as any).store as any as { revalidate?: number })
.revalidate || false,
}
return cacheEntry
} }
return cacheEntry
// Send the response now that we have copied it into the cache.
await sendResponse(req, res, response)
return null
}
} catch (err) {
// If an error was thrown while handling an app route request, we
// should return a 500 response.
if (match.definition.kind === RouteKind.APP_ROUTE) {
// If this is during static generation, throw the error again.
if (isSSG) throw err
// Otherwise, send a 500 response.
Log.error(err)
await sendResponse(req, res, handleInternalServerErrorResponse())
return null
} }
// dynamic response so send here
await sendResponse(req, res, response)
return null
} }
} }
......
...@@ -26,17 +26,14 @@ export class RouteHandlerManager { ...@@ -26,17 +26,14 @@ export class RouteHandlerManager {
match: RouteMatch, match: RouteMatch,
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
context?: any, context?: any
bubbleResult?: boolean ): Promise<Response | undefined> {
): Promise<boolean> {
const handler = this.handlers[match.definition.kind] const handler = this.handlers[match.definition.kind]
if (!handler) return false if (!handler) return
const result = await handler.handle(match, req, res, context, bubbleResult) // Get the response from the handler.
const response = await handler.handle(match, req, res, context)
if (bubbleResult) { return response
return result as any
}
return true
} }
} }
...@@ -2,7 +2,7 @@ import { AppPageRouteMatch } from '../route-matches/app-page-route-match' ...@@ -2,7 +2,7 @@ import { AppPageRouteMatch } from '../route-matches/app-page-route-match'
import { RouteHandler } from './route-handler' import { RouteHandler } from './route-handler'
export class AppPageRouteHandler implements RouteHandler<AppPageRouteMatch> { export class AppPageRouteHandler implements RouteHandler<AppPageRouteMatch> {
public async handle(): Promise<void> { public async handle(): Promise<Response> {
throw new Error('Method not implemented.') throw new Error('Method not implemented.')
} }
} }
...@@ -13,8 +13,8 @@ import { ...@@ -13,8 +13,8 @@ import {
RequestAsyncStorageWrapper, RequestAsyncStorageWrapper,
type RequestContext, type RequestContext,
} from '../../async-storage/request-async-storage-wrapper' } from '../../async-storage/request-async-storage-wrapper'
import type { BaseNextRequest, BaseNextResponse } from '../../base-http' import { BaseNextRequest, BaseNextResponse } from '../../base-http'
import type { NodeNextRequest, NodeNextResponse } from '../../base-http/node' import { NodeNextRequest, NodeNextResponse } from '../../base-http/node'
import { getRequestMeta } from '../../request-meta' import { getRequestMeta } from '../../request-meta'
import { import {
handleBadRequestResponse, handleBadRequestResponse,
...@@ -38,6 +38,8 @@ import { AppConfig } from '../../../build/utils' ...@@ -38,6 +38,8 @@ import { AppConfig } from '../../../build/utils'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
import { NextURL } from '../../web/next-url' import { NextURL } from '../../web/next-url'
import { NextConfig } from '../../config-shared' import { NextConfig } from '../../config-shared'
import { AppRouteRouteDefinition } from '../route-definitions/app-route-route-definition'
import { WebNextRequest } from '../../base-http/web'
// TODO-APP: This module has a dynamic require so when bundling for edge it causes issues. // TODO-APP: This module has a dynamic require so when bundling for edge it causes issues.
const NodeModuleLoader = const NodeModuleLoader =
...@@ -104,7 +106,7 @@ export type StaticGenerationContext = { ...@@ -104,7 +106,7 @@ export type StaticGenerationContext = {
* @param req base request to adapt for use with app routes * @param req base request to adapt for use with app routes
* @returns the wrapped request. * @returns the wrapped request.
*/ */
function wrapRequest(req: BaseNextRequest): Request { function wrapRequest(req: BaseNextRequest): NextRequest {
const { originalRequest } = req as NodeNextRequest const { originalRequest } = req as NodeNextRequest
const url = getRequestMeta(originalRequest, '__NEXT_INIT_URL') const url = getRequestMeta(originalRequest, '__NEXT_INIT_URL')
...@@ -123,7 +125,7 @@ function wrapRequest(req: BaseNextRequest): Request { ...@@ -123,7 +125,7 @@ function wrapRequest(req: BaseNextRequest): Request {
}) })
} }
function resolveHandlerError(err: any, bubbleResult?: boolean): Response { function resolveHandlerError(err: any): Response | false {
if (isRedirectError(err)) { if (isRedirectError(err)) {
const redirect = getURLFromRedirectError(err) const redirect = getURLFromRedirectError(err)
if (!redirect) { if (!redirect) {
...@@ -139,60 +141,8 @@ function resolveHandlerError(err: any, bubbleResult?: boolean): Response { ...@@ -139,60 +141,8 @@ function resolveHandlerError(err: any, bubbleResult?: boolean): Response {
return handleNotFoundResponse() return handleNotFoundResponse()
} }
if (bubbleResult) { // Return false to indicate that this is not a handled error.
throw err return false
}
// TODO: validate the correct handling behavior
Log.error(err)
return handleInternalServerErrorResponse()
}
export async function sendResponse(
req: BaseNextRequest,
res: BaseNextResponse,
response: Response
): Promise<void> {
// Don't use in edge runtime
if (process.env.NEXT_RUNTIME !== 'edge') {
// Copy over the response status.
res.statusCode = response.status
res.statusMessage = response.statusText
// Copy over the response headers.
response.headers?.forEach((value, name) => {
// The append handling is special cased for `set-cookie`.
if (name.toLowerCase() === 'set-cookie') {
res.setHeader(name, value)
} else {
res.appendHeader(name, value)
}
})
/**
* The response can't be directly piped to the underlying response. The
* following is duplicated from the edge runtime handler.
*
* See packages/next/server/next-server.ts
*/
const originalResponse = (res as NodeNextResponse).originalResponse
// A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD
if (response.body && req.method !== 'HEAD') {
const { consumeUint8ArrayReadableStream } =
require('next/dist/compiled/edge-runtime') as typeof import('next/dist/compiled/edge-runtime')
const iterator = consumeUint8ArrayReadableStream(response.body)
try {
for await (const chunk of iterator) {
originalResponse.write(chunk)
}
} finally {
originalResponse.end()
}
} else {
originalResponse.end()
}
}
} }
function cleanURL(urlString: string): string { function cleanURL(urlString: string): string {
...@@ -203,7 +153,10 @@ function cleanURL(urlString: string): string { ...@@ -203,7 +153,10 @@ function cleanURL(urlString: string): string {
return url.toString() return url.toString()
} }
function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest { function proxyRequest(
req: NextRequest | Request,
module: AppRouteModule
): Request {
function handleNextUrlBailout(prop: string | symbol) { function handleNextUrlBailout(prop: string | symbol) {
switch (prop) { switch (prop) {
case 'search': case 'search':
...@@ -263,30 +216,33 @@ function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest { ...@@ -263,30 +216,33 @@ function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest {
} }
} }
const wrappedNextUrl = new Proxy(req.nextUrl, { const wrappedNextUrl =
get(target, prop) { 'nextUrl' in req
handleNextUrlBailout(prop) ? new Proxy(req.nextUrl, {
get(target, prop) {
if ( handleNextUrlBailout(prop)
module.handlers.dynamic === 'force-static' &&
typeof prop === 'string' if (
) { module.handlers.dynamic === 'force-static' &&
const result = handleForceStatic(target.href, prop) typeof prop === 'string'
if (result !== undefined) return result ) {
} const result = handleForceStatic(target.href, prop)
const value = (target as any)[prop] if (result !== undefined) return result
}
const value = (target as any)[prop]
if (typeof value === 'function') { if (typeof value === 'function') {
return value.bind(target) return value.bind(target)
} }
return value return value
}, },
set(target, prop, value) { set(target, prop, value) {
handleNextUrlBailout(prop) handleNextUrlBailout(prop)
;(target as any)[prop] = value ;(target as any)[prop] = value
return true return true
}, },
}) })
: undefined
const handleReqBailout = (prop: string | symbol) => { const handleReqBailout = (prop: string | symbol) => {
switch (prop) { switch (prop) {
...@@ -377,6 +333,12 @@ function validateModule(mod: AppRouteModule) { ...@@ -377,6 +333,12 @@ function validateModule(mod: AppRouteModule) {
} }
export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
/**
* The module for this handler. When set, this will be used instead of loading
* the module from the loader.
*/
public module: AppRouteModule | undefined
constructor( constructor(
private readonly nextConfigOutput: NextConfig['output'] = undefined, private readonly nextConfigOutput: NextConfig['output'] = undefined,
private readonly requestAsyncLocalStorageWrapper: AsyncStorageWrapper< private readonly requestAsyncLocalStorageWrapper: AsyncStorageWrapper<
...@@ -449,16 +411,38 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -449,16 +411,38 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
return handleMethodNotAllowedResponse return handleMethodNotAllowedResponse
} }
/**
* Loads and patches the module for the given route definition unless it's
* already been loaded.
*
* @param definition the route definition to load the module for
* @returns the loaded and patched module
*/
private async load(
definition: AppRouteRouteDefinition
): Promise<AppRouteModule> {
// Modules that have been provided by the user are already patched.
if (this.module) return this.module
// Load the module using the module loader.
const module = await this.moduleLoader.load(definition.filename)
// Patch the module with the fetch polyfill.
patchFetch(module)
return module
}
// TODO-APP: this is temporarily used for edge. // TODO-APP: this is temporarily used for edge.
public async execute( public async execute(
{ params, definition }: AppRouteRouteMatch, { params, definition }: AppRouteRouteMatch,
module: AppRouteModule,
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
context?: StaticGenerationContext, context?: StaticGenerationContext
// TODO-APP: this is temporarily used for edge.
request?: Request
): Promise<Response> { ): Promise<Response> {
// Load the module.
const module = await this.load(definition)
// Get the handler function for the given method. // Get the handler function for the given method.
const handle = this.resolve(req.method, module) const handle = this.resolve(req.method, module)
...@@ -544,8 +528,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -544,8 +528,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
// Wrap the request so we can add additional functionality to cases // Wrap the request so we can add additional functionality to cases
// that might change it's output or affect the rendering. // that might change it's output or affect the rendering.
const wrappedRequest = proxyRequest( const wrappedRequest = proxyRequest(
// TODO: investigate why/how this cast is necessary/possible req instanceof WebNextRequest ? req.request : wrapRequest(req),
(request ? request : wrapRequest(req)) as NextRequest,
module module
) )
...@@ -601,38 +584,21 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -601,38 +584,21 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
match: AppRouteRouteMatch, match: AppRouteRouteMatch,
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
context?: StaticGenerationContext, context?: StaticGenerationContext
bubbleResult?: boolean ): Promise<Response> {
): Promise<any> {
try { try {
// Load the module using the module loader.
const appRouteModule: AppRouteModule = await this.moduleLoader.load(
match.definition.filename
)
patchFetch(appRouteModule)
// Execute the route to get the response. // Execute the route to get the response.
const response = await this.execute( const response = await this.execute(match, req, res, context)
match,
appRouteModule,
req,
res,
context
)
if (bubbleResult) { // The response was handled, return it.
return response return response
}
// Send the response back to the response.
await sendResponse(req, res, response)
} catch (err) { } catch (err) {
const response = resolveHandlerError(err, bubbleResult) // Try to resolve the error to a response, else throw it again.
const response = resolveHandlerError(err)
if (!response) throw err
if (bubbleResult) { // The response was resolved, return it.
return response return response
}
// Get the correct response based on the error.
await sendResponse(req, res, response)
} }
} }
} }
...@@ -2,7 +2,7 @@ import { PagesAPIRouteMatch } from '../route-matches/pages-api-route-match' ...@@ -2,7 +2,7 @@ import { PagesAPIRouteMatch } from '../route-matches/pages-api-route-match'
import { RouteHandler } from './route-handler' import { RouteHandler } from './route-handler'
export class PagesAPIRouteHandler implements RouteHandler<PagesAPIRouteMatch> { export class PagesAPIRouteHandler implements RouteHandler<PagesAPIRouteMatch> {
public async handle(): Promise<void> { public async handle(): Promise<Response> {
throw new Error('Method not implemented.') throw new Error('Method not implemented.')
} }
} }
...@@ -2,7 +2,7 @@ import { PagesRouteMatch } from '../route-matches/pages-route-match' ...@@ -2,7 +2,7 @@ import { PagesRouteMatch } from '../route-matches/pages-route-match'
import { RouteHandler } from './route-handler' import { RouteHandler } from './route-handler'
export class PagesRouteHandler implements RouteHandler<PagesRouteMatch> { export class PagesRouteHandler implements RouteHandler<PagesRouteMatch> {
public async handle(): Promise<void> { public async handle(): Promise<Response> {
throw new Error('Method not implemented.') throw new Error('Method not implemented.')
} }
} }
...@@ -6,7 +6,6 @@ export interface RouteHandler<M extends RouteMatch = RouteMatch> { ...@@ -6,7 +6,6 @@ export interface RouteHandler<M extends RouteMatch = RouteMatch> {
match: M, match: M,
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
context?: any, context?: any
bubbleResult?: boolean ): Promise<Response>
): Promise<any>
} }
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { NodeNextResponse } from './base-http/node'
/**
* Sends the response on the underlying next response object.
*
* @param req the underlying request object
* @param res the underlying response object
* @param response the response to send
*/
export async function sendResponse(
req: BaseNextRequest,
res: BaseNextResponse,
response: Response
): Promise<void> {
// Don't use in edge runtime
if (process.env.NEXT_RUNTIME !== 'edge') {
// Copy over the response status.
res.statusCode = response.status
res.statusMessage = response.statusText
// Copy over the response headers.
response.headers?.forEach((value, name) => {
// The append handling is special cased for `set-cookie`.
if (name.toLowerCase() === 'set-cookie') {
res.setHeader(name, value)
} else {
res.appendHeader(name, value)
}
})
/**
* The response can't be directly piped to the underlying response. The
* following is duplicated from the edge runtime handler.
*
* See packages/next/server/next-server.ts
*/
const originalResponse = (res as NodeNextResponse).originalResponse
// A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD
if (response.body && req.method !== 'HEAD') {
const { consumeUint8ArrayReadableStream } =
require('next/dist/compiled/edge-runtime') as typeof import('next/dist/compiled/edge-runtime')
const iterator = consumeUint8ArrayReadableStream(response.body)
try {
for await (const chunk of iterator) {
originalResponse.write(chunk)
}
} finally {
originalResponse.end()
}
} else {
originalResponse.end()
}
}
}
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