Unverified Commit 0bf6c279 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update tags handling during server action redirect (#49227)

Updates the tag handling during a server action direct to pass through
the revalidated tags for immediate revalidation as discussed.

x-ref: [slack
thread](https://vercel.slack.com/archives/C042LHPJ1NX/p1683218335368759)
parent bf49f62c
...@@ -31,6 +31,8 @@ export interface StaticGenerationStore { ...@@ -31,6 +31,8 @@ export interface StaticGenerationStore {
pathWasRevalidated?: boolean pathWasRevalidated?: boolean
tags?: string[] tags?: string[]
revalidatedTags?: string[]
fetchMetrics?: Array<{ fetchMetrics?: Array<{
url: string url: string
idx: number idx: number
......
...@@ -142,6 +142,18 @@ async function createRedirectRenderResult( ...@@ -142,6 +142,18 @@ async function createRedirectRenderResult(
staticGenerationStore.incrementalCache?.requestProtocol || 'https' staticGenerationStore.incrementalCache?.requestProtocol || 'https'
const fetchUrl = new URL(`${proto}://${host}${redirectUrl}`) const fetchUrl = new URL(`${proto}://${host}${redirectUrl}`)
if (staticGenerationStore.revalidatedTags) {
forwardedHeaders.set(
'x-next-revalidated-tags',
staticGenerationStore.revalidatedTags.join(',')
)
forwardedHeaders.set(
'x-next-revalidate-tag-token',
staticGenerationStore.incrementalCache?.prerenderManifest?.preview
?.previewModeId || ''
)
}
try { try {
const headResponse = await fetchIPv4v6(fetchUrl, { const headResponse = await fetchIPv4v6(fetchUrl, {
method: 'HEAD', method: 'HEAD',
......
...@@ -2,6 +2,7 @@ import LRUCache from 'next/dist/compiled/lru-cache' ...@@ -2,6 +2,7 @@ import LRUCache from 'next/dist/compiled/lru-cache'
import { FETCH_CACHE_HEADER } from '../../../client/components/app-router-headers' import { FETCH_CACHE_HEADER } from '../../../client/components/app-router-headers'
import { CACHE_ONE_YEAR } from '../../../lib/constants' import { CACHE_ONE_YEAR } from '../../../lib/constants'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './' import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
import { getDerivedTags } from './utils'
let memoryCache: LRUCache<string, CacheHandlerValue> | undefined let memoryCache: LRUCache<string, CacheHandlerValue> | undefined
...@@ -16,10 +17,12 @@ export default class FetchCache implements CacheHandler { ...@@ -16,10 +17,12 @@ export default class FetchCache implements CacheHandler {
private headers: Record<string, string> private headers: Record<string, string>
private cacheEndpoint?: string private cacheEndpoint?: string
private debug: boolean private debug: boolean
private revalidatedTags: string[]
constructor(ctx: CacheHandlerContext) { constructor(ctx: CacheHandlerContext) {
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
this.headers = {} this.headers = {}
this.revalidatedTags = ctx.revalidatedTags
this.headers['Content-Type'] = 'application/json' this.headers['Content-Type'] = 'application/json'
if (FETCH_CACHE_HEADER in ctx._requestHeaders) { if (FETCH_CACHE_HEADER in ctx._requestHeaders) {
...@@ -189,6 +192,21 @@ export default class FetchCache implements CacheHandler { ...@@ -189,6 +192,21 @@ export default class FetchCache implements CacheHandler {
} }
} }
} }
// if a tag was revalidated we don't return stale data
if (data?.value?.kind === 'FETCH') {
const innerData = data.value.data
const derivedTags = getDerivedTags(innerData.tags || [])
if (
derivedTags.some((tag) => {
return this.revalidatedTags.includes(tag)
})
) {
data = undefined
}
}
return data || null return data || null
} }
......
...@@ -4,6 +4,7 @@ import LRUCache from 'next/dist/compiled/lru-cache' ...@@ -4,6 +4,7 @@ import LRUCache from 'next/dist/compiled/lru-cache'
import { CacheFs } from '../../../shared/lib/utils' import { CacheFs } from '../../../shared/lib/utils'
import path from '../../../shared/lib/isomorphic/path' import path from '../../../shared/lib/isomorphic/path'
import { CachedFetchValue } from '../../response-cache' import { CachedFetchValue } from '../../response-cache'
import { getDerivedTags } from './utils'
type FileSystemCacheContext = Omit< type FileSystemCacheContext = Omit<
CacheHandlerContext, CacheHandlerContext,
...@@ -26,12 +27,14 @@ export default class FileSystemCache implements CacheHandler { ...@@ -26,12 +27,14 @@ export default class FileSystemCache implements CacheHandler {
private serverDistDir: FileSystemCacheContext['serverDistDir'] private serverDistDir: FileSystemCacheContext['serverDistDir']
private appDir: boolean private appDir: boolean
private tagsManifestPath?: string private tagsManifestPath?: string
private revalidatedTags: string[]
constructor(ctx: FileSystemCacheContext) { constructor(ctx: FileSystemCacheContext) {
this.fs = ctx.fs this.fs = ctx.fs
this.flushToDisk = ctx.flushToDisk this.flushToDisk = ctx.flushToDisk
this.serverDistDir = ctx.serverDistDir this.serverDistDir = ctx.serverDistDir
this.appDir = !!ctx._appDir this.appDir = !!ctx._appDir
this.revalidatedTags = ctx.revalidatedTags
if (ctx.maxMemoryCacheSize && !memoryCache) { if (ctx.maxMemoryCacheSize && !memoryCache) {
memoryCache = new LRUCache({ memoryCache = new LRUCache({
...@@ -241,33 +244,6 @@ export default class FileSystemCache implements CacheHandler { ...@@ -241,33 +244,6 @@ export default class FileSystemCache implements CacheHandler {
} }
} }
const getDerivedTags = (tags: string[]): string[] => {
const derivedTags: string[] = ['/']
for (const tag of tags || []) {
if (tag.startsWith('/')) {
const pathnameParts = tag.split('/')
// we automatically add the current path segments as tags
// for revalidatePath handling
for (let i = 1; i < pathnameParts.length + 1; i++) {
const curPathname = pathnameParts.slice(0, i).join('/')
if (curPathname) {
derivedTags.push(curPathname)
if (!derivedTags.includes(curPathname)) {
derivedTags.push(curPathname)
}
}
}
} else if (!derivedTags.includes(tag)) {
derivedTags.push(tag)
}
}
return derivedTags
}
if (data?.value?.kind === 'PAGE' && cacheTags?.length) { if (data?.value?.kind === 'PAGE' && cacheTags?.length) {
this.loadTagsManifest() this.loadTagsManifest()
const derivedTags = getDerivedTags(cacheTags || []) const derivedTags = getDerivedTags(cacheTags || [])
...@@ -290,6 +266,10 @@ export default class FileSystemCache implements CacheHandler { ...@@ -290,6 +266,10 @@ export default class FileSystemCache implements CacheHandler {
const derivedTags = getDerivedTags(innerData.tags || []) const derivedTags = getDerivedTags(innerData.tags || [])
const wasRevalidated = derivedTags.some((tag) => { const wasRevalidated = derivedTags.some((tag) => {
if (this.revalidatedTags.includes(tag)) {
return true
}
return ( return (
tagsManifest?.items[tag]?.revalidatedAt && tagsManifest?.items[tag]?.revalidatedAt &&
tagsManifest?.items[tag].revalidatedAt >= tagsManifest?.items[tag].revalidatedAt >=
......
...@@ -24,6 +24,7 @@ export interface CacheHandlerContext { ...@@ -24,6 +24,7 @@ export interface CacheHandlerContext {
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest prerenderManifest?: PrerenderManifest
revalidatedTags: string[]
_appDir: boolean _appDir: boolean
_requestHeaders: IncrementalCache['requestHeaders'] _requestHeaders: IncrementalCache['requestHeaders']
} }
...@@ -68,6 +69,7 @@ export class IncrementalCache { ...@@ -68,6 +69,7 @@ export class IncrementalCache {
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
minimalMode?: boolean minimalMode?: boolean
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
revalidatedTags?: string[]
constructor({ constructor({
fs, fs,
...@@ -120,6 +122,16 @@ export class IncrementalCache { ...@@ -120,6 +122,16 @@ export class IncrementalCache {
this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys
this.prerenderManifest = getPrerenderManifest() this.prerenderManifest = getPrerenderManifest()
this.fetchCacheKeyPrefix = fetchCacheKeyPrefix this.fetchCacheKeyPrefix = fetchCacheKeyPrefix
let revalidatedTags: string[] = []
if (
minimalMode &&
typeof requestHeaders['x-next-revalidated-tags'] === 'string' &&
requestHeaders['x-next-revalidats-tag-token'] ===
this.prerenderManifest?.preview?.previewModeId
) {
revalidatedTags = requestHeaders['x-next-revalidated-tags'].split(',')
}
if (CurCacheHandler) { if (CurCacheHandler) {
this.cacheHandler = new CurCacheHandler({ this.cacheHandler = new CurCacheHandler({
...@@ -127,6 +139,7 @@ export class IncrementalCache { ...@@ -127,6 +139,7 @@ export class IncrementalCache {
fs, fs,
flushToDisk, flushToDisk,
serverDistDir, serverDistDir,
revalidatedTags,
maxMemoryCacheSize, maxMemoryCacheSize,
_appDir: !!appDir, _appDir: !!appDir,
_requestHeaders: requestHeaders, _requestHeaders: requestHeaders,
......
export const getDerivedTags = (tags: string[]): string[] => {
const derivedTags: string[] = ['/']
for (const tag of tags || []) {
if (tag.startsWith('/')) {
const pathnameParts = tag.split('/')
// we automatically add the current path segments as tags
// for revalidatePath handling
for (let i = 1; i < pathnameParts.length + 1; i++) {
const curPathname = pathnameParts.slice(0, i).join('/')
if (curPathname) {
derivedTags.push(curPathname)
if (!derivedTags.includes(curPathname)) {
derivedTags.push(curPathname)
}
}
}
} else if (!derivedTags.includes(tag)) {
derivedTags.push(tag)
}
}
return derivedTags
}
...@@ -16,6 +16,12 @@ export function revalidateTag(tag: string) { ...@@ -16,6 +16,12 @@ export function revalidateTag(tag: string) {
`Invariant: static generation store missing in revalidateTag ${tag}` `Invariant: static generation store missing in revalidateTag ${tag}`
) )
} }
if (!store.revalidatedTags) {
store.revalidatedTags = []
}
if (!store.revalidatedTags.includes(tag)) {
store.revalidatedTags.push(tag)
}
if (!store.pendingRevalidates) { if (!store.pendingRevalidates) {
store.pendingRevalidates = [] store.pendingRevalidates = []
......
...@@ -13,6 +13,7 @@ describe('FileSystemCache', () => { ...@@ -13,6 +13,7 @@ describe('FileSystemCache', () => {
flushToDisk: true, flushToDisk: true,
fs: nodeFs, fs: nodeFs,
serverDistDir: cacheDir, serverDistDir: cacheDir,
revalidatedTags: [],
}) })
const binary = await fs.readFile( const binary = await fs.readFile(
......
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