vercel/next.js · #102505
[CC] Allow scheduling sequential tasks via setImmediate
packages/next/src/build/define-env.ts2 + / 0 −
@@ -193,6 +193,8 @@ export function getDefineEnv({ dev && !!config.experimental.requestInsights, 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled, 'process.env.__NEXT_USE_NODE_STREAMS': isEdgeServer ? false : true,+ 'process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING':+ config.experimental.sequentialTaskScheduling ?? 'unstable_timer', 'process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS': config.supportsImmutableAssets || false,packages/next/src/build/index.ts4 + / 0 −
@@ -1069,6 +1069,10 @@ export function createStaticWorker( config.supportsImmutableAssets || !config.deploymentId ? '' : `?dpl=${config.deploymentId}`,+ // Page-data collection loads precompiled app-render bundles, which select+ // the scheduler at module initialization, before prerendering starts.+ __NEXT_SEQUENTIAL_TASK_SCHEDULING:+ config.experimental.sequentialTaskScheduling ?? 'unstable_timer', }, }, }) as StaticWorkerpackages/next/src/server/app-render/app-render-scheduling/__tests__/mock-set-immediate.util.tsadded34 + / 0 −
@@ -0,0 +1,34 @@+import { promisify } from 'node:util'++// Exclude weird __promisify__ property+type SetImmediate = ((+ ...args: Parameters<typeof setImmediate>+) => ReturnType<typeof setImmediate>) & {+ [promisify.custom]?: (...args: any[]) => any+}++let mockedSetImmediate: SetImmediate | null = null++export function mockSetImmediate(implementation: SetImmediate | null) {+ mockedSetImmediate = implementation+}++const originalSetImmediate = globalThis.setImmediate++export { originalSetImmediate as unmockedSetImmediate }++const wrappedSetImmediate: SetImmediate = (...args) => {+ if (mockedSetImmediate !== null) {+ return mockedSetImmediate(...args)+ } else {+ return originalSetImmediate(...args)+ }+}++// We don't care about promisify for tests, but preserving the original just in case+wrappedSetImmediate[promisify.custom] =+ // @ts-expect-error the types for setImmediate's promisify are strange+ originalSetImmediate[promisify.custom]++// Cast as workaround for missing __promisify__, which is not a real property+globalThis.setImmediate = wrappedSetImmediate as unknown as typeof setImmediatepackages/next/src/server/app-render/app-render-scheduling/immediate-scheduler.tsadded165 + / 0 −
@@ -0,0 +1,165 @@+import { InvariantError } from '../../../shared/lib/invariant-error'+import { unpatchedSetImmediate } from '../../node-environment-extensions/fast-set-immediate.external'+import type { SequentialTaskScheduler } from './types'++let hasBadSetImmediate = false++function warnAboutSetImmediate() {+ console.warn(+ "Next.js cannot guarantee that Cache Components will run as expected due to the current runtime's implementation of `setImmediate()`.\nPlease report a github issue here: https://github.com/vercel/next.js/issues/new/"+ )+}++const enum ExecutionState {+ Before = 1,+ ScheduledTasks = 2,+ ExecutingTasks = 3,+ Finished = 4,+}++type Execution = {+ state: ExecutionState+ pendingTimeout: NodeJS.Timeout | null+}++/**+ * Allows scheduling multiple tasks that are guaranteed to run in the same iteration of the event loop.+ * Conceptually equivalent to calling `setImmediate(cb)` for each callback.+ *+ * @param tasks - the callbacks to run. NOTE: the array is cleared after tasks are executed or aborted.+ * */+export const scheduleSequentialTasks: SequentialTaskScheduler = (+ tasks,+ signal+) => {+ if (process.env.NEXT_RUNTIME === 'edge') {+ throw new InvariantError(+ 'scheduleSequentialTasks cannot be called in the edge runtime'+ )+ } else {+ if (tasks.length === 0) return+ if (signal?.aborted) return++ const execution: Execution = {+ pendingTimeout: null,+ state: ExecutionState.Before,+ }++ const remainingImmediates: (NodeJS.Immediate | null)[] = []++ const onEnd = () => {+ execution.state = ExecutionState.Finished+ tasks.length = 0+ remainingImmediates.length = 0++ if (execution.pendingTimeout !== null) {+ clearTimeout(execution.pendingTimeout)+ execution.pendingTimeout = null+ }++ if (signal && onAbort) {+ signal.removeEventListener('abort', onAbort)+ }+ }++ let onAbort: (() => void) | undefined+ if (signal) {+ onAbort = () => {+ for (let i = 0; i < remainingImmediates.length; i++) {+ const timer = remainingImmediates[i]+ if (timer !== null) {+ clearImmediate(timer)+ }+ }+ onEnd()+ }+ signal.addEventListener('abort', onAbort, ONCE)+ }++ const runCallback = (callback: () => void, taskIndex: number) => {+ if (taskIndex === 0) {+ // When the first task runs, we should be in the ScheduledTasks state.+ // If we're not, something's very wrong with the scheduling.+ if (+ !hasBadSetImmediate &&+ execution.state !== ExecutionState.ScheduledTasks+ ) {+ hasBadSetImmediate = true+ warnAboutSetImmediate()+ }++ execution.state = ExecutionState.ExecutingTasks+ }++ remainingImmediates[taskIndex] = null++ try {+ return callback()+ } finally {+ if (taskIndex === tasks.length - 1) {+ onEnd()+ }+ }+ }++ try {+ for (let taskIndex = 0; taskIndex < tasks.length; taskIndex++) {+ const task = tasks[taskIndex]++ const immediate = unpatchedSetImmediate(runCallback, task, taskIndex)+ remainingImmediates.push(immediate)++ // If we have more than one task, schedule a sentinel timeout between+ // scheduling the first and second tasks.+ if (!hasBadSetImmediate && taskIndex === 0 && tasks.length > 1) {+ execution.pendingTimeout = setTimeout(+ validateInterleavingInTimeout,+ 0,+ execution+ )+ }+ }+ execution.state = ExecutionState.ScheduledTasks+ } catch (err) {+ onEnd()+ throw err+ }+ }+}++function validateInterleavingInTimeout(execution: Execution) {+ execution.pendingTimeout = null+ if (hasBadSetImmediate) {+ return+ }++ switch (execution.state) {+ case ExecutionState.Before: {+ // The timeout should never run before tasks are scheduled (synchronously).+ hasBadSetImmediate = true+ break+ }+ case ExecutionState.ScheduledTasks: {+ // In theory, it's okay to run timers before immediates, as long+ // as they consistently run separately.+ break+ }+ case ExecutionState.ExecutingTasks: {+ // The timeout should never run while tasks are running. This means that timeouts+ // interleaved with immediates, which can happen if a runtime polyfills `setImmediate`+ // as `setTimeout(_, 0)`.+ hasBadSetImmediate = true+ break+ }+ case ExecutionState.Finished: {+ // We should've cleared this timeout once we reached the+ // finished state, so this should be unreachable.+ break+ }+ }+ if (hasBadSetImmediate) {+ warnAboutSetImmediate()+ }+}++const ONCE = { once: true }packages/next/src/server/app-render/app-render-scheduling/index.ts9 + / 1 −
@@ -1 +1,9 @@-export { scheduleSequentialTasks } from './timer-scheduler'+import type { SequentialTaskScheduler } from './types'++const Impl =+ process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING === 'unstable_immediate'+ ? (require('./immediate-scheduler') as typeof import('./immediate-scheduler'))+ : (require('./timer-scheduler') as typeof import('./timer-scheduler'))++export const scheduleSequentialTasks: SequentialTaskScheduler =+ Impl.scheduleSequentialTaskspackages/next/src/server/app-render/app-render-scheduling/schedulers.test.ts65 + / 2 −
@@ -1,8 +1,13 @@+import {+ mockSetImmediate,+ unmockedSetImmediate,+} from './__tests__/mock-set-immediate.util' import { AsyncLocalStorage } from 'node:async_hooks' import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers' import * as fsPromises from 'node:fs/promises' import * as TimerScheduler from './timer-scheduler'+import * as ImmediateScheduler from './immediate-scheduler' function createLogger() { const logs: string[] = []@@ -24,15 +29,15 @@ function createLogger() { } function runInNewTask(callback: () => void) {- setImmediate(callback)+ unmockedSetImmediate(callback) } // NOTE: fast-set-immediate.external.test.ts includes more scenarios // that exercise task scheduling and fast immediates together. describe.each([ { description: 'Timer scheduler', scheduler: TimerScheduler },- // (more coming soon)+ { description: 'Immediate scheduler', scheduler: ImmediateScheduler }, ])('$description', ({ scheduler }) => { const { scheduleSequentialTasks } = scheduler @@ -473,6 +478,64 @@ describe('Timer scheduler', () => { }) }) +describe('Immediate scheduler', () => {+ // After each test we reset the module-level flag we set when we detect+ // unexpected scheduling behavior.+ const getScheduler = () => import('./immediate-scheduler')+ afterEach(() => {+ jest.resetModules()+ })++ it('warns if setImmediate is implemented as setTimeout', async () => {+ const { scheduleSequentialTasks } = await getScheduler()++ const { log, logs } = createLogger()+ const done = createPromiseWithResolvers<void>()++ const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation()+ using _s = deferSync(() => consoleWarnSpy.mockRestore())++ // Note: we're using a custom mocking mechanism to avoid any interactions+ // with the patching that fast-set-immediate does.+ const setImmediatePolyfilledAsTimeout = jest.fn(+ (callback: (...args: any[]) => any, ...args: any[]) => {+ return setTimeout(callback, 0, ...args) as unknown as NodeJS.Immediate+ }+ )+ mockSetImmediate(setImmediatePolyfilledAsTimeout)+ using _i = deferSync(() => mockSetImmediate(null))++ runInNewTask(() => {+ scheduleSequentialTasks([+ () => {+ log('task 1')+ },+ () => {+ log('task 2')+ },+ () => {+ log('task 3')+ done.resolve()+ },+ ])+ })++ await done.promise++ // Sanity check that we successfully mocked setImmediate+ expect(setImmediatePolyfilledAsTimeout).toHaveBeenCalled()++ expect(logs).toEqual(['task 1', 'task 2', 'task 3'])++ expect(consoleWarnSpy).toHaveBeenCalledTimes(1)+ expect(consoleWarnSpy).toHaveBeenCalledWith(+ expect.stringContaining(+ 'Next.js cannot guarantee that Cache Components will run as expected'+ )+ )+ })+})+ function deferSync(callback: () => void): Disposable { return { [Symbol.dispose]: async () => {packages/next/src/server/config-schema.ts3 + / 0 −
@@ -520,6 +520,9 @@ export const experimentalSchema = { typedEnv: z.boolean().optional(), serverComponentsHmrCache: z.boolean().optional(), serverComponentsHmrCancellation: z.boolean().optional(),+ sequentialTaskScheduling: z+ .enum(['unstable_timer', 'unstable_immediate'])+ .optional(), authInterrupts: z.boolean().optional(), useCache: z.boolean().optional(), durableUseCacheEntries: z.boolean().optional(),packages/next/src/server/config-shared.ts28 + / 0 −
@@ -1623,6 +1623,31 @@ export interface ExperimentalConfig { */ serverComponentsHmrCancellation?: boolean + /**+ * Selects the scheduling mechanism used for sequential tasks in Cache Components.+ *+ * Warning: This option is highly experimental, and should be used with caution.+ * Depending on the runtime, it may lead to non-deterministic and hard-to-debug problems,+ * such as:+ *+ * - content missing from prerenders+ * - poisoning the ISR cache with uncached data that should be omitted from a prerender+ *+ * It is intended for experimention by people maintaining Next.js integrations with+ * non-Node.js runtimes. Do not change the default setting unless you fully understand the+ * implications and your runtime's scheduling behavior.+ *+ * - `unstable_timer` (default): Sequential tasks will be scheduled using `setTimeout()`.+ * Note that this implementation relies on internals of Node.js `Timeout` objects+ * to ensure consistent behavior, so it may not be portable.+ * - `unstable_immediate`: Sequential tasks will be scheduled using `setImmediate()`.+ * Assumes that multiple immediates queued synchronously will run without interruption+ * by other tasks.+ *+ * @default 'unstable_timer'+ */+ sequentialTaskScheduling?: 'unstable_timer' | 'unstable_immediate'+ /** * Render <style> tags inline in the HTML for imported CSS assets. * Supports app-router in production mode only.@@ -2626,6 +2651,7 @@ export const defaultConfig = Object.freeze({ staticGenerationRetryCount: undefined, serverComponentsHmrCache: true, serverComponentsHmrCancellation: false,+ sequentialTaskScheduling: 'unstable_timer', staticGenerationMaxConcurrency: 8, staticGenerationMinPagesPerWorker: 25, transitionIndicator: false,@@ -2762,6 +2788,7 @@ export interface NextConfigRuntime { | 'largePageDataBytes' | 'serverComponentsHmrCache' | 'serverComponentsHmrCancellation'+ | 'sequentialTaskScheduling' | 'caseSensitiveRoutes' | 'validateRSCRequestHeaders' | 'sri'@@ -2836,6 +2863,7 @@ export function getNextConfigRuntime( largePageDataBytes: ex.largePageDataBytes, serverComponentsHmrCache: ex.serverComponentsHmrCache, serverComponentsHmrCancellation: ex.serverComponentsHmrCancellation,+ sequentialTaskScheduling: ex.sequentialTaskScheduling, caseSensitiveRoutes: ex.caseSensitiveRoutes, validateRSCRequestHeaders: ex.validateRSCRequestHeaders, sri: ex.sri,packages/next/src/server/config.ts21 + / 0 −
@@ -2592,6 +2592,27 @@ function enforceExperimentalFeatures( config.partialPrefetching = true } + const sequentialTaskScheduling = process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING+ if (+ (sequentialTaskScheduling === 'unstable_timer' ||+ sequentialTaskScheduling === 'unstable_immediate') &&+ // We do respect an explicit value in the user config.+ (config.experimental.sequentialTaskScheduling === undefined ||+ (isDefaultConfig &&+ config.experimental.sequentialTaskScheduling === 'unstable_timer'))+ ) {+ config.experimental.sequentialTaskScheduling = sequentialTaskScheduling++ if (configuredExperimentalFeatures) {+ addConfiguredExperimentalFeature(+ configuredExperimentalFeatures,+ 'sequentialTaskScheduling',+ sequentialTaskScheduling,+ 'set by `__NEXT_SEQUENTIAL_TASK_SCHEDULING`'+ )+ }+ }+ // TODO: Remove this once cachedNavigations is the default. if ( process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS === 'true' &&packages/next/src/server/next-server.ts3 + / 0 −
@@ -231,6 +231,9 @@ export default class NextNodeServer extends BaseServer< if (this.renderOpts.nextScriptWorkers) { process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true) }+ // Precompiled app-render bundles do not receive the app's build-time defines.+ process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING =+ this.nextConfig.experimental.sequentialTaskScheduling ?? 'unstable_timer' if ( (isDev || process.env.__NEXT_DEV_SERVER) && this.nextConfig.experimental.requestInsightspackages/next/src/server/node-environment-extensions/fast-set-immediate.external.test.ts2 + / 1 −
@@ -11,6 +11,7 @@ import { } from './fast-set-immediate.external' import * as TimerScheduler from '../app-render/app-render-scheduling/timer-scheduler'+import * as ImmediateScheduler from '../app-render/app-render-scheduling/immediate-scheduler' function createLogger() { const logs: string[] = []@@ -33,7 +34,7 @@ function createLogger() { describe.each([ { description: 'Timer scheduler', scheduler: TimerScheduler },- // (more coming soon)+ { description: 'Immediate scheduler', scheduler: ImmediateScheduler }, ])('$description', ({ scheduler }) => { const { scheduleSequentialTasks } = scheduler test/development/app-dir/cache-components-tasks/cache-components-tasks.partial-prefetching.immediate.test.tsadded3 + / 0 −
@@ -0,0 +1,3 @@+process.env.__NEXT_PARTIAL_PREFETCHING = 'true'+process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING = 'unstable_immediate'+require('./cache-components-tasks.test')test/development/app-dir/cache-components-tasks/cache-components-tasks.test.ts1 + / 1 −
@@ -60,7 +60,7 @@ describe.each([ ) // We should not see warnings related to setTimeout. expect(next.cliOutput).not.toContain(- "Next.js cannot guarantee that Cache Components will run as expected due to the current runtime's implementation of `setTimeout()`"+ 'Next.js cannot guarantee that Cache Components will run as expected' ) } test/development/app-dir/react-performance-track/react-performance-track.partial-prefetching.immediate.test.tsadded3 + / 0 −
@@ -0,0 +1,3 @@+process.env.__NEXT_PARTIAL_PREFETCHING = 'true'+process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING = 'unstable_immediate'+require('./react-performance-track.test')test/development/app-dir/react-performance-track/react-performance-track.test.ts8 + / 0 −
@@ -50,6 +50,8 @@ describe('react-performance-track', () => { ) }) + // React's IO tracking does not consider setImmediate callbacks to be IO.+ // @gate sequentialTaskScheduling !== 'unstable_immediate' it('should show params', async () => { const browser = await next.browser('/params/next', { extraHTTPHeaders }) await browser.elementByCss('[data-react-server-requests-done]', {@@ -67,6 +69,8 @@ describe('react-performance-track', () => { ) }) + // React's IO tracking does not consider setImmediate callbacks to be IO.+ // @gate sequentialTaskScheduling !== 'unstable_immediate' it('should show searchParams', async () => { const browser = await next.browser('/searchparams?slug=next', { extraHTTPHeaders,@@ -86,6 +90,8 @@ describe('react-performance-track', () => { ) }) + // React's IO tracking does not consider setImmediate callbacks to be IO.+ // @gate sequentialTaskScheduling !== 'unstable_immediate' it('should show cookies', async () => { const browser = await next.browser('/cookies', { extraHTTPHeaders }) await browser.elementByCss('[data-react-server-requests-done]', {@@ -113,6 +119,8 @@ describe('react-performance-track', () => { expect(track).toEqual([]) }) + // React's IO tracking does not consider setImmediate callbacks to be IO.+ // @gate sequentialTaskScheduling !== 'unstable_immediate' it('should show headers', async () => { const browser = await next.browser('/headers', { extraHTTPHeaders }) await browser.elementByCss('[data-react-server-requests-done]', {test/e2e/app-dir/segment-cache/prefetch-app-shell/prefetch-app-shell.immediate.test.tsadded2 + / 0 −
@@ -0,0 +1,2 @@+process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING = 'unstable_immediate'+require('./prefetch-app-shell.test')test/e2e/app-dir/segment-cache/prefetch-static-shell/prefetch-static-shell.immediate.test.tsadded2 + / 0 −
@@ -0,0 +1,2 @@+process.env.__NEXT_SEQUENTIAL_TASK_SCHEDULING = 'unstable_immediate'+require('./prefetch-static-shell.test')test/lib/e2e-utils/deployment-test-env.ts1 + / 0 −
@@ -1,6 +1,7 @@ const deploymentTestFlags = [ '__NEXT_CACHE_COMPONENTS', '__NEXT_PARTIAL_PREFETCHING',+ '__NEXT_SEQUENTIAL_TASK_SCHEDULING', '__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS', '__NEXT_TEST_AXIS', ]test/lib/gate/conditions.ts4 + / 0 −
@@ -210,6 +210,10 @@ export const conditions: Record<string, Condition> = { 'Partial Prefetching is enabled globally for the fixture (does not check `export const prefetch = "partial"`)', (config) => config.partialPrefetching ),+ sequentialTaskScheduling: lazyCondition(+ 'the sequential task scheduler selected for the fixture',+ (config) => config.experimental?.sequentialTaskScheduling+ ), ppr: lazyCondition( 'partial prerendering is enabled (implied by `cacheComponents`)', (config) => config.experimental?.pprtest/unit/deployment-test-env/deployment-test-env.test.ts2 + / 0 −
@@ -4,6 +4,7 @@ import { getDeploymentTestEnvAssignments } from '../../lib/e2e-utils/deployment- describe.each([ '__NEXT_CACHE_COMPONENTS', '__NEXT_PARTIAL_PREFETCHING',+ '__NEXT_SEQUENTIAL_TASK_SCHEDULING', '__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS', '__NEXT_TEST_AXIS', ])('deployment capture of %s', (flag) => {@@ -12,6 +13,7 @@ describe.each([ ...process.env, __NEXT_CACHE_COMPONENTS: '', __NEXT_PARTIAL_PREFETCHING: '',+ __NEXT_SEQUENTIAL_TASK_SCHEDULING: '', __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS: '', __NEXT_TEST_AXIS: '', })