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 = {
}
export function getHandle({ page, mod, nextConfigOutput }: HandleProps) {
const appRouteRouteHandler = new AppRouteRouteHandler(nextConfigOutput)
const appRouteRouteMatcher = new AppRouteRouteMatcher({
const handler = new AppRouteRouteHandler(nextConfigOutput)
// 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,
pathname: normalizeAppPath(page),
page: '',
......@@ -31,17 +35,16 @@ export function getHandle({ page, mod, nextConfigOutput }: HandleProps) {
return async function handle(request: Request) {
const extendedReq = new WebNextRequest(request)
const extendedRes = new WebNextResponse()
const match = appRouteRouteMatcher.match(
const match = matcher.match(
removeTrailingSlash(new URL(request.url).pathname)
)!
const response = await appRouteRouteHandler.execute(
const response = await handler.handle(
match,
mod,
extendedReq,
extendedRes,
// TODO: pass incrementalCache here
{ supportsDynamicHTML: true },
request
{ supportsDynamicHTML: true }
)
return response
......
......@@ -41,6 +41,7 @@ import { RouteKind } from '../server/future/route-kind'
import { NodeNextRequest, NodeNextResponse } from '../server/base-http/node'
import { StaticGenerationContext } from '../server/future/route-handlers/app-route-route-handler'
import { isAppRouteRoute } from '../lib/is-app-route-route'
import { AppRouteRouteMatch } from '../server/future/route-matches/app-route-route-match'
loadRequireHook()
......@@ -393,24 +394,26 @@ export default async function exportPage({
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 {
const routeHandler = new AppRouteRouteHandler(nextConfigOuput)
const response: Response = await routeHandler.handle(
{
params: query,
definition: {
filename: posix.join(distDir, 'server', 'app', page),
bundlePath: posix.join('app', page),
kind: RouteKind.APP_ROUTE,
page,
pathname: path,
},
},
const handler = new AppRouteRouteHandler(nextConfigOuput)
const response = await handler.handle(
match,
nodeReq,
nodeRes,
staticContext,
true
staticContext
)
// we don't consider error status for static generation
// except for 404
// TODO: do we want to cache other status codes?
......
......@@ -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 { getTracer, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants'
import { sendResponse } from './future/route-handlers/app-route-route-handler'
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 = {
components: LoadComponentsReturnType
......@@ -1456,37 +1458,56 @@ export default abstract class Server<ServerOptions extends Options = Options> {
supportsDynamicHTML,
incrementalCache,
}
let response: Response | undefined = (await this.handlers.handle(
match,
req,
res,
context,
isSSG
)) as any
if (response) {
if (isSSG && process.env.NEXT_RUNTIME !== 'edge') {
const blob = await response.blob()
const headers = Object.fromEntries(response.headers)
if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type
}
const cacheEntry: ResponseCacheEntry = {
value: {
kind: 'ROUTE',
status: response.status,
body: Buffer.from(await blob.arrayBuffer()),
headers,
},
revalidate:
((context as any).store as any as { revalidate?: number })
.revalidate || false,
try {
// Handle the match and collect the response if it's a static response.
const response = await this.handlers.handle(match, req, res, context)
if (response) {
// If the request is for a static response, we can cache it so long
// as it's not edge.
if (isSSG && process.env.NEXT_RUNTIME !== 'edge') {
const blob = await response.blob()
// Copy the headers from the response.
const headers = Object.fromEntries(response.headers)
if (!headers['content-type'] && blob.type) {
headers['content-type'] = blob.type
}
// Create the cache entry for the response.
const cacheEntry: ResponseCacheEntry = {
value: {
kind: 'ROUTE',
status: response.status,
body: Buffer.from(await blob.arrayBuffer()),
headers,
},
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 {
match: RouteMatch,
req: BaseNextRequest,
res: BaseNextResponse,
context?: any,
bubbleResult?: boolean
): Promise<boolean> {
context?: any
): Promise<Response | undefined> {
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 result as any
}
return true
return response
}
}
......@@ -2,7 +2,7 @@ import { AppPageRouteMatch } from '../route-matches/app-page-route-match'
import { RouteHandler } from './route-handler'
export class AppPageRouteHandler implements RouteHandler<AppPageRouteMatch> {
public async handle(): Promise<void> {
public async handle(): Promise<Response> {
throw new Error('Method not implemented.')
}
}
......@@ -13,8 +13,8 @@ import {
RequestAsyncStorageWrapper,
type RequestContext,
} from '../../async-storage/request-async-storage-wrapper'
import type { BaseNextRequest, BaseNextResponse } from '../../base-http'
import type { NodeNextRequest, NodeNextResponse } from '../../base-http/node'
import { BaseNextRequest, BaseNextResponse } from '../../base-http'
import { NodeNextRequest, NodeNextResponse } from '../../base-http/node'
import { getRequestMeta } from '../../request-meta'
import {
handleBadRequestResponse,
......@@ -38,6 +38,8 @@ import { AppConfig } from '../../../build/utils'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
import { NextURL } from '../../web/next-url'
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.
const NodeModuleLoader =
......@@ -104,7 +106,7 @@ export type StaticGenerationContext = {
* @param req base request to adapt for use with app routes
* @returns the wrapped request.
*/
function wrapRequest(req: BaseNextRequest): Request {
function wrapRequest(req: BaseNextRequest): NextRequest {
const { originalRequest } = req as NodeNextRequest
const url = getRequestMeta(originalRequest, '__NEXT_INIT_URL')
......@@ -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)) {
const redirect = getURLFromRedirectError(err)
if (!redirect) {
......@@ -139,60 +141,8 @@ function resolveHandlerError(err: any, bubbleResult?: boolean): Response {
return handleNotFoundResponse()
}
if (bubbleResult) {
throw err
}
// 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()
}
}
// Return false to indicate that this is not a handled error.
return false
}
function cleanURL(urlString: string): string {
......@@ -203,7 +153,10 @@ function cleanURL(urlString: string): string {
return url.toString()
}
function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest {
function proxyRequest(
req: NextRequest | Request,
module: AppRouteModule
): Request {
function handleNextUrlBailout(prop: string | symbol) {
switch (prop) {
case 'search':
......@@ -263,30 +216,33 @@ function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest {
}
}
const wrappedNextUrl = new Proxy(req.nextUrl, {
get(target, prop) {
handleNextUrlBailout(prop)
if (
module.handlers.dynamic === 'force-static' &&
typeof prop === 'string'
) {
const result = handleForceStatic(target.href, prop)
if (result !== undefined) return result
}
const value = (target as any)[prop]
const wrappedNextUrl =
'nextUrl' in req
? new Proxy(req.nextUrl, {
get(target, prop) {
handleNextUrlBailout(prop)
if (
module.handlers.dynamic === 'force-static' &&
typeof prop === 'string'
) {
const result = handleForceStatic(target.href, prop)
if (result !== undefined) return result
}
const value = (target as any)[prop]
if (typeof value === 'function') {
return value.bind(target)
}
return value
},
set(target, prop, value) {
handleNextUrlBailout(prop)
;(target as any)[prop] = value
return true
},
})
if (typeof value === 'function') {
return value.bind(target)
}
return value
},
set(target, prop, value) {
handleNextUrlBailout(prop)
;(target as any)[prop] = value
return true
},
})
: undefined
const handleReqBailout = (prop: string | symbol) => {
switch (prop) {
......@@ -377,6 +333,12 @@ function validateModule(mod: AppRouteModule) {
}
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(
private readonly nextConfigOutput: NextConfig['output'] = undefined,
private readonly requestAsyncLocalStorageWrapper: AsyncStorageWrapper<
......@@ -449,16 +411,38 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
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.
public async execute(
{ params, definition }: AppRouteRouteMatch,
module: AppRouteModule,
req: BaseNextRequest,
res: BaseNextResponse,
context?: StaticGenerationContext,
// TODO-APP: this is temporarily used for edge.
request?: Request
context?: StaticGenerationContext
): Promise<Response> {
// Load the module.
const module = await this.load(definition)
// Get the handler function for the given method.
const handle = this.resolve(req.method, module)
......@@ -544,8 +528,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
// Wrap the request so we can add additional functionality to cases
// that might change it's output or affect the rendering.
const wrappedRequest = proxyRequest(
// TODO: investigate why/how this cast is necessary/possible
(request ? request : wrapRequest(req)) as NextRequest,
req instanceof WebNextRequest ? req.request : wrapRequest(req),
module
)
......@@ -601,38 +584,21 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
match: AppRouteRouteMatch,
req: BaseNextRequest,
res: BaseNextResponse,
context?: StaticGenerationContext,
bubbleResult?: boolean
): Promise<any> {
context?: StaticGenerationContext
): Promise<Response> {
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.
const response = await this.execute(
match,
appRouteModule,
req,
res,
context
)
const response = await this.execute(match, req, res, context)
if (bubbleResult) {
return response
}
// Send the response back to the response.
await sendResponse(req, res, response)
// The response was handled, return it.
return response
} 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) {
return response
}
// Get the correct response based on the error.
await sendResponse(req, res, response)
// The response was resolved, return it.
return response
}
}
}
......@@ -2,7 +2,7 @@ import { PagesAPIRouteMatch } from '../route-matches/pages-api-route-match'
import { RouteHandler } from './route-handler'
export class PagesAPIRouteHandler implements RouteHandler<PagesAPIRouteMatch> {
public async handle(): Promise<void> {
public async handle(): Promise<Response> {
throw new Error('Method not implemented.')
}
}
......@@ -2,7 +2,7 @@ import { PagesRouteMatch } from '../route-matches/pages-route-match'
import { RouteHandler } from './route-handler'
export class PagesRouteHandler implements RouteHandler<PagesRouteMatch> {
public async handle(): Promise<void> {
public async handle(): Promise<Response> {
throw new Error('Method not implemented.')
}
}
......@@ -6,7 +6,6 @@ export interface RouteHandler<M extends RouteMatch = RouteMatch> {
match: M,
req: BaseNextRequest,
res: BaseNextResponse,
context?: any,
bubbleResult?: boolean
): Promise<any>
context?: any
): Promise<Response>
}
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