Unverified Commit 025f5b6b authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update revalidateTag to batch tags in one request (#65296)

As discussed this collects all `revalidateTag` calls and invokes in a
single request to avoid race conditions and overhead from multiple
pending requests.

x-ref: [slack
thread](https://vercel.slack.com/archives/C0676QZBWKS/p1714688045037509?thread_ts=1710902198.529179&cid=C0676QZBWKS)

Closes NEXT-3306
parent ec74cd9c
...@@ -113,9 +113,12 @@ async function addRevalidationHeader( ...@@ -113,9 +113,12 @@ async function addRevalidationHeader(
requestStore: RequestStore requestStore: RequestStore
} }
) { ) {
await Promise.all( await Promise.all([
Object.values(staticGenerationStore.pendingRevalidates || []) staticGenerationStore.incrementalCache?.revalidateTag(
) staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
// If a tag was revalidated, the client router needs to invalidate all the // If a tag was revalidated, the client router needs to invalidate all the
// client router cache as they may be stale. And if a path was revalidated, the // client router cache as they may be stale. And if a path was revalidated, the
...@@ -480,9 +483,12 @@ export async function handleAction({ ...@@ -480,9 +483,12 @@ export async function handleAction({
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 res.statusCode = 500
await Promise.all( await Promise.all([
Object.values(staticGenerationStore.pendingRevalidates || []) staticGenerationStore.incrementalCache?.revalidateTag(
) staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
const promise = Promise.reject(error) const promise = Promise.reject(error)
try { try {
...@@ -867,9 +873,12 @@ export async function handleAction({ ...@@ -867,9 +873,12 @@ export async function handleAction({
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 res.statusCode = 500
await Promise.all( await Promise.all([
Object.values(staticGenerationStore.pendingRevalidates || []) staticGenerationStore.incrementalCache?.revalidateTag(
) staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
const promise = Promise.reject(err) const promise = Promise.reject(err)
try { try {
// we need to await the promise to trigger the rejection early // we need to await the promise to trigger the rejection early
......
...@@ -1374,9 +1374,12 @@ async function renderToHTMLOrFlightImpl( ...@@ -1374,9 +1374,12 @@ async function renderToHTMLOrFlightImpl(
// If we have pending revalidates, wait until they are all resolved. // If we have pending revalidates, wait until they are all resolved.
if (staticGenerationStore.pendingRevalidates) { if (staticGenerationStore.pendingRevalidates) {
options.waitUntil = Promise.all( options.waitUntil = Promise.all([
Object.values(staticGenerationStore.pendingRevalidates) staticGenerationStore.incrementalCache?.revalidateTag(
) staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
} }
addImplicitTags(staticGenerationStore) addImplicitTags(staticGenerationStore)
......
...@@ -395,11 +395,14 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -395,11 +395,14 @@ export class AppRouteRouteModule extends RouteModule<
context.renderOpts.fetchMetrics = context.renderOpts.fetchMetrics =
staticGenerationStore.fetchMetrics staticGenerationStore.fetchMetrics
context.renderOpts.waitUntil = Promise.all( context.renderOpts.waitUntil = Promise.all([
Object.values( staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.pendingRevalidates || [] staticGenerationStore.revalidatedTags || []
) ),
) ...Object.values(
staticGenerationStore.pendingRevalidates || {}
),
])
addImplicitTags(staticGenerationStore) addImplicitTags(staticGenerationStore)
;(context.renderOpts as any).fetchTags = ;(context.renderOpts as any).fetchTags =
......
...@@ -126,11 +126,17 @@ export default class FetchCache implements CacheHandler { ...@@ -126,11 +126,17 @@ export default class FetchCache implements CacheHandler {
memoryCache?.reset() memoryCache?.reset()
} }
public async revalidateTag(tag: string) { public async revalidateTag(
...args: Parameters<CacheHandler['revalidateTag']>
) {
let [tags] = args
tags = typeof tags === 'string' ? [tags] : tags
if (this.debug) { if (this.debug) {
console.log('revalidateTag', tag) console.log('revalidateTag', tags)
} }
if (!tags.length) return
if (Date.now() < rateLimitedUntil) { if (Date.now() < rateLimitedUntil) {
if (this.debug) { if (this.debug) {
console.log('rate limited ', rateLimitedUntil) console.log('rate limited ', rateLimitedUntil)
...@@ -140,9 +146,9 @@ export default class FetchCache implements CacheHandler { ...@@ -140,9 +146,9 @@ export default class FetchCache implements CacheHandler {
try { try {
const res = await fetch( const res = await fetch(
`${ `${this.cacheEndpoint}/v1/suspense-cache/revalidate?tags=${tags
this.cacheEndpoint .map((tag) => encodeURIComponent(tag))
}/v1/suspense-cache/revalidate?tags=${encodeURIComponent(tag)}`, .join(',')}`,
{ {
method: 'POST', method: 'POST',
headers: this.headers, headers: this.headers,
...@@ -160,7 +166,7 @@ export default class FetchCache implements CacheHandler { ...@@ -160,7 +166,7 @@ export default class FetchCache implements CacheHandler {
throw new Error(`Request failed with status ${res.status}.`) throw new Error(`Request failed with status ${res.status}.`)
} }
} catch (err) { } catch (err) {
console.warn(`Failed to revalidate tag ${tag}`, err) console.warn(`Failed to revalidate tag ${tags}`, err)
} }
} }
......
...@@ -105,9 +105,18 @@ export default class FileSystemCache implements CacheHandler { ...@@ -105,9 +105,18 @@ export default class FileSystemCache implements CacheHandler {
if (this.debug) console.log('loadTagsManifest', tagsManifest) if (this.debug) console.log('loadTagsManifest', tagsManifest)
} }
public async revalidateTag(tag: string) { public async revalidateTag(
...args: Parameters<CacheHandler['revalidateTag']>
) {
let [tags] = args
tags = typeof tags === 'string' ? [tags] : tags
if (this.debug) { if (this.debug) {
console.log('revalidateTag', tag) console.log('revalidateTag', tags)
}
if (tags.length === 0) {
return
} }
// we need to ensure the tagsManifest is refreshed // we need to ensure the tagsManifest is refreshed
...@@ -118,9 +127,11 @@ export default class FileSystemCache implements CacheHandler { ...@@ -118,9 +127,11 @@ export default class FileSystemCache implements CacheHandler {
return return
} }
const data = tagsManifest.items[tag] || {} for (const tag of tags) {
data.revalidatedAt = Date.now() const data = tagsManifest.items[tag] || {}
tagsManifest.items[tag] = data data.revalidatedAt = Date.now()
tagsManifest.items[tag] = data
}
try { try {
await this.fs.mkdir(path.dirname(this.tagsManifestPath)) await this.fs.mkdir(path.dirname(this.tagsManifestPath))
......
...@@ -58,7 +58,9 @@ export class CacheHandler { ...@@ -58,7 +58,9 @@ export class CacheHandler {
..._args: Parameters<IncrementalCache['set']> ..._args: Parameters<IncrementalCache['set']>
): Promise<void> {} ): Promise<void> {}
public async revalidateTag(_tag: string): Promise<void> {} public async revalidateTag(
..._args: Parameters<IncrementalCache['revalidateTag']>
): Promise<void> {}
public resetRequestCache(): void {} public resetRequestCache(): void {}
} }
...@@ -280,7 +282,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -280,7 +282,7 @@ export class IncrementalCache implements IncrementalCacheType {
return unlockNext return unlockNext
} }
async revalidateTag(tag: string) { async revalidateTag(tags: string | string[]): Promise<void> {
if ( if (
process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT && process.env.__NEXT_INCREMENTAL_CACHE_IPC_PORT &&
process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY && process.env.__NEXT_INCREMENTAL_CACHE_IPC_KEY &&
...@@ -296,7 +298,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -296,7 +298,7 @@ export class IncrementalCache implements IncrementalCacheType {
}) })
} }
return this.cacheHandler?.revalidateTag?.(tag) return this.cacheHandler?.revalidateTag?.(tags)
} }
// 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
......
...@@ -68,15 +68,6 @@ function revalidate(tag: string, expression: string) { ...@@ -68,15 +68,6 @@ function revalidate(tag: string, expression: string) {
store.revalidatedTags.push(tag) store.revalidatedTags.push(tag)
} }
if (!store.pendingRevalidates) {
store.pendingRevalidates = {}
}
store.pendingRevalidates[tag] = store.incrementalCache
.revalidateTag?.(tag)
.catch((err) => {
console.error(`revalidate failed for ${tag}`, err)
})
// TODO: only revalidate if the path matches // TODO: only revalidate if the path matches
store.pathWasRevalidated = true store.pathWasRevalidated = 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