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(
config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife,
buildId,
deploymentId: config.deploymentId,
clientAssetToken:
config.experimental.immutableAssetToken || config.deploymentId,
sriEnabled,
......@@ -2318,6 +2319,7 @@ export default async function build(
config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife,
buildId,
deploymentId: config.deploymentId,
clientAssetToken:
config.experimental.immutableAssetToken ||
config.deploymentId,
......
......@@ -797,6 +797,7 @@ export async function buildAppStaticPaths({
isRoutePPREnabled = false,
partialFallbacksEnabled = false,
buildId,
deploymentId,
rootParamKeys,
}: {
dir: string
......@@ -820,6 +821,7 @@ export async function buildAppStaticPaths({
isRoutePPREnabled: boolean
partialFallbacksEnabled?: boolean
buildId: string
deploymentId: string
rootParamKeys: readonly string[]
}): Promise<StaticPathsResult> {
if (
......@@ -871,6 +873,7 @@ export async function buildAppStaticPaths({
onAfterTaskError: afterRunner.context.onTaskError,
},
buildId,
deploymentId,
previouslyRevalidatedTags: [],
})
......
......@@ -134,6 +134,7 @@ export async function handler(
const {
buildId,
deploymentId,
params,
nextConfig,
parsedUrl,
......@@ -262,6 +263,7 @@ export async function handler(
},
sharedContext: {
buildId,
deploymentId,
},
}
const nodeNextReq = new NodeNextRequest(req)
......
......@@ -669,6 +669,7 @@ export async function isPageStatic({
pprConfig,
partialFallbacksEnabled,
buildId,
deploymentId,
clientAssetToken,
sriEnabled,
}: {
......@@ -697,6 +698,7 @@ export async function isPageStatic({
pprConfig: ExperimentalPPRConfig | undefined
partialFallbacksEnabled: boolean
buildId: string
deploymentId: string
clientAssetToken: string
sriEnabled: boolean
}): Promise<PageIsStaticResult> {
......@@ -861,6 +863,7 @@ export async function isPageStatic({
isRoutePPREnabled,
partialFallbacksEnabled,
buildId,
deploymentId,
rootParamKeys,
}))
}
......
......@@ -49,7 +49,8 @@ export async function exportAppRoute(
fileWriter: MultiFileWriter,
cacheComponents: boolean,
experimental: Required<Pick<ExperimentalConfig, 'authInterrupts'>>,
buildId: string
buildId: string,
deploymentId: string
): Promise<ExportRouteResult> {
// Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}`
......@@ -84,6 +85,7 @@ export async function exportAppRoute(
},
sharedContext: {
buildId,
deploymentId,
},
}
......
......@@ -254,7 +254,8 @@ async function exportPageImpl(
fileWriter,
commonRenderOpts.cacheComponents,
commonRenderOpts.experimental,
buildId
buildId,
deploymentId
)
}
......
......@@ -2734,6 +2734,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
// @TODO move to workUnitStore of type Request
isPrefetchRequest,
buildId: sharedContext.buildId,
deploymentId: sharedContext.deploymentId,
previouslyRevalidatedTags,
nonce,
})
......@@ -5433,6 +5434,7 @@ async function validateInstantConfigInBuildWithSample(
isPrefetchRequest: false,
buildId: outerWorkStore.buildId,
deploymentId: outerWorkStore.deploymentId,
reactLoadableManifest: outerWorkStore.reactLoadableManifest,
assetPrefix: outerWorkStore.assetPrefix,
nonce: outerWorkStore.nonce,
......
......@@ -86,6 +86,10 @@ export interface WorkStore {
isUnstableNoStore?: 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
*/
......
......@@ -62,6 +62,11 @@ export type WorkStoreContext = {
RequestLifecycleOpts &
Partial<Pick<RenderOpts, 'reactLoadableManifest'>>
/**
* The deployment ID of the current build.
*/
deploymentId: string
/**
* The build ID of the current build.
*/
......@@ -77,6 +82,7 @@ export function createWorkStore({
renderOpts,
isPrefetchRequest,
buildId,
deploymentId,
previouslyRevalidatedTags,
nonce,
}: WorkStoreContext): WorkStore {
......@@ -129,6 +135,7 @@ export function createWorkStore({
isPrefetchRequest,
buildId,
deploymentId,
reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
assetPrefix: renderOpts?.assetPrefix || '',
nonce,
......
......@@ -818,6 +818,7 @@ export default class DevServer extends Server {
cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,
nextConfigOutput: this.nextConfig.output,
buildId: this.buildId,
deploymentId: this.deploymentId,
authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),
sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),
})
......
......@@ -57,6 +57,7 @@ export async function loadStaticPaths({
cacheLifeProfiles,
nextConfigOutput,
buildId,
deploymentId,
authInterrupts,
sriEnabled,
}: {
......@@ -80,6 +81,7 @@ export async function loadStaticPaths({
}
nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string
deploymentId: string
authInterrupts: boolean
sriEnabled: boolean
}): Promise<StaticPathsResult> {
......@@ -150,6 +152,7 @@ export async function loadStaticPaths({
isRoutePPREnabled,
partialFallbacksEnabled: config.partialFallbacks,
buildId,
deploymentId,
authInterrupts,
rootParamKeys,
})
......
......@@ -104,6 +104,7 @@ export type AppRouteModule = typeof import('../../../build/templates/app-route')
export type AppRouteSharedContext = {
buildId: string
deploymentId: string
}
/**
......@@ -732,6 +733,7 @@ export class AppRouteRouteModule extends RouteModule<
page: this.definition.page,
renderOpts: context.renderOpts,
buildId: context.sharedContext.buildId,
deploymentId: context.sharedContext.deploymentId,
previouslyRevalidatedTags: [],
}
......
......@@ -1239,7 +1239,7 @@ export async function cache(
// 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
// 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
// cache key. This ensures that cache entries are not reused when server
......
......@@ -147,6 +147,7 @@ export async function adapter(
buildId = (requestURL as NextURL).buildId || ''
requestURL.buildId = ''
}
let deploymentId = process.env.NEXT_DEPLOYMENT_ID
const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers)
const isNextDataRequest = requestHeaders.has('x-nextjs-data')
......@@ -316,6 +317,7 @@ export async function adapter(
isPrefetchRequest:
request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',
buildId: buildId ?? '',
deploymentId: deploymentId ?? '',
previouslyRevalidatedTags: [],
})
......
......@@ -131,6 +131,7 @@ export class EdgeRouteModuleWrapper {
},
sharedContext: {
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