Unverified Commit 5c6d0707 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update isStale checking for fetch cache (#46331

This ensures we set `lastModified` when pulling from upstream cache
instead of using `isStale` on the cache entry since once it's stored to
the memory cache the `isStale` field would never be updated.
parent 4f0d76c4
import type { ServerRuntime } from '../../types'
// in seconds
export const CACHE_ONE_YEAR = 31536000
// Patterns to detect middleware files
export const MIDDLEWARE_FILENAME = 'middleware'
export const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`
......
import LRUCache from 'next/dist/compiled/lru-cache'
import { FETCH_CACHE_HEADER } from '../../../client/components/app-router-headers'
import { CACHE_ONE_YEAR } from '../../../lib/constants'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
let memoryCache: LRUCache<string, CacheHandlerValue> | undefined
......@@ -103,9 +104,13 @@ export default class FetchCache implements CacheHandler {
const age = res.headers.get('age')
data = {
age: age === null ? undefined : parseInt(age, 10),
cacheState: cacheState || undefined,
value: cached,
// if it's already stale set it to a year in the future
// if not derive last modified from age
lastModified:
cacheState === 'stale'
? Date.now() + CACHE_ONE_YEAR
: Date.now() - parseInt(age || '0', 10) * 1000,
}
if (this.debug) {
console.log(
......@@ -146,7 +151,11 @@ export default class FetchCache implements CacheHandler {
if (data !== null && 'revalidate' in data) {
this.headers['x-vercel-revalidate'] = data.revalidate.toString()
}
if (data !== null && 'data' in data) {
if (
!this.headers['x-vercel-revalidate'] &&
data !== null &&
'data' in data
) {
this.headers['x-vercel-cache-control'] =
data.data.headers['cache-control']
}
......
......@@ -197,13 +197,11 @@ export class IncrementalCache {
if (cacheData?.value?.kind === 'FETCH') {
const revalidate = cacheData.value.revalidate
const age =
cacheData.age ||
Math.round((Date.now() - (cacheData.lastModified || 0)) / 1000)
const age = Math.round(
(Date.now() - (cacheData.lastModified || 0)) / 1000
)
const isStale = cacheData.cacheState
? cacheData.cacheState !== 'fresh'
: age > revalidate
const isStale = age > revalidate
const data = cacheData.value.data
return {
......
import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage'
import { AppRenderSpan } from './trace/constants'
import { getTracer, SpanKind } from './trace/tracer'
import { CACHE_ONE_YEAR } from '../../lib/constants'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
const CACHE_ONE_YEAR = 31536000
// we patch fetch to collect cache information used for
// determining if a page is static or not
......
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