Unverified Commit feacb44f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Add debug logging to default cache handler and `"use cache"` wrapper (#77827)

When the env variable `NEXT_PRIVATE_DEBUG_CACHE` is defined (see https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#verifying-correct-production-behavior), the default cache handler and the `"use cache"` wrapper will now emit debug logs.

Note: This variable can already be used for `"use cache"` debug logging when deploying to Vercel.
parent 6d537d3a
...@@ -41,13 +41,23 @@ const memoryCache = new LRUCache<PrivateCacheEntry>( ...@@ -41,13 +41,23 @@ const memoryCache = new LRUCache<PrivateCacheEntry>(
) )
const pendingSets = new Map<string, Promise<void>>() const pendingSets = new Map<string, Promise<void>>()
const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
? console.debug.bind(console, 'DefaultCacheHandler:')
: undefined
const DefaultCacheHandler: CacheHandlerV2 = { const DefaultCacheHandler: CacheHandlerV2 = {
async get(cacheKey) { async get(cacheKey) {
await pendingSets.get(cacheKey) const pendingPromise = pendingSets.get(cacheKey)
if (pendingPromise) {
debug?.('get', cacheKey, 'pending')
await pendingPromise
}
const privateEntry = memoryCache.get(cacheKey) const privateEntry = memoryCache.get(cacheKey)
if (!privateEntry) { if (!privateEntry) {
debug?.('get', cacheKey, 'not found')
return undefined return undefined
} }
...@@ -59,15 +69,26 @@ const DefaultCacheHandler: CacheHandlerV2 = { ...@@ -59,15 +69,26 @@ const DefaultCacheHandler: CacheHandlerV2 = {
// In-memory caches should expire after revalidate time because it is // In-memory caches should expire after revalidate time because it is
// unlikely that a new entry will be able to be used before it is dropped // unlikely that a new entry will be able to be used before it is dropped
// from the cache. // from the cache.
debug?.('get', cacheKey, 'expired')
return undefined return undefined
} }
if (isStale(entry.tags, entry.timestamp)) { if (isStale(entry.tags, entry.timestamp)) {
debug?.('get', cacheKey, 'had stale tag')
return undefined return undefined
} }
const [returnStream, newSaved] = entry.value.tee() const [returnStream, newSaved] = entry.value.tee()
entry.value = newSaved entry.value = newSaved
debug?.('get', cacheKey, 'found', {
tags: entry.tags,
timestamp: entry.timestamp,
revalidate: entry.revalidate,
expire: entry.expire,
})
return { return {
...entry, ...entry,
value: returnStream, value: returnStream,
...@@ -75,6 +96,8 @@ const DefaultCacheHandler: CacheHandlerV2 = { ...@@ -75,6 +96,8 @@ const DefaultCacheHandler: CacheHandlerV2 = {
}, },
async set(cacheKey, pendingEntry) { async set(cacheKey, pendingEntry) {
debug?.('set', cacheKey, 'start')
let resolvePending: () => void = () => {} let resolvePending: () => void = () => {}
const pendingPromise = new Promise<void>((resolve) => { const pendingPromise = new Promise<void>((resolve) => {
resolvePending = resolve resolvePending = resolve
...@@ -100,8 +123,11 @@ const DefaultCacheHandler: CacheHandlerV2 = { ...@@ -100,8 +123,11 @@ const DefaultCacheHandler: CacheHandlerV2 = {
errorRetryCount: 0, errorRetryCount: 0,
size, size,
}) })
} catch {
debug?.('set', cacheKey, 'done')
} catch (err) {
// TODO: store partial buffer with error after we retry 3 times // TODO: store partial buffer with error after we retry 3 times
debug?.('set', cacheKey, 'failed', err)
} finally { } finally {
resolvePending() resolvePending()
pendingSets.delete(cacheKey) pendingSets.delete(cacheKey)
...@@ -113,11 +139,18 @@ const DefaultCacheHandler: CacheHandlerV2 = { ...@@ -113,11 +139,18 @@ const DefaultCacheHandler: CacheHandlerV2 = {
}, },
async getExpiration(...tags) { async getExpiration(...tags) {
return Math.max(...tags.map((tag) => tagsManifest.get(tag) ?? 0)) const expiration = Math.max(
...tags.map((tag) => tagsManifest.get(tag) ?? 0)
)
debug?.('getExpiration', { tags, expiration })
return expiration
}, },
async expireTags(...tags) { async expireTags(...tags) {
const timestamp = Math.round(performance.timeOrigin + performance.now()) const timestamp = Math.round(performance.timeOrigin + performance.now())
debug?.('expireTags', { tags, timestamp })
for (const tag of tags) { for (const tag of tags) {
// TODO: update file-system-cache? // TODO: update file-system-cache?
......
...@@ -5,7 +5,7 @@ const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE ...@@ -5,7 +5,7 @@ const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
? (message: string, ...args: any[]) => { ? (message: string, ...args: any[]) => {
console.log(`use-cache: ${message}`, ...args) console.log(`use-cache: ${message}`, ...args)
} }
: () => {} : undefined
const handlersSymbol = Symbol.for('@next/cache-handlers') const handlersSymbol = Symbol.for('@next/cache-handlers')
const handlersMapSymbol = Symbol.for('@next/cache-handlers-map') const handlersMapSymbol = Symbol.for('@next/cache-handlers-map')
...@@ -32,40 +32,40 @@ const reference: typeof globalThis & { ...@@ -32,40 +32,40 @@ const reference: typeof globalThis & {
export function initializeCacheHandlers(): boolean { export function initializeCacheHandlers(): boolean {
// If the cache handlers have already been initialized, don't do it again. // If the cache handlers have already been initialized, don't do it again.
if (reference[handlersMapSymbol]) { if (reference[handlersMapSymbol]) {
debug('cache handlers already initialized') debug?.('cache handlers already initialized')
return false return false
} }
debug('initializing cache handlers') debug?.('initializing cache handlers')
reference[handlersMapSymbol] = new Map<string, CacheHandlerCompat>() reference[handlersMapSymbol] = new Map<string, CacheHandlerCompat>()
// Initialize the cache from the symbol contents first. // Initialize the cache from the symbol contents first.
if (reference[handlersSymbol]) { if (reference[handlersSymbol]) {
let fallback: CacheHandlerCompat let fallback: CacheHandlerCompat
if (reference[handlersSymbol].DefaultCache) { if (reference[handlersSymbol].DefaultCache) {
debug('setting "default" cache handler from symbol') debug?.('setting "default" cache handler from symbol')
fallback = reference[handlersSymbol].DefaultCache fallback = reference[handlersSymbol].DefaultCache
} else { } else {
debug('setting "default" cache handler from default') debug?.('setting "default" cache handler from default')
fallback = DefaultCacheHandler fallback = DefaultCacheHandler
} }
reference[handlersMapSymbol].set('default', fallback) reference[handlersMapSymbol].set('default', fallback)
if (reference[handlersSymbol].RemoteCache) { if (reference[handlersSymbol].RemoteCache) {
debug('setting "remote" cache handler from symbol') debug?.('setting "remote" cache handler from symbol')
reference[handlersMapSymbol].set( reference[handlersMapSymbol].set(
'remote', 'remote',
reference[handlersSymbol].RemoteCache reference[handlersSymbol].RemoteCache
) )
} else { } else {
debug('setting "remote" cache handler from default') debug?.('setting "remote" cache handler from default')
reference[handlersMapSymbol].set('remote', fallback) reference[handlersMapSymbol].set('remote', fallback)
} }
} else { } else {
debug('setting "default" cache handler from default') debug?.('setting "default" cache handler from default')
reference[handlersMapSymbol].set('default', DefaultCacheHandler) reference[handlersMapSymbol].set('default', DefaultCacheHandler)
debug('setting "remote" cache handler from default') debug?.('setting "remote" cache handler from default')
reference[handlersMapSymbol].set('remote', DefaultCacheHandler) reference[handlersMapSymbol].set('remote', DefaultCacheHandler)
} }
...@@ -135,7 +135,7 @@ export function setCacheHandler( ...@@ -135,7 +135,7 @@ export function setCacheHandler(
throw new Error('Cache handlers not initialized') throw new Error('Cache handlers not initialized')
} }
debug('setting cache handler for "%s"', kind) debug?.('setting cache handler for "%s"', kind)
reference[handlersMapSymbol].set(kind, cacheHandler) reference[handlersMapSymbol].set(kind, cacheHandler)
reference[handlersSetSymbol].add(cacheHandler) reference[handlersSetSymbol].add(cacheHandler)
} }
...@@ -66,6 +66,10 @@ export interface UseCachePageComponentProps { ...@@ -66,6 +66,10 @@ export interface UseCachePageComponentProps {
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
? console.debug.bind(console, 'use-cache:')
: undefined
function generateCacheEntry( function generateCacheEntry(
workStore: WorkStore, workStore: WorkStore,
outerWorkUnitStore: WorkUnitStore | undefined, outerWorkUnitStore: WorkUnitStore | undefined,
...@@ -716,6 +720,7 @@ export function cache( ...@@ -716,6 +720,7 @@ export function cache(
entry && entry &&
(await shouldDiscardCacheEntry(entry, workStore, implicitTags)) (await shouldDiscardCacheEntry(entry, workStore, implicitTags))
) { ) {
debug?.('discarding stale entry', serializedCacheKey)
entry = undefined entry = undefined
} }
...@@ -756,6 +761,19 @@ export function cache( ...@@ -756,6 +761,19 @@ export function cache(
// Note: It is important that we await at least once before this because it lets us // Note: It is important that we await at least once before this because it lets us
// pop out of any stack specific contexts as well - aka "Sync" Local Storage. // pop out of any stack specific contexts as well - aka "Sync" Local Storage.
if (entry) {
if (currentTime > entry.timestamp + entry.expire * 1000) {
debug?.('entry is expired', serializedCacheKey)
}
if (
workStore.isStaticGeneration &&
currentTime > entry.timestamp + entry.revalidate * 1000
) {
debug?.('static generation, entry is stale', serializedCacheKey)
}
}
const [newStream, pendingCacheEntry] = await generateCacheEntry( const [newStream, pendingCacheEntry] = await generateCacheEntry(
workStore, workStore,
workUnitStore, workUnitStore,
...@@ -942,6 +960,13 @@ async function shouldDiscardCacheEntry( ...@@ -942,6 +960,13 @@ async function shouldDiscardCacheEntry(
// If the cache entry was created before any of the implicit tags were // If the cache entry was created before any of the implicit tags were
// revalidated last, we also need to discard it. // revalidated last, we also need to discard it.
if (entry.timestamp <= (await implicitTags.expiration)) { if (entry.timestamp <= (await implicitTags.expiration)) {
debug?.(
'entry was created at',
entry.timestamp,
'before implicit tags were revalidated at',
implicitTags.expiration
)
return true return true
} }
...@@ -962,6 +987,8 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean { ...@@ -962,6 +987,8 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean {
// Was the tag previously revalidated (e.g. by a redirecting server action)? // Was the tag previously revalidated (e.g. by a redirecting server action)?
if (previouslyRevalidatedTags.includes(tag)) { if (previouslyRevalidatedTags.includes(tag)) {
debug?.('tag', tag, 'was previously revalidated')
return true return true
} }
...@@ -969,6 +996,8 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean { ...@@ -969,6 +996,8 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean {
// In this case the revalidation might not have been propagated to the cache // In this case the revalidation might not have been propagated to the cache
// handler yet, so we read it from the pending tags in the work store. // handler yet, so we read it from the pending tags in the work store.
if (pendingRevalidatedTags?.includes(tag)) { if (pendingRevalidatedTags?.includes(tag)) {
debug?.('tag', tag, 'was just revalidated')
return true return true
} }
......
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