Skip to content

Commit

Permalink
remove waitUntil and onClose from renderOpts
Browse files Browse the repository at this point in the history
  • Loading branch information
lubieowoce committed Sep 24, 2024
1 parent b0958b3 commit 8199296
Show file tree
Hide file tree
Showing 16 changed files with 101 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,10 @@ export function getRender({
request: NextRequestHint,
event?: NextFetchEvent
) {
const extendedReq = new WebNextRequest(request)
const extendedReq = new WebNextRequest(
request,
event ? { waitUntil: event.waitUntil.bind(event) } : undefined
)
const extendedRes = new WebNextResponse(
undefined,
// tracking onClose adds overhead, so only do it if `experimental.after` is on.
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/export/routes/app-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export async function exportAppPage(

try {
const result = await lazyRenderAppPage(
new NodeNextRequest(req),
new NodeNextRequest(req, undefined),
new NodeNextResponse(res),
pathname,
query,
Expand Down
8 changes: 5 additions & 3 deletions packages/next/src/export/routes/app-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function exportAppRoute(

// Adapt the request and response to the Next.js request and response.
const request = NextRequestAdapter.fromNodeNextRequest(
new NodeNextRequest(req),
new NodeNextRequest(req, undefined),
signalFromNodeResponse(res)
)

Expand All @@ -69,13 +69,15 @@ export async function exportAppRoute(
},
notFoundRoutes: [],
},
context: {
waitUntil: undefined,
onClose: undefined,
},
renderOpts: {
experimental,
nextExport: true,
supportsDynamicResponse: false,
incrementalCache,
waitUntil: undefined,
onClose: undefined,
},
}

Expand Down
6 changes: 1 addition & 5 deletions packages/next/src/export/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import type { OutgoingHttpHeaders } from 'http'
import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { Revalidate } from '../server/lib/revalidate'
import type {
NextEnabledDirectories,
RequestLifecycleOpts,
} from '../server/base-server'
import type { NextEnabledDirectories } from '../server/base-server'
import type {
SerializableTurborepoAccessTraceResult,
TurborepoAccessTraceResult,
Expand Down Expand Up @@ -116,7 +113,6 @@ export type WorkerRenderOptsPartial = PagesRenderOptsPartial &
AppRenderOptsPartial

export type WorkerRenderOpts = WorkerRenderOptsPartial &
RequestLifecycleOpts &
LoadComponentsReturnType

export interface ExportAppOptions {
Expand Down
2 changes: 0 additions & 2 deletions packages/next/src/export/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,6 @@ async function exportPageImpl(
...input.renderOpts.experimental,
isRoutePPREnabled,
},
waitUntil: undefined,
onClose: undefined,
}

if (hasNextSupport) {
Expand Down
4 changes: 1 addition & 3 deletions packages/next/src/server/app-render/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type { LoadingModuleData } from '../../shared/lib/app-router-context.shar
import type { DeepReadonly } from '../../shared/lib/deep-readonly'

import s from 'next/dist/compiled/superstruct'
import type { RequestLifecycleOpts } from '../base-server'
import type { InstrumentationOnRequestError } from '../instrumentation/types'
import type { NextRequestHint } from '../web/adapter'
import type { BaseNextRequest } from '../base-http'
Expand Down Expand Up @@ -201,8 +200,7 @@ export interface RenderOptsPartial {
}

export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
RenderOptsPartial &
RequestLifecycleOpts
RenderOptsPartial

export type PreloadCallbacks = (() => void)[]

Expand Down
61 changes: 34 additions & 27 deletions packages/next/src/server/async-storage/with-request-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,15 @@ function getMutableCookies(
return MutableRequestCookiesAdapter.wrap(cookies, onUpdateCookies)
}

export type WrapperRenderOpts = RequestLifecycleOpts &
Partial<
Pick<
RenderOpts,
| 'ComponentMod'
| 'onUpdateCookies'
| 'assetPrefix'
| 'reactLoadableManifest'
>
> & {
experimental: Pick<RenderOpts['experimental'], 'after'>
previewProps?: __ApiPreviewProps
}
export type WrapperRenderOpts = Partial<
Pick<
RenderOpts,
'ComponentMod' | 'onUpdateCookies' | 'assetPrefix' | 'reactLoadableManifest'
>
> & {
experimental: Pick<RenderOpts['experimental'], 'after'>
previewProps?: __ApiPreviewProps
}

export type RequestContext = RequestResponsePair & {
/**
Expand All @@ -79,8 +75,8 @@ export type RequestContext = RequestResponsePair & {
}

type RequestResponsePair =
| { req: BaseNextRequest; res: BaseNextResponse } // for an app page
| { req: NextRequest; res: undefined } // in an api route or middleware
| { req: BaseNextRequest; res: BaseNextResponse; context?: undefined } // for an app page
| { req: NextRequest; res: undefined; context: Partial<RequestLifecycleOpts> } // in an api route or middleware

/**
* If middleware set cookies in this request (indicated by `x-middleware-set-cookie`),
Expand Down Expand Up @@ -115,16 +111,11 @@ export const withRequestStore: WithStore<RequestStore, RequestContext> = <
Result,
>(
storage: AsyncLocalStorage<RequestStore>,
{
req,
url,
res,
renderOpts,
isHmrRefresh,
serverComponentsHmrCache,
}: RequestContext,
args: RequestContext,
callback: (store: RequestStore) => Result
): Result => {
const { req, url, res, renderOpts, isHmrRefresh, serverComponentsHmrCache } =
args
function defaultOnUpdateCookies(cookies: string[]) {
if (res) {
res.setHeader('Set-Cookie', cookies)
Expand Down Expand Up @@ -198,7 +189,7 @@ export const withRequestStore: WithStore<RequestStore, RequestContext> = <

reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
assetPrefix: renderOpts?.assetPrefix || '',
afterContext: createAfterContext(renderOpts),
afterContext: createAfterContext(args),
isHmrRefresh,
serverComponentsHmrCache:
serverComponentsHmrCache ||
Expand All @@ -215,12 +206,28 @@ export const withRequestStore: WithStore<RequestStore, RequestContext> = <
}

function createAfterContext(
renderOpts: WrapperRenderOpts | undefined
args: RequestResponsePair & Pick<RequestContext, 'renderOpts'>
): AfterContext | undefined {
if (!isAfterEnabled(renderOpts)) {
if (!isAfterEnabled(args.renderOpts)) {
return undefined
}
const { waitUntil, onClose } = renderOpts

if (args.context) {
return new AfterContext({
waitUntil: args.context.waitUntil,
onClose: args.context.onClose,
})
}

const { req, res } = args
// For some reason, `req instanceof BaseNextRequest` is always false here,
// so just check for the `context` property instead
const waitUntil = 'context' in req ? req.context?.waitUntil : undefined

// For some reason, `req instanceof BaseNextResponse` is always false here,
// so just check for the `onClose` property instead
const onClose = 'onClose' in res ? res.onClose.bind(res) : undefined

return new AfterContext({ waitUntil, onClose })
}

Expand Down
6 changes: 5 additions & 1 deletion packages/next/src/server/base-http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { I18NConfig } from '../config-shared'
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import type { NextApiRequestCookies } from '../api-utils'
import { getCookieParser } from '../api-utils/get-cookie-parser'
import type { WaitUntil } from '../after/builtin-request-context'

export interface BaseNextRequestConfig {
basePath: string | undefined
Expand All @@ -25,6 +26,8 @@ export type FetchMetric = {

export type FetchMetrics = Array<FetchMetric>

export type NextRequestContext = { waitUntil: WaitUntil }

export abstract class BaseNextRequest<Body = any> {
protected _cookies: NextApiRequestCookies | undefined
public abstract headers: IncomingHttpHeaders
Expand All @@ -33,7 +36,8 @@ export abstract class BaseNextRequest<Body = any> {
constructor(
public method: string,
public url: string,
public body: Body
public body: Body,
public readonly context: NextRequestContext | undefined
) {}

// Utils implemented using the abstract methods above
Expand Down
14 changes: 11 additions & 3 deletions packages/next/src/server/base-http/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import type { NextApiRequestCookies } from '../api-utils'
import { NEXT_REQUEST_META } from '../request-meta'
import type { RequestMeta } from '../request-meta'

import { BaseNextRequest, BaseNextResponse, type FetchMetric } from './index'
import {
BaseNextRequest,
BaseNextResponse,
type FetchMetric,
type NextRequestContext,
} from './index'
import type { OutgoingHttpHeaders } from 'node:http'

type Req = IncomingMessage & {
Expand All @@ -22,8 +27,11 @@ export class NodeNextRequest extends BaseNextRequest<Readable> {

[NEXT_REQUEST_META]: RequestMeta = this._req[NEXT_REQUEST_META] || {}

constructor(private _req: Req) {
super(_req.method!.toUpperCase(), _req.url!, _req)
constructor(
private _req: Req,
context: NextRequestContext | undefined
) {
super(_req.method!.toUpperCase(), _req.url!, _req, context)
}

get originalRequest() {
Expand Down
10 changes: 7 additions & 3 deletions packages/next/src/server/base-http/web.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'
import type { FetchMetrics } from './index'
import type { FetchMetrics, NextRequestContext } from './index'

import { toNodeOutgoingHttpHeaders } from '../web/utils'
import { BaseNextRequest, BaseNextResponse } from './index'
Expand All @@ -13,13 +13,17 @@ export class WebNextRequest extends BaseNextRequest<ReadableStream | null> {
public headers: IncomingHttpHeaders
public fetchMetrics?: FetchMetrics

constructor(request: NextRequestHint) {
constructor(
request: NextRequestHint,
context: NextRequestContext | undefined
) {
const url = new URL(request.url)

super(
request.method,
url.href.slice(url.origin.length),
request.clone().body
request.clone().body,
context
)
this.request = request
this.fetchMetrics = request.fetchMetrics
Expand Down
12 changes: 5 additions & 7 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,7 @@ export interface Options {

export type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial

export type LoadedRenderOpts = RenderOpts &
LoadComponentsReturnType &
RequestLifecycleOpts
export type LoadedRenderOpts = RenderOpts & LoadComponentsReturnType

export type RequestLifecycleOpts = {
waitUntil: ((promise: Promise<any>) => void) | undefined
Expand Down Expand Up @@ -2437,8 +2435,6 @@ export default abstract class Server<
isDraftMode: isPreviewMode,
isServerAction,
postponed,
waitUntil: this.getWaitUntil(),
onClose: res.onClose.bind(res),
// only available in dev
setAppIsrStatus: (this as any).setAppIsrStatus,
}
Expand Down Expand Up @@ -2474,6 +2470,10 @@ export default abstract class Server<
const context: AppRouteRouteHandlerContext = {
params: opts.params,
prerenderManifest,
context: {
waitUntil: req.context?.waitUntil,
onClose: res.onClose.bind(res),
},
renderOpts: {
experimental: {
after: renderOpts.experimental.after,
Expand All @@ -2482,8 +2482,6 @@ export default abstract class Server<
supportsDynamicResponse,
incrementalCache,
isRevalidate: isSSG,
waitUntil: this.getWaitUntil(),
onClose: res.onClose.bind(res),
onInstrumentationRequestError:
this.renderOpts.onInstrumentationRequestError,
},
Expand Down
13 changes: 9 additions & 4 deletions packages/next/src/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1083,7 +1083,11 @@ export default class NextNodeServer extends BaseServer<
protected normalizeReq(
req: NodeNextRequest | IncomingMessage
): NodeNextRequest {
return !(req instanceof NodeNextRequest) ? new NodeNextRequest(req) : req
if (!(req instanceof NodeNextRequest)) {
const waitUntil = this.getWaitUntil()
return new NodeNextRequest(req, waitUntil ? { waitUntil } : undefined)
}
return req
}

protected normalizeRes(
Expand Down Expand Up @@ -1133,8 +1137,9 @@ export default class NextNodeServer extends BaseServer<
})

const handler = this.getRequestHandler()
const waitUntil = this.getWaitUntil()
await handler(
new NodeNextRequest(mocked.req),
new NodeNextRequest(mocked.req, waitUntil ? { waitUntil } : undefined),
new NodeNextResponse(mocked.res)
)
await mocked.res.hasStreamed
Expand Down Expand Up @@ -1465,7 +1470,7 @@ export default class NextNodeServer extends BaseServer<
page,
body: getRequestMeta(params.request, 'clonableBody'),
signal: signalFromNodeResponse(params.response.originalResponse),
waitUntil: this.getWaitUntil(),
waitUntil: params.request.context?.waitUntil,
},
useCache: true,
onWarning: params.onWarning,
Expand Down Expand Up @@ -1769,7 +1774,7 @@ export default class NextNodeServer extends BaseServer<
},
body: getRequestMeta(params.req, 'clonableBody'),
signal: signalFromNodeResponse(params.res.originalResponse),
waitUntil: this.getWaitUntil(),
waitUntil: params.req.context?.waitUntil,
},
useCache: true,
onError: params.onError,
Expand Down
5 changes: 3 additions & 2 deletions packages/next/src/server/route-modules/app-route/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import { ReflectAdapter } from '../../web/spec-extension/adapters/reflect'
import type { RenderOptsPartial } from '../../app-render/types'
import { CacheSignal } from '../../app-render/cache-signal'
import { scheduleImmediate } from '../../../lib/scheduler'
import type { RequestLifecycleOpts } from '../../base-server'

/**
* The AppRouteModule is the type of the module exported by the bundled App
Expand All @@ -83,6 +84,7 @@ export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
renderOpts: StaticGenerationContext['renderOpts'] &
Pick<RenderOptsPartial, 'onInstrumentationRequestError'>
prerenderManifest: DeepReadonly<PrerenderManifest>
context: RequestLifecycleOpts
}

/**
Expand Down Expand Up @@ -277,11 +279,10 @@ export class AppRouteRouteModule extends RouteModule<
const requestContext: RequestContext = {
req: rawRequest,
res: undefined,
context: context.context,
url: rawRequest.nextUrl,
renderOpts: {
previewProps: context.prerenderManifest.preview,
waitUntil: context.renderOpts.waitUntil,
onClose: context.renderOpts.onClose,
experimental: context.renderOpts.experimental,
},
}
Expand Down
Loading

0 comments on commit 8199296

Please sign in to comment.