Unverified Commit 3a1d3f84 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[unstable_after] always use 'waitUntil' from '@next/request-context' if available (#66119)

This PR changes the `getWaitUntil` logic to always check if the platform
provided a request context with a `waitUntil` implementation (via [the
`@next/request-context`
symbol](https://github.com/vercel/next.js/blob/05e6b825768355372dcdfff06dfcd264f78507d3/packages/next/src/server/after/wait-until-builtin.ts#L12))
, regardless of minimalMode or runtime.

Previously, we wouldn't check the context at all unless `minimalMode`
was set, and defaulted `waitUntil` to a noop otherwise. This would make
integration more difficult for providers who don't use `minimalMode`,
because they'd have no way to inject their `waitUntil` implementation.
parent 05e6b825
export type WaitUntil = (promise: Promise<any>) => void export function getBuiltinRequestContext():
| BuiltinRequestContextValue
export function getBuiltinWaitUntil(): WaitUntil | undefined { | undefined {
const _globalThis = globalThis as GlobalThisWithRequestContext const _globalThis = globalThis as GlobalThisWithRequestContext
const ctx = const ctx =
_globalThis[NEXT_REQUEST_CONTEXT_SYMBOL] ?? _globalThis[NEXT_REQUEST_CONTEXT_SYMBOL] ??
_globalThis[VERCEL_REQUEST_CONTEXT_SYMBOL] _globalThis[VERCEL_REQUEST_CONTEXT_SYMBOL]
return ctx?.get()?.waitUntil return ctx?.get()
} }
/** This should be considered unstable until `unstable_after` is stablized. */ /** This should be considered unstable until `unstable_after` is stablized. */
...@@ -16,12 +16,16 @@ const NEXT_REQUEST_CONTEXT_SYMBOL = Symbol.for('@next/request-context') ...@@ -16,12 +16,16 @@ const NEXT_REQUEST_CONTEXT_SYMBOL = Symbol.for('@next/request-context')
const VERCEL_REQUEST_CONTEXT_SYMBOL = Symbol.for('@vercel/request-context') const VERCEL_REQUEST_CONTEXT_SYMBOL = Symbol.for('@vercel/request-context')
type GlobalThisWithRequestContext = typeof globalThis & { type GlobalThisWithRequestContext = typeof globalThis & {
[NEXT_REQUEST_CONTEXT_SYMBOL]?: RequestContext [NEXT_REQUEST_CONTEXT_SYMBOL]?: BuiltinRequestContext
/** @deprecated */ /** @deprecated */
[VERCEL_REQUEST_CONTEXT_SYMBOL]?: RequestContext [VERCEL_REQUEST_CONTEXT_SYMBOL]?: BuiltinRequestContext
} }
/** This should be considered unstable until `unstable_after` is stablized. */ /** A request context provided by the platform.
type RequestContext = { * It should be considered unstable until `unstable_after` is stablized. */
get(): { waitUntil: WaitUntil } | undefined export type BuiltinRequestContext = {
get(): BuiltinRequestContextValue | undefined
} }
export type BuiltinRequestContextValue = { waitUntil?: WaitUntil }
export type WaitUntil = (promise: Promise<any>) => void
...@@ -146,7 +146,10 @@ import type { DeepReadonly } from '../shared/lib/deep-readonly' ...@@ -146,7 +146,10 @@ import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers' import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header' import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'
import { checkIsAppPPREnabled } from './lib/experimental/ppr' import { checkIsAppPPREnabled } from './lib/experimental/ppr'
import { getBuiltinWaitUntil } from './after/wait-until-builtin' import {
getBuiltinRequestContext,
type WaitUntil,
} from './after/builtin-request-context'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -1667,24 +1670,36 @@ export default abstract class Server< ...@@ -1667,24 +1670,36 @@ export default abstract class Server<
) )
} }
private getWaitUntil() { private getWaitUntil(): WaitUntil | undefined {
const useBuiltinWaitUntil = const builtinRequestContext = getBuiltinRequestContext()
process.env.NEXT_RUNTIME === 'edge' || this.minimalMode if (builtinRequestContext) {
// the platform provided a request context.
// use the `waitUntil` from there, whether actually present or not --
// if not present, `unstable_after` will error.
return builtinRequestContext.waitUntil
}
let waitUntil = useBuiltinWaitUntil ? getBuiltinWaitUntil() : undefined if (process.env.__NEXT_TEST_MODE) {
// we're in a test, use a no-op.
return Server.noopWaitUntil
}
if (!waitUntil) { if (this.minimalMode || process.env.NEXT_RUNTIME === 'edge') {
// if we're not running in a serverless environment, // we're built for a serverless environment, and `waitUntil` is not available,
// we don't actually need waitUntil -- the server will stay alive anyway. // but using a noop would likely lead to incorrect behavior,
// the only thing we want to do is prevent unhandled rejections. // because we have no way of keeping the invocation alive.
waitUntil = function noopWaitUntil(promise) { // return nothing, and `unstable_after` will error if used.
promise.catch((err: unknown) => { return undefined
console.error(err)
})
}
} }
return waitUntil // we're in `next start` or `next dev`. noop is fine for both.
return Server.noopWaitUntil
}
private static noopWaitUntil(promise: Promise<any>) {
promise.catch((err: unknown) => {
console.error(err)
})
} }
private async renderImpl( private async renderImpl(
......
import { unstable_after as after } from 'next/server'
import { cliLog } from '../../utils/log'
export default function Page() {
after(() => {
cliLog({ source: '[page] /provided-request-context' })
})
return <div>provided-request-context</div>
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import { createProxyServer } from 'next/experimental/testmode/proxy' import { createProxyServer } from 'next/experimental/testmode/proxy'
import { outdent } from 'outdent'
import { sandbox } from '../../../lib/development-sandbox' import { sandbox } from '../../../lib/development-sandbox'
import * as fs from 'fs' import * as fs from 'fs'
import * as path from 'path' import * as path from 'path'
...@@ -58,6 +59,10 @@ describe.each(runtimes)('unstable_after() in %s runtime', (runtimeValue) => { ...@@ -58,6 +59,10 @@ describe.each(runtimes)('unstable_after() in %s runtime', (runtimeValue) => {
}) })
const getLogs = () => { const getLogs = () => {
if (next.cliOutput.length < currentCliOutputIndex) {
// cliOutput shrank since we started the test, so something (like a `sandbox`) reset the logs
currentCliOutputIndex = 0
}
return Log.readCliLogs(next.cliOutput.slice(currentCliOutputIndex)) return Log.readCliLogs(next.cliOutput.slice(currentCliOutputIndex))
} }
...@@ -274,6 +279,40 @@ describe.each(runtimes)('unstable_after() in %s runtime', (runtimeValue) => { ...@@ -274,6 +279,40 @@ describe.each(runtimes)('unstable_after() in %s runtime', (runtimeValue) => {
} }
}) })
it('uses waitUntil from request context if available', async () => {
const { cleanup } = await sandbox(
next,
new Map([
[
// this needs to be injected as early as possible, before the server tries to read the context
// (which may be even before we load the page component in dev mode)
'instrumentation.js',
outdent`
import { injectRequestContext } from './utils/provided-request-context'
export function register() {
injectRequestContext();
}
`,
],
]),
'/provided-request-context'
)
try {
await retry(() => {
const logs = getLogs()
expect(logs).toContainEqual(
'waitUntil from "@next/request-context" was called'
)
expect(logs).toContainEqual({
source: '[page] /provided-request-context',
})
})
} finally {
await cleanup()
}
})
if (isNextDev) { if (isNextDev) {
// TODO: these are at the end because they destroy the next server. // TODO: these are at the end because they destroy the next server.
// is there a cleaner way to do this without making the tests slower? // is there a cleaner way to do this without making the tests slower?
......
...@@ -3,5 +3,6 @@ module.exports = { ...@@ -3,5 +3,6 @@ module.exports = {
experimental: { experimental: {
after: true, after: true,
testProxy: true, testProxy: true,
instrumentationHook: true,
}, },
} }
export function cliLog(/** @type {Record<string, any>} */ data) { export function cliLog(/** @type {string | Record<string, any>} */ data) {
console.log('<test-log>' + JSON.stringify(data) + '</test-log>') console.log('<test-log>' + JSON.stringify(data) + '</test-log>')
} }
......
import { cliLog } from './log'
export function injectRequestContext() {
// eslint-disable-next-line no-undef
const _globalThis = globalThis
/** @type {import('next/dist/server/after/builtin-request-context').BuiltinRequestContext} */
_globalThis[Symbol.for('@next/request-context')] = {
get() {
return {
waitUntil(/** @type {Promise<any>} */ promise) {
cliLog('waitUntil from "@next/request-context" was called')
promise.catch((err) => {
console.error(err)
})
},
}
},
}
return () => {
delete _globalThis[Symbol.for('@next/request-context')]
}
}
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