Unverified Commit 1e000f6f authored by Sebastian Markbåge's avatar Sebastian Markbåge Committed by GitHub

Unify RequestStore, PrerenderStore and CacheStore (#70819)

Stacked on #70889.

This merges these three stores into a single AsyncLocalStorage context
containing a disjoint union named WorkUnitStore. That way they're
mutually exclusive. This prevents us from leaking RequestStore
information in either PrerenderStore or CacheStore.

---------
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent 1df28819
...@@ -32,25 +32,19 @@ const routeModule = new AppRouteRouteModule({ ...@@ -32,25 +32,19 @@ const routeModule = new AppRouteRouteModule({
// Pull out the exports that we need to expose from the module. This should // Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These // be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route. // are used to hook into the route.
const { const { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule
requestAsyncStorage,
workAsyncStorage,
prerenderAsyncStorage,
serverHooks,
} = routeModule
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
workAsyncStorage, workAsyncStorage,
requestAsyncStorage, workUnitAsyncStorage,
prerenderAsyncStorage,
}) })
} }
export { export {
routeModule, routeModule,
requestAsyncStorage,
workAsyncStorage, workAsyncStorage,
workUnitAsyncStorage,
serverHooks, serverHooks,
patchFetch, patchFetch,
} }
...@@ -131,7 +131,7 @@ const browserNonTranspileModules = [ ...@@ -131,7 +131,7 @@ const browserNonTranspileModules = [
const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/ const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/
const asyncStoragesRegex = const asyncStoragesRegex =
/next[\\/]dist[\\/](esm[\\/])?client[\\/]components[\\/](work-async-storage|action-async-storage|request-async-storage)/ /next[\\/]dist[\\/](esm[\\/])?(client[\\/]components|server[\\/]app-render|)[\\/](work-async-storage|action-async-storage|work-unit-async-storage)/
// Support for NODE_PATH // Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '') const nodePathList = (process.env.NODE_PATH || '')
......
import { createAsyncLocalStorage } from './async-local-storage'
import type { RequestAsyncStorage } from './request-async-storage.external'
export const requestAsyncStorage: RequestAsyncStorage =
createAsyncLocalStorage()
import PromiseQueue from 'next/dist/compiled/p-queue' import PromiseQueue from 'next/dist/compiled/p-queue'
import { import {
requestAsyncStorage, workUnitAsyncStorage,
type RequestStore, type RequestStore,
} from '../../client/components/request-async-storage.external' type WorkUnitStore,
} from '../../server/app-render/work-unit-async-storage.external'
import { ResponseCookies } from '../web/spec-extension/cookies' import { ResponseCookies } from '../web/spec-extension/cookies'
import type { RequestLifecycleOpts } from '../base-server' import type { RequestLifecycleOpts } from '../base-server'
import type { AfterCallback, AfterTask } from './after' import type { AfterCallback, AfterTask } from './after'
...@@ -20,7 +21,7 @@ export class AfterContext { ...@@ -20,7 +21,7 @@ export class AfterContext {
private waitUntil: RequestLifecycleOpts['waitUntil'] | undefined private waitUntil: RequestLifecycleOpts['waitUntil'] | undefined
private onClose: RequestLifecycleOpts['onClose'] | undefined private onClose: RequestLifecycleOpts['onClose'] | undefined
private requestStore: RequestStore | undefined private workUnitStore: WorkUnitStore | undefined
private runCallbacksOnClosePromise: Promise<void> | undefined private runCallbacksOnClosePromise: Promise<void> | undefined
private callbackQueue: PromiseQueue private callbackQueue: PromiseQueue
...@@ -55,11 +56,11 @@ export class AfterContext { ...@@ -55,11 +56,11 @@ export class AfterContext {
if (!this.waitUntil) { if (!this.waitUntil) {
errorWaitUntilNotAvailable() errorWaitUntilNotAvailable()
} }
if (!this.requestStore) { if (!this.workUnitStore) {
// We just stash the first request store we have but this is not sufficient. // We just stash the first request store we have but this is not sufficient.
// TODO: We should store a request store per callback since each callback might // TODO: We should store a request store per callback since each callback might
// be inside a different store. E.g. inside different batched actions, prerenders or caches. // be inside a different store. E.g. inside different batched actions, prerenders or caches.
this.requestStore = requestAsyncStorage.getStore() this.workUnitStore = workUnitAsyncStorage.getStore()
} }
if (!this.onClose) { if (!this.onClose) {
throw new InvariantError( throw new InvariantError(
...@@ -72,7 +73,7 @@ export class AfterContext { ...@@ -72,7 +73,7 @@ export class AfterContext {
// NOTE: We're creating a promise here, which means that // NOTE: We're creating a promise here, which means that
// we will propagate any AsyncLocalStorage contexts we're currently in // we will propagate any AsyncLocalStorage contexts we're currently in
// to the callbacks that'll execute later. // to the callbacks that'll execute later.
// This includes e.g. `requestAsyncStorage` and React's `requestStorage` (which backs `React.cache()`). // This includes e.g. `workUnitAsyncStorage` and React's `requestStorage` (which backs `React.cache()`).
this.runCallbacksOnClosePromise = this.runCallbacksOnClose() this.runCallbacksOnClosePromise = this.runCallbacksOnClose()
this.waitUntil(this.runCallbacksOnClosePromise) this.waitUntil(this.runCallbacksOnClosePromise)
} }
...@@ -94,19 +95,19 @@ export class AfterContext { ...@@ -94,19 +95,19 @@ export class AfterContext {
private async runCallbacksOnClose() { private async runCallbacksOnClose() {
await new Promise<void>((resolve) => this.onClose!(resolve)) await new Promise<void>((resolve) => this.onClose!(resolve))
return this.runCallbacks(this.requestStore) return this.runCallbacks(this.workUnitStore)
} }
private async runCallbacks( private async runCallbacks(
requestStore: undefined | RequestStore workUnitStore: undefined | WorkUnitStore
): Promise<void> { ): Promise<void> {
if (this.callbackQueue.size === 0) return if (this.callbackQueue.size === 0) return
const readonlyRequestStore: undefined | RequestStore = const readonlyRequestStore: undefined | WorkUnitStore =
requestStore === undefined workUnitStore === undefined || workUnitStore.type !== 'request'
? undefined ? undefined
: // TODO: This is not sufficient. It should just be the same store that mutates. : // TODO: This is not sufficient. It should just be the same store that mutates.
wrapRequestStoreForAfterCallbacks(requestStore) wrapRequestStoreForAfterCallbacks(workUnitStore)
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
...@@ -114,7 +115,7 @@ export class AfterContext { ...@@ -114,7 +115,7 @@ export class AfterContext {
// Clearing it out or running the first request store. // Clearing it out or running the first request store.
// TODO: This needs to be the request store that was active at the time the // TODO: This needs to be the request store that was active at the time the
// callback was scheduled but p-queue makes this hard so need further refactoring. // callback was scheduled but p-queue makes this hard so need further refactoring.
requestAsyncStorage.run(readonlyRequestStore as any, async () => { workUnitAsyncStorage.run(readonlyRequestStore as any, async () => {
this.callbackQueue.start() this.callbackQueue.start()
await this.callbackQueue.onIdle() await this.callbackQueue.onIdle()
}) })
...@@ -133,6 +134,7 @@ function wrapRequestStoreForAfterCallbacks( ...@@ -133,6 +134,7 @@ function wrapRequestStoreForAfterCallbacks(
requestStore: RequestStore requestStore: RequestStore
): RequestStore { ): RequestStore {
return { return {
type: 'request',
url: requestStore.url, url: requestStore.url,
get headers() { get headers() {
return requestStore.headers return requestStore.headers
......
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { cacheAsyncStorage } from '../../server/app-render/cache-async-storage.external' import { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering' import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'
...@@ -12,7 +12,7 @@ export type AfterCallback<T = unknown> = () => T | Promise<T> ...@@ -12,7 +12,7 @@ export type AfterCallback<T = unknown> = () => T | Promise<T>
*/ */
export function unstable_after<T>(task: AfterTask<T>): void { export function unstable_after<T>(task: AfterTask<T>): void {
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workStore) { if (workStore) {
const { afterContext } = workStore const { afterContext } = workStore
...@@ -29,7 +29,7 @@ export function unstable_after<T>(task: AfterTask<T>): void { ...@@ -29,7 +29,7 @@ export function unstable_after<T>(task: AfterTask<T>): void {
`Route ${workStore.route} with \`dynamic = "force-static"\` couldn't be rendered statically because it used \`${callingExpression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${workStore.route} with \`dynamic = "force-static"\` couldn't be rendered statically because it used \`${callingExpression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
) )
} else { } else {
markCurrentScopeAsDynamic(workStore, cacheStore, callingExpression) markCurrentScopeAsDynamic(workStore, workUnitStore, callingExpression)
} }
afterContext.after(task) afterContext.after(task)
......
import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http' import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http'
import type { SizeLimit } from '../../types' import type { SizeLimit } from '../../types'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type { RequestStore } from '../../server/app-render/work-unit-async-storage.external'
import type { AppRenderContext, GenerateFlight } from './app-render' import type { AppRenderContext, GenerateFlight } from './app-render'
import type { AppPageModule } from '../../server/route-modules/app-page/module' import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
......
...@@ -12,7 +12,7 @@ import type { ...@@ -12,7 +12,7 @@ import type {
InitialRSCPayload, InitialRSCPayload,
} from './types' } from './types'
import type { WorkStore } from '../../client/components/work-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type { RequestStore } from '../../server/app-render/work-unit-async-storage.external'
import type { NextParsedUrlQuery } from '../request-meta' import type { NextParsedUrlQuery } from '../request-meta'
import type { LoaderTree } from '../lib/app-dir-module' import type { LoaderTree } from '../lib/app-dir-module'
import type { AppPageModule } from '../route-modules/app-page/module' import type { AppPageModule } from '../route-modules/app-page/module'
...@@ -150,9 +150,9 @@ import { ...@@ -150,9 +150,9 @@ import {
} from '../app-render/app-render-prerender-utils' } from '../app-render/app-render-prerender-utils'
import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler' import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'
import { import {
prerenderAsyncStorage, workUnitAsyncStorage,
type PrerenderStore, type PrerenderStore,
} from './prerender-async-storage.external' } from './work-unit-async-storage.external'
import { CacheSignal } from './cache-signal' import { CacheSignal } from './cache-signal'
import { getTracedMetadata } from '../lib/trace/utils' import { getTracedMetadata } from '../lib/trace/utils'
...@@ -921,7 +921,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -921,7 +921,7 @@ async function renderToHTMLOrFlightImpl(
) { ) {
req.originalRequest.on('end', () => { req.originalRequest.on('end', () => {
const staticGenStore = ComponentMod.workAsyncStorage.getStore() const staticGenStore = ComponentMod.workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
const isPPR = const isPPR =
prerenderStore && prerenderStore.type === 'prerender' prerenderStore && prerenderStore.type === 'prerender'
? !!prerenderStore.dynamicTracking?.dynamicAccesses?.length ? !!prerenderStore.dynamicTracking?.dynamicAccesses?.length
...@@ -1128,7 +1128,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1128,7 +1128,7 @@ async function renderToHTMLOrFlightImpl(
]) ])
} }
addImplicitTags(workStore, requestStore, undefined, undefined) addImplicitTags(workStore, requestStore)
if (workStore.tags) { if (workStore.tags) {
metadata.fetchTags = workStore.tags.join(',') metadata.fetchTags = workStore.tags.join(',')
...@@ -1237,7 +1237,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1237,7 +1237,7 @@ async function renderToHTMLOrFlightImpl(
]) ])
} }
addImplicitTags(workStore, requestStore, undefined, undefined) addImplicitTags(workStore, requestStore)
if (workStore.tags) { if (workStore.tags) {
metadata.fetchTags = workStore.tags.join(',') metadata.fetchTags = workStore.tags.join(',')
...@@ -1300,7 +1300,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1300,7 +1300,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
} }
return withRequestStore( return withRequestStore(
renderOpts.ComponentMod.requestAsyncStorage, renderOpts.ComponentMod.workUnitAsyncStorage,
{ {
req, req,
url, url,
...@@ -1309,8 +1309,12 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1309,8 +1309,12 @@ export const renderToHTMLOrFlight: AppPageRender = (
isHmrRefresh, isHmrRefresh,
serverComponentsHmrCache, serverComponentsHmrCache,
}, },
(requestStore) => (requestStore) => {
withWorkStore( if (requestStore.type !== 'request') {
// TODO: Refactor to not need a RequestStore for prerenders.
throw new Error('This should never happen.')
}
return withWorkStore(
renderOpts.ComponentMod.workAsyncStorage, renderOpts.ComponentMod.workAsyncStorage,
{ {
page: renderOpts.routeModule.definition.page, page: renderOpts.routeModule.definition.page,
...@@ -1333,6 +1337,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1333,6 +1337,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
postponedState postponedState
) )
) )
}
) )
} }
...@@ -1881,7 +1886,7 @@ async function prerenderToStream( ...@@ -1881,7 +1886,7 @@ async function prerenderToStream(
// We're not going to use the result of this render because the only time it could be used // We're not going to use the result of this render because the only time it could be used
// is if it completes in a microtask and that's likely very rare for any non-trivial app // is if it completes in a microtask and that's likely very rare for any non-trivial app
const firstAttemptRSCPayload = await prerenderAsyncStorage.run( const firstAttemptRSCPayload = await workUnitAsyncStorage.run(
prospectiveRenderPrerenderStore, prospectiveRenderPrerenderStore,
getRSCPayload, getRSCPayload,
tree, tree,
...@@ -1892,7 +1897,7 @@ async function prerenderToStream( ...@@ -1892,7 +1897,7 @@ async function prerenderToStream(
let didError = false let didError = false
let prospectiveRenderError: unknown = null let prospectiveRenderError: unknown = null
;( ;(
prerenderAsyncStorage.run( workUnitAsyncStorage.run(
// The store to scope // The store to scope
prospectiveRenderPrerenderStore, prospectiveRenderPrerenderStore,
// The function to run // The function to run
...@@ -1961,7 +1966,7 @@ async function prerenderToStream( ...@@ -1961,7 +1966,7 @@ async function prerenderToStream(
reactServerIsDynamic = true reactServerIsDynamic = true
} }
} }
const finalAttemptRSCPayload = await prerenderAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
finalRenderPrerenderStore, finalRenderPrerenderStore,
getRSCPayload, getRSCPayload,
tree, tree,
...@@ -1972,7 +1977,7 @@ async function prerenderToStream( ...@@ -1972,7 +1977,7 @@ async function prerenderToStream(
await createReactServerPrerenderResult( await createReactServerPrerenderResult(
prerenderAndAbortInSequentialTasks( prerenderAndAbortInSequentialTasks(
() => () =>
prerenderAsyncStorage.run( workUnitAsyncStorage.run(
// The store to scope // The store to scope
finalRenderPrerenderStore, finalRenderPrerenderStore,
// The function to run // The function to run
...@@ -2047,7 +2052,7 @@ async function prerenderToStream( ...@@ -2047,7 +2052,7 @@ async function prerenderToStream(
.prerender as (typeof import('react-dom/static.edge'))['prerender'] .prerender as (typeof import('react-dom/static.edge'))['prerender']
const { prelude, postponed } = await prerenderAndAbortInSequentialTasks( const { prelude, postponed } = await prerenderAndAbortInSequentialTasks(
() => () =>
prerenderAsyncStorage.run( workUnitAsyncStorage.run(
ssrPrerenderStore, ssrPrerenderStore,
prerender, prerender,
<App <App
...@@ -2214,7 +2219,7 @@ async function prerenderToStream( ...@@ -2214,7 +2219,7 @@ async function prerenderToStream(
dynamicTracking, dynamicTracking,
} }
const firstAttemptRSCPayload = await prerenderAsyncStorage.run( const firstAttemptRSCPayload = await workUnitAsyncStorage.run(
prospectiveRenderPrerenderStore, prospectiveRenderPrerenderStore,
getRSCPayload, getRSCPayload,
tree, tree,
...@@ -2238,7 +2243,7 @@ async function prerenderToStream( ...@@ -2238,7 +2243,7 @@ async function prerenderToStream(
} }
try { try {
const prospectiveStream = prerenderAsyncStorage.run( const prospectiveStream = workUnitAsyncStorage.run(
// The store to scope // The store to scope
prospectiveRenderPrerenderStore, prospectiveRenderPrerenderStore,
// The function to run // The function to run
...@@ -2305,7 +2310,7 @@ async function prerenderToStream( ...@@ -2305,7 +2310,7 @@ async function prerenderToStream(
dynamicTracking, dynamicTracking,
} }
const finalAttemptRSCPayload = await prerenderAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
finalRenderPrerenderStore, finalRenderPrerenderStore,
getRSCPayload, getRSCPayload,
tree, tree,
...@@ -2341,7 +2346,7 @@ async function prerenderToStream( ...@@ -2341,7 +2346,7 @@ async function prerenderToStream(
htmlStream = await prerenderAndAbortInSequentialTasks( htmlStream = await prerenderAndAbortInSequentialTasks(
() => { () => {
const teedStream = ( const teedStream = (
prerenderAsyncStorage.run( workUnitAsyncStorage.run(
// The store to scope // The store to scope
finalRenderPrerenderStore, finalRenderPrerenderStore,
// The function to run // The function to run
...@@ -2361,7 +2366,7 @@ async function prerenderToStream( ...@@ -2361,7 +2366,7 @@ async function prerenderToStream(
const renderToReadableStream = require('react-dom/server.edge') const renderToReadableStream = require('react-dom/server.edge')
.renderToReadableStream as (typeof import('react-dom/server.edge'))['renderToReadableStream'] .renderToReadableStream as (typeof import('react-dom/server.edge'))['renderToReadableStream']
const pendingHTMLStream = prerenderAsyncStorage.run( const pendingHTMLStream = workUnitAsyncStorage.run(
ssrPrerenderStore, ssrPrerenderStore,
renderToReadableStream, renderToReadableStream,
<App <App
...@@ -2480,7 +2485,7 @@ async function prerenderToStream( ...@@ -2480,7 +2485,7 @@ async function prerenderToStream(
controller: null, controller: null,
dynamicTracking, dynamicTracking,
} }
const RSCPayload = await prerenderAsyncStorage.run( const RSCPayload = await workUnitAsyncStorage.run(
reactServerPrerenderStore, reactServerPrerenderStore,
getRSCPayload, getRSCPayload,
tree, tree,
...@@ -2489,7 +2494,7 @@ async function prerenderToStream( ...@@ -2489,7 +2494,7 @@ async function prerenderToStream(
) )
const reactServerResult = (reactServerPrerenderResult = const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResultFromRender( await createReactServerPrerenderResultFromRender(
prerenderAsyncStorage.run( workUnitAsyncStorage.run(
reactServerPrerenderStore, reactServerPrerenderStore,
ComponentMod.renderToReadableStream, ComponentMod.renderToReadableStream,
// ... the arguments for the function to run // ... the arguments for the function to run
...@@ -2511,7 +2516,7 @@ async function prerenderToStream( ...@@ -2511,7 +2516,7 @@ async function prerenderToStream(
const prerender = require('react-dom/static.edge') const prerender = require('react-dom/static.edge')
.prerender as (typeof import('react-dom/static.edge'))['prerender'] .prerender as (typeof import('react-dom/static.edge'))['prerender']
const { prelude, postponed } = await prerenderAsyncStorage.run( const { prelude, postponed } = await workUnitAsyncStorage.run(
ssrPrerenderStore, ssrPrerenderStore,
prerender, prerender,
<App <App
...@@ -2665,7 +2670,7 @@ async function prerenderToStream( ...@@ -2665,7 +2670,7 @@ async function prerenderToStream(
} }
// This is a regular static generation. We don't do dynamic tracking because we rely on // This is a regular static generation. We don't do dynamic tracking because we rely on
// the old-school dynamic error handling to bail out of static generation // the old-school dynamic error handling to bail out of static generation
const RSCPayload = await prerenderAsyncStorage.run( const RSCPayload = await workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
getRSCPayload, getRSCPayload,
tree, tree,
...@@ -2674,7 +2679,7 @@ async function prerenderToStream( ...@@ -2674,7 +2679,7 @@ async function prerenderToStream(
) )
const reactServerResult = (reactServerPrerenderResult = const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResultFromRender( await createReactServerPrerenderResultFromRender(
prerenderAsyncStorage.run( workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
ComponentMod.renderToReadableStream, ComponentMod.renderToReadableStream,
RSCPayload, RSCPayload,
......
import type { CacheAsyncStorage } from './cache-async-storage.external'
import { createAsyncLocalStorage } from '../../client/components/async-local-storage'
export const cacheAsyncStorage: CacheAsyncStorage = createAsyncLocalStorage()
import type { AsyncLocalStorage } from 'async_hooks'
// Share the instance module in the next-shared layer
import { cacheAsyncStorage } from './cache-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
export type UseCacheStore = {
type: 'cache'
// TODO: Inside this scope we'll track tags and life times of this scope.
}
export type UnstableCacheStore = {
type: 'unstable-cache'
}
/**
* The Cache store is for tracking information inside a "use cache" or unstable_cache context.
* Inside this context we should never expose any request or page specific information.
*/
export type CacheStore = UseCacheStore | UnstableCacheStore
export type CacheAsyncStorage = AsyncLocalStorage<CacheStore>
export { cacheAsyncStorage }
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
*/ */
import type { WorkStore } from '../../client/components/work-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { CacheStore } from '../../server/app-render/cache-async-storage.external' import type { WorkUnitStore } from '../../server/app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly // Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react' import React from 'react'
...@@ -30,10 +30,9 @@ import { DynamicServerError } from '../../client/components/hooks-server-context ...@@ -30,10 +30,9 @@ import { DynamicServerError } from '../../client/components/hooks-server-context
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreModern, type PrerenderStoreModern,
} from './prerender-async-storage.external' } from './work-unit-async-storage.external'
import { cacheAsyncStorage } from './cache-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
import { import {
...@@ -117,11 +116,14 @@ export function getFirstDynamicReason( ...@@ -117,11 +116,14 @@ export function getFirstDynamicReason(
*/ */
export function markCurrentScopeAsDynamic( export function markCurrentScopeAsDynamic(
store: WorkStore, store: WorkStore,
cacheStore: void | CacheStore, workUnitStore: undefined | WorkUnitStore,
expression: string expression: string
): void { ): void {
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache' || cacheStore.type === 'unstable-cache') { if (
workUnitStore.type === 'cache' ||
workUnitStore.type === 'unstable-cache'
) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope // inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is // creates a cache boundary. This is subtly different from reading a dynamic data source which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
...@@ -140,7 +142,7 @@ export function markCurrentScopeAsDynamic( ...@@ -140,7 +142,7 @@ export function markCurrentScopeAsDynamic(
) )
} }
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore && prerenderStore.type === 'prerender') { if (prerenderStore && prerenderStore.type === 'prerender') {
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
// We're prerendering the RSC stream with dynamicIO enabled and we need to abort the // We're prerendering the RSC stream with dynamicIO enabled and we need to abort the
...@@ -187,7 +189,7 @@ export function trackFallbackParamAccessed( ...@@ -187,7 +189,7 @@ export function trackFallbackParamAccessed(
store: WorkStore, store: WorkStore,
expression: string expression: string
): void { ): void {
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (!prerenderStore || prerenderStore.type !== 'prerender') return if (!prerenderStore || prerenderStore.type !== 'prerender') return
postponeWithTracking(store.route, expression, prerenderStore.dynamicTracking) postponeWithTracking(store.route, expression, prerenderStore.dynamicTracking)
...@@ -204,15 +206,15 @@ export function trackFallbackParamAccessed( ...@@ -204,15 +206,15 @@ export function trackFallbackParamAccessed(
*/ */
export function trackDynamicDataAccessed( export function trackDynamicDataAccessed(
store: WorkStore, store: WorkStore,
cacheStore: void | CacheStore, workUnitStore: undefined | WorkUnitStore,
expression: string expression: string
): void { ): void {
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache') { if (workUnitStore.type === 'cache') {
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
} else if (cacheStore.type === 'unstable-cache') { } else if (workUnitStore.type === 'unstable-cache') {
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
) )
...@@ -224,7 +226,7 @@ export function trackDynamicDataAccessed( ...@@ -224,7 +226,7 @@ export function trackDynamicDataAccessed(
) )
} }
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore && prerenderStore.type === 'prerender') { if (prerenderStore && prerenderStore.type === 'prerender') {
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
// We're prerendering the RSC stream with dynamicIO enabled and we need to abort the // We're prerendering the RSC stream with dynamicIO enabled and we need to abort the
...@@ -268,15 +270,18 @@ export function trackDynamicDataAccessed( ...@@ -268,15 +270,18 @@ export function trackDynamicDataAccessed(
export function throwToInterruptStaticGeneration( export function throwToInterruptStaticGeneration(
expression: string, expression: string,
store: WorkStore, store: WorkStore,
cacheStore: void | CacheStore workUnitStore: undefined | WorkUnitStore
): never { ): never {
// We aren't prerendering but we are generating a static page. We need to bail out of static generation // We aren't prerendering but we are generating a static page. We need to bail out of static generation
const err = new DynamicServerError( const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error` `Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
) )
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache' || cacheStore.type === 'unstable-cache') { if (
workUnitStore.type === 'cache' ||
workUnitStore.type === 'unstable-cache'
) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope // inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is // creates a cache boundary. This is subtly different from reading a dynamic data source which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
...@@ -301,10 +306,13 @@ export function throwToInterruptStaticGeneration( ...@@ -301,10 +306,13 @@ export function throwToInterruptStaticGeneration(
*/ */
export function trackDynamicDataInDynamicRender( export function trackDynamicDataInDynamicRender(
store: WorkStore, store: WorkStore,
cacheStore: void | CacheStore workUnitStore: void | WorkUnitStore
) { ) {
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache' || cacheStore.type === 'unstable-cache') { if (
workUnitStore.type === 'cache' ||
workUnitStore.type === 'unstable-cache'
) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope // inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is // creates a cache boundary. This is subtly different from reading a dynamic data source which is
// forbidden inside a cache scope. // forbidden inside a cache scope.
...@@ -379,7 +387,7 @@ type PostponeProps = { ...@@ -379,7 +387,7 @@ type PostponeProps = {
route: string route: string
} }
export function Postpone({ reason, route }: PostponeProps): never { export function Postpone({ reason, route }: PostponeProps): never {
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
const dynamicTracking = const dynamicTracking =
prerenderStore && prerenderStore.type === 'prerender' prerenderStore && prerenderStore.type === 'prerender'
? prerenderStore.dynamicTracking ? prerenderStore.dynamicTracking
...@@ -567,7 +575,7 @@ export function useDynamicRouteParams(expression: string) { ...@@ -567,7 +575,7 @@ export function useDynamicRouteParams(expression: string) {
) { ) {
// There are fallback route params, we should track these as dynamic // There are fallback route params, we should track these as dynamic
// accesses. // accesses.
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore && prerenderStore.type === 'prerender') { if (prerenderStore && prerenderStore.type === 'prerender') {
// We're prerendering with dynamicIO or PPR or both // We're prerendering with dynamicIO or PPR or both
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
...@@ -585,8 +593,8 @@ export function useDynamicRouteParams(expression: string) { ...@@ -585,8 +593,8 @@ export function useDynamicRouteParams(expression: string) {
} }
} else { } else {
// We're prerendering in legacy mode // We're prerendering in legacy mode
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
throwToInterruptStaticGeneration(expression, workStore, cacheStore) throwToInterruptStaticGeneration(expression, workStore, workUnitStore)
} }
} }
} }
......
...@@ -12,8 +12,7 @@ export { prerender } from 'react-server-dom-webpack/static.edge' ...@@ -12,8 +12,7 @@ export { prerender } from 'react-server-dom-webpack/static.edge'
import LayoutRouter from '../../client/components/layout-router' import LayoutRouter from '../../client/components/layout-router'
import RenderFromTemplateContext from '../../client/components/render-from-template-context' import RenderFromTemplateContext from '../../client/components/render-from-template-context'
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { requestAsyncStorage } from '../../client/components/request-async-storage.external' import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { prerenderAsyncStorage } from './prerender-async-storage.external'
import { actionAsyncStorage } from '../../client/components/action-async-storage.external' import { actionAsyncStorage } from '../../client/components/action-async-storage.external'
import { ClientPageRoot } from '../../client/components/client-page' import { ClientPageRoot } from '../../client/components/client-page'
import { ClientSegmentRoot } from '../../client/components/client-segment' import { ClientSegmentRoot } from '../../client/components/client-segment'
...@@ -48,8 +47,7 @@ import { taintObjectReference } from './rsc/taint' ...@@ -48,8 +47,7 @@ import { taintObjectReference } from './rsc/taint'
function patchFetch() { function patchFetch() {
return _patchFetch({ return _patchFetch({
workAsyncStorage, workAsyncStorage,
requestAsyncStorage, workUnitAsyncStorage,
prerenderAsyncStorage,
}) })
} }
...@@ -57,7 +55,7 @@ export { ...@@ -57,7 +55,7 @@ export {
LayoutRouter, LayoutRouter,
RenderFromTemplateContext, RenderFromTemplateContext,
workAsyncStorage, workAsyncStorage,
requestAsyncStorage, workUnitAsyncStorage,
actionAsyncStorage, actionAsyncStorage,
createServerSearchParamsForServerPage, createServerSearchParamsForServerPage,
createServerSearchParamsForMetadata, createServerSearchParamsForMetadata,
......
import type { AsyncLocalStorage } from 'async_hooks'
import type { CacheSignal } from './cache-signal'
import type { DynamicTrackingState } from './dynamic-rendering'
// Share the instance module in the next-shared layer
import { prerenderAsyncStorage } from './prerender-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
/**
* The Prerender store is for tracking information related to prerenders.
*
* It can be used for both RSC and SSR prerendering and should be scoped as close
* to the individual `renderTo...` API call as possible. To keep the type simple
* we don't distinguish between RSC and SSR prerendering explicitly but instead
* use conditional object properties to infer which mode we are in. For instance cache tracking
* only needs to happen during the RSC prerender when we are prospectively prerendering
* to fill all caches.
*/
export type PrerenderStoreModern = {
type: 'prerender'
pathname: string | undefined
/**
* This is the AbortController passed to React. It can be used to abort the prerender
* if we encounter conditions that do not require further rendering
*/
readonly controller: null | AbortController
/**
* when not null this signal is used to track cache reads during prerendering and
* to await all cache reads completing before aborting the prerender.
*/
readonly cacheSignal: null | CacheSignal
/**
* During some prerenders we want to track dynamic access.
*/
readonly dynamicTracking: null | DynamicTrackingState
}
export type PrerenderStoreLegacy = {
type: 'prerender-legacy'
pathname: string | undefined
}
export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern
export function isDynamicIOPrerender(prerenderStore: PrerenderStore): boolean {
return (
prerenderStore.type === 'prerender' &&
!!(prerenderStore.controller || prerenderStore.cacheSignal)
)
}
export type PrerenderAsyncStorage = AsyncLocalStorage<PrerenderStore>
export { prerenderAsyncStorage }
import type { PrerenderAsyncStorage } from './prerender-async-storage.external'
import { createAsyncLocalStorage } from '../../client/components/async-local-storage' import { createAsyncLocalStorage } from '../../client/components/async-local-storage'
import type { WorkUnitAsyncStorage } from './work-unit-async-storage.external'
export const prerenderAsyncStorage: PrerenderAsyncStorage = export const workUnitAsyncStorage: WorkUnitAsyncStorage =
createAsyncLocalStorage() createAsyncLocalStorage()
...@@ -3,15 +3,16 @@ import type { DraftModeProvider } from '../../server/async-storage/draft-mode-pr ...@@ -3,15 +3,16 @@ import type { DraftModeProvider } from '../../server/async-storage/draft-mode-pr
import type { ResponseCookies } from '../../server/web/spec-extension/cookies' import type { ResponseCookies } from '../../server/web/spec-extension/cookies'
import type { ReadonlyHeaders } from '../../server/web/spec-extension/adapters/headers' import type { ReadonlyHeaders } from '../../server/web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/adapters/request-cookies' import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/adapters/request-cookies'
import type { CacheSignal } from './cache-signal'
import type { DynamicTrackingState } from './dynamic-rendering'
// Share the instance module in the next-shared layer // Share the instance module in the next-shared layer
import { requestAsyncStorage } from './request-async-storage-instance' with { 'turbopack-transition': 'next-shared' } import { workUnitAsyncStorage } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import type { ServerComponentsHmrCache } from '../../server/response-cache' import type { ServerComponentsHmrCache } from '../../server/response-cache'
import { cacheAsyncStorage } from '../../server/app-render/cache-async-storage.external' export type RequestStore = {
import { prerenderAsyncStorage } from '../../server/app-render/prerender-async-storage.external' type: 'request'
export interface RequestStore {
/** /**
* The URL of the request. This only specifies the pathname and the search * The URL of the request. This only specifies the pathname and the search
* part of the URL. * part of the URL.
...@@ -37,27 +38,94 @@ export interface RequestStore { ...@@ -37,27 +38,94 @@ export interface RequestStore {
readonly serverComponentsHmrCache?: ServerComponentsHmrCache readonly serverComponentsHmrCache?: ServerComponentsHmrCache
} }
export type RequestAsyncStorage = AsyncLocalStorage<RequestStore> /**
* The Prerender store is for tracking information related to prerenders.
*
* It can be used for both RSC and SSR prerendering and should be scoped as close
* to the individual `renderTo...` API call as possible. To keep the type simple
* we don't distinguish between RSC and SSR prerendering explicitly but instead
* use conditional object properties to infer which mode we are in. For instance cache tracking
* only needs to happen during the RSC prerender when we are prospectively prerendering
* to fill all caches.
*/
export type PrerenderStoreModern = {
type: 'prerender'
pathname: string | undefined
/**
* This is the AbortController passed to React. It can be used to abort the prerender
* if we encounter conditions that do not require further rendering
*/
readonly controller: null | AbortController
export { requestAsyncStorage } /**
* when not null this signal is used to track cache reads during prerendering and
* to await all cache reads completing before aborting the prerender.
*/
readonly cacheSignal: null | CacheSignal
export function getExpectedRequestStore(callingExpression: string) { /**
const prerenderStore = prerenderAsyncStorage.getStore() * During some prerenders we want to track dynamic access.
if (prerenderStore) { */
// This should not happen because we should have checked it already. readonly dynamicTracking: null | DynamicTrackingState
throw new Error( }
`\`${callingExpression}\` cannot be called inside a prerender. This is a bug in Next.js.`
) export type PrerenderStoreLegacy = {
} type: 'prerender-legacy'
const store = requestAsyncStorage.getStore() pathname: string | undefined
if (store) return store }
const cacheStore = cacheAsyncStorage.getStore()
if (cacheStore) { export type PrerenderStore = PrerenderStoreLegacy | PrerenderStoreModern
if (cacheStore.type === 'cache') {
export function isDynamicIOPrerender(workUnitStore: WorkUnitStore): boolean {
return (
workUnitStore.type === 'prerender' &&
!!(workUnitStore.controller || workUnitStore.cacheSignal)
)
}
export type UseCacheStore = {
type: 'cache'
// TODO: Inside this scope we'll track tags and life times of this scope.
}
export type UnstableCacheStore = {
type: 'unstable-cache'
}
/**
* The Cache store is for tracking information inside a "use cache" or unstable_cache context.
* Inside this context we should never expose any request or page specific information.
*/
export type CacheStore = UseCacheStore | UnstableCacheStore
export type WorkUnitStore = RequestStore | CacheStore | PrerenderStore
export type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>
export { workUnitAsyncStorage }
export function getExpectedRequestStore(
callingExpression: string
): RequestStore {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
if (workUnitStore.type === 'request') {
return workUnitStore
}
if (
workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-legacy'
) {
// This should not happen because we should have checked it already.
throw new Error(
`\`${callingExpression}\` cannot be called inside a prerender. This is a bug in Next.js.`
)
}
if (workUnitStore.type === 'cache') {
throw new Error( throw new Error(
`\`${callingExpression}\` cannot be called inside "use cache". Call it outside and pass an argument instead. Read more: https://nextjs.org/docs/messages/next-request-in-use-cache` `\`${callingExpression}\` cannot be called inside "use cache". Call it outside and pass an argument instead. Read more: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
} else if (cacheStore.type === 'unstable-cache') { } else if (workUnitStore.type === 'unstable-cache') {
throw new Error( throw new Error(
`\`${callingExpression}\` cannot be called inside unstable_cache. Call it outside and pass an argument instead. Read more: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `\`${callingExpression}\` cannot be called inside unstable_cache. Call it outside and pass an argument instead. Read more: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
) )
......
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { IncomingHttpHeaders } from 'http' import type { IncomingHttpHeaders } from 'http'
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type {
RequestStore,
WorkUnitStore,
} from '../../server/app-render/work-unit-async-storage.external'
import type { RenderOpts } from '../app-render/types' import type { RenderOpts } from '../app-render/types'
import type { WithStore } from './with-store' import type { WithStore } from './with-store'
import type { NextRequest } from '../web/spec-extension/request' import type { NextRequest } from '../web/spec-extension/request'
...@@ -99,10 +102,10 @@ function mergeMiddlewareCookies( ...@@ -99,10 +102,10 @@ function mergeMiddlewareCookies(
} }
} }
export const withRequestStore: WithStore<RequestStore, RequestContext> = < export const withRequestStore: WithStore<WorkUnitStore, RequestContext> = <
Result, Result,
>( >(
storage: AsyncLocalStorage<RequestStore>, storage: AsyncLocalStorage<WorkUnitStore>,
{ {
req, req,
url, url,
...@@ -127,6 +130,7 @@ export const withRequestStore: WithStore<RequestStore, RequestContext> = < ...@@ -127,6 +130,7 @@ export const withRequestStore: WithStore<RequestStore, RequestContext> = <
} = {} } = {}
const store: RequestStore = { const store: RequestStore = {
type: 'request',
// Rather than just using the whole `url` here, we pull the parts we want // Rather than just using the whole `url` here, we pull the parts we want
// to ensure we don't use parts of the URL that we shouldn't. This also // to ensure we don't use parts of the URL that we shouldn't. This also
// lets us avoid requiring an empty string for `search` in the type. // lets us avoid requiring an empty string for `search` in the type.
......
import { AsyncLocalStorage } from 'node:async_hooks' import { AsyncLocalStorage } from 'node:async_hooks'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type { WorkUnitStore } from '../../server/app-render/work-unit-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { IncrementalCache } from './incremental-cache' import type { IncrementalCache } from './incremental-cache'
import { createPatchedFetcher } from './patch-fetch' import { createPatchedFetcher } from './patch-fetch'
import type { PrerenderStore } from '../app-render/prerender-async-storage.external'
describe('createPatchedFetcher', () => { describe('createPatchedFetcher', () => {
it('should not buffer a streamed response', async () => { it('should not buffer a streamed response', async () => {
...@@ -24,13 +23,12 @@ describe('createPatchedFetcher', () => { ...@@ -24,13 +23,12 @@ describe('createPatchedFetcher', () => {
const workAsyncStorage = new AsyncLocalStorage<WorkStore>() const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const prerenderAsyncStorage = new AsyncLocalStorage<PrerenderStore>() const workUnitAsyncStorage = new AsyncLocalStorage<WorkUnitStore>()
const patchedFetch = createPatchedFetcher(mockFetch, { const patchedFetch = createPatchedFetcher(mockFetch, {
// requestAsyncStorage does not need to provide a store for this test. // workUnitAsyncStorage does not need to provide a store for this test.
requestAsyncStorage: new AsyncLocalStorage<RequestStore>(),
workAsyncStorage, workAsyncStorage,
prerenderAsyncStorage, workUnitAsyncStorage,
}) })
let resolveIncrementalCacheSet: () => void let resolveIncrementalCacheSet: () => void
......
...@@ -15,20 +15,15 @@ import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering' ...@@ -15,20 +15,15 @@ import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'
import type { FetchMetric } from '../base-http' import type { FetchMetric } from '../base-http'
import { createDedupeFetch } from './dedupe-fetch' import { createDedupeFetch } from './dedupe-fetch'
import type { import type {
RequestAsyncStorage, WorkUnitAsyncStorage,
WorkUnitStore,
RequestStore, RequestStore,
} from '../../client/components/request-async-storage.external' } from '../../server/app-render/work-unit-async-storage.external'
import type { PrerenderStore } from '../app-render/prerender-async-storage.external'
import {
cacheAsyncStorage,
type CacheStore,
} from '../../server/app-render/cache-async-storage.external'
import { import {
CachedRouteKind, CachedRouteKind,
IncrementalCacheKind, IncrementalCacheKind,
type CachedFetchData, type CachedFetchData,
} from '../response-cache' } from '../response-cache'
import type { PrerenderAsyncStorage } from '../app-render/prerender-async-storage.external'
import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler' import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -144,9 +139,7 @@ const getDerivedTags = (pathname: string): string[] => { ...@@ -144,9 +139,7 @@ const getDerivedTags = (pathname: string): string[] => {
export function addImplicitTags( export function addImplicitTags(
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore | undefined, workUnitStore: WorkUnitStore | undefined
prerenderStore: PrerenderStore | undefined,
cacheStore: CacheStore | undefined
) { ) {
const newTags: string[] = [] const newTags: string[] = []
const { page, fallbackRouteParams } = workStore const { page, fallbackRouteParams } = workStore
...@@ -155,8 +148,8 @@ export function addImplicitTags( ...@@ -155,8 +148,8 @@ export function addImplicitTags(
// Ini the tags array if it doesn't exist. // Ini the tags array if it doesn't exist.
if ( if (
!cacheStore || !workUnitStore ||
(cacheStore.type !== 'cache' && cacheStore.type !== 'unstable-cache') (workUnitStore.type !== 'cache' && workUnitStore.type !== 'unstable-cache')
) { ) {
workStore.tags ??= [] workStore.tags ??= []
} }
...@@ -166,8 +159,9 @@ export function addImplicitTags( ...@@ -166,8 +159,9 @@ export function addImplicitTags(
for (let tag of derivedTags) { for (let tag of derivedTags) {
tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}` tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`
if ( if (
!cacheStore || !workUnitStore ||
(cacheStore.type !== 'cache' && cacheStore.type !== 'unstable-cache') (workUnitStore.type !== 'cache' &&
workUnitStore.type !== 'unstable-cache')
) { ) {
if (!workStore.tags?.includes(tag)) { if (!workStore.tags?.includes(tag)) {
workStore.tags?.push(tag) workStore.tags?.push(tag)
...@@ -177,23 +171,21 @@ export function addImplicitTags( ...@@ -177,23 +171,21 @@ export function addImplicitTags(
} }
const renderedPathname = const renderedPathname =
requestStore !== undefined workUnitStore !== undefined
? requestStore.url.pathname ? workUnitStore.type === 'request'
: prerenderStore !== undefined ? workUnitStore.url.pathname
? prerenderStore.pathname : workUnitStore.type === 'prerender' ||
: undefined workUnitStore.type === 'prerender-legacy'
? workUnitStore.pathname
: undefined
: undefined
// Add the tags from the pathname. If the route has unknown params, we don't // Add the tags from the pathname. If the route has unknown params, we don't
// want to add the pathname as a tag, as it will be invalid. // want to add the pathname as a tag, as it will be invalid.
if (renderedPathname && !hasFallbackRouteParams) { if (renderedPathname && !hasFallbackRouteParams) {
const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${renderedPathname}` const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${renderedPathname}`
if ( if (!workStore.tags?.includes(tag)) {
!cacheStore || workStore.tags?.push(tag)
(cacheStore.type !== 'cache' && cacheStore.type !== 'unstable-cache')
) {
if (!workStore.tags?.includes(tag)) {
workStore.tags?.push(tag)
}
} }
newTags.push(tag) newTags.push(tag)
} }
...@@ -235,17 +227,12 @@ function trackFetchMetric( ...@@ -235,17 +227,12 @@ function trackFetchMetric(
interface PatchableModule { interface PatchableModule {
workAsyncStorage: WorkAsyncStorage workAsyncStorage: WorkAsyncStorage
requestAsyncStorage: RequestAsyncStorage workUnitAsyncStorage: WorkUnitAsyncStorage
prerenderAsyncStorage: PrerenderAsyncStorage
} }
export function createPatchedFetcher( export function createPatchedFetcher(
originFetch: Fetcher, originFetch: Fetcher,
{ { workAsyncStorage, workUnitAsyncStorage }: PatchableModule
workAsyncStorage,
requestAsyncStorage,
prerenderAsyncStorage,
}: PatchableModule
): PatchedFetcher { ): PatchedFetcher {
// Create the patched fetch function. We don't set the type here, as it's // Create the patched fetch function. We don't set the type here, as it's
// verified as the return value of this function. // verified as the return value of this function.
...@@ -272,7 +259,7 @@ export function createPatchedFetcher( ...@@ -272,7 +259,7 @@ export function createPatchedFetcher(
const hideSpan = process.env.NEXT_OTEL_FETCH_DISABLED === '1' const hideSpan = process.env.NEXT_OTEL_FETCH_DISABLED === '1'
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const result = getTracer().trace( const result = getTracer().trace(
isInternal ? NextNodeServerSpan.internalFetch : AppRenderSpan.fetch, isInternal ? NextNodeServerSpan.internalFetch : AppRenderSpan.fetch,
...@@ -293,9 +280,6 @@ export function createPatchedFetcher( ...@@ -293,9 +280,6 @@ export function createPatchedFetcher(
return originFetch(input, init) return originFetch(input, init)
} }
const requestStore = requestAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore()
// If the workStore is not available, we can't do any // If the workStore is not available, we can't do any
// special treatment of fetch, therefore fallback to the original // special treatment of fetch, therefore fallback to the original
// fetch implementation. // fetch implementation.
...@@ -337,8 +321,9 @@ export function createPatchedFetcher( ...@@ -337,8 +321,9 @@ export function createPatchedFetcher(
) )
if ( if (
!cacheStore || !workUnitStore ||
(cacheStore.type !== 'cache' && cacheStore.type !== 'unstable-cache') (workUnitStore.type !== 'cache' &&
workUnitStore.type !== 'unstable-cache')
) { ) {
if (Array.isArray(tags)) { if (Array.isArray(tags)) {
if (!workStore.tags) { if (!workStore.tags) {
...@@ -352,16 +337,11 @@ export function createPatchedFetcher( ...@@ -352,16 +337,11 @@ export function createPatchedFetcher(
} }
} }
const implicitTags = addImplicitTags( const implicitTags = addImplicitTags(workStore, workUnitStore)
workStore,
requestStore,
prerenderStore,
cacheStore
)
// Inside unstable-cache we treat it the same as force-no-store on the page. // Inside unstable-cache we treat it the same as force-no-store on the page.
const pageFetchCacheMode = const pageFetchCacheMode =
cacheStore && cacheStore.type === 'unstable-cache' workUnitStore && workUnitStore.type === 'unstable-cache'
? 'force-no-store' ? 'force-no-store'
: workStore.fetchCache : workStore.fetchCache
const isUsingNoStore = !!workStore.isUnstableNoStore const isUsingNoStore = !!workStore.isUnstableNoStore
...@@ -535,16 +515,16 @@ export function createPatchedFetcher( ...@@ -535,16 +515,16 @@ export function createPatchedFetcher(
finalRevalidate < workStore.revalidate)))) finalRevalidate < workStore.revalidate))))
) { ) {
if ( if (
!cacheStore || !workUnitStore ||
(cacheStore.type !== 'cache' && (workUnitStore.type !== 'cache' &&
cacheStore.type !== 'unstable-cache') workUnitStore.type !== 'unstable-cache')
) { ) {
// If we were setting the revalidate value to 0, we should try to // If we were setting the revalidate value to 0, we should try to
// postpone instead first. // postpone instead first.
if (finalRevalidate === 0) { if (finalRevalidate === 0) {
markCurrentScopeAsDynamic( markCurrentScopeAsDynamic(
workStore, workStore,
cacheStore, workUnitStore,
`revalidate: 0 fetch ${input} ${workStore.route}` `revalidate: 0 fetch ${input} ${workStore.route}`
) )
} }
...@@ -560,6 +540,11 @@ export function createPatchedFetcher( ...@@ -560,6 +540,11 @@ export function createPatchedFetcher(
let cacheKey: string | undefined let cacheKey: string | undefined
const { incrementalCache } = workStore const { incrementalCache } = workStore
const requestStore: undefined | RequestStore =
workUnitStore !== undefined && workUnitStore.type === 'request'
? workUnitStore
: undefined
if ( if (
incrementalCache && incrementalCache &&
(isCacheableRevalidate || requestStore?.serverComponentsHmrCache) (isCacheableRevalidate || requestStore?.serverComponentsHmrCache)
...@@ -652,7 +637,7 @@ export function createPatchedFetcher( ...@@ -652,7 +637,7 @@ export function createPatchedFetcher(
cacheKey && cacheKey &&
(isCacheableRevalidate || requestStore?.serverComponentsHmrCache) (isCacheableRevalidate || requestStore?.serverComponentsHmrCache)
) { ) {
if (prerenderStore) { if (workUnitStore && workUnitStore.type === 'prerender') {
// We are prerendering at build time or revalidate time so we need to // We are prerendering at build time or revalidate time so we need to
// buffer the response so we can guarantee it can be read in a microtask // buffer the response so we can guarantee it can be read in a microtask
...@@ -783,7 +768,7 @@ export function createPatchedFetcher( ...@@ -783,7 +768,7 @@ export function createPatchedFetcher(
// We sometimes use the cache to dedupe fetches that do not specify a cache configuration // We sometimes use the cache to dedupe fetches that do not specify a cache configuration
// In these cases we want to make sure we still exclude them from prerenders if dynamicIO is on // In these cases we want to make sure we still exclude them from prerenders if dynamicIO is on
// so we introduce an artificial Task boundary here. // so we introduce an artificial Task boundary here.
if (prerenderStore) { if (workUnitStore && workUnitStore.type === 'prerender') {
await waitAtLeastOneReactRenderTask() await waitAtLeastOneReactRenderTask()
} }
} }
...@@ -857,7 +842,7 @@ export function createPatchedFetcher( ...@@ -857,7 +842,7 @@ export function createPatchedFetcher(
// If enabled, we should bail out of static generation. // If enabled, we should bail out of static generation.
markCurrentScopeAsDynamic( markCurrentScopeAsDynamic(
workStore, workStore,
cacheStore, workUnitStore,
`no-store fetch ${input} ${workStore.route}` `no-store fetch ${input} ${workStore.route}`
) )
} }
...@@ -874,16 +859,16 @@ export function createPatchedFetcher( ...@@ -874,16 +859,16 @@ export function createPatchedFetcher(
// If enabled, we should bail out of static generation. // If enabled, we should bail out of static generation.
markCurrentScopeAsDynamic( markCurrentScopeAsDynamic(
workStore, workStore,
cacheStore, workUnitStore,
`revalidate: 0 fetch ${input} ${workStore.route}` `revalidate: 0 fetch ${input} ${workStore.route}`
) )
} }
if (!workStore.forceStatic || next.revalidate !== 0) { if (!workStore.forceStatic || next.revalidate !== 0) {
if ( if (
!cacheStore || !workUnitStore ||
(cacheStore.type !== 'cache' && (workUnitStore.type !== 'cache' &&
cacheStore.type !== 'unstable-cache') workUnitStore.type !== 'unstable-cache')
) { ) {
workStore.revalidate = next.revalidate workStore.revalidate = next.revalidate
} }
...@@ -964,12 +949,12 @@ export function createPatchedFetcher( ...@@ -964,12 +949,12 @@ export function createPatchedFetcher(
) )
if ( if (
prerenderStore && workUnitStore &&
prerenderStore.type === 'prerender' && workUnitStore.type === 'prerender' &&
prerenderStore.cacheSignal workUnitStore.cacheSignal
) { ) {
// During static generation we track cache reads so we can reason about when they fill // During static generation we track cache reads so we can reason about when they fill
const cacheSignal = prerenderStore.cacheSignal const cacheSignal = workUnitStore.cacheSignal
cacheSignal.beginRead() cacheSignal.beginRead()
try { try {
return await result return await result
......
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, workUnitAsyncStorage,
} from '../app-render/prerender-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { cacheAsyncStorage } from '../../server/app-render/cache-async-storage.external'
import { import {
postponeWithTracking, postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
...@@ -19,8 +18,7 @@ import { makeHangingPromise } from '../dynamic-rendering-utils' ...@@ -19,8 +18,7 @@ import { makeHangingPromise } from '../dynamic-rendering-utils'
*/ */
export function connection(): Promise<void> { export function connection(): Promise<void> {
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore()
if (workStore) { if (workStore) {
if (workStore.forceStatic) { if (workStore.forceStatic) {
...@@ -29,12 +27,12 @@ export function connection(): Promise<void> { ...@@ -29,12 +27,12 @@ export function connection(): Promise<void> {
return Promise.resolve(undefined) return Promise.resolve(undefined)
} }
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache') { if (workUnitStore.type === 'cache') {
throw new Error( throw new Error(
`Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used "connection" inside "use cache". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
} else if (cacheStore.type === 'unstable-cache') { } else if (workUnitStore.type === 'unstable-cache') {
throw new Error( throw new Error(
`Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
) )
...@@ -46,10 +44,10 @@ export function connection(): Promise<void> { ...@@ -46,10 +44,10 @@ export function connection(): Promise<void> {
) )
} }
if (prerenderStore && prerenderStore.type === 'prerender') { if (workUnitStore && workUnitStore.type === 'prerender') {
// We are in PPR and/or dynamicIO mode and prerendering // We are in PPR and/or dynamicIO mode and prerendering
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(workUnitStore)) {
// We use the controller and cacheSignal as an indication we are in dynamicIO mode. // We use the controller and cacheSignal as an indication we are in dynamicIO mode.
// When resolving headers for a prerender with dynamic IO we return a forever promise // When resolving headers for a prerender with dynamic IO we return a forever promise
// along with property access tracked synchronous headers. // along with property access tracked synchronous headers.
...@@ -64,17 +62,17 @@ export function connection(): Promise<void> { ...@@ -64,17 +62,17 @@ export function connection(): Promise<void> {
postponeWithTracking( postponeWithTracking(
workStore.route, workStore.route,
'connection', 'connection',
prerenderStore.dynamicTracking workUnitStore.dynamicTracking
) )
} }
} else if (workStore.isStaticGeneration) { } else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We treat this function call as a bailout of static generation // We treat this function call as a bailout of static generation
throwToInterruptStaticGeneration('connection', workStore, cacheStore) throwToInterruptStaticGeneration('connection', workStore, workUnitStore)
} }
// We fall through to the dynamic context below but we still track dynamic access // We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context // because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(workStore, cacheStore) trackDynamicDataInDynamicRender(workStore, workUnitStore)
} }
return Promise.resolve(undefined) return Promise.resolve(undefined)
......
...@@ -7,17 +7,16 @@ import { RequestCookies } from '../../server/web/spec-extension/cookies' ...@@ -7,17 +7,16 @@ import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreModern, type PrerenderStoreModern,
} from '../app-render/prerender-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { cacheAsyncStorage } from '../../server/app-render/cache-async-storage.external'
import { import {
postponeWithTracking, postponeWithTracking,
abortAndThrowOnSynchronousDynamicDataAccess, abortAndThrowOnSynchronousDynamicDataAccess,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../../server/app-render/dynamic-rendering' } from '../../server/app-render/dynamic-rendering'
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external' import { getExpectedRequestStore } from '../../server/app-render/work-unit-async-storage.external'
import { actionAsyncStorage } from '../../client/components/action-async-storage.external' import { actionAsyncStorage } from '../../client/components/action-async-storage.external'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { makeResolvedReactPromise } from './utils' import { makeResolvedReactPromise } from './utils'
...@@ -53,8 +52,7 @@ export type UnsafeUnwrappedCookies = ReadonlyRequestCookies ...@@ -53,8 +52,7 @@ export type UnsafeUnwrappedCookies = ReadonlyRequestCookies
export function cookies(): Promise<ReadonlyRequestCookies> { export function cookies(): Promise<ReadonlyRequestCookies> {
const callingExpression = 'cookies' const callingExpression = 'cookies'
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore()
if (workStore) { if (workStore) {
if (workStore.forceStatic) { if (workStore.forceStatic) {
...@@ -64,12 +62,12 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -64,12 +62,12 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
return makeUntrackedExoticCookies(underlyingCookies) return makeUntrackedExoticCookies(underlyingCookies)
} }
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache') { if (workUnitStore.type === 'cache') {
throw new Error( throw new Error(
`Route ${workStore.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
} else if (cacheStore.type === 'unstable-cache') { } else if (workUnitStore.type === 'unstable-cache') {
throw new Error( throw new Error(
`Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
) )
...@@ -81,11 +79,11 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -81,11 +79,11 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
) )
} }
if (prerenderStore) { if (workUnitStore) {
if (prerenderStore.type === 'prerender') { if (workUnitStore.type === 'prerender') {
// We are in PPR and/or dynamicIO mode and prerendering // We are in PPR and/or dynamicIO mode and prerendering
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(workUnitStore)) {
// We use the controller and cacheSignal as an indication we are in dynamicIO mode. // We use the controller and cacheSignal as an indication we are in dynamicIO mode.
// When resolving cookies for a prerender with dynamic IO we return a forever promise // When resolving cookies for a prerender with dynamic IO we return a forever promise
// along with property access tracked synchronous cookies. // along with property access tracked synchronous cookies.
...@@ -94,7 +92,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -94,7 +92,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
// one of the properties of the cookies object. // one of the properties of the cookies object.
return makeDynamicallyTrackedExoticCookies( return makeDynamicallyTrackedExoticCookies(
workStore.route, workStore.route,
prerenderStore workUnitStore
) )
} else { } else {
// We are prerendering with PPR. We need track dynamic access here eagerly // We are prerendering with PPR. We need track dynamic access here eagerly
...@@ -103,23 +101,23 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -103,23 +101,23 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
postponeWithTracking( postponeWithTracking(
workStore.route, workStore.route,
callingExpression, callingExpression,
prerenderStore.dynamicTracking workUnitStore.dynamicTracking
) )
} }
} else if (prerenderStore.type === 'prerender-legacy') { } else if (workUnitStore.type === 'prerender-legacy') {
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the cookies in // We track dynamic access here so we don't need to wrap the cookies in
// individual property access tracking. // individual property access tracking.
throwToInterruptStaticGeneration( throwToInterruptStaticGeneration(
callingExpression, callingExpression,
workStore, workStore,
cacheStore workUnitStore
) )
} }
} }
// We fall through to the dynamic context below but we still track dynamic access // We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using cookies inside a cache context // because in dev we can still error for things like using cookies inside a cache context
trackDynamicDataInDynamicRender(workStore, cacheStore) trackDynamicDataInDynamicRender(workStore, workUnitStore)
} }
// cookies is being called in a dynamic context // cookies is being called in a dynamic context
......
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external' import { getExpectedRequestStore } from '../../server/app-render/work-unit-async-storage.external'
import type { DraftModeProvider } from '../../server/async-storage/draft-mode-provider' import type { DraftModeProvider } from '../../server/async-storage/draft-mode-provider'
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { cacheAsyncStorage } from '../../server/app-render/cache-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { prerenderAsyncStorage } from '../../server/app-render/prerender-async-storage.external'
import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering' import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger'
...@@ -37,15 +36,14 @@ export type UnsafeUnwrappedDraftMode = DraftMode ...@@ -37,15 +36,14 @@ export type UnsafeUnwrappedDraftMode = DraftMode
export function draftMode(): Promise<DraftMode> { export function draftMode(): Promise<DraftMode> {
const callingExpression = 'draftMode' const callingExpression = 'draftMode'
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore()
if ( if (
(cacheStore && workUnitStore &&
(cacheStore.type === 'cache' || cacheStore.type === 'unstable-cache')) || (workUnitStore.type === 'cache' ||
(prerenderStore && workUnitStore.type === 'unstable-cache' ||
(prerenderStore.type === 'prerender' || workUnitStore.type === 'prerender' ||
prerenderStore.type === 'prerender-legacy')) workUnitStore.type === 'prerender-legacy')
) { ) {
// Return empty draft mode // Return empty draft mode
if ( if (
...@@ -169,11 +167,11 @@ class DraftMode { ...@@ -169,11 +167,11 @@ class DraftMode {
} }
public enable() { public enable() {
const store = workAsyncStorage.getStore() const store = workAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (store) { if (store) {
// We we have a store we want to track dynamic data access to ensure we // We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode. // don't statically generate routes that manipulate draft mode.
trackDynamicDataAccessed(store, cacheStore, 'draftMode().enable()') trackDynamicDataAccessed(store, workUnitStore, 'draftMode().enable()')
} }
if (this._provider !== null) { if (this._provider !== null) {
this._provider.enable() this._provider.enable()
...@@ -181,11 +179,11 @@ class DraftMode { ...@@ -181,11 +179,11 @@ class DraftMode {
} }
public disable() { public disable() {
const store = workAsyncStorage.getStore() const store = workAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (store) { if (store) {
// We we have a store we want to track dynamic data access to ensure we // We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode. // don't statically generate routes that manipulate draft mode.
trackDynamicDataAccessed(store, cacheStore, 'draftMode().disable()') trackDynamicDataAccessed(store, workUnitStore, 'draftMode().disable()')
} }
if (this._provider !== null) { if (this._provider !== null) {
this._provider.disable() this._provider.disable()
......
...@@ -3,13 +3,12 @@ import { ...@@ -3,13 +3,12 @@ import {
type ReadonlyHeaders, type ReadonlyHeaders,
} from '../../server/web/spec-extension/adapters/headers' } from '../../server/web/spec-extension/adapters/headers'
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external' import { getExpectedRequestStore } from '../app-render/work-unit-async-storage.external'
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreModern, type PrerenderStoreModern,
} from '../app-render/prerender-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { cacheAsyncStorage } from '../../server/app-render/cache-async-storage.external'
import { import {
postponeWithTracking, postponeWithTracking,
abortAndThrowOnSynchronousDynamicDataAccess, abortAndThrowOnSynchronousDynamicDataAccess,
...@@ -58,8 +57,7 @@ export type UnsafeUnwrappedHeaders = ReadonlyHeaders ...@@ -58,8 +57,7 @@ export type UnsafeUnwrappedHeaders = ReadonlyHeaders
*/ */
export function headers(): Promise<ReadonlyHeaders> { export function headers(): Promise<ReadonlyHeaders> {
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore()
if (workStore) { if (workStore) {
if (workStore.forceStatic) { if (workStore.forceStatic) {
...@@ -69,12 +67,12 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -69,12 +67,12 @@ export function headers(): Promise<ReadonlyHeaders> {
return makeUntrackedExoticHeaders(underlyingHeaders) return makeUntrackedExoticHeaders(underlyingHeaders)
} }
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache') { if (workUnitStore.type === 'cache') {
throw new Error( throw new Error(
`Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache` `Route ${workStore.route} used "headers" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
) )
} else if (cacheStore.type === 'unstable-cache') { } else if (workUnitStore.type === 'unstable-cache') {
throw new Error( throw new Error(
`Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache` `Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
) )
...@@ -86,11 +84,11 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -86,11 +84,11 @@ export function headers(): Promise<ReadonlyHeaders> {
) )
} }
if (prerenderStore) { if (workUnitStore) {
if (prerenderStore.type === 'prerender') { if (workUnitStore.type === 'prerender') {
// We are in PPR and/or dynamicIO mode and prerendering // We are in PPR and/or dynamicIO mode and prerendering
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(workUnitStore)) {
// We use the controller and cacheSignal as an indication we are in dynamicIO mode. // We use the controller and cacheSignal as an indication we are in dynamicIO mode.
// When resolving headers for a prerender with dynamic IO we return a forever promise // When resolving headers for a prerender with dynamic IO we return a forever promise
// along with property access tracked synchronous headers. // along with property access tracked synchronous headers.
...@@ -99,7 +97,7 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -99,7 +97,7 @@ export function headers(): Promise<ReadonlyHeaders> {
// one of the properties of the headers object. // one of the properties of the headers object.
return makeDynamicallyTrackedExoticHeaders( return makeDynamicallyTrackedExoticHeaders(
workStore.route, workStore.route,
prerenderStore workUnitStore
) )
} else { } else {
// We are prerendering with PPR. We need track dynamic access here eagerly // We are prerendering with PPR. We need track dynamic access here eagerly
...@@ -108,19 +106,19 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -108,19 +106,19 @@ export function headers(): Promise<ReadonlyHeaders> {
postponeWithTracking( postponeWithTracking(
workStore.route, workStore.route,
'headers', 'headers',
prerenderStore.dynamicTracking workUnitStore.dynamicTracking
) )
} }
} else if (prerenderStore.type === 'prerender-legacy') { } else if (workUnitStore.type === 'prerender-legacy') {
// We are in a legacy static generation mode while prerendering // We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the headers in // We track dynamic access here so we don't need to wrap the headers in
// individual property access tracking. // individual property access tracking.
throwToInterruptStaticGeneration('headers', workStore, cacheStore) throwToInterruptStaticGeneration('headers', workStore, workUnitStore)
} }
} }
// We fall through to the dynamic context below but we still track dynamic access // We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context // because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(workStore, cacheStore) trackDynamicDataInDynamicRender(workStore, workUnitStore)
} }
const requestStore = getExpectedRequestStore('headers') const requestStore = getExpectedRequestStore('headers')
......
...@@ -10,10 +10,10 @@ import { ...@@ -10,10 +10,10 @@ import {
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, workUnitAsyncStorage,
type PrerenderStore, type WorkUnitStore,
type PrerenderStoreModern, type PrerenderStoreModern,
} from '../app-render/prerender-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { makeResolvedReactPromise, describeStringPropertyAccess } from './utils' import { makeResolvedReactPromise, describeStringPropertyAccess } from './utils'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
...@@ -94,7 +94,7 @@ export function createPrerenderParamsForClientSegment( ...@@ -94,7 +94,7 @@ export function createPrerenderParamsForClientSegment(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore workStore: WorkStore
): Promise<Params> { ): Promise<Params> {
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore && prerenderStore.type === 'prerender') { if (prerenderStore && prerenderStore.type === 'prerender') {
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
const fallbackParams = workStore.fallbackRouteParams const fallbackParams = workStore.fallbackRouteParams
...@@ -132,7 +132,7 @@ function createPrerenderParams( ...@@ -132,7 +132,7 @@ function createPrerenderParams(
if (hasSomeFallbackParams) { if (hasSomeFallbackParams) {
// params need to be treated as dynamic because we have at least one fallback param // params need to be treated as dynamic because we have at least one fallback param
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore && prerenderStore.type === 'prerender') { if (prerenderStore && prerenderStore.type === 'prerender') {
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
// We are in a dynamicIO (PPR or otherwise) prerender // We are in a dynamicIO (PPR or otherwise) prerender
...@@ -249,7 +249,7 @@ function makeErroringExoticParams( ...@@ -249,7 +249,7 @@ function makeErroringExoticParams(
underlyingParams: Params, underlyingParams: Params,
fallbackParams: FallbackRouteParams, fallbackParams: FallbackRouteParams,
workStore: WorkStore, workStore: WorkStore,
prerenderStore: undefined | PrerenderStore prerenderStore: undefined | WorkUnitStore
): Promise<Params> { ): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams) const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) { if (cachedParams) {
...@@ -311,7 +311,11 @@ function makeErroringExoticParams( ...@@ -311,7 +311,11 @@ function makeErroringExoticParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration(expression, workStore) throwToInterruptStaticGeneration(
expression,
workStore,
undefined
)
} }
}, },
enumerable: true, enumerable: true,
...@@ -332,7 +336,11 @@ function makeErroringExoticParams( ...@@ -332,7 +336,11 @@ function makeErroringExoticParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
throwToInterruptStaticGeneration(expression, workStore) throwToInterruptStaticGeneration(
expression,
workStore,
undefined
)
} }
}, },
set(newValue) { set(newValue) {
......
...@@ -11,11 +11,10 @@ import { ...@@ -11,11 +11,10 @@ import {
import { import {
isDynamicIOPrerender, isDynamicIOPrerender,
prerenderAsyncStorage, workUnitAsyncStorage,
type PrerenderStore, type WorkUnitStore,
type PrerenderStoreModern, type PrerenderStoreModern,
} from '../app-render/prerender-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { cacheAsyncStorage } from '../app-render/cache-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger'
...@@ -90,7 +89,7 @@ export function createPrerenderSearchParamsForClientPage( ...@@ -90,7 +89,7 @@ export function createPrerenderSearchParamsForClientPage(
return Promise.resolve({}) return Promise.resolve({})
} }
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore) { if (prerenderStore) {
if (isDynamicIOPrerender(prerenderStore)) { if (isDynamicIOPrerender(prerenderStore)) {
// We're prerendering in a mode that aborts (dynamicIO) and should stall // We're prerendering in a mode that aborts (dynamicIO) and should stall
...@@ -113,7 +112,7 @@ function createPrerenderSearchParams( ...@@ -113,7 +112,7 @@ function createPrerenderSearchParams(
return Promise.resolve({}) return Promise.resolve({})
} }
const prerenderStore = prerenderAsyncStorage.getStore() const prerenderStore = workUnitAsyncStorage.getStore()
if (prerenderStore && prerenderStore.type === 'prerender') { if (prerenderStore && prerenderStore.type === 'prerender') {
if (prerenderStore.controller || prerenderStore.cacheSignal) { if (prerenderStore.controller || prerenderStore.cacheSignal) {
// We are in a dynamicIO (PPR or otherwise) prerender // We are in a dynamicIO (PPR or otherwise) prerender
...@@ -259,7 +258,7 @@ function makeAbortingExoticSearchParams( ...@@ -259,7 +258,7 @@ function makeAbortingExoticSearchParams(
function makeErroringExoticSearchParams( function makeErroringExoticSearchParams(
workStore: WorkStore, workStore: WorkStore,
prerenderStore: undefined | PrerenderStore prerenderStore: undefined | WorkUnitStore
): Promise<SearchParams> { ): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(workStore) const cachedSearchParams = CachedSearchParams.get(workStore)
if (cachedSearchParams) { if (cachedSearchParams) {
...@@ -319,8 +318,12 @@ function makeErroringExoticSearchParams( ...@@ -319,8 +318,12 @@ function makeErroringExoticSearchParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
throwToInterruptStaticGeneration(expression, workStore, cacheStore) throwToInterruptStaticGeneration(
expression,
workStore,
workUnitStore
)
} }
return return
} }
...@@ -339,8 +342,12 @@ function makeErroringExoticSearchParams( ...@@ -339,8 +342,12 @@ function makeErroringExoticSearchParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
throwToInterruptStaticGeneration(expression, workStore, cacheStore) throwToInterruptStaticGeneration(
expression,
workStore,
workUnitStore
)
} }
return return
} }
...@@ -362,11 +369,11 @@ function makeErroringExoticSearchParams( ...@@ -362,11 +369,11 @@ function makeErroringExoticSearchParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
throwToInterruptStaticGeneration( throwToInterruptStaticGeneration(
expression, expression,
workStore, workStore,
cacheStore workUnitStore
) )
} }
} }
...@@ -396,8 +403,8 @@ function makeErroringExoticSearchParams( ...@@ -396,8 +403,8 @@ function makeErroringExoticSearchParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
throwToInterruptStaticGeneration(expression, workStore, cacheStore) throwToInterruptStaticGeneration(expression, workStore, workUnitStore)
} }
return false return false
} }
...@@ -418,8 +425,8 @@ function makeErroringExoticSearchParams( ...@@ -418,8 +425,8 @@ function makeErroringExoticSearchParams(
prerenderStore.dynamicTracking prerenderStore.dynamicTracking
) )
} else { } else {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
throwToInterruptStaticGeneration(expression, workStore, cacheStore) throwToInterruptStaticGeneration(expression, workStore, workUnitStore)
} }
}, },
}) })
...@@ -475,8 +482,8 @@ function makeUntrackedExoticSearchParams( ...@@ -475,8 +482,8 @@ function makeUntrackedExoticSearchParams(
default: { default: {
Object.defineProperty(promise, prop, { Object.defineProperty(promise, prop, {
get() { get() {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataInDynamicRender(store, cacheStore) trackDynamicDataInDynamicRender(store, workUnitStore)
return underlyingSearchParams[prop] return underlyingSearchParams[prop]
}, },
set(value) { set(value) {
...@@ -525,8 +532,8 @@ function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings( ...@@ -525,8 +532,8 @@ function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
expression expression
) )
} }
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataInDynamicRender(store, cacheStore) trackDynamicDataInDynamicRender(store, workUnitStore)
} }
return ReflectAdapter.get(target, prop, receiver) return ReflectAdapter.get(target, prop, receiver)
}, },
......
...@@ -37,23 +37,19 @@ import { parsedUrlQueryToParams } from './helpers/parsed-url-query-to-params' ...@@ -37,23 +37,19 @@ import { parsedUrlQueryToParams } from './helpers/parsed-url-query-to-params'
import * as serverHooks from '../../../client/components/hooks-server-context' import * as serverHooks from '../../../client/components/hooks-server-context'
import { DynamicServerError } from '../../../client/components/hooks-server-context' import { DynamicServerError } from '../../../client/components/hooks-server-context'
import {
requestAsyncStorage,
type RequestStore,
} from '../../../client/components/request-async-storage.external'
import { import {
workAsyncStorage, workAsyncStorage,
type WorkStore, type WorkStore,
} from '../../../client/components/work-async-storage.external' } from '../../../client/components/work-async-storage.external'
import { import {
prerenderAsyncStorage, workUnitAsyncStorage,
type WorkUnitStore,
type PrerenderStore, type PrerenderStore,
} from '../../app-render/prerender-async-storage.external' } from '../../app-render/work-unit-async-storage.external'
import { import {
actionAsyncStorage, actionAsyncStorage,
type ActionStore, type ActionStore,
} from '../../../client/components/action-async-storage.external' } from '../../../client/components/action-async-storage.external'
import { cacheAsyncStorage } from '../../../server/app-render/cache-async-storage.external'
import * as sharedModules from './shared-modules' import * as sharedModules from './shared-modules'
import { getIsServerAction } from '../../lib/server-action-request-meta' import { getIsServerAction } from '../../lib/server-action-request-meta'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies' import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
...@@ -167,19 +163,13 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -167,19 +163,13 @@ export class AppRouteRouteModule extends RouteModule<
/** /**
* A reference to the request async storage. * A reference to the request async storage.
*/ */
public readonly requestAsyncStorage = requestAsyncStorage public readonly workUnitAsyncStorage = workUnitAsyncStorage
/** /**
* A reference to the static generation async storage. * A reference to the static generation async storage.
*/ */
public readonly workAsyncStorage = workAsyncStorage public readonly workAsyncStorage = workAsyncStorage
/**
* prerenderAsyncStorage is used to scope a prerender context for renders ocurring
* during a build or revalidate.
*/
public readonly prerenderAsyncStorage = prerenderAsyncStorage
/** /**
* An interface to call server hooks which interact with the underlying * An interface to call server hooks which interact with the underlying
* storage. * storage.
...@@ -287,7 +277,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -287,7 +277,7 @@ export class AppRouteRouteModule extends RouteModule<
handler: AppRouteHandlerFn, handler: AppRouteHandlerFn,
actionStore: ActionStore, actionStore: ActionStore,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore, workUnitStore: WorkUnitStore,
request: NextRequest, request: NextRequest,
context: AppRouteRouteHandlerContext context: AppRouteRouteHandlerContext
) { ) {
...@@ -297,8 +287,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -297,8 +287,7 @@ export class AppRouteRouteModule extends RouteModule<
// Patch the global fetch. // Patch the global fetch.
patchFetch({ patchFetch({
workAsyncStorage: this.workAsyncStorage, workAsyncStorage: this.workAsyncStorage,
requestAsyncStorage: this.requestAsyncStorage, workUnitAsyncStorage: this.workUnitAsyncStorage,
prerenderAsyncStorage: this.prerenderAsyncStorage,
}) })
const handlerContext: AppRouteHandlerFnContext = { const handlerContext: AppRouteHandlerFnContext = {
...@@ -310,6 +299,14 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -310,6 +299,14 @@ export class AppRouteRouteModule extends RouteModule<
: undefined, : undefined,
} }
const pathname =
workUnitStore.type === 'request'
? workUnitStore.url.pathname
: workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-legacy'
? workUnitStore.pathname
: undefined
let res: unknown let res: unknown
try { try {
if (isStaticGeneration && dynamicIOEnabled) { if (isStaticGeneration && dynamicIOEnabled) {
...@@ -334,9 +331,10 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -334,9 +331,10 @@ export class AppRouteRouteModule extends RouteModule<
let prospectiveRenderIsDynamic = false let prospectiveRenderIsDynamic = false
const cacheSignal = new CacheSignal() const cacheSignal = new CacheSignal()
let dynamicTracking = createDynamicTrackingState(undefined) let dynamicTracking = createDynamicTrackingState(undefined)
const prospectiveRoutePrerenderStore: PrerenderStore = { const prospectiveRoutePrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
pathname: requestStore.url.pathname, pathname,
cacheSignal, cacheSignal,
// During prospective render we don't use a controller // During prospective render we don't use a controller
// because we need to let all caches fill. // because we need to let all caches fill.
...@@ -345,7 +343,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -345,7 +343,7 @@ export class AppRouteRouteModule extends RouteModule<
} }
let prospectiveResult let prospectiveResult
try { try {
prospectiveResult = this.prerenderAsyncStorage.run( prospectiveResult = this.workUnitAsyncStorage.run(
prospectiveRoutePrerenderStore, prospectiveRoutePrerenderStore,
handler, handler,
request, request,
...@@ -404,7 +402,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -404,7 +402,7 @@ export class AppRouteRouteModule extends RouteModule<
const finalRoutePrerenderStore: PrerenderStore = { const finalRoutePrerenderStore: PrerenderStore = {
type: 'prerender', type: 'prerender',
pathname: requestStore.url.pathname, pathname,
cacheSignal: null, cacheSignal: null,
controller, controller,
dynamicTracking, dynamicTracking,
...@@ -414,7 +412,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -414,7 +412,7 @@ export class AppRouteRouteModule extends RouteModule<
res = await new Promise((resolve, reject) => { res = await new Promise((resolve, reject) => {
scheduleImmediate(async () => { scheduleImmediate(async () => {
try { try {
const result = await (this.prerenderAsyncStorage.run( const result = await (this.workUnitAsyncStorage.run(
finalRoutePrerenderStore, finalRoutePrerenderStore,
handler, handler,
request, request,
...@@ -465,10 +463,10 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -465,10 +463,10 @@ export class AppRouteRouteModule extends RouteModule<
}) })
}) })
} else if (isStaticGeneration) { } else if (isStaticGeneration) {
res = await prerenderAsyncStorage.run( res = await workUnitAsyncStorage.run(
{ {
type: 'prerender-legacy', type: 'prerender-legacy',
pathname: requestStore.url.pathname, pathname,
}, },
handler, handler,
request, request,
...@@ -490,7 +488,9 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -490,7 +488,9 @@ export class AppRouteRouteModule extends RouteModule<
// Let's append any cookies that were added by the // Let's append any cookies that were added by the
// cookie API. // cookie API.
appendMutableCookies(headers, requestStore.mutableCookies) if (workUnitStore.type === 'request') {
appendMutableCookies(headers, workUnitStore.mutableCookies)
}
// Return the redirect response. // Return the redirect response.
return new Response(null, { return new Response(null, {
...@@ -525,14 +525,17 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -525,14 +525,17 @@ export class AppRouteRouteModule extends RouteModule<
...Object.values(workStore.pendingRevalidates || {}), ...Object.values(workStore.pendingRevalidates || {}),
]) ])
addImplicitTags(workStore, requestStore, undefined, undefined) addImplicitTags(workStore, workUnitStore)
;(context.renderOpts as any).fetchTags = workStore.tags?.join(',') ;(context.renderOpts as any).fetchTags = workStore.tags?.join(',')
// It's possible cookies were set in the handler, so we need // It's possible cookies were set in the handler, so we need
// to merge the modified cookies and the returned response // to merge the modified cookies and the returned response
// here. // here.
const headers = new Headers(res.headers) const headers = new Headers(res.headers)
if (appendMutableCookies(headers, requestStore.mutableCookies)) { if (
workUnitStore.type === 'request' &&
appendMutableCookies(headers, workUnitStore.mutableCookies)
) {
return new Response(res.body, { return new Response(res.body, {
status: res.status, status: res.status,
statusText: res.statusText, statusText: res.statusText,
...@@ -583,9 +586,9 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -583,9 +586,9 @@ export class AppRouteRouteModule extends RouteModule<
actionStore, actionStore,
() => () =>
withRequestStore( withRequestStore(
this.requestAsyncStorage, this.workUnitAsyncStorage,
requestContext, requestContext,
(requestStore) => (workUnitStore) =>
withWorkStore( withWorkStore(
this.workAsyncStorage, this.workAsyncStorage,
staticGenerationContext, staticGenerationContext,
...@@ -667,7 +670,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -667,7 +670,7 @@ export class AppRouteRouteModule extends RouteModule<
handler, handler,
actionStore, actionStore,
workStore, workStore,
requestStore, workUnitStore,
request, request,
context context
) )
...@@ -873,8 +876,8 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) { ...@@ -873,8 +876,8 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) {
case 'toJSON': case 'toJSON':
case 'toString': case 'toString':
case 'origin': { case 'origin': {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataAccessed(workStore, cacheStore, `nextUrl.${prop}`) trackDynamicDataAccessed(workStore, workUnitStore, `nextUrl.${prop}`)
return ReflectAdapter.get(target, prop, receiver) return ReflectAdapter.get(target, prop, receiver)
} }
case 'clone': case 'clone':
...@@ -909,8 +912,8 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) { ...@@ -909,8 +912,8 @@ function proxyNextRequest(request: NextRequest, workStore: WorkStore) {
case 'text': case 'text':
case 'arrayBuffer': case 'arrayBuffer':
case 'formData': { case 'formData': {
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataAccessed(workStore, cacheStore, `request.${prop}`) trackDynamicDataAccessed(workStore, workUnitStore, `request.${prop}`)
// The receiver arg is intentionally the same as the target to fix an issue with // The receiver arg is intentionally the same as the target to fix an issue with
// edge runtime, where attempting to access internal slots with the wrong `this` context // edge runtime, where attempting to access internal slots with the wrong `this` context
// results in an error. // results in an error.
......
...@@ -14,8 +14,8 @@ import { ...@@ -14,8 +14,8 @@ import {
import type { WorkStore } from '../../client/components/work-async-storage.external' import type { WorkStore } from '../../client/components/work-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import type { UseCacheStore } from '../app-render/cache-async-storage.external' import type { UseCacheStore } from '../app-render/work-unit-async-storage.external'
import { cacheAsyncStorage } from '../app-render/cache-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { runInCleanSnapshot } from '../app-render/clean-async-snapshot.external' import { runInCleanSnapshot } from '../app-render/clean-async-snapshot.external'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
...@@ -136,7 +136,7 @@ function generateCacheEntryWithCacheContext( ...@@ -136,7 +136,7 @@ function generateCacheEntryWithCacheContext(
) { ) {
// Initialize the Store for this Cache entry. // Initialize the Store for this Cache entry.
const cacheStore: UseCacheStore = { type: 'cache' } const cacheStore: UseCacheStore = { type: 'cache' }
return cacheAsyncStorage.run( return workUnitAsyncStorage.run(
cacheStore, cacheStore,
generateCacheEntryImpl, generateCacheEntryImpl,
workStore, workStore,
......
...@@ -13,7 +13,7 @@ import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths' ...@@ -13,7 +13,7 @@ import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'
import { FLIGHT_HEADERS } from '../../client/components/app-router-headers' import { FLIGHT_HEADERS } from '../../client/components/app-router-headers'
import { ensureInstrumentationRegistered } from './globals' import { ensureInstrumentationRegistered } from './globals'
import { withRequestStore } from '../async-storage/with-request-store' import { withRequestStore } from '../async-storage/with-request-store'
import { requestAsyncStorage } from '../../client/components/request-async-storage.external' import { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'
import { import {
withWorkStore, withWorkStore,
type WorkStoreContext, type WorkStoreContext,
...@@ -263,7 +263,7 @@ export async function adapter( ...@@ -263,7 +263,7 @@ export async function adapter(
}, },
() => () =>
withRequestStore( withRequestStore(
requestAsyncStorage, workUnitAsyncStorage,
{ {
req: request, req: request,
res: undefined, res: undefined,
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
NEXT_CACHE_SOFT_TAG_MAX_LENGTH, NEXT_CACHE_SOFT_TAG_MAX_LENGTH,
} from '../../../lib/constants' } from '../../../lib/constants'
import { workAsyncStorage } from '../../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
import { cacheAsyncStorage } from '../../../server/app-render/cache-async-storage.external' import { workUnitAsyncStorage } from '../../../server/app-render/work-unit-async-storage.external'
/** /**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag. * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
...@@ -49,13 +49,13 @@ function revalidate(tag: string, expression: string) { ...@@ -49,13 +49,13 @@ function revalidate(tag: string, expression: string) {
) )
} }
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (cacheStore) { if (workUnitStore) {
if (cacheStore.type === 'cache') { if (workUnitStore.type === 'cache') {
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
) )
} else if (cacheStore.type === 'unstable-cache') { } else if (workUnitStore.type === 'unstable-cache') {
throw new Error( throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering` `Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
) )
...@@ -64,7 +64,7 @@ function revalidate(tag: string, expression: string) { ...@@ -64,7 +64,7 @@ function revalidate(tag: string, expression: string) {
// a route that makes use of revalidation APIs should be considered dynamic // a route that makes use of revalidation APIs should be considered dynamic
// as otherwise it would be impossible to revalidate // as otherwise it would be impossible to revalidate
trackDynamicDataAccessed(store, cacheStore, expression) trackDynamicDataAccessed(store, workUnitStore, expression)
if (!store.revalidatedTags) { if (!store.revalidatedTags) {
store.revalidatedTags = [] store.revalidatedTags = []
......
...@@ -7,15 +7,13 @@ import { ...@@ -7,15 +7,13 @@ import {
validateTags, validateTags,
} from '../../lib/patch-fetch' } from '../../lib/patch-fetch'
import { workAsyncStorage } from '../../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
import { requestAsyncStorage } from '../../../client/components/request-async-storage.external' import { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'
import { import {
CachedRouteKind, CachedRouteKind,
IncrementalCacheKind, IncrementalCacheKind,
type CachedFetchData, type CachedFetchData,
} from '../../response-cache' } from '../../response-cache'
import { prerenderAsyncStorage } from '../../app-render/prerender-async-storage.external' import type { UnstableCacheStore } from '../../app-render/work-unit-async-storage.external'
import type { UnstableCacheStore } from '../../app-render/cache-async-storage.external'
import { cacheAsyncStorage } from '../../app-render/cache-async-storage.external'
type Callback = (...args: any[]) => Promise<any> type Callback = (...args: any[]) => Promise<any>
...@@ -100,8 +98,7 @@ export function unstable_cache<T extends Callback>( ...@@ -100,8 +98,7 @@ export function unstable_cache<T extends Callback>(
const cachedCb = async (...args: any[]) => { const cachedCb = async (...args: any[]) => {
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
const requestStore = requestAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore()
// We must be able to find the incremental cache otherwise we throw // We must be able to find the incremental cache otherwise we throw
const maybeIncrementalCache: const maybeIncrementalCache:
...@@ -116,10 +113,9 @@ export function unstable_cache<T extends Callback>( ...@@ -116,10 +113,9 @@ export function unstable_cache<T extends Callback>(
} }
const incrementalCache = maybeIncrementalCache const incrementalCache = maybeIncrementalCache
const prerenderStore = prerenderAsyncStorage.getStore()
const cacheSignal = const cacheSignal =
prerenderStore && prerenderStore.type === 'prerender' workUnitStore && workUnitStore.type === 'prerender'
? prerenderStore.cacheSignal ? workUnitStore.cacheSignal
: null : null
if (cacheSignal) { if (cacheSignal) {
cacheSignal.beginRead() cacheSignal.beginRead()
...@@ -129,6 +125,10 @@ export function unstable_cache<T extends Callback>( ...@@ -129,6 +125,10 @@ export function unstable_cache<T extends Callback>(
// router) and if there's no static generation store, we aren't in app // router) and if there's no static generation store, we aren't in app
// router. Default to an empty pathname and search params when there's no // router. Default to an empty pathname and search params when there's no
// request store or static generation store available. // request store or static generation store available.
const requestStore =
workUnitStore && workUnitStore.type === 'request'
? workUnitStore
: undefined
const pathname = requestStore?.url.pathname ?? workStore?.route ?? '' const pathname = requestStore?.url.pathname ?? workStore?.route ?? ''
const searchParams = new URLSearchParams(requestStore?.url.search ?? '') const searchParams = new URLSearchParams(requestStore?.url.search ?? '')
...@@ -153,8 +153,9 @@ export function unstable_cache<T extends Callback>( ...@@ -153,8 +153,9 @@ export function unstable_cache<T extends Callback>(
workStore.nextFetchId = fetchIdx + 1 workStore.nextFetchId = fetchIdx + 1
const isNestedCache = const isNestedCache =
cacheStore && workUnitStore &&
(cacheStore.type === 'unstable-cache' || cacheStore.type === 'cache') (workUnitStore.type === 'unstable-cache' ||
workUnitStore.type === 'cache')
// We are in an App Router context. We try to return the cached entry if it exists and is valid // We are in an App Router context. We try to return the cached entry if it exists and is valid
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
...@@ -193,12 +194,7 @@ export function unstable_cache<T extends Callback>( ...@@ -193,12 +194,7 @@ export function unstable_cache<T extends Callback>(
} }
// @TODO check on this API. addImplicitTags mutates the store and returns the implicit tags. The naming // @TODO check on this API. addImplicitTags mutates the store and returns the implicit tags. The naming
// of this function is potentially a little confusing // of this function is potentially a little confusing
const implicitTags = addImplicitTags( const implicitTags = addImplicitTags(workStore, workUnitStore)
workStore,
requestStore,
prerenderStore,
cacheStore
)
if ( if (
// when we are nested inside of other unstable_cache's // when we are nested inside of other unstable_cache's
...@@ -247,26 +243,27 @@ export function unstable_cache<T extends Callback>( ...@@ -247,26 +243,27 @@ export function unstable_cache<T extends Callback>(
type: 'unstable-cache', type: 'unstable-cache',
} }
// We run the cache function asynchronously and save the result when it completes // We run the cache function asynchronously and save the result when it completes
workStore.pendingRevalidates[invocationKey] = cacheAsyncStorage workStore.pendingRevalidates[invocationKey] =
.run(innerCacheStore, cb, ...args) workUnitAsyncStorage
.then((result) => { .run(innerCacheStore, cb, ...args)
return cacheNewResult( .then((result) => {
result, return cacheNewResult(
incrementalCache, result,
cacheKey, incrementalCache,
tags, cacheKey,
options.revalidate, tags,
fetchIdx, options.revalidate,
fetchUrl fetchIdx,
) fetchUrl
}) )
// @TODO This error handling seems wrong. We swallow the error? })
.catch((err) => // @TODO This error handling seems wrong. We swallow the error?
console.error( .catch((err) =>
`revalidating cache with key: ${invocationKey}`, console.error(
err `revalidating cache with key: ${invocationKey}`,
err
)
) )
)
} }
// We had a valid cache entry so we return it here // We had a valid cache entry so we return it here
return cachedResponse return cachedResponse
...@@ -278,7 +275,11 @@ export function unstable_cache<T extends Callback>( ...@@ -278,7 +275,11 @@ export function unstable_cache<T extends Callback>(
type: 'unstable-cache', type: 'unstable-cache',
} }
// If we got this far then we had an invalid cache entry and need to generate a new one // If we got this far then we had an invalid cache entry and need to generate a new one
const result = await cacheAsyncStorage.run(innerCacheStore, cb, ...args) const result = await workUnitAsyncStorage.run(
innerCacheStore,
cb,
...args
)
if (!workStore.isDraftMode) { if (!workStore.isDraftMode) {
cacheNewResult( cacheNewResult(
...@@ -306,8 +307,7 @@ export function unstable_cache<T extends Callback>( ...@@ -306,8 +307,7 @@ export function unstable_cache<T extends Callback>(
// @TODO check on this API. addImplicitTags mutates the store and returns the implicit tags. The naming // @TODO check on this API. addImplicitTags mutates the store and returns the implicit tags. The naming
// of this function is potentially a little confusing // of this function is potentially a little confusing
const implicitTags = const implicitTags =
workStore && workStore && addImplicitTags(workStore, workUnitStore)
addImplicitTags(workStore, requestStore, prerenderStore, cacheStore)
const cacheEntry = await incrementalCache.get(cacheKey, { const cacheEntry = await incrementalCache.get(cacheKey, {
kind: IncrementalCacheKind.FETCH, kind: IncrementalCacheKind.FETCH,
...@@ -342,7 +342,11 @@ export function unstable_cache<T extends Callback>( ...@@ -342,7 +342,11 @@ export function unstable_cache<T extends Callback>(
type: 'unstable-cache', type: 'unstable-cache',
} }
// If we got this far then we had an invalid cache entry and need to generate a new one // If we got this far then we had an invalid cache entry and need to generate a new one
const result = await cacheAsyncStorage.run(innerCacheStore, cb, ...args) const result = await workUnitAsyncStorage.run(
innerCacheStore,
cb,
...args
)
cacheNewResult( cacheNewResult(
result, result,
incrementalCache, incrementalCache,
......
import { workAsyncStorage } from '../../../client/components/work-async-storage.external' import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
import { cacheAsyncStorage } from '../../../server/app-render/cache-async-storage.external' import { workUnitAsyncStorage } from '../../../server/app-render/work-unit-async-storage.external'
import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering' import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
/** /**
...@@ -20,7 +20,7 @@ import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering' ...@@ -20,7 +20,7 @@ import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
export function unstable_noStore() { export function unstable_noStore() {
const callingExpression = 'unstable_noStore()' const callingExpression = 'unstable_noStore()'
const store = workAsyncStorage.getStore() const store = workAsyncStorage.getStore()
const cacheStore = cacheAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (!store) { if (!store) {
// This generally implies we are being called in Pages router. We should probably not support // This generally implies we are being called in Pages router. We should probably not support
// unstable_noStore in contexts outside of `react-server` condition but since we historically // unstable_noStore in contexts outside of `react-server` condition but since we historically
...@@ -30,6 +30,6 @@ export function unstable_noStore() { ...@@ -30,6 +30,6 @@ export function unstable_noStore() {
return return
} else { } else {
store.isUnstableNoStore = true store.isUnstableNoStore = true
markCurrentScopeAsDynamic(store, cacheStore, callingExpression) markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)
} }
} }
import { requestAsyncStorage } from 'next/dist/client/components/request-async-storage.external' import { workUnitAsyncStorage } from 'next/dist/server/app-render/work-unit-async-storage.external'
export default async function Page() { export default async function Page() {
// cookies is undefined if not set // cookies is undefined if not set
return !!requestAsyncStorage.getStore().cookies ? 'success' : 'fail' return !!workUnitAsyncStorage.getStore().cookies ? 'success' : 'fail'
} }
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
...@@ -261,7 +261,7 @@ describe('app dir - middleware with middleware in src dir', () => { ...@@ -261,7 +261,7 @@ describe('app dir - middleware with middleware in src dir', () => {
}, },
}) })
it('works without crashing when using requestAsyncStorage', async () => { it('works without crashing when using RequestStore', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await browser.addCookie({ await browser.addCookie({
name: 'test-cookie', name: 'test-cookie',
......
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