Unverified Commit 55e90412 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Refactor: Get rid of overly generic `getExpectedRequestStore` function (#81791)

The places in which we called `getExpectedRequestStore()` were already narrowing down the work unit store type to a request store. This allows us to delete the function, and call `throwForMissingRequestStore()` directly instead.
parent 78dd954f
......@@ -250,43 +250,6 @@ export type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>
export { workUnitAsyncStorageInstance as workUnitAsyncStorage }
export function getExpectedRequestStore(
callingExpression: string
): RequestStore {
const workUnitStore = workUnitAsyncStorageInstance.getStore()
if (!workUnitStore) {
throwForMissingRequestStore(callingExpression)
}
switch (workUnitStore.type) {
case 'request':
return workUnitStore
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case '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.`
)
case 'cache':
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`
)
case 'unstable-cache':
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`
)
default:
return workUnitStore satisfies never
}
}
export function throwForMissingRequestStore(callingExpression: string): never {
throw new Error(
`\`${callingExpression}\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
......
......@@ -14,7 +14,7 @@ import {
MutableRequestCookiesAdapter,
RequestCookiesAdapter,
responseCookiesToRequestCookies,
wrapWithMutableAccessCheck,
createCookiesWithMutableAccessCheck,
type ReadonlyRequestCookies,
} from '../web/spec-extension/adapters/request-cookies'
import { ResponseCookies, RequestCookies } from '../web/spec-extension/cookies'
......@@ -235,9 +235,8 @@ function createRequestStoreImpl(
},
get userspaceMutableCookies() {
if (!cache.userspaceMutableCookies) {
const userspaceMutableCookies = wrapWithMutableAccessCheck(
this.mutableCookies
)
const userspaceMutableCookies =
createCookiesWithMutableAccessCheck(this)
cache.userspaceMutableCookies = userspaceMutableCookies
}
return cache.userspaceMutableCookies
......
......@@ -7,6 +7,7 @@ import {
import { RequestCookies } from '../web/spec-extension/cookies'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import {
throwForMissingRequestStore,
workUnitAsyncStorage,
type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
......@@ -16,7 +17,6 @@ import {
trackDynamicDataInDynamicRender,
trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering'
import { getExpectedRequestStore } from '../app-render/work-unit-async-storage.external'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -116,6 +116,36 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
let underlyingCookies: ReadonlyRequestCookies
if (areCookiesMutableInCurrentPhase(workUnitStore)) {
// We can't conditionally return different types here based on the context.
// To avoid confusion, we always return the readonly type here.
underlyingCookies =
workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies
} else {
underlyingCookies = workUnitStore.cookies
}
if (
process.env.NODE_ENV === 'development' &&
!workStore?.isPrefetchRequest
) {
if (process.env.__NEXT_CACHE_COMPONENTS) {
return makeUntrackedCookiesWithDevWarnings(
underlyingCookies,
workStore?.route
)
}
return makeUntrackedExoticCookiesWithDevWarnings(
underlyingCookies,
workStore?.route
)
} else {
return makeUntrackedExoticCookies(underlyingCookies)
}
break
default:
workUnitStore satisfies never
......@@ -123,36 +153,8 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
}
}
// cookies is being called in a dynamic context
const requestStore = getExpectedRequestStore(callingExpression)
let underlyingCookies: ReadonlyRequestCookies
if (areCookiesMutableInCurrentPhase(requestStore)) {
// We can't conditionally return different types here based on the context.
// To avoid confusion, we always return the readonly type here.
underlyingCookies =
requestStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies
} else {
underlyingCookies = requestStore.cookies
}
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
if (process.env.__NEXT_CACHE_COMPONENTS) {
return makeUntrackedCookiesWithDevWarnings(
underlyingCookies,
workStore?.route
)
}
return makeUntrackedExoticCookiesWithDevWarnings(
underlyingCookies,
workStore?.route
)
} else {
return makeUntrackedExoticCookies(underlyingCookies)
}
// If we end up here, there was no work store or work unit store present.
throwForMissingRequestStore(callingExpression)
}
function createEmptyCookies(): ReadonlyRequestCookies {
......
......@@ -3,7 +3,7 @@ import {
type ReadonlyHeaders,
} from '../web/spec-extension/adapters/headers'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { getExpectedRequestStore } from '../app-render/work-unit-async-storage.external'
import { throwForMissingRequestStore } from '../app-render/work-unit-async-storage.external'
import {
workUnitAsyncStorage,
type PrerenderStoreModern,
......@@ -55,6 +55,7 @@ export type UnsafeUnwrappedHeaders = ReadonlyHeaders
* Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)
*/
export function headers(): Promise<ReadonlyHeaders> {
const callingExpression = 'headers'
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
......@@ -122,7 +123,7 @@ export function headers(): Promise<ReadonlyHeaders> {
// TODO consider switching the semantic to throw on property access instead
return postponeWithTracking(
workStore.route,
'headers',
callingExpression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
......@@ -131,12 +132,31 @@ export function headers(): Promise<ReadonlyHeaders> {
// We track dynamic access here so we don't need to wrap the headers in
// individual property access tracking.
return throwToInterruptStaticGeneration(
'headers',
callingExpression,
workStore,
workUnitStore
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
if (
process.env.NODE_ENV === 'development' &&
!workStore?.isPrefetchRequest
) {
if (process.env.__NEXT_CACHE_COMPONENTS) {
return makeUntrackedHeadersWithDevWarnings(
workUnitStore.headers,
workStore?.route
)
}
return makeUntrackedExoticHeadersWithDevWarnings(
workUnitStore.headers,
workStore?.route
)
} else {
return makeUntrackedExoticHeaders(workUnitStore.headers)
}
break
default:
workUnitStore satisfies never
......@@ -144,22 +164,8 @@ export function headers(): Promise<ReadonlyHeaders> {
}
}
const requestStore = getExpectedRequestStore('headers')
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
if (process.env.__NEXT_CACHE_COMPONENTS) {
return makeUntrackedHeadersWithDevWarnings(
requestStore.headers,
workStore?.route
)
}
return makeUntrackedExoticHeadersWithDevWarnings(
requestStore.headers,
workStore?.route
)
} else {
return makeUntrackedExoticHeaders(requestStore.headers)
}
// If we end up here, there was no work store or work unit store present.
throwForMissingRequestStore(callingExpression)
}
interface CacheLifetime {}
......
......@@ -7,7 +7,7 @@ import {
ReadonlyRequestCookiesError,
RequestCookiesAdapter,
MutableRequestCookiesAdapter,
wrapWithMutableAccessCheck,
createCookiesWithMutableAccessCheck,
} from './request-cookies'
describe('RequestCookiesAdapter', () => {
......@@ -107,15 +107,21 @@ describe('MutableRequestCookiesAdapter', () => {
})
describe('wrapWithMutableAccessCheck', () => {
const createMockRequestStore = (phase: RequestStore['phase']) =>
({ type: 'request', phase }) as RequestStore
const createMockRequestStore = (phase: RequestStore['phase']) => {
const headers = new Headers({})
const underlyingCookies = new ResponseCookies(headers)
return {
type: 'request',
phase,
mutableCookies: underlyingCookies,
} as RequestStore
}
it('prevents setting cookies in the render phase', () => {
const requestStore = createMockRequestStore('action')
workUnitAsyncStorage.run(requestStore, () => {
const headers = new Headers({})
const underlyingCookies = new ResponseCookies(headers)
const wrappedCookies = wrapWithMutableAccessCheck(underlyingCookies)
const cookies = createCookiesWithMutableAccessCheck(requestStore)
// simulate changing phases
requestStore.phase = 'render'
......@@ -124,20 +130,18 @@ describe('wrapWithMutableAccessCheck', () => {
/Cookies can only be modified in a Server Action or Route Handler\./
expect(() => {
wrappedCookies.set('foo', '1')
cookies.set('foo', '1')
}).toThrow(EXPECTED_ERROR)
expect(wrappedCookies.get('foo')).toBe(undefined)
expect(cookies.get('foo')).toBe(undefined)
})
})
it('prevents deleting cookies in the render phase', () => {
const requestStore = createMockRequestStore('action')
workUnitAsyncStorage.run(requestStore, () => {
const headers = new Headers({})
const underlyingCookies = new ResponseCookies(headers)
const wrappedCookies = wrapWithMutableAccessCheck(underlyingCookies)
wrappedCookies.set('foo', '1')
const cookies = createCookiesWithMutableAccessCheck(requestStore)
cookies.set('foo', '1')
// simulate changing phases
requestStore.phase = 'render'
......@@ -146,9 +150,9 @@ describe('wrapWithMutableAccessCheck', () => {
/Cookies can only be modified in a Server Action or Route Handler\./
expect(() => {
wrappedCookies.delete('foo')
cookies.delete('foo')
}).toThrow(EXPECTED_ERROR)
expect(wrappedCookies.get('foo')?.value).toEqual('1')
expect(cookies.get('foo')?.value).toEqual('1')
})
})
})
......@@ -3,10 +3,7 @@ import { RequestCookies } from '../cookies'
import { ResponseCookies } from '../cookies'
import { ReflectAdapter } from './reflect'
import { workAsyncStorage } from '../../../app-render/work-async-storage.external'
import {
getExpectedRequestStore,
type RequestStore,
} from '../../../app-render/work-unit-async-storage.external'
import type { RequestStore } from '../../../app-render/work-unit-async-storage.external'
/**
* @internal
......@@ -180,21 +177,21 @@ export class MutableRequestCookiesAdapter {
}
}
export function wrapWithMutableAccessCheck(
responseCookies: ResponseCookies
export function createCookiesWithMutableAccessCheck(
requestStore: RequestStore
): ResponseCookies {
const wrappedCookies = new Proxy(responseCookies, {
const wrappedCookies = new Proxy(requestStore.mutableCookies, {
get(target, prop, receiver) {
switch (prop) {
case 'delete':
return function (...args: [string] | [ResponseCookie]) {
ensureCookiesAreStillMutable('cookies().delete')
ensureCookiesAreStillMutable(requestStore, 'cookies().delete')
target.delete(...args)
return wrappedCookies
}
case 'set':
return function (...args: SetCookieArgs) {
ensureCookiesAreStillMutable('cookies().set')
ensureCookiesAreStillMutable(requestStore, 'cookies().set')
target.set(...args)
return wrappedCookies
}
......@@ -218,8 +215,10 @@ export function areCookiesMutableInCurrentPhase(requestStore: RequestStore) {
* 'render' -> 'after'
* 'action' -> 'render'
* */
function ensureCookiesAreStillMutable(callingExpression: string) {
const requestStore = getExpectedRequestStore(callingExpression)
function ensureCookiesAreStillMutable(
requestStore: RequestStore,
_callingExpression: string
) {
if (!areCookiesMutableInCurrentPhase(requestStore)) {
// TODO: maybe we can give a more precise error message based on callingExpression?
throw new ReadonlyRequestCookiesError()
......
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