Unverified Commit 8ffa6c74 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure global cache handlers are used properly (#74626)

Currently any cache handlers configured under the global symbol are
overridden by the default built-in cache handle unexpectedly. The
default built-in cache handler should only be used if no user configured
one is available and no global symbol provided one is available.

This also fixes `expireTags` not being called on configured cache
handlers at all due to that part not being wired up.

Regression tests for the above are also added to ensure this is behaving
as expected.
parent 94bda499
...@@ -2,24 +2,21 @@ import type { ParamValue, Params } from '../../server/request/params' ...@@ -2,24 +2,21 @@ import type { ParamValue, Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module' import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { AppSegment } from '../segment-config/app/app-segments' import type { AppSegment } from '../segment-config/app/app-segments'
import type { StaticPathsResult } from './types' import type { StaticPathsResult } from './types'
import type { CacheHandler } from '../../server/lib/incremental-cache'
import path from 'path' import path from 'path'
import { AfterRunner } from '../../server/after/run-with-after' import { AfterRunner } from '../../server/after/run-with-after'
import { createWorkStore } from '../../server/async-storage/work-store' import { createWorkStore } from '../../server/async-storage/work-store'
import { FallbackMode } from '../../lib/fallback' import { FallbackMode } from '../../lib/fallback'
import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'
import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../../shared/lib/router/utils/route-matcher'
import { import {
getRouteRegex, getRouteRegex,
type RouteRegex, type RouteRegex,
} from '../../shared/lib/router/utils/route-regex' } from '../../shared/lib/router/utils/route-regex'
import { IncrementalCache } from '../../server/lib/incremental-cache' import type { IncrementalCache } from '../../server/lib/incremental-cache'
import { interopDefault } from '../../lib/interop-default'
import { nodeFs } from '../../server/lib/node-fs-methods'
import { normalizePathname, encodeParam } from './utils' import { normalizePathname, encodeParam } from './utils'
import * as ciEnvironment from '../../server/ci-info'
import escapePathDelimiters from '../../shared/lib/router/utils/escape-path-delimiters' import escapePathDelimiters from '../../shared/lib/router/utils/escape-path-delimiters'
import { createIncrementalCache } from '../../export/helpers/create-incremental-cache'
import type { NextConfigComplete } from '../../server/config-shared'
/** /**
* Compares two parameters to see if they're equal. * Compares two parameters to see if they're equal.
...@@ -263,6 +260,7 @@ export async function buildAppStaticPaths({ ...@@ -263,6 +260,7 @@ export async function buildAppStaticPaths({
cacheHandler, cacheHandler,
cacheLifeProfiles, cacheLifeProfiles,
requestHeaders, requestHeaders,
cacheHandlers,
maxMemoryCacheSize, maxMemoryCacheSize,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
nextConfigOutput, nextConfigOutput,
...@@ -280,6 +278,7 @@ export async function buildAppStaticPaths({ ...@@ -280,6 +278,7 @@ export async function buildAppStaticPaths({
isrFlushToDisk?: boolean isrFlushToDisk?: boolean
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
cacheHandler?: string cacheHandler?: string
cacheHandlers?: NextConfigComplete['experimental']['cacheHandlers']
cacheLifeProfiles?: { cacheLifeProfiles?: {
[profile: string]: import('../../server/use-cache/cache-life').CacheLife [profile: string]: import('../../server/use-cache/cache-life').CacheLife
} }
...@@ -302,33 +301,16 @@ export async function buildAppStaticPaths({ ...@@ -302,33 +301,16 @@ export async function buildAppStaticPaths({
ComponentMod.patchFetch() ComponentMod.patchFetch()
let CurCacheHandler: typeof CacheHandler | undefined const incrementalCache = await createIncrementalCache({
if (cacheHandler) { dir,
CurCacheHandler = interopDefault( distDir,
await import(formatDynamicImportPath(dir, cacheHandler)).then(
(mod) => mod.default || mod
)
)
}
const incrementalCache = new IncrementalCache({
fs: nodeFs,
dev: true,
dynamicIO, dynamicIO,
flushToDisk: isrFlushToDisk, cacheHandler,
serverDistDir: path.join(distDir, 'server'), cacheHandlers,
fetchCacheKeyPrefix,
maxMemoryCacheSize,
getPrerenderManifest: () => ({
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: null as any, // `preview` is special case read in next-dev-server
}),
CurCacheHandler,
requestHeaders, requestHeaders,
minimalMode: ciEnvironment.hasNextSupport, fetchCacheKeyPrefix,
flushToDisk: isrFlushToDisk,
cacheMaxMemorySize: maxMemoryCacheSize,
}) })
const regex = getRouteRegex(page) const regex = getRouteRegex(page)
......
...@@ -13,14 +13,24 @@ import type { NextConfigComplete } from '../../server/config-shared' ...@@ -13,14 +13,24 @@ import type { NextConfigComplete } from '../../server/config-shared'
import { PAGE_TYPES } from '../../lib/page-types' import { PAGE_TYPES } from '../../lib/page-types'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils' import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils'
import { createServerModuleMap } from '../../server/app-render/action-utils' import { createServerModuleMap } from '../../server/app-render/action-utils'
import {
cacheHandlerGlobal,
cacheHandlersSymbol,
} from '../../server/use-cache/constants'
declare const incrementalCacheHandler: any declare const incrementalCacheHandler: any
// OPTIONAL_IMPORT:incrementalCacheHandler // OPTIONAL_IMPORT:incrementalCacheHandler
const cacheHandlers = {} const cacheHandlers = {}
if (!(globalThis as any).__nextCacheHandlers) { if (!cacheHandlerGlobal.__nextCacheHandlers) {
;(globalThis as any).__nextCacheHandlers = cacheHandlers cacheHandlerGlobal.__nextCacheHandlers = cacheHandlers
if (!cacheHandlerGlobal.__nextCacheHandlers.default) {
cacheHandlerGlobal.__nextCacheHandlers.default =
cacheHandlerGlobal[cacheHandlersSymbol]?.DefaultCache ||
cacheHandlerGlobal.__nextCacheHandlers.__nextDefault
}
} }
const Document: DocumentType = null! const Document: DocumentType = null!
......
...@@ -23,6 +23,10 @@ import type { RequestData } from '../../server/web/types' ...@@ -23,6 +23,10 @@ import type { RequestData } from '../../server/web/types'
import type { BuildManifest } from '../../server/get-page-files' import type { BuildManifest } from '../../server/get-page-files'
import type { NextConfigComplete } from '../../server/config-shared' import type { NextConfigComplete } from '../../server/config-shared'
import type { PAGE_TYPES } from '../../lib/page-types' import type { PAGE_TYPES } from '../../lib/page-types'
import {
cacheHandlerGlobal,
cacheHandlersSymbol,
} from '../../server/use-cache/constants'
// injected by the loader afterwards. // injected by the loader afterwards.
declare const pagesType: PAGE_TYPES declare const pagesType: PAGE_TYPES
...@@ -42,8 +46,14 @@ declare const user500RouteModuleOptions: any ...@@ -42,8 +46,14 @@ declare const user500RouteModuleOptions: any
const cacheHandlers = {} const cacheHandlers = {}
if (!(globalThis as any).__nextCacheHandlers) { if (!cacheHandlerGlobal.__nextCacheHandlers) {
;(globalThis as any).__nextCacheHandlers = cacheHandlers cacheHandlerGlobal.__nextCacheHandlers = cacheHandlers
if (!cacheHandlerGlobal.__nextCacheHandlers.default) {
cacheHandlerGlobal.__nextCacheHandlers.default =
cacheHandlerGlobal[cacheHandlersSymbol]?.DefaultCache ||
cacheHandlerGlobal.__nextCacheHandlers.__nextDefault
}
} }
const pageMod = { const pageMod = {
......
...@@ -36,7 +36,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue ...@@ -36,7 +36,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}') const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}')
if (!cacheHandlers.default) { if (!cacheHandlers.default) {
cacheHandlers.default = require.resolve( cacheHandlers.__nextDefault = require.resolve(
'../../../../server/lib/cache-handlers/default' '../../../../server/lib/cache-handlers/default'
) )
} }
......
...@@ -85,7 +85,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -85,7 +85,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}') const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}')
if (!cacheHandlers.default) { if (!cacheHandlers.default) {
cacheHandlers.default = require.resolve( cacheHandlers.__nextDefault = require.resolve(
'../../../../server/lib/cache-handlers/default' '../../../../server/lib/cache-handlers/default'
) )
} }
......
...@@ -4,6 +4,8 @@ import { hasNextSupport } from '../../server/ci-info' ...@@ -4,6 +4,8 @@ import { hasNextSupport } from '../../server/ci-info'
import { nodeFs } from '../../server/lib/node-fs-methods' import { nodeFs } from '../../server/lib/node-fs-methods'
import { interopDefault } from '../../lib/interop-default' import { interopDefault } from '../../lib/interop-default'
import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path' import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'
import { cacheHandlerGlobal } from '../../server/use-cache/constants'
import DefaultCacheHandler from '../../server/lib/cache-handlers/default'
export async function createIncrementalCache({ export async function createIncrementalCache({
cacheHandler, cacheHandler,
...@@ -14,6 +16,7 @@ export async function createIncrementalCache({ ...@@ -14,6 +16,7 @@ export async function createIncrementalCache({
dir, dir,
flushToDisk, flushToDisk,
cacheHandlers, cacheHandlers,
requestHeaders,
}: { }: {
dynamicIO: boolean dynamicIO: boolean
cacheHandler?: string cacheHandler?: string
...@@ -22,6 +25,7 @@ export async function createIncrementalCache({ ...@@ -22,6 +25,7 @@ export async function createIncrementalCache({
distDir: string distDir: string
dir: string dir: string
flushToDisk?: boolean flushToDisk?: boolean
requestHeaders?: Record<string, string | string[] | undefined>
cacheHandlers?: Record<string, string | undefined> cacheHandlers?: Record<string, string | undefined>
}) { }) {
// Custom cache handler overrides. // Custom cache handler overrides.
...@@ -34,8 +38,8 @@ export async function createIncrementalCache({ ...@@ -34,8 +38,8 @@ export async function createIncrementalCache({
) )
} }
if (!(globalThis as any).__nextCacheHandlers && cacheHandlers) { if (!cacheHandlerGlobal.__nextCacheHandlers && cacheHandlers) {
;(globalThis as any).__nextCacheHandlers = {} cacheHandlerGlobal.__nextCacheHandlers = {}
for (const key of Object.keys(cacheHandlers)) { for (const key of Object.keys(cacheHandlers)) {
if (cacheHandlers[key]) { if (cacheHandlers[key]) {
...@@ -46,11 +50,15 @@ export async function createIncrementalCache({ ...@@ -46,11 +50,15 @@ export async function createIncrementalCache({
) )
} }
} }
if (!cacheHandlers.default) {
cacheHandlerGlobal.__nextCacheHandlers.default = DefaultCacheHandler
}
} }
const incrementalCache = new IncrementalCache({ const incrementalCache = new IncrementalCache({
dev: false, dev: false,
requestHeaders: {}, requestHeaders: requestHeaders || {},
flushToDisk, flushToDisk,
dynamicIO, dynamicIO,
maxMemoryCacheSize: cacheMaxMemorySize, maxMemoryCacheSize: cacheMaxMemorySize,
......
...@@ -1359,7 +1359,7 @@ export default abstract class Server< ...@@ -1359,7 +1359,7 @@ export default abstract class Server<
) || [] ) || []
for (const handler of Object.values(_globalThis.__nextCacheHandlers)) { for (const handler of Object.values(_globalThis.__nextCacheHandlers)) {
if (typeof handler.receiveExpiredTags === 'function') { if (typeof handler?.receiveExpiredTags === 'function') {
await handler.receiveExpiredTags(...expiredTags) await handler.receiveExpiredTags(...expiredTags)
} }
} }
......
...@@ -770,6 +770,7 @@ export default class DevServer extends Server { ...@@ -770,6 +770,7 @@ export default class DevServer extends Server {
isAppPath, isAppPath,
requestHeaders, requestHeaders,
cacheHandler: this.nextConfig.cacheHandler, cacheHandler: this.nextConfig.cacheHandler,
cacheHandlers: this.nextConfig.experimental.cacheHandlers,
cacheLifeProfiles: this.nextConfig.experimental.cacheLife, cacheLifeProfiles: this.nextConfig.experimental.cacheLife,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix, fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk, isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
......
...@@ -18,6 +18,7 @@ import { InvariantError } from '../../shared/lib/invariant-error' ...@@ -18,6 +18,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys' import { collectRootParamKeys } from '../../build/segment-config/app/collect-root-param-keys'
import { buildAppStaticPaths } from '../../build/static-paths/app' import { buildAppStaticPaths } from '../../build/static-paths/app'
import { buildPagesStaticPaths } from '../../build/static-paths/pages' import { buildPagesStaticPaths } from '../../build/static-paths/pages'
import { createIncrementalCache } from '../../export/helpers/create-incremental-cache'
type RuntimeConfig = { type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
...@@ -45,6 +46,7 @@ export async function loadStaticPaths({ ...@@ -45,6 +46,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize, maxMemoryCacheSize,
requestHeaders, requestHeaders,
cacheHandler, cacheHandler,
cacheHandlers,
cacheLifeProfiles, cacheLifeProfiles,
nextConfigOutput, nextConfigOutput,
buildId, buildId,
...@@ -65,6 +67,7 @@ export async function loadStaticPaths({ ...@@ -65,6 +67,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
cacheHandler?: string cacheHandler?: string
cacheHandlers?: NextConfigComplete['experimental']['cacheHandlers']
cacheLifeProfiles?: { cacheLifeProfiles?: {
[profile: string]: import('../../server/use-cache/cache-life').CacheLife [profile: string]: import('../../server/use-cache/cache-life').CacheLife
} }
...@@ -73,6 +76,20 @@ export async function loadStaticPaths({ ...@@ -73,6 +76,20 @@ export async function loadStaticPaths({
authInterrupts: boolean authInterrupts: boolean
sriEnabled: boolean sriEnabled: boolean
}): Promise<Partial<StaticPathsResult>> { }): Promise<Partial<StaticPathsResult>> {
// this needs to be initialized before loadComponents otherwise
// "use cache" could be missing it's cache handlers
await createIncrementalCache({
dir,
distDir,
dynamicIO: false,
cacheHandler,
cacheHandlers,
requestHeaders,
fetchCacheKeyPrefix,
flushToDisk: isrFlushToDisk,
cacheMaxMemorySize: maxMemoryCacheSize,
})
// update work memory runtime-config // update work memory runtime-config
require('../../shared/lib/runtime-config.external').setConfig(config) require('../../shared/lib/runtime-config.external').setConfig(config)
setHttpClientAndAgentOptions({ setHttpClientAndAgentOptions({
......
...@@ -103,7 +103,7 @@ const DefaultCacheHandler: CacheHandler = { ...@@ -103,7 +103,7 @@ const DefaultCacheHandler: CacheHandler = {
} }
}, },
async unstable_expireTags(...tags) { async expireTags(...tags) {
for (const tag of tags) { for (const tag of tags) {
if (!tagsManifest.items[tag]) { if (!tagsManifest.items[tag]) {
tagsManifest.items[tag] = {} tagsManifest.items[tag] = {}
...@@ -113,8 +113,11 @@ const DefaultCacheHandler: CacheHandler = { ...@@ -113,8 +113,11 @@ const DefaultCacheHandler: CacheHandler = {
} }
}, },
// This is only meant to invalidate in memory tags
// not meant to be propagated like expireTags would
// in multi-instance scenario
async receiveExpiredTags(...tags): Promise<void> { async receiveExpiredTags(...tags): Promise<void> {
return this.unstable_expireTags(...tags) return this.expireTags(...tags)
}, },
} }
......
...@@ -44,9 +44,9 @@ export interface CacheHandler { ...@@ -44,9 +44,9 @@ export interface CacheHandler {
set(cacheKey: string, entry: Promise<CacheEntry>): Promise<void> set(cacheKey: string, entry: Promise<CacheEntry>): Promise<void>
// This is called when unstable_expireTags('') is called // This is called when expireTags('') is called
// and should update tags manifest accordingly // and should update tags manifest accordingly
unstable_expireTags(...tags: string[]): Promise<void> expireTags(...tags: string[]): Promise<void>
// This is called when an action request sends // This is called when an action request sends
// NEXT_CACHE_REVALIDATED_TAGS_HEADER and tells // NEXT_CACHE_REVALIDATED_TAGS_HEADER and tells
......
...@@ -249,7 +249,22 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -249,7 +249,22 @@ export class IncrementalCache implements IncrementalCacheType {
} }
async revalidateTag(tags: string | string[]): Promise<void> { async revalidateTag(tags: string | string[]): Promise<void> {
return this.cacheHandler?.revalidateTag?.(tags) const _globalThis: typeof globalThis & {
__nextCacheHandlers?: Record<
string,
import('../cache-handlers/types').CacheHandler
>
} = globalThis
return Promise.all([
// call expireTags on all configured cache handlers
Object.values(_globalThis.__nextCacheHandlers || {}).map(
(cacheHandler) =>
typeof cacheHandler.expireTags === 'function' &&
cacheHandler.expireTags(...(Array.isArray(tags) ? tags : [tags]))
),
this.cacheHandler?.revalidateTag?.(tags),
]).then(() => {})
} }
// x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23 // x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
......
...@@ -109,6 +109,7 @@ import { InvariantError } from '../shared/lib/invariant-error' ...@@ -109,6 +109,7 @@ import { InvariantError } from '../shared/lib/invariant-error'
import { AwaiterOnce } from './after/awaiter' import { AwaiterOnce } from './after/awaiter'
import { AsyncCallbackSet } from './lib/async-callback-set' import { AsyncCallbackSet } from './lib/async-callback-set'
import DefaultCacheHandler from './lib/cache-handlers/default' import DefaultCacheHandler from './lib/cache-handlers/default'
import { cacheHandlerGlobal, cacheHandlersSymbol } from './use-cache/constants'
export * from './base-server' export * from './base-server'
...@@ -379,8 +380,8 @@ export default class NextNodeServer extends BaseServer< ...@@ -379,8 +380,8 @@ export default class NextNodeServer extends BaseServer<
protected async loadCustomCacheHandlers() { protected async loadCustomCacheHandlers() {
const { cacheHandlers } = this.nextConfig.experimental const { cacheHandlers } = this.nextConfig.experimental
if (!(globalThis as any).__nextCacheHandlers && cacheHandlers) { if (!cacheHandlerGlobal.__nextCacheHandlers && cacheHandlers) {
;(globalThis as any).__nextCacheHandlers = {} cacheHandlerGlobal.__nextCacheHandlers = {}
for (const key of Object.keys(cacheHandlers)) { for (const key of Object.keys(cacheHandlers)) {
if (cacheHandlers[key]) { if (cacheHandlers[key]) {
...@@ -393,7 +394,9 @@ export default class NextNodeServer extends BaseServer< ...@@ -393,7 +394,9 @@ export default class NextNodeServer extends BaseServer<
} }
if (!cacheHandlers.default) { if (!cacheHandlers.default) {
;(globalThis as any).__nextCacheHandlers.default = DefaultCacheHandler cacheHandlerGlobal.__nextCacheHandlers.default =
cacheHandlerGlobal[cacheHandlersSymbol]?.DefaultCache ||
DefaultCacheHandler
} }
} }
} }
......
import type { CacheHandler } from '../lib/cache-handlers/types'
// If the expire time is less than .
export const DYNAMIC_EXPIRE = 300
export const cacheHandlersSymbol = Symbol.for('@next/cache-handlers')
export const cacheHandlerGlobal: typeof globalThis & {
[cacheHandlersSymbol]?: {
RemoteCache?: CacheHandler
DefaultCache?: CacheHandler
}
__nextCacheHandlers?: Record<string, CacheHandler>
} = globalThis
...@@ -33,39 +33,16 @@ import { ...@@ -33,39 +33,16 @@ import {
getClientReferenceManifestForRsc, getClientReferenceManifestForRsc,
getServerModuleMap, getServerModuleMap,
} from '../app-render/encryption-utils' } from '../app-render/encryption-utils'
import DefaultCacheHandler from '../lib/cache-handlers/default'
import type { CacheHandler, CacheEntry } from '../lib/cache-handlers/types' import type { CacheHandler, CacheEntry } from '../lib/cache-handlers/types'
import type { CacheSignal } from '../app-render/cache-signal' import type { CacheSignal } from '../app-render/cache-signal'
import { decryptActionBoundArgs } from '../app-render/encryption' import { decryptActionBoundArgs } from '../app-render/encryption'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { getDigestForWellKnownError } from '../app-render/create-error-handler' import { getDigestForWellKnownError } from '../app-render/create-error-handler'
import { cacheHandlerGlobal, DYNAMIC_EXPIRE } from './constants'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
// If the expire time is less than . const cacheHandlerMap: Map<string, CacheHandler> = new Map()
const DYNAMIC_EXPIRE = 300
const cacheHandlersSymbol = Symbol.for('@next/cache-handlers')
const _globalThis: typeof globalThis & {
[cacheHandlersSymbol]?: {
RemoteCache?: CacheHandler
DefaultCache?: CacheHandler
}
__nextCacheHandlers?: Record<string, CacheHandler>
} = globalThis
const cacheHandlerMap: Map<string, CacheHandler> = new Map([
[
'default',
_globalThis[cacheHandlersSymbol]?.DefaultCache || DefaultCacheHandler,
],
[
'remote',
// in dev remote maps to default handler
// and is meant to be overridden in prod
_globalThis[cacheHandlersSymbol]?.RemoteCache || DefaultCacheHandler,
],
])
function generateCacheEntry( function generateCacheEntry(
workStore: WorkStore, workStore: WorkStore,
...@@ -455,7 +432,7 @@ export function cache( ...@@ -455,7 +432,7 @@ export function cache(
fn: any fn: any
) { ) {
for (const [key, value] of Object.entries( for (const [key, value] of Object.entries(
_globalThis.__nextCacheHandlers || {} cacheHandlerGlobal.__nextCacheHandlers || {}
)) { )) {
cacheHandlerMap.set(key, value as CacheHandler) cacheHandlerMap.set(key, value as CacheHandler)
} }
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import React, { Suspense } from 'react'
async function Random({ cached }: { cached?: boolean }) {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.text())
return (
<>
<p>now: {Date.now()}</p>
<p>
{cached ? 'cached ' : ''}random: {data}
</p>
</>
)
}
async function CachedRandom() {
'use cache'
return <Random cached />
}
export default function Page() {
return (
<>
<p>index page</p>
<Suspense fallback={<p>Loading...</p>}>
<Random />
</Suspense>
<Suspense fallback={<p>Loading...</p>}>
<CachedRandom />
</Suspense>
</>
)
}
import { revalidateTag } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
export async function GET(req: NextRequest) {
console.log(req.url.toString())
revalidateTag(req.nextUrl.searchParams.get('tag') || '')
return NextResponse.json({ success: true })
}
import path from 'path'
import { createNext, FileRef, NextInstance } from 'e2e-utils'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
retry,
} from 'next-test-utils'
describe('dynamic-io-cache-handlers', () => {
let appPort: number
let server: any
let output = ''
let next: NextInstance
if (process.env.__NEXT_EXPERIMENTAL_PPR) {
return it('should skip', () => {})
}
beforeAll(async () => {
next = await createNext({
files: new FileRef(__dirname),
skipStart: true,
})
await next.build()
const standaloneServer = '.next/standalone/server.js'
await next.patchFile(
standaloneServer,
`
globalThis[Symbol.for('@next/cache-handlers')] = {
DefaultCache: {
get(cacheKey, softTags) {
console.log('symbol get', cacheKey, softTags)
},
set(cacheKey, entry) {
console.log('symbol set', cacheKey)
},
expireTags(...tags) {
console.log('symbol expireTags', tags)
},
receiveExpiredTags(...tags) {
console.log('symbol receiveExpiredTags', tags)
}
}
}
${await next.readFile(standaloneServer)}`
)
appPort = await findPort()
require('console').error(
'starting standalone mode',
path.join(next.testDir, standaloneServer)
)
server = await initNextServerScript(
path.join(next.testDir, standaloneServer),
/- Local:/,
{
...process.env,
PORT: `${appPort}`,
},
undefined,
{
cwd: next.testDir,
shouldRejectOnError: true,
onStdout(data) {
output += data
require('console').log(data)
},
onStderr(data) {
output += data
require('console').log(data)
},
}
)
})
afterAll(async () => {
await next.destroy()
await killApp(server)
})
it('should use global symbol for default cache handler', async () => {
const res = await fetchViaHTTP(appPort, '/')
expect(res.status).toBe(200)
await retry(() => {
expect(output).toContain('symbol receiveExpiredTags')
expect(output).toContain('symbol get')
expect(output).toContain('symbol set')
})
})
it('should call expireTags on global default cache handler', async () => {
const res = await fetchViaHTTP(appPort, '/revalidate-tag', { tag: 'tag1' })
expect(res.status).toBe(200)
await retry(() => {
expect(output).toContain('symbol receiveExpiredTags')
expect(output).toContain('symbol expireTags')
expect(output).toContain('tag1')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
output: 'standalone',
experimental: {
dynamicIO: true,
},
}
module.exports = nextConfig
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