Unverified Commit 75d19ecb authored by Josh Story's avatar Josh Story Committed by GitHub

[backport] Include deployment id in `cacheHandlers` keys (#93471)

Backport #93453 to 16.2

How was this ever working for dev? In that case, `buildId =
"development"` and so it always uses the same cache key
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 7ab1e2e9
...@@ -2089,6 +2089,7 @@ export default async function build( ...@@ -2089,6 +2089,7 @@ export default async function build(
config.experimental.partialFallbacks === true, config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife, cacheLifeProfiles: config.cacheLife,
buildId, buildId,
deploymentId: config.deploymentId,
clientAssetToken: clientAssetToken:
config.experimental.immutableAssetToken || config.deploymentId, config.experimental.immutableAssetToken || config.deploymentId,
sriEnabled, sriEnabled,
...@@ -2318,6 +2319,7 @@ export default async function build( ...@@ -2318,6 +2319,7 @@ export default async function build(
config.experimental.partialFallbacks === true, config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife, cacheLifeProfiles: config.cacheLife,
buildId, buildId,
deploymentId: config.deploymentId,
clientAssetToken: clientAssetToken:
config.experimental.immutableAssetToken || config.experimental.immutableAssetToken ||
config.deploymentId, config.deploymentId,
......
...@@ -797,6 +797,7 @@ export async function buildAppStaticPaths({ ...@@ -797,6 +797,7 @@ export async function buildAppStaticPaths({
isRoutePPREnabled = false, isRoutePPREnabled = false,
partialFallbacksEnabled = false, partialFallbacksEnabled = false,
buildId, buildId,
deploymentId,
rootParamKeys, rootParamKeys,
}: { }: {
dir: string dir: string
...@@ -820,6 +821,7 @@ export async function buildAppStaticPaths({ ...@@ -820,6 +821,7 @@ export async function buildAppStaticPaths({
isRoutePPREnabled: boolean isRoutePPREnabled: boolean
partialFallbacksEnabled?: boolean partialFallbacksEnabled?: boolean
buildId: string buildId: string
deploymentId: string
rootParamKeys: readonly string[] rootParamKeys: readonly string[]
}): Promise<StaticPathsResult> { }): Promise<StaticPathsResult> {
if ( if (
...@@ -871,6 +873,7 @@ export async function buildAppStaticPaths({ ...@@ -871,6 +873,7 @@ export async function buildAppStaticPaths({
onAfterTaskError: afterRunner.context.onTaskError, onAfterTaskError: afterRunner.context.onTaskError,
}, },
buildId, buildId,
deploymentId,
previouslyRevalidatedTags: [], previouslyRevalidatedTags: [],
}) })
......
...@@ -134,6 +134,7 @@ export async function handler( ...@@ -134,6 +134,7 @@ export async function handler(
const { const {
buildId, buildId,
deploymentId,
params, params,
nextConfig, nextConfig,
parsedUrl, parsedUrl,
...@@ -262,6 +263,7 @@ export async function handler( ...@@ -262,6 +263,7 @@ export async function handler(
}, },
sharedContext: { sharedContext: {
buildId, buildId,
deploymentId,
}, },
} }
const nodeNextReq = new NodeNextRequest(req) const nodeNextReq = new NodeNextRequest(req)
......
...@@ -669,6 +669,7 @@ export async function isPageStatic({ ...@@ -669,6 +669,7 @@ export async function isPageStatic({
pprConfig, pprConfig,
partialFallbacksEnabled, partialFallbacksEnabled,
buildId, buildId,
deploymentId,
clientAssetToken, clientAssetToken,
sriEnabled, sriEnabled,
}: { }: {
...@@ -697,6 +698,7 @@ export async function isPageStatic({ ...@@ -697,6 +698,7 @@ export async function isPageStatic({
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
partialFallbacksEnabled: boolean partialFallbacksEnabled: boolean
buildId: string buildId: string
deploymentId: string
clientAssetToken: string clientAssetToken: string
sriEnabled: boolean sriEnabled: boolean
}): Promise<PageIsStaticResult> { }): Promise<PageIsStaticResult> {
...@@ -861,6 +863,7 @@ export async function isPageStatic({ ...@@ -861,6 +863,7 @@ export async function isPageStatic({
isRoutePPREnabled, isRoutePPREnabled,
partialFallbacksEnabled, partialFallbacksEnabled,
buildId, buildId,
deploymentId,
rootParamKeys, rootParamKeys,
})) }))
} }
......
...@@ -49,7 +49,8 @@ export async function exportAppRoute( ...@@ -49,7 +49,8 @@ export async function exportAppRoute(
fileWriter: MultiFileWriter, fileWriter: MultiFileWriter,
cacheComponents: boolean, cacheComponents: boolean,
experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>, experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>,
buildId: string buildId: string,
deploymentId: string
): Promise<ExportRouteResult> { ): Promise<ExportRouteResult> {
// Ensure that the URL is absolute. // Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}` req.url = `http://localhost:3000${req.url}`
...@@ -84,6 +85,7 @@ export async function exportAppRoute( ...@@ -84,6 +85,7 @@ export async function exportAppRoute(
}, },
sharedContext: { sharedContext: {
buildId, buildId,
deploymentId,
}, },
} }
......
...@@ -254,7 +254,8 @@ async function exportPageImpl( ...@@ -254,7 +254,8 @@ async function exportPageImpl(
fileWriter, fileWriter,
commonRenderOpts.cacheComponents, commonRenderOpts.cacheComponents,
commonRenderOpts.experimental, commonRenderOpts.experimental,
buildId buildId,
deploymentId
) )
} }
......
...@@ -2734,6 +2734,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -2734,6 +2734,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
// @TODO move to workUnitStore of type Request // @TODO move to workUnitStore of type Request
isPrefetchRequest, isPrefetchRequest,
buildId: sharedContext.buildId, buildId: sharedContext.buildId,
deploymentId: sharedContext.deploymentId,
previouslyRevalidatedTags, previouslyRevalidatedTags,
nonce, nonce,
}) })
...@@ -5433,6 +5434,7 @@ async function validateInstantConfigInBuildWithSample( ...@@ -5433,6 +5434,7 @@ async function validateInstantConfigInBuildWithSample(
isPrefetchRequest: false, isPrefetchRequest: false,
buildId: outerWorkStore.buildId, buildId: outerWorkStore.buildId,
deploymentId: outerWorkStore.deploymentId,
reactLoadableManifest: outerWorkStore.reactLoadableManifest, reactLoadableManifest: outerWorkStore.reactLoadableManifest,
assetPrefix: outerWorkStore.assetPrefix, assetPrefix: outerWorkStore.assetPrefix,
nonce: outerWorkStore.nonce, nonce: outerWorkStore.nonce,
......
...@@ -86,6 +86,10 @@ export interface WorkStore { ...@@ -86,6 +86,10 @@ export interface WorkStore {
isUnstableNoStore?: boolean isUnstableNoStore?: boolean
isPrefetchRequest?: boolean isPrefetchRequest?: boolean
/**
* This only exists because it's needed in use-cache-wrapper
*/
deploymentId: string
/** /**
* Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper * Prefer `sharedContext.buildId` instead. This only exists because it's needed in use-cache-wrapper
*/ */
......
...@@ -62,6 +62,11 @@ export type WorkStoreContext = { ...@@ -62,6 +62,11 @@ export type WorkStoreContext = {
RequestLifecycleOpts & RequestLifecycleOpts &
Partial<Pick<RenderOpts, 'reactLoadableManifest'>> Partial<Pick<RenderOpts, 'reactLoadableManifest'>>
/**
* The deployment ID of the current build.
*/
deploymentId: string
/** /**
* The build ID of the current build. * The build ID of the current build.
*/ */
...@@ -77,6 +82,7 @@ export function createWorkStore({ ...@@ -77,6 +82,7 @@ export function createWorkStore({
renderOpts, renderOpts,
isPrefetchRequest, isPrefetchRequest,
buildId, buildId,
deploymentId,
previouslyRevalidatedTags, previouslyRevalidatedTags,
nonce, nonce,
}: WorkStoreContext): WorkStore { }: WorkStoreContext): WorkStore {
...@@ -129,6 +135,7 @@ export function createWorkStore({ ...@@ -129,6 +135,7 @@ export function createWorkStore({
isPrefetchRequest, isPrefetchRequest,
buildId, buildId,
deploymentId,
reactLoadableManifest: renderOpts?.reactLoadableManifest || {}, reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
assetPrefix: renderOpts?.assetPrefix || '', assetPrefix: renderOpts?.assetPrefix || '',
nonce, nonce,
......
...@@ -818,6 +818,7 @@ export default class DevServer extends Server { ...@@ -818,6 +818,7 @@ export default class DevServer extends Server {
cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize, cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,
nextConfigOutput: this.nextConfig.output, nextConfigOutput: this.nextConfig.output,
buildId: this.buildId, buildId: this.buildId,
deploymentId: this.deploymentId,
authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts), authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),
sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm), sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),
}) })
......
...@@ -57,6 +57,7 @@ export async function loadStaticPaths({ ...@@ -57,6 +57,7 @@ export async function loadStaticPaths({
cacheLifeProfiles, cacheLifeProfiles,
nextConfigOutput, nextConfigOutput,
buildId, buildId,
deploymentId,
authInterrupts, authInterrupts,
sriEnabled, sriEnabled,
}: { }: {
...@@ -80,6 +81,7 @@ export async function loadStaticPaths({ ...@@ -80,6 +81,7 @@ export async function loadStaticPaths({
} }
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string buildId: string
deploymentId: string
authInterrupts: boolean authInterrupts: boolean
sriEnabled: boolean sriEnabled: boolean
}): Promise<StaticPathsResult> { }): Promise<StaticPathsResult> {
...@@ -150,6 +152,7 @@ export async function loadStaticPaths({ ...@@ -150,6 +152,7 @@ export async function loadStaticPaths({
isRoutePPREnabled, isRoutePPREnabled,
partialFallbacksEnabled: config.partialFallbacks, partialFallbacksEnabled: config.partialFallbacks,
buildId, buildId,
deploymentId,
authInterrupts, authInterrupts,
rootParamKeys, rootParamKeys,
}) })
......
...@@ -104,6 +104,7 @@ export type AppRouteModule = typeof import('../../../build/templates/app-route') ...@@ -104,6 +104,7 @@ export type AppRouteModule = typeof import('../../../build/templates/app-route')
export type AppRouteSharedContext = { export type AppRouteSharedContext = {
buildId: string buildId: string
deploymentId: string
} }
/** /**
...@@ -732,6 +733,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -732,6 +733,7 @@ export class AppRouteRouteModule extends RouteModule<
page: this.definition.page, page: this.definition.page,
renderOpts: context.renderOpts, renderOpts: context.renderOpts,
buildId: context.sharedContext.buildId, buildId: context.sharedContext.buildId,
deploymentId: context.sharedContext.deploymentId,
previouslyRevalidatedTags: [], previouslyRevalidatedTags: [],
} }
......
...@@ -1239,7 +1239,7 @@ export async function cache( ...@@ -1239,7 +1239,7 @@ export async function cache(
// safely reuse the results across builds yet. In the meantime we add the buildId to the // safely reuse the results across builds yet. In the meantime we add the buildId to the
// arguments as a seed to ensure they're not reused. Remove this once Action IDs hash // arguments as a seed to ensure they're not reused. Remove this once Action IDs hash
// the implementation. // the implementation.
const buildId = workStore.buildId const buildId = workStore.deploymentId || workStore.buildId
// In dev mode, when the HMR refresh hash is set, we include it in the // In dev mode, when the HMR refresh hash is set, we include it in the
// cache key. This ensures that cache entries are not reused when server // cache key. This ensures that cache entries are not reused when server
......
...@@ -147,6 +147,7 @@ export async function adapter( ...@@ -147,6 +147,7 @@ export async function adapter(
buildId = (requestURL as NextURL).buildId || '' buildId = (requestURL as NextURL).buildId || ''
requestURL.buildId = '' requestURL.buildId = ''
} }
let deploymentId = process.env.NEXT_DEPLOYMENT_ID
const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers) const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)
const isNextDataRequest = requestHeaders.has('x-nextjs-data') const isNextDataRequest = requestHeaders.has('x-nextjs-data')
...@@ -316,6 +317,7 @@ export async function adapter( ...@@ -316,6 +317,7 @@ export async function adapter(
isPrefetchRequest: isPrefetchRequest:
request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1', request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',
buildId: buildId ?? '', buildId: buildId ?? '',
deploymentId: deploymentId ?? '',
previouslyRevalidatedTags: [], previouslyRevalidatedTags: [],
}) })
......
...@@ -131,6 +131,7 @@ export class EdgeRouteModuleWrapper { ...@@ -131,6 +131,7 @@ export class EdgeRouteModuleWrapper {
}, },
sharedContext: { sharedContext: {
buildId: '', // TODO: Populate this properly. buildId: '', // TODO: Populate this properly.
deploymentId: '', // TODO: Populate this properly.
}, },
} }
......
import { Suspense } from 'react'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<head />
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
async function getData() {
'use cache'
return new Date().toISOString()
}
async function AsyncComp() {
let data = await getData()
return <p id="data">{data}</p>
}
export default async function Home() {
await connection()
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<AsyncComp />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
import { cacheLife } from 'next/cache'
// The id prop is just used to assert on the logged cache key in tests.
async function DynamicCache({ id }: { id: string }) {
'use cache'
cacheLife('seconds')
return <p id="data">{new Date().toISOString()}</p>
}
export default function Page() {
return (
<p>
This page uses a short-lived "use cache", which is omitted from the
prerender, but should still be saved in the cache handler.
<Suspense>
<DynamicCache id="dynamic-cache" />
</Suspense>
</p>
)
}
// @ts-check
const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default.external').default
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey, softTags) {
console.log('CustomCacheHandler::get', cacheKey, JSON.stringify([softTags]))
return defaultCacheHandler.get(cacheKey, softTags)
},
async set(cacheKey, pendingEntry) {
console.log('CustomCacheHandler::set', cacheKey)
return defaultCacheHandler.set(cacheKey, pendingEntry)
},
async refreshTags() {
return defaultCacheHandler.refreshTags()
},
async getExpiration(tags) {
// Expecting soft tags in `get` to be used by the cache handler for checking
// the expiration of a cache entry, instead of letting Next.js handle it.
return Infinity
},
async updateTags(tags) {
return defaultCacheHandler.updateTags(tags)
},
}
module.exports = cacheHandler
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
cacheHandlers: {
default: require.resolve('./handler.js'),
},
generateBuildId: process.env.BUILD_ID
? async () => {
return process.env.BUILD_ID
}
: undefined,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
const isoDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
describe.each(['NEXT_DEPLOYMENT_ID', 'BUILD_ID', 'default'])(
'use-cache-cross-deployment with %s',
(envKey) => {
const { next, skipped } = nextTestSetup({
files: __dirname,
disableAutoSkewProtection: true,
skipStart: true,
})
if (skipped) return
// In the future, this assertion can be relaxed to only prevent sharing if the implementation
// changed.
it('should not have the same cache key across deployments', async () => {
async function execute(id: string) {
await next.stop()
if (envKey !== 'default') {
next.env[envKey] = id
}
try {
await next.start()
let keyRoot: string, keyPrerender: string
{
let match = next.cliOutput.match(
/CustomCacheHandler::get \["([A-Za-z0-9_-]+)","([0-9a-f]{2})+",\[\{"id":"dynamic-cache"\}\]\] \[\["_N_T_\/layout","_N_T_\/prerender\/layout","_N_T_\/prerender\/page","_N_T_\/prerender"\]\]/
)
expect(match).toBeDefined()
keyPrerender = match[0]
}
{
let logs = next.getCliOutputFromHere()
const browser = await next.browser(`/`)
const initialData = await browser.elementById('data').text()
expect(initialData).toMatch(isoDateRegExp)
let match = logs().match(
/CustomCacheHandler::get \["([A-Za-z0-9_-]+)","([0-9a-f]{2})+",\[\]\] \[\["_N_T_\/layout","_N_T_\/page","_N_T_\/","_N_T_\/index"\]\]/
)
expect(match).toBeDefined()
keyRoot = match[0]
}
return { keyRoot, keyPrerender }
} finally {
if (envKey !== 'default') {
delete next.env[envKey]
}
}
}
let key1 = await execute('value-1')
let key2 = await execute('value-2')
// Second run should not use the same key
expect(key1.keyRoot).not.toBe(key2.keyRoot)
expect(key1.keyPrerender).not.toBe(key2.keyPrerender)
})
}
)
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