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