Unverified Commit 4c7a31a7 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Refactor: move `"use cache"` revalidation logic out of incremental cache (#77577)

The `revalidateTag` method of the incremental cache should not also handle the revalidation for the `"use cache"` cache handlers.

This PR relocates those bits to the revalidation utils module, which was previously used for `after`, and has now been lifted one level up.

There should be no behavioral change in this refactoring.
parent c4d94ee1
...@@ -4,7 +4,7 @@ import type { AfterCallback, AfterTask } from './after' ...@@ -4,7 +4,7 @@ import type { AfterCallback, AfterTask } from './after'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { isThenable } from '../../shared/lib/is-thenable' import { isThenable } from '../../shared/lib/is-thenable'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { withExecuteRevalidates } from './revalidation-utils' import { withExecuteRevalidates } from '../revalidation-utils'
import { bindSnapshot } from '../app-render/async-local-storage' import { bindSnapshot } from '../app-render/async-local-storage'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
......
...@@ -49,6 +49,7 @@ import { synchronizeMutableCookies } from '../async-storage/request-store' ...@@ -49,6 +49,7 @@ import { synchronizeMutableCookies } from '../async-storage/request-store'
import type { TemporaryReferenceSet } from 'react-server-dom-webpack/server.edge' import type { TemporaryReferenceSet } from 'react-server-dom-webpack/server.edge'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { executeRevalidates } from '../revalidation-utils'
function formDataFromSearchQueryString(query: string) { function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query) const searchParams = new URLSearchParams(query)
...@@ -517,15 +518,7 @@ export async function handleAction({ ...@@ -517,15 +518,7 @@ export async function handleAction({
requestStore.phase = 'action' requestStore.phase = 'action'
const resolvePendingRevalidations = async () => const resolvePendingRevalidations = async () =>
workUnitAsyncStorage.run(requestStore, () => workUnitAsyncStorage.run(requestStore, () => executeRevalidates(workStore))
Promise.all([
workStore.incrementalCache?.revalidateTag(
workStore.pendingRevalidatedTags || []
),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
])
)
// When running actions the default is no-store, you can still `cache: 'force-cache'` // When running actions the default is no-store, you can still `cache: 'force-cache'`
workStore.fetchCache = 'default-no-store' workStore.fetchCache = 'default-no-store'
......
...@@ -187,6 +187,7 @@ import isError from '../../lib/is-error' ...@@ -187,6 +187,7 @@ import isError from '../../lib/is-error'
import { isUseCacheTimeoutError } from '../use-cache/use-cache-errors' import { isUseCacheTimeoutError } from '../use-cache/use-cache-errors'
import { createServerInsertedMetadata } from './metadata-insertion/create-server-inserted-metadata' import { createServerInsertedMetadata } from './metadata-insertion/create-server-inserted-metadata'
import { getPreviouslyRevalidatedTags } from '../server-utils' import { getPreviouslyRevalidatedTags } from '../server-utils'
import { executeRevalidates } from '../revalidation-utils'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -1413,13 +1414,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1413,13 +1414,7 @@ async function renderToHTMLOrFlightImpl(
workStore.pendingRevalidateWrites || workStore.pendingRevalidateWrites ||
workStore.pendingRevalidatedTags workStore.pendingRevalidatedTags
) { ) {
const pendingPromise = Promise.all([ const pendingPromise = executeRevalidates(workStore).finally(() => {
workStore.incrementalCache?.revalidateTag(
workStore.pendingRevalidatedTags || []
),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
]).finally(() => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.log('pending revalidates promise finished for:', url) console.log('pending revalidates promise finished for:', url)
} }
...@@ -1588,13 +1583,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1588,13 +1583,7 @@ async function renderToHTMLOrFlightImpl(
workStore.pendingRevalidateWrites || workStore.pendingRevalidateWrites ||
workStore.pendingRevalidatedTags workStore.pendingRevalidatedTags
) { ) {
const pendingPromise = Promise.all([ const pendingPromise = executeRevalidates(workStore).finally(() => {
workStore.incrementalCache?.revalidateTag(
workStore.pendingRevalidatedTags || []
),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
]).finally(() => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.log('pending revalidates promise finished for:', url) console.log('pending revalidates promise finished for:', url)
} }
......
...@@ -30,10 +30,8 @@ import { ...@@ -30,10 +30,8 @@ import {
getRenderResumeDataCache, getRenderResumeDataCache,
workUnitAsyncStorage, workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external' } from '../../app-render/work-unit-async-storage.external'
import { getCacheHandlers } from '../../use-cache/handlers'
import { InvariantError } from '../../../shared/lib/invariant-error' import { InvariantError } from '../../../shared/lib/invariant-error'
import type { Revalidate } from '../cache-control' import type { Revalidate } from '../cache-control'
import { updateImplicitTagsExpiration } from '../implicit-tags'
import { getPreviouslyRevalidatedTags } from '../../server-utils' import { getPreviouslyRevalidatedTags } from '../../server-utils'
import { workAsyncStorage } from '../../app-render/work-async-storage.external' import { workAsyncStorage } from '../../app-render/work-async-storage.external'
...@@ -260,36 +258,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -260,36 +258,7 @@ export class IncrementalCache implements IncrementalCacheType {
} }
async revalidateTag(tags: string | string[]): Promise<void> { async revalidateTag(tags: string | string[]): Promise<void> {
tags = Array.isArray(tags) ? tags : [tags] return this.cacheHandler?.revalidateTag(tags)
if (tags.length === 0) {
return
}
const promises: Promise<void>[] = []
if (this.cacheHandler?.revalidateTag) {
promises.push(this.cacheHandler.revalidateTag(tags))
}
const handlers = getCacheHandlers()
if (handlers) {
for (const handler of handlers) {
promises.push(handler.expireTags(...tags))
}
}
await Promise.all(promises)
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore?.implicitTags) {
const tagsSet = new Set(tags)
if (workUnitStore.implicitTags.tags.some((tag) => tagsSet.has(tag))) {
await updateImplicitTagsExpiration(workUnitStore.implicitTags)
}
}
} }
// 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
......
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from './app-render/work-async-storage.external'
import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'
import { updateImplicitTagsExpiration } from './lib/implicit-tags'
import type { IncrementalCache } from './lib/incremental-cache'
import { getCacheHandlers } from './use-cache/handlers'
/** Run a callback, and execute any *new* revalidations added during its runtime. */ /** Run a callback, and execute any *new* revalidations added during its runtime. */
export async function withExecuteRevalidates<T>( export async function withExecuteRevalidates<T>(
...@@ -63,16 +67,55 @@ function diffRevalidationState( ...@@ -63,16 +67,55 @@ function diffRevalidationState(
} }
} }
async function executeRevalidates( async function revalidateTags(
tags: string[],
incrementalCache: IncrementalCache | undefined
): Promise<void> {
if (tags.length === 0) {
return
}
const promises: Promise<void>[] = []
if (incrementalCache) {
promises.push(incrementalCache.revalidateTag(tags))
}
const handlers = getCacheHandlers()
if (handlers) {
for (const handler of handlers) {
promises.push(handler.expireTags(...tags))
}
}
await Promise.all(promises)
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore?.implicitTags) {
const tagsSet = new Set(tags)
if (workUnitStore.implicitTags.tags.some((tag) => tagsSet.has(tag))) {
await updateImplicitTagsExpiration(workUnitStore.implicitTags)
}
}
}
export async function executeRevalidates(
workStore: WorkStore, workStore: WorkStore,
{ state?: RevalidationState
pendingRevalidatedTags,
pendingRevalidates,
pendingRevalidateWrites,
}: RevalidationState
) { ) {
const pendingRevalidatedTags =
state?.pendingRevalidatedTags ?? workStore.pendingRevalidatedTags ?? []
const pendingRevalidates =
state?.pendingRevalidates ?? workStore.pendingRevalidates ?? {}
const pendingRevalidateWrites =
state?.pendingRevalidateWrites ?? workStore.pendingRevalidateWrites ?? []
return Promise.all([ return Promise.all([
workStore.incrementalCache?.revalidateTag(pendingRevalidatedTags), revalidateTags(pendingRevalidatedTags, workStore.incrementalCache),
...Object.values(pendingRevalidates), ...Object.values(pendingRevalidates),
...pendingRevalidateWrites, ...pendingRevalidateWrites,
]) ])
......
...@@ -82,6 +82,7 @@ import { ...@@ -82,6 +82,7 @@ import {
} from '../../../client/components/http-access-fallback/http-access-fallback' } from '../../../client/components/http-access-fallback/http-access-fallback'
import { RedirectStatusCode } from '../../../client/components/redirect-status-code' import { RedirectStatusCode } from '../../../client/components/redirect-status-code'
import { INFINITE_CACHE } from '../../../lib/constants' import { INFINITE_CACHE } from '../../../lib/constants'
import { executeRevalidates } from '../../revalidation-utils'
export class WrappedNextRouterError { export class WrappedNextRouterError {
constructor( constructor(
...@@ -323,13 +324,9 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -323,13 +324,9 @@ export class AppRouteRouteModule extends RouteModule<
} }
const resolvePendingRevalidations = () => { const resolvePendingRevalidations = () => {
context.renderOpts.pendingWaitUntil = Promise.all([ context.renderOpts.pendingWaitUntil = executeRevalidates(
workStore.incrementalCache?.revalidateTag( workStore
workStore.pendingRevalidatedTags || [] ).finally(() => {
),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
]).finally(() => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.log( console.log(
'pending revalidates promise finished for:', 'pending revalidates promise finished for:',
......
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