Unverified Commit ca735270 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

refactor: incremental cache cleanup (#68602)

This replaces usage of string constant types within the cache layers to
instead use enum types. These enum types given names carry much more
meaning than passing around string constants making it easier to read
and understand. With these changes, due to now us knowing the correct
page type we're getting from the cache because of the routing layer,
makes the route kind a required option that's passed in.

Now that the route kind is known prior to cache access, first access of
pages no long call into the filesystem needlessly, and improves cache
performance for the filesystem based cache. This also lets us remove the
kind discovery system that was in place previously allowing it to get
simplified.
parent 016ba387
...@@ -1374,9 +1374,6 @@ export async function buildAppStaticPaths({ ...@@ -1374,9 +1374,6 @@ export async function buildAppStaticPaths({
const incrementalCache = new IncrementalCache({ const incrementalCache = new IncrementalCache({
fs: nodeFs, fs: nodeFs,
dev: true, dev: true,
// Enabled both for build as we're only writing this cache, not reading it.
pagesDir: true,
appDir: true,
flushToDisk: isrFlushToDisk, flushToDisk: isrFlushToDisk,
serverDistDir: path.join(distDir, 'server'), serverDistDir: path.join(distDir, 'server'),
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
......
import type { NextEnabledDirectories } from '../../server/base-server'
import path from 'path' import path from 'path'
import { IncrementalCache } from '../../server/lib/incremental-cache' import { IncrementalCache } from '../../server/lib/incremental-cache'
import { hasNextSupport } from '../../telemetry/ci-info' import { hasNextSupport } from '../../telemetry/ci-info'
...@@ -13,7 +11,6 @@ export async function createIncrementalCache({ ...@@ -13,7 +11,6 @@ export async function createIncrementalCache({
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
distDir, distDir,
dir, dir,
enabledDirectories,
flushToDisk, flushToDisk,
}: { }: {
cacheHandler?: string cacheHandler?: string
...@@ -21,7 +18,6 @@ export async function createIncrementalCache({ ...@@ -21,7 +18,6 @@ export async function createIncrementalCache({
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
distDir: string distDir: string
dir: string dir: string
enabledDirectories: NextEnabledDirectories
flushToDisk?: boolean flushToDisk?: boolean
}) { }) {
// Custom cache handler overrides. // Custom cache handler overrides.
...@@ -53,8 +49,6 @@ export async function createIncrementalCache({ ...@@ -53,8 +49,6 @@ export async function createIncrementalCache({
notFoundRoutes: [], notFoundRoutes: [],
}), }),
fs: nodeFs, fs: nodeFs,
pagesDir: enabledDirectories.pages,
appDir: enabledDirectories.app,
serverDistDir: path.join(distDir, 'server'), serverDistDir: path.join(distDir, 'server'),
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport, minimalMode: hasNextSupport,
......
...@@ -551,7 +551,6 @@ async function exportAppImpl( ...@@ -551,7 +551,6 @@ async function exportAppImpl(
dir, dir,
distDir, distDir,
outDir, outDir,
enabledDirectories,
nextConfig, nextConfig,
cacheHandler: nextConfig.cacheHandler, cacheHandler: nextConfig.cacheHandler,
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize, cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
......
...@@ -55,7 +55,6 @@ export interface ExportPagesInput { ...@@ -55,7 +55,6 @@ export interface ExportPagesInput {
fetchCache: boolean | undefined fetchCache: boolean | undefined
cacheHandler: string | undefined cacheHandler: string | undefined
fetchCacheKeyPrefix: string | undefined fetchCacheKeyPrefix: string | undefined
enabledDirectories: NextEnabledDirectories
options: ExportAppOptions options: ExportAppOptions
} }
......
...@@ -328,7 +328,6 @@ export async function exportPages( ...@@ -328,7 +328,6 @@ export async function exportPages(
cacheHandler, cacheHandler,
cacheMaxMemorySize, cacheMaxMemorySize,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
enabledDirectories,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
nextConfig, nextConfig,
...@@ -343,7 +342,6 @@ export async function exportPages( ...@@ -343,7 +342,6 @@ export async function exportPages(
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
distDir, distDir,
dir, dir,
enabledDirectories: enabledDirectories,
// skip writing to disk in minimal mode for now, pending some // skip writing to disk in minimal mode for now, pending some
// changes to better support it // changes to better support it
flushToDisk: !hasNextSupport, flushToDisk: !hasNextSupport,
......
...@@ -15,13 +15,15 @@ import type { ...@@ -15,13 +15,15 @@ import type {
RenderOptsPartial as AppRenderOptsPartial, RenderOptsPartial as AppRenderOptsPartial,
ServerOnInstrumentationRequestError, ServerOnInstrumentationRequestError,
} from './app-render/types' } from './app-render/types'
import type { import {
CachedAppPageValue, type CachedAppPageValue,
CachedPageValue, type CachedPageValue,
ServerComponentsHmrCache, type ServerComponentsHmrCache,
ResponseCacheBase, type ResponseCacheBase,
ResponseCacheEntry, type ResponseCacheEntry,
ResponseGenerator, type ResponseGenerator,
CachedRouteKind,
type CachedRedirectValue,
} from './response-cache' } from './response-cache'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import { import {
...@@ -159,6 +161,8 @@ import { ...@@ -159,6 +161,8 @@ import {
} from './after/builtin-request-context' } from './after/builtin-request-context'
import { ENCODED_TAGS } from './stream-utils/encodedTags' import { ENCODED_TAGS } from './stream-utils/encodedTags'
import { NextRequestHint } from './web/adapter' import { NextRequestHint } from './web/adapter'
import { RouteKind } from './route-kind'
import type { RouteModule } from './route-modules/route-module'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -2043,7 +2047,10 @@ export default abstract class Server< ...@@ -2043,7 +2047,10 @@ export default abstract class Server<
) )
} }
const { routeModule } = components let routeModule: RouteModule | undefined
if (components.routeModule) {
routeModule = components.routeModule
}
/** /**
* If the route being rendered is an app page, and the ppr feature has been * If the route being rendered is an app page, and the ppr feature has been
...@@ -2493,7 +2500,7 @@ export default abstract class Server< ...@@ -2493,7 +2500,7 @@ export default abstract class Server<
// Create the cache entry for the response. // Create the cache entry for the response.
const cacheEntry: ResponseCacheEntry = { const cacheEntry: ResponseCacheEntry = {
value: { value: {
kind: 'ROUTE', kind: CachedRouteKind.APP_ROUTE,
status: response.status, status: response.status,
body: Buffer.from(await blob.arrayBuffer()), body: Buffer.from(await blob.arrayBuffer()),
headers, headers,
...@@ -2657,9 +2664,9 @@ export default abstract class Server< ...@@ -2657,9 +2664,9 @@ export default abstract class Server<
if (metadata.isRedirect) { if (metadata.isRedirect) {
return { return {
value: { value: {
kind: 'REDIRECT', kind: CachedRouteKind.REDIRECT,
props: metadata.pageData ?? metadata.flightData, props: metadata.pageData ?? metadata.flightData,
}, } satisfies CachedRedirectValue,
revalidate: metadata.revalidate, revalidate: metadata.revalidate,
} }
} }
...@@ -2673,7 +2680,7 @@ export default abstract class Server< ...@@ -2673,7 +2680,7 @@ export default abstract class Server<
if (isAppPath) { if (isAppPath) {
return { return {
value: { value: {
kind: 'APP_PAGE', kind: CachedRouteKind.APP_PAGE,
html: result, html: result,
headers, headers,
rscData: metadata.flightData, rscData: metadata.flightData,
...@@ -2686,7 +2693,7 @@ export default abstract class Server< ...@@ -2686,7 +2693,7 @@ export default abstract class Server<
return { return {
value: { value: {
kind: 'PAGE', kind: CachedRouteKind.PAGES,
html: result, html: result,
pageData: metadata.pageData ?? metadata.flightData, pageData: metadata.pageData ?? metadata.flightData,
headers, headers,
...@@ -2802,11 +2809,11 @@ export default abstract class Server< ...@@ -2802,11 +2809,11 @@ export default abstract class Server<
return { return {
value: { value: {
kind: 'PAGE', kind: CachedRouteKind.PAGES,
html: RenderResult.fromStatic(html), html: RenderResult.fromStatic(html),
pageData: {},
status: undefined, status: undefined,
headers: undefined, headers: undefined,
pageData: {},
}, },
} }
} }
...@@ -2845,12 +2852,12 @@ export default abstract class Server< ...@@ -2845,12 +2852,12 @@ export default abstract class Server<
return { return {
revalidate: 1, revalidate: 1,
value: { value: {
kind: 'PAGE', kind: CachedRouteKind.PAGES,
html: RenderResult.fromStatic(''), html: RenderResult.fromStatic(''),
pageData: {}, pageData: {},
headers: undefined, headers: undefined,
status: undefined, status: undefined,
}, } satisfies CachedPageValue,
} }
} }
...@@ -2871,7 +2878,11 @@ export default abstract class Server< ...@@ -2871,7 +2878,11 @@ export default abstract class Server<
ssgCacheKey, ssgCacheKey,
responseGenerator, responseGenerator,
{ {
routeKind: routeModule?.definition.kind, routeKind:
// If the route module is not defined, we can assume it's a page being
// rendered and thus check isAppPath.
routeModule?.definition.kind ??
(isAppPath ? RouteKind.APP_PAGE : RouteKind.PAGES),
incrementalCache, incrementalCache,
isOnDemandRevalidate, isOnDemandRevalidate,
isPrefetch: req.headers.purpose === 'prefetch', isPrefetch: req.headers.purpose === 'prefetch',
...@@ -2892,7 +2903,7 @@ export default abstract class Server< ...@@ -2892,7 +2903,7 @@ export default abstract class Server<
} }
const didPostpone = const didPostpone =
cacheEntry.value?.kind === 'APP_PAGE' && cacheEntry.value?.kind === CachedRouteKind.APP_PAGE &&
typeof cacheEntry.value.postponed === 'string' typeof cacheEntry.value.postponed === 'string'
if ( if (
...@@ -2924,7 +2935,7 @@ export default abstract class Server< ...@@ -2924,7 +2935,7 @@ export default abstract class Server<
const { value: cachedData } = cacheEntry const { value: cachedData } = cacheEntry
// If the cache value is an image, we should error early. // If the cache value is an image, we should error early.
if (cachedData?.kind === 'IMAGE') { if (cachedData?.kind === CachedRouteKind.IMAGE) {
throw new Error('invariant SSG should not return an image cache value') throw new Error('invariant SSG should not return an image cache value')
} }
...@@ -3007,7 +3018,7 @@ export default abstract class Server< ...@@ -3007,7 +3018,7 @@ export default abstract class Server<
value: { value: {
...cacheEntry.value, ...cacheEntry.value,
kind: kind:
cacheEntry.value?.kind === 'APP_PAGE' cacheEntry.value?.kind === CachedRouteKind.APP_PAGE
? 'PAGE' ? 'PAGE'
: cacheEntry.value?.kind, : cacheEntry.value?.kind,
}, },
...@@ -3049,7 +3060,7 @@ export default abstract class Server< ...@@ -3049,7 +3060,7 @@ export default abstract class Server<
} }
await this.render404(req, res, { pathname, query }, false) await this.render404(req, res, { pathname, query }, false)
return null return null
} else if (cachedData.kind === 'REDIRECT') { } else if (cachedData.kind === CachedRouteKind.REDIRECT) {
if (cacheEntry.revalidate) { if (cacheEntry.revalidate) {
res.setHeader( res.setHeader(
'Cache-Control', 'Cache-Control',
...@@ -3073,7 +3084,7 @@ export default abstract class Server< ...@@ -3073,7 +3084,7 @@ export default abstract class Server<
await handleRedirect(cachedData.props) await handleRedirect(cachedData.props)
return null return null
} }
} else if (cachedData.kind === 'ROUTE') { } else if (cachedData.kind === CachedRouteKind.APP_ROUTE) {
const headers = { ...cachedData.headers } const headers = { ...cachedData.headers }
if (!(this.minimalMode && isSSG)) { if (!(this.minimalMode && isSSG)) {
...@@ -3089,7 +3100,7 @@ export default abstract class Server< ...@@ -3089,7 +3100,7 @@ export default abstract class Server<
}) })
) )
return null return null
} else if (cachedData.kind === 'APP_PAGE') { } else if (cachedData.kind === CachedRouteKind.APP_PAGE) {
// If the request has a postponed state and it's a resume request we // If the request has a postponed state and it's a resume request we
// should error. // should error.
if (cachedData.postponed && minimalPostponed) { if (cachedData.postponed && minimalPostponed) {
...@@ -3224,7 +3235,7 @@ export default abstract class Server< ...@@ -3224,7 +3235,7 @@ export default abstract class Server<
throw new Error('Invariant: expected a result to be returned') throw new Error('Invariant: expected a result to be returned')
} }
if (result.value?.kind !== 'APP_PAGE') { if (result.value?.kind !== CachedRouteKind.APP_PAGE) {
throw new Error( throw new Error(
`Invariant: expected a page response, got ${result.value?.kind}` `Invariant: expected a page response, got ${result.value?.kind}`
) )
......
...@@ -14,9 +14,10 @@ import { hasMatch } from '../shared/lib/match-remote-pattern' ...@@ -14,9 +14,10 @@ import { hasMatch } from '../shared/lib/match-remote-pattern'
import type { NextConfigComplete } from './config-shared' import type { NextConfigComplete } from './config-shared'
import { createRequestResponseMocks } from './lib/mock-request' import { createRequestResponseMocks } from './lib/mock-request'
import type { NextUrlWithParsedQuery } from './request-meta' import type { NextUrlWithParsedQuery } from './request-meta'
import type { import {
IncrementalCacheEntry, CachedRouteKind,
IncrementalCacheValue, type IncrementalCacheEntry,
type IncrementalCacheValue,
} from './response-cache' } from './response-cache'
import { sendEtagResponse } from './send-payload' import { sendEtagResponse } from './send-payload'
import { getContentType, getExtension } from './serve-static' import { getContentType, getExtension } from './serve-static'
...@@ -359,7 +360,7 @@ export class ImageOptimizerCache { ...@@ -359,7 +360,7 @@ export class ImageOptimizerCache {
return { return {
value: { value: {
kind: 'IMAGE', kind: CachedRouteKind.IMAGE,
etag, etag,
buffer, buffer,
extension, extension,
...@@ -385,7 +386,7 @@ export class ImageOptimizerCache { ...@@ -385,7 +386,7 @@ export class ImageOptimizerCache {
revalidate?: number | false revalidate?: number | false
} }
) { ) {
if (value?.kind !== 'IMAGE') { if (value?.kind !== CachedRouteKind.IMAGE) {
throw new Error('invariant attempted to set non-image to image-cache') throw new Error('invariant attempted to set non-image to image-cache')
} }
......
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './' import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
import type { IncrementalCacheValue } from '../../response-cache' import {
CachedRouteKind,
IncrementalCacheKind,
type IncrementalCacheValue,
} from '../../response-cache'
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import { import {
...@@ -128,20 +132,22 @@ export default class FetchCache implements CacheHandler { ...@@ -128,20 +132,22 @@ export default class FetchCache implements CacheHandler {
length({ value }) { length({ value }) {
if (!value) { if (!value) {
return 25 return 25
} else if (value.kind === 'REDIRECT') { } else if (value.kind === CachedRouteKind.REDIRECT) {
return JSON.stringify(value.props).length return JSON.stringify(value.props).length
} else if (value.kind === 'IMAGE') { } else if (value.kind === CachedRouteKind.IMAGE) {
throw new Error('invariant image should not be incremental-cache') throw new Error('invariant image should not be incremental-cache')
} else if (value.kind === 'FETCH') { } else if (value.kind === CachedRouteKind.FETCH) {
return JSON.stringify(value.data || '').length return JSON.stringify(value.data || '').length
} else if (value.kind === 'ROUTE') { } else if (value.kind === CachedRouteKind.APP_ROUTE) {
return value.body.length return value.body.length
} }
// rough estimate of size of cache value // rough estimate of size of cache value
return ( return (
value.html.length + value.html.length +
(JSON.stringify( (JSON.stringify(
value.kind === 'APP_PAGE' ? value.rscData : value.pageData value.kind === CachedRouteKind.APP_PAGE
? value.rscData
: value.pageData
)?.length || 0) )?.length || 0)
) )
}, },
...@@ -203,10 +209,10 @@ export default class FetchCache implements CacheHandler { ...@@ -203,10 +209,10 @@ export default class FetchCache implements CacheHandler {
} }
public async get(...args: Parameters<CacheHandler['get']>) { public async get(...args: Parameters<CacheHandler['get']>) {
const [key, ctx = {}] = args const [key, ctx] = args
const { tags, softTags, kindHint, fetchIdx, fetchUrl } = ctx const { tags, softTags, kind: kindHint, fetchIdx, fetchUrl } = ctx
if (kindHint !== 'fetch') { if (kindHint !== IncrementalCacheKind.FETCH) {
return null return null
} }
...@@ -223,7 +229,7 @@ export default class FetchCache implements CacheHandler { ...@@ -223,7 +229,7 @@ export default class FetchCache implements CacheHandler {
let data = memoryCache?.get(key) let data = memoryCache?.get(key)
const hasFetchKindAndMatchingTags = const hasFetchKindAndMatchingTags =
data?.value?.kind === 'FETCH' && data?.value?.kind === CachedRouteKind.FETCH &&
this.hasMatchingTags(tags ?? [], data.value.tags ?? []) this.hasMatchingTags(tags ?? [], data.value.tags ?? [])
// Get data from fetch cache. Also check if new tags have been // Get data from fetch cache. Also check if new tags have been
...@@ -274,13 +280,13 @@ export default class FetchCache implements CacheHandler { ...@@ -274,13 +280,13 @@ export default class FetchCache implements CacheHandler {
const cached: IncrementalCacheValue = await res.json() const cached: IncrementalCacheValue = await res.json()
if (!cached || cached.kind !== 'FETCH') { if (!cached || cached.kind !== CachedRouteKind.FETCH) {
DEBUG && console.log({ cached }) DEBUG && console.log({ cached })
throw new Error('invalid cache value') throw new Error('invalid cache value')
} }
// if new tags were specified, merge those tags to the existing tags // if new tags were specified, merge those tags to the existing tags
if (cached.kind === 'FETCH') { if (cached.kind === CachedRouteKind.FETCH) {
cached.tags ??= [] cached.tags ??= []
for (const tag of tags ?? []) { for (const tag of tags ?? []) {
if (!cached.tags.includes(tag)) { if (!cached.tags.includes(tag)) {
...@@ -331,11 +337,12 @@ export default class FetchCache implements CacheHandler { ...@@ -331,11 +337,12 @@ export default class FetchCache implements CacheHandler {
public async set(...args: Parameters<CacheHandler['set']>) { public async set(...args: Parameters<CacheHandler['set']>) {
const [key, data, ctx] = args const [key, data, ctx] = args
const newValue = data?.kind === 'FETCH' ? data.data : undefined const newValue =
data?.kind === CachedRouteKind.FETCH ? data.data : undefined
const existingCache = memoryCache?.get(key) const existingCache = memoryCache?.get(key)
const existingValue = existingCache?.value const existingValue = existingCache?.value
if ( if (
existingValue?.kind === 'FETCH' && existingValue?.kind === CachedRouteKind.FETCH &&
Object.keys(existingValue.data).every( Object.keys(existingValue.data).every(
(field) => (field) =>
JSON.stringify( JSON.stringify(
......
import type { CacheFs } from '../../../shared/lib/utils' import type { CacheFs } from '../../../shared/lib/utils'
import type { PrerenderManifest } from '../../../build' import type { PrerenderManifest } from '../../../build'
import type { import {
IncrementalCacheValue, type IncrementalCacheValue,
IncrementalCacheEntry, type IncrementalCacheEntry,
IncrementalCache as IncrementalCacheType, type IncrementalCache as IncrementalCacheType,
IncrementalCacheKindHint, IncrementalCacheKind,
CachedRouteKind,
} from '../../response-cache' } from '../../response-cache'
import type { Revalidate } from '../revalidate' import type { Revalidate } from '../revalidate'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
...@@ -31,8 +32,6 @@ export interface CacheHandlerContext { ...@@ -31,8 +32,6 @@ export interface CacheHandlerContext {
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest prerenderManifest?: PrerenderManifest
revalidatedTags: string[] revalidatedTags: string[]
_appDir: boolean
_pagesDir: boolean
_requestHeaders: IncrementalCache['requestHeaders'] _requestHeaders: IncrementalCache['requestHeaders']
} }
...@@ -90,8 +89,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -90,8 +89,6 @@ export class IncrementalCache implements IncrementalCacheType {
constructor({ constructor({
fs, fs,
dev, dev,
appDir,
pagesDir,
flushToDisk, flushToDisk,
fetchCache, fetchCache,
minimalMode, minimalMode,
...@@ -106,8 +103,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -106,8 +103,6 @@ export class IncrementalCache implements IncrementalCacheType {
}: { }: {
fs?: CacheFs fs?: CacheFs
dev: boolean dev: boolean
appDir?: boolean
pagesDir?: boolean
fetchCache?: boolean fetchCache?: boolean
minimalMode?: boolean minimalMode?: boolean
serverDistDir?: string serverDistDir?: string
...@@ -186,8 +181,6 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -186,8 +181,6 @@ export class IncrementalCache implements IncrementalCacheType {
serverDistDir, serverDistDir,
revalidatedTags, revalidatedTags,
maxMemoryCacheSize, maxMemoryCacheSize,
_pagesDir: !!pagesDir,
_appDir: !!appDir,
_requestHeaders: requestHeaders, _requestHeaders: requestHeaders,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
}) })
...@@ -384,33 +377,36 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -384,33 +377,36 @@ export class IncrementalCache implements IncrementalCacheType {
async get( async get(
cacheKey: string, cacheKey: string,
ctx: { ctx: {
kindHint?: IncrementalCacheKindHint kind: IncrementalCacheKind
revalidate?: Revalidate revalidate?: Revalidate
fetchUrl?: string fetchUrl?: string
fetchIdx?: number fetchIdx?: number
tags?: string[] tags?: string[]
softTags?: string[] softTags?: string[]
isRoutePPREnabled?: boolean isRoutePPREnabled?: boolean
} = {} }
): Promise<IncrementalCacheEntry | null> { ): Promise<IncrementalCacheEntry | null> {
// we don't leverage the prerender cache in dev mode // we don't leverage the prerender cache in dev mode
// so that getStaticProps is always called for easier debugging // so that getStaticProps is always called for easier debugging
if ( if (
this.disableForTestmode || this.disableForTestmode ||
(this.dev && (this.dev &&
(ctx.kindHint !== 'fetch' || (ctx.kind !== IncrementalCacheKind.FETCH ||
this.requestHeaders['cache-control'] === 'no-cache')) this.requestHeaders['cache-control'] === 'no-cache'))
) { ) {
return null return null
} }
cacheKey = this._getPathname(cacheKey, ctx.kindHint === 'fetch') cacheKey = this._getPathname(
cacheKey,
ctx.kind === IncrementalCacheKind.FETCH
)
let entry: IncrementalCacheEntry | null = null let entry: IncrementalCacheEntry | null = null
let revalidate = ctx.revalidate let revalidate = ctx.revalidate
const cacheData = await this.cacheHandler?.get(cacheKey, ctx) const cacheData = await this.cacheHandler?.get(cacheKey, ctx)
if (cacheData?.value?.kind === 'FETCH') { if (cacheData?.value?.kind === CachedRouteKind.FETCH) {
const combinedTags = [...(ctx.tags || []), ...(ctx.softTags || [])] const combinedTags = [...(ctx.tags || []), ...(ctx.softTags || [])]
// if a tag was revalidated we don't return stale data // if a tag was revalidated we don't return stale data
if ( if (
...@@ -430,7 +426,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -430,7 +426,7 @@ export class IncrementalCache implements IncrementalCacheType {
return { return {
isStale: isStale, isStale: isStale,
value: { value: {
kind: 'FETCH', kind: CachedRouteKind.FETCH,
data, data,
revalidate: revalidate, revalidate: revalidate,
}, },
...@@ -450,7 +446,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -450,7 +446,7 @@ export class IncrementalCache implements IncrementalCacheType {
revalidateAfter = this.calculateRevalidate( revalidateAfter = this.calculateRevalidate(
cacheKey, cacheKey,
cacheData?.lastModified || Date.now(), cacheData?.lastModified || Date.now(),
this.dev && ctx.kindHint !== 'fetch' this.dev && ctx.kind !== IncrementalCacheKind.FETCH
) )
isStale = isStale =
revalidateAfter !== false && revalidateAfter < Date.now() revalidateAfter !== false && revalidateAfter < Date.now()
......
...@@ -18,7 +18,11 @@ import type { ...@@ -18,7 +18,11 @@ import type {
RequestAsyncStorage, RequestAsyncStorage,
RequestStore, RequestStore,
} from '../../client/components/request-async-storage.external' } from '../../client/components/request-async-storage.external'
import type { CachedFetchData } from '../response-cache' import {
CachedRouteKind,
IncrementalCacheKind,
type CachedFetchData,
} from '../response-cache'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -615,7 +619,7 @@ export function createPatchedFetcher( ...@@ -615,7 +619,7 @@ export function createPatchedFetcher(
await incrementalCache.set( await incrementalCache.set(
cacheKey, cacheKey,
{ {
kind: 'FETCH', kind: CachedRouteKind.FETCH,
data: fetchedData, data: fetchedData,
revalidate: normalizedRevalidate, revalidate: normalizedRevalidate,
}, },
...@@ -666,7 +670,7 @@ export function createPatchedFetcher( ...@@ -666,7 +670,7 @@ export function createPatchedFetcher(
const entry = staticGenerationStore.isOnDemandRevalidate const entry = staticGenerationStore.isOnDemandRevalidate
? null ? null
: await incrementalCache.get(cacheKey, { : await incrementalCache.get(cacheKey, {
kindHint: 'fetch', kind: IncrementalCacheKind.FETCH,
revalidate: finalRevalidate, revalidate: finalRevalidate,
fetchUrl, fetchUrl,
fetchIdx, fetchIdx,
...@@ -681,7 +685,7 @@ export function createPatchedFetcher( ...@@ -681,7 +685,7 @@ export function createPatchedFetcher(
cacheReasonOverride = 'cache-control: no-cache (hard refresh)' cacheReasonOverride = 'cache-control: no-cache (hard refresh)'
} }
if (entry?.value && entry.value.kind === 'FETCH') { if (entry?.value && entry.value.kind === CachedRouteKind.FETCH) {
// when stale and is revalidating we wait for fresh data // when stale and is revalidating we wait for fresh data
// so the revalidated entry has the updated data // so the revalidated entry has the updated data
if (staticGenerationStore.isRevalidate && entry.isStale) { if (staticGenerationStore.isRevalidate && entry.isStale) {
......
...@@ -74,7 +74,7 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing- ...@@ -74,7 +74,7 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info' import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { getCloneableBody } from './body-streams' import { getCloneableBody } from './body-streams'
import { checkIsOnDemandRevalidate } from './api-utils' import { checkIsOnDemandRevalidate } from './api-utils'
import ResponseCache from './response-cache' import ResponseCache, { CachedRouteKind } from './response-cache'
import { IncrementalCache } from './lib/incremental-cache' import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
...@@ -101,6 +101,7 @@ import { formatDynamicImportPath } from '../lib/format-dynamic-import-path' ...@@ -101,6 +101,7 @@ import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites' import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'
import type { ServerOnInstrumentationRequestError } from './app-render/types' import type { ServerOnInstrumentationRequestError } from './app-render/types'
import { RouteKind } from './route-kind'
export * from './base-server' export * from './base-server'
...@@ -374,8 +375,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -374,8 +375,6 @@ export default class NextNodeServer extends BaseServer<
dev, dev,
requestHeaders, requestHeaders,
requestProtocol, requestProtocol,
pagesDir: this.enabledDirectories.pages,
appDir: this.enabledDirectories.app,
allowedRevalidateHeaderKeys: allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys, this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode, minimalMode: this.minimalMode,
...@@ -876,7 +875,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -876,7 +875,7 @@ export default class NextNodeServer extends BaseServer<
return { return {
value: { value: {
kind: 'IMAGE', kind: CachedRouteKind.IMAGE,
buffer, buffer,
etag, etag,
extension: getExtension(contentType) as string, extension: getExtension(contentType) as string,
...@@ -885,11 +884,12 @@ export default class NextNodeServer extends BaseServer< ...@@ -885,11 +884,12 @@ export default class NextNodeServer extends BaseServer<
} }
}, },
{ {
routeKind: RouteKind.IMAGE,
incrementalCache: imageOptimizerCache, incrementalCache: imageOptimizerCache,
} }
) )
if (cacheEntry?.value?.kind !== 'IMAGE') { if (cacheEntry?.value?.kind !== CachedRouteKind.IMAGE) {
throw new Error( throw new Error(
'invariant did not get entry from image response cache' 'invariant did not get entry from image response cache'
) )
......
import type { import {
IncrementalCache, type IncrementalCache,
ResponseCacheEntry, type ResponseCacheEntry,
ResponseGenerator, type ResponseGenerator,
IncrementalCacheItem, type IncrementalCacheItem,
ResponseCacheBase, type ResponseCacheBase,
IncrementalCacheKindHint, CachedRouteKind,
} from './types' } from './types'
import { RouteKind } from '../route-kind'
import { Batcher } from '../../lib/batcher' import { Batcher } from '../../lib/batcher'
import { scheduleOnNextTick } from '../../lib/scheduler' import { scheduleOnNextTick } from '../../lib/scheduler'
import { fromResponseCacheEntry, toResponseCacheEntry } from './utils' import {
fromResponseCacheEntry,
routeKindToIncrementalCacheKind,
toResponseCacheEntry,
} from './utils'
import type { RouteKind } from '../route-kind'
export * from './types' export * from './types'
...@@ -49,7 +53,7 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -49,7 +53,7 @@ export default class ResponseCache implements ResponseCacheBase {
key: string | null, key: string | null,
responseGenerator: ResponseGenerator, responseGenerator: ResponseGenerator,
context: { context: {
routeKind?: RouteKind routeKind: RouteKind
isOnDemandRevalidate?: boolean isOnDemandRevalidate?: boolean
isPrefetch?: boolean isPrefetch?: boolean
incrementalCache: IncrementalCache incrementalCache: IncrementalCache
...@@ -76,28 +80,20 @@ export default class ResponseCache implements ResponseCacheBase { ...@@ -76,28 +80,20 @@ export default class ResponseCache implements ResponseCacheBase {
} }
// Coerce the kindHint into a given kind for the incremental cache. // Coerce the kindHint into a given kind for the incremental cache.
let kindHint: IncrementalCacheKindHint | undefined const kind = routeKindToIncrementalCacheKind(context.routeKind)
if (
context.routeKind === RouteKind.APP_PAGE ||
context.routeKind === RouteKind.APP_ROUTE
) {
kindHint = 'app'
} else if (context.routeKind === RouteKind.PAGES) {
kindHint = 'pages'
}
let resolved = false let resolved = false
let cachedResponse: IncrementalCacheItem = null let cachedResponse: IncrementalCacheItem = null
try { try {
cachedResponse = !this.minimalMode cachedResponse = !this.minimalMode
? await incrementalCache.get(key, { ? await incrementalCache.get(key, {
kindHint, kind,
isRoutePPREnabled: context.isRoutePPREnabled, isRoutePPREnabled: context.isRoutePPREnabled,
}) })
: null : null
if (cachedResponse && !isOnDemandRevalidate) { if (cachedResponse && !isOnDemandRevalidate) {
if (cachedResponse.value?.kind === 'FETCH') { if (cachedResponse.value?.kind === CachedRouteKind.FETCH) {
throw new Error( throw new Error(
`invariant: unexpected cachedResponse of kind fetch in response cache` `invariant: unexpected cachedResponse of kind fetch in response cache`
) )
......
...@@ -16,7 +16,7 @@ export interface ResponseCacheBase { ...@@ -16,7 +16,7 @@ export interface ResponseCacheBase {
* this is so it knows where to look up the cache entry from. If not * this is so it knows where to look up the cache entry from. If not
* provided it will test the filesystem to check. * provided it will test the filesystem to check.
*/ */
routeKind?: RouteKind routeKind: RouteKind
isRoutePPREnabled?: boolean isRoutePPREnabled?: boolean
} }
...@@ -37,8 +37,17 @@ export type CachedFetchData = { ...@@ -37,8 +37,17 @@ export type CachedFetchData = {
status?: number status?: number
} }
export const enum CachedRouteKind {
APP_PAGE = 'APP_PAGE',
APP_ROUTE = 'APP_ROUTE',
PAGES = 'PAGES',
FETCH = 'FETCH',
REDIRECT = 'REDIRECT',
IMAGE = 'IMAGE',
}
export interface CachedFetchValue { export interface CachedFetchValue {
kind: 'FETCH' kind: CachedRouteKind.FETCH
data: CachedFetchData data: CachedFetchData
// tags are only present with file-system-cache // tags are only present with file-system-cache
// fetch cache stores tags outside of cache entry // fetch cache stores tags outside of cache entry
...@@ -47,12 +56,12 @@ export interface CachedFetchValue { ...@@ -47,12 +56,12 @@ export interface CachedFetchValue {
} }
export interface CachedRedirectValue { export interface CachedRedirectValue {
kind: 'REDIRECT' kind: CachedRouteKind.REDIRECT
props: Object props: Object
} }
export interface CachedAppPageValue { export interface CachedAppPageValue {
kind: 'APP_PAGE' kind: CachedRouteKind.APP_PAGE
// this needs to be a RenderResult so since renderResponse // this needs to be a RenderResult so since renderResponse
// expects that type instead of a string // expects that type instead of a string
html: RenderResult html: RenderResult
...@@ -63,7 +72,7 @@ export interface CachedAppPageValue { ...@@ -63,7 +72,7 @@ export interface CachedAppPageValue {
} }
export interface CachedPageValue { export interface CachedPageValue {
kind: 'PAGE' kind: CachedRouteKind.PAGES
// this needs to be a RenderResult so since renderResponse // this needs to be a RenderResult so since renderResponse
// expects that type instead of a string // expects that type instead of a string
html: RenderResult html: RenderResult
...@@ -73,7 +82,7 @@ export interface CachedPageValue { ...@@ -73,7 +82,7 @@ export interface CachedPageValue {
} }
export interface CachedRouteValue { export interface CachedRouteValue {
kind: 'ROUTE' kind: CachedRouteKind.APP_ROUTE
// this needs to be a RenderResult so since renderResponse // this needs to be a RenderResult so since renderResponse
// expects that type instead of a string // expects that type instead of a string
body: Buffer body: Buffer
...@@ -82,7 +91,7 @@ export interface CachedRouteValue { ...@@ -82,7 +91,7 @@ export interface CachedRouteValue {
} }
export interface CachedImageValue { export interface CachedImageValue {
kind: 'IMAGE' kind: CachedRouteKind.IMAGE
etag: string etag: string
buffer: Buffer buffer: Buffer
extension: string extension: string
...@@ -91,7 +100,7 @@ export interface CachedImageValue { ...@@ -91,7 +100,7 @@ export interface CachedImageValue {
} }
export interface IncrementalCachedAppPageValue { export interface IncrementalCachedAppPageValue {
kind: 'APP_PAGE' kind: CachedRouteKind.APP_PAGE
// this needs to be a string since the cache expects to store // this needs to be a string since the cache expects to store
// the string value // the string value
html: string html: string
...@@ -102,7 +111,7 @@ export interface IncrementalCachedAppPageValue { ...@@ -102,7 +111,7 @@ export interface IncrementalCachedAppPageValue {
} }
export interface IncrementalCachedPageValue { export interface IncrementalCachedPageValue {
kind: 'PAGE' kind: CachedRouteKind.PAGES
// this needs to be a string since the cache expects to store // this needs to be a string since the cache expects to store
// the string value // the string value
html: string html: string
...@@ -161,17 +170,19 @@ export type IncrementalCacheItem = { ...@@ -161,17 +170,19 @@ export type IncrementalCacheItem = {
isMiss?: boolean isMiss?: boolean
} | null } | null
export type IncrementalCacheKindHint = 'app' | 'pages' | 'fetch' export const enum IncrementalCacheKind {
APP_PAGE = 'APP_PAGE',
APP_ROUTE = 'APP_ROUTE',
PAGES = 'PAGES',
FETCH = 'FETCH',
IMAGE = 'IMAGE',
}
export interface IncrementalCache { export interface IncrementalCache {
get: ( get: (
key: string, key: string,
ctx?: { ctx: {
/** kind: IncrementalCacheKind
* The kind of cache entry to get. If not provided it will try to
* determine the kind from the filesystem.
*/
kindHint?: IncrementalCacheKindHint
isRoutePPREnabled?: boolean isRoutePPREnabled?: boolean
} }
......
import type { IncrementalCacheItem, ResponseCacheEntry } from './types' import {
CachedRouteKind,
IncrementalCacheKind,
type CachedAppPageValue,
type CachedPageValue,
type IncrementalCacheItem,
type ResponseCacheEntry,
} from './types'
import RenderResult from '../render-result' import RenderResult from '../render-result'
import { RouteKind } from '../route-kind'
export async function fromResponseCacheEntry( export async function fromResponseCacheEntry(
cacheEntry: ResponseCacheEntry cacheEntry: ResponseCacheEntry
...@@ -8,17 +16,17 @@ export async function fromResponseCacheEntry( ...@@ -8,17 +16,17 @@ export async function fromResponseCacheEntry(
return { return {
...cacheEntry, ...cacheEntry,
value: value:
cacheEntry.value?.kind === 'PAGE' cacheEntry.value?.kind === CachedRouteKind.PAGES
? { ? {
kind: 'PAGE', kind: CachedRouteKind.PAGES,
html: await cacheEntry.value.html.toUnchunkedString(true), html: await cacheEntry.value.html.toUnchunkedString(true),
pageData: cacheEntry.value.pageData, pageData: cacheEntry.value.pageData,
headers: cacheEntry.value.headers, headers: cacheEntry.value.headers,
status: cacheEntry.value.status, status: cacheEntry.value.status,
} }
: cacheEntry.value?.kind === 'APP_PAGE' : cacheEntry.value?.kind === CachedRouteKind.APP_PAGE
? { ? {
kind: 'APP_PAGE', kind: CachedRouteKind.APP_PAGE,
html: await cacheEntry.value.html.toUnchunkedString(true), html: await cacheEntry.value.html.toUnchunkedString(true),
postponed: cacheEntry.value.postponed, postponed: cacheEntry.value.postponed,
rscData: cacheEntry.value.rscData, rscData: cacheEntry.value.rscData,
...@@ -34,7 +42,7 @@ export async function toResponseCacheEntry( ...@@ -34,7 +42,7 @@ export async function toResponseCacheEntry(
): Promise<ResponseCacheEntry | null> { ): Promise<ResponseCacheEntry | null> {
if (!response) return null if (!response) return null
if (response.value?.kind === 'FETCH') { if (response.value?.kind === CachedRouteKind.FETCH) {
throw new Error( throw new Error(
'Invariant: unexpected cachedResponse of kind fetch in response cache' 'Invariant: unexpected cachedResponse of kind fetch in response cache'
) )
...@@ -45,23 +53,40 @@ export async function toResponseCacheEntry( ...@@ -45,23 +53,40 @@ export async function toResponseCacheEntry(
isStale: response.isStale, isStale: response.isStale,
revalidate: response.revalidate, revalidate: response.revalidate,
value: value:
response.value?.kind === 'PAGE' response.value?.kind === CachedRouteKind.PAGES
? { ? ({
kind: 'PAGE', kind: CachedRouteKind.PAGES,
html: RenderResult.fromStatic(response.value.html), html: RenderResult.fromStatic(response.value.html),
pageData: response.value.pageData, pageData: response.value.pageData,
headers: response.value.headers, headers: response.value.headers,
status: response.value.status, status: response.value.status,
} } satisfies CachedPageValue)
: response.value?.kind === 'APP_PAGE' : response.value?.kind === CachedRouteKind.APP_PAGE
? { ? ({
kind: 'APP_PAGE', kind: CachedRouteKind.APP_PAGE,
html: RenderResult.fromStatic(response.value.html), html: RenderResult.fromStatic(response.value.html),
rscData: response.value.rscData, rscData: response.value.rscData,
headers: response.value.headers, headers: response.value.headers,
status: response.value.status, status: response.value.status,
postponed: response.value.postponed, postponed: response.value.postponed,
} } satisfies CachedAppPageValue)
: response.value, : response.value,
} }
} }
export function routeKindToIncrementalCacheKind(
routeKind: RouteKind
): IncrementalCacheKind {
switch (routeKind) {
case RouteKind.PAGES:
return IncrementalCacheKind.PAGES
case RouteKind.APP_PAGE:
return IncrementalCacheKind.APP_PAGE
case RouteKind.IMAGE:
return IncrementalCacheKind.IMAGE
case RouteKind.APP_ROUTE:
return IncrementalCacheKind.APP_ROUTE
default:
throw new Error(`Unexpected route kind ${routeKind}`)
}
}
...@@ -17,4 +17,9 @@ export const enum RouteKind { ...@@ -17,4 +17,9 @@ export const enum RouteKind {
* filename of `route.{j,t}s{,x}`. * filename of `route.{j,t}s{,x}`.
*/ */
APP_ROUTE = 'APP_ROUTE', APP_ROUTE = 'APP_ROUTE',
/**
* `IMAGE` represents all the images that are generated by `next/image`.
*/
IMAGE = 'IMAGE',
} }
...@@ -81,8 +81,6 @@ export default class NextWebServer extends BaseServer< ...@@ -81,8 +81,6 @@ export default class NextWebServer extends BaseServer<
dev, dev,
requestHeaders, requestHeaders,
requestProtocol: 'https', requestProtocol: 'https',
pagesDir: this.enabledDirectories.pages,
appDir: this.enabledDirectories.app,
allowedRevalidateHeaderKeys: allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys, this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode, minimalMode: this.minimalMode,
......
...@@ -8,6 +8,11 @@ import { ...@@ -8,6 +8,11 @@ import {
} from '../../lib/patch-fetch' } from '../../lib/patch-fetch'
import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external' import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external'
import { requestAsyncStorage } from '../../../client/components/request-async-storage.external' import { requestAsyncStorage } from '../../../client/components/request-async-storage.external'
import {
CachedRouteKind,
IncrementalCacheKind,
type CachedFetchData,
} from '../../response-cache'
type Callback = (...args: any[]) => Promise<any> type Callback = (...args: any[]) => Promise<any>
...@@ -25,14 +30,14 @@ async function cacheNewResult<T>( ...@@ -25,14 +30,14 @@ async function cacheNewResult<T>(
await incrementalCache.set( await incrementalCache.set(
cacheKey, cacheKey,
{ {
kind: 'FETCH', kind: CachedRouteKind.FETCH,
data: { data: {
headers: {}, headers: {},
// TODO: handle non-JSON values? // TODO: handle non-JSON values?
body: JSON.stringify(result), body: JSON.stringify(result),
status: 200, status: 200,
url: '', url: '',
}, } satisfies CachedFetchData,
revalidate: typeof revalidate !== 'number' ? CACHE_ONE_YEAR : revalidate, revalidate: typeof revalidate !== 'number' ? CACHE_ONE_YEAR : revalidate,
}, },
{ {
...@@ -185,7 +190,7 @@ export function unstable_cache<T extends Callback>( ...@@ -185,7 +190,7 @@ export function unstable_cache<T extends Callback>(
) { ) {
// We attempt to get the current cache entry from the incremental cache. // We attempt to get the current cache entry from the incremental cache.
const cacheEntry = await incrementalCache.get(cacheKey, { const cacheEntry = await incrementalCache.get(cacheKey, {
kindHint: 'fetch', kind: IncrementalCacheKind.FETCH,
revalidate: options.revalidate, revalidate: options.revalidate,
tags, tags,
softTags: implicitTags, softTags: implicitTags,
...@@ -195,7 +200,7 @@ export function unstable_cache<T extends Callback>( ...@@ -195,7 +200,7 @@ export function unstable_cache<T extends Callback>(
if (cacheEntry && cacheEntry.value) { if (cacheEntry && cacheEntry.value) {
// The entry exists and has a value // The entry exists and has a value
if (cacheEntry.value.kind !== 'FETCH') { if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {
// The entry is invalid and we need a special warning // The entry is invalid and we need a special warning
// @TODO why do we warn this way? Should this just be an error? How are these errors surfaced // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced
// so bugs can be reported // so bugs can be reported
...@@ -298,7 +303,7 @@ export function unstable_cache<T extends Callback>( ...@@ -298,7 +303,7 @@ export function unstable_cache<T extends Callback>(
addImplicitTags(staticGenerationStore, requestStore) addImplicitTags(staticGenerationStore, requestStore)
const cacheEntry = await incrementalCache.get(cacheKey, { const cacheEntry = await incrementalCache.get(cacheKey, {
kindHint: 'fetch', kind: IncrementalCacheKind.FETCH,
revalidate: options.revalidate, revalidate: options.revalidate,
tags, tags,
fetchIdx, fetchIdx,
...@@ -308,7 +313,7 @@ export function unstable_cache<T extends Callback>( ...@@ -308,7 +313,7 @@ export function unstable_cache<T extends Callback>(
if (cacheEntry && cacheEntry.value) { if (cacheEntry && cacheEntry.value) {
// The entry exists and has a value // The entry exists and has a value
if (cacheEntry.value.kind !== 'FETCH') { if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {
// The entry is invalid and we need a special warning // The entry is invalid and we need a special warning
// @TODO why do we warn this way? Should this just be an error? How are these errors surfaced // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced
// so bugs can be reported // so bugs can be reported
......
...@@ -2,14 +2,16 @@ import { promises as fs } from 'node:fs' ...@@ -2,14 +2,16 @@ import { promises as fs } from 'node:fs'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
import FileSystemCache from 'next/dist/server/lib/incremental-cache/file-system-cache' import FileSystemCache from 'next/dist/server/lib/incremental-cache/file-system-cache'
import { nodeFs } from 'next/dist/server/lib/node-fs-methods' import { nodeFs } from 'next/dist/server/lib/node-fs-methods'
import {
CachedRouteKind,
IncrementalCacheKind,
} from 'next/dist/server/response-cache'
const cacheDir = fileURLToPath(new URL('./cache', import.meta.url)) const cacheDir = fileURLToPath(new URL('./cache', import.meta.url))
describe('FileSystemCache', () => { describe('FileSystemCache', () => {
it('set image route', async () => { it('set image route', async () => {
const fsCache = new FileSystemCache({ const fsCache = new FileSystemCache({
_appDir: true,
_pagesDir: true,
_requestHeaders: {}, _requestHeaders: {},
flushToDisk: true, flushToDisk: true,
fs: nodeFs, fs: nodeFs,
...@@ -29,26 +31,30 @@ describe('FileSystemCache', () => { ...@@ -29,26 +31,30 @@ describe('FileSystemCache', () => {
'Content-Type': 'image/png', 'Content-Type': 'image/png',
}, },
status: 200, status: 200,
kind: 'ROUTE', kind: CachedRouteKind.APP_ROUTE,
}, },
{} {}
) )
expect((await fsCache.get('icon.png'))?.value).toEqual({ expect(
(
await fsCache.get('icon.png', {
kind: IncrementalCacheKind.APP_ROUTE,
})
)?.value
).toEqual({
body: binary, body: binary,
headers: { headers: {
'Content-Type': 'image/png', 'Content-Type': 'image/png',
}, },
status: 200, status: 200,
kind: 'ROUTE', kind: IncrementalCacheKind.APP_ROUTE,
}) })
}) })
}) })
describe('FileSystemCache (isrMemory 0)', () => { describe('FileSystemCache (isrMemory 0)', () => {
const fsCache = new FileSystemCache({ const fsCache = new FileSystemCache({
_appDir: true,
_pagesDir: true,
_requestHeaders: {}, _requestHeaders: {},
flushToDisk: true, flushToDisk: true,
fs: nodeFs, fs: nodeFs,
...@@ -61,7 +67,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -61,7 +67,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
await fsCache.set( await fsCache.set(
'fetch-cache', 'fetch-cache',
{ {
kind: 'FETCH', kind: CachedRouteKind.FETCH,
data: { data: {
headers: {}, headers: {},
body: 'MTcwMDA1NjM4MQ==', body: 'MTcwMDA1NjM4MQ==',
...@@ -81,7 +87,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -81,7 +87,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
const res = await fsCache.get('fetch-cache', { const res = await fsCache.get('fetch-cache', {
tags: ['server-time'], tags: ['server-time'],
kindHint: 'fetch', kind: IncrementalCacheKind.FETCH,
}) })
expect(res?.value).toEqual({ expect(res?.value).toEqual({
...@@ -101,7 +107,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -101,7 +107,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
await fsCache.set( await fsCache.set(
'unstable-cache', 'unstable-cache',
{ {
kind: 'FETCH', kind: CachedRouteKind.FETCH,
data: { headers: {}, body: '1700056381', status: 200, url: '' }, data: { headers: {}, body: '1700056381', status: 200, url: '' },
revalidate: 30, revalidate: 30,
}, },
...@@ -110,7 +116,7 @@ describe('FileSystemCache (isrMemory 0)', () => { ...@@ -110,7 +116,7 @@ describe('FileSystemCache (isrMemory 0)', () => {
const res = await fsCache.get('unstable-cache', { const res = await fsCache.get('unstable-cache', {
tags: ['server-time'], tags: ['server-time'],
kindHint: 'fetch', kind: IncrementalCacheKind.FETCH,
}) })
expect(res?.value).toEqual({ expect(res?.value).toEqual({
......
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