| import type { IncrementalCache } from '../../lib/incremental-cache' |
|
|
| import { CACHE_ONE_YEAR } from '../../../lib/constants' |
| import { validateRevalidate, validateTags } from '../../lib/patch-fetch' |
| import { |
| workAsyncStorage, |
| type WorkStore, |
| } from '../../app-render/work-async-storage.external' |
| import { |
| getCacheSignal, |
| getDraftModeProviderForCacheScope, |
| workUnitAsyncStorage, |
| } from '../../app-render/work-unit-async-storage.external' |
| import { |
| CachedRouteKind, |
| IncrementalCacheKind, |
| type CachedFetchData, |
| } from '../../response-cache' |
| import type { |
| UnstableCacheStore, |
| WorkUnitStore, |
| } from '../../app-render/work-unit-async-storage.external' |
|
|
| type Callback = (...args: any[]) => Promise<any> |
|
|
| let noStoreFetchIdx = 0 |
|
|
| async function cacheNewResult<T>( |
| result: T, |
| incrementalCache: IncrementalCache, |
| cacheKey: string, |
| tags: string[], |
| revalidate: number | false | undefined, |
| fetchIdx: number, |
| fetchUrl: string |
| ): Promise<unknown> { |
| await incrementalCache.set( |
| cacheKey, |
| { |
| kind: CachedRouteKind.FETCH, |
| data: { |
| headers: {}, |
| |
| body: JSON.stringify(result), |
| status: 200, |
| url: '', |
| } satisfies CachedFetchData, |
| revalidate: typeof revalidate !== 'number' ? CACHE_ONE_YEAR : revalidate, |
| }, |
| { fetchCache: true, tags, fetchIdx, fetchUrl } |
| ) |
| return |
| } |
|
|
| |
| |
| |
| |
| |
| export function unstable_cache<T extends Callback>( |
| cb: T, |
| keyParts?: string[], |
| options: { |
| |
| |
| |
| revalidate?: number | false |
| tags?: string[] |
| } = {} |
| ): T { |
| if (options.revalidate === 0) { |
| throw new Error( |
| `Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${cb.toString()}` |
| ) |
| } |
|
|
| |
| const tags = options.tags |
| ? validateTags(options.tags, `unstable_cache ${cb.toString()}`) |
| : [] |
|
|
| |
| validateRevalidate( |
| options.revalidate, |
| `unstable_cache ${cb.name || cb.toString()}` |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
| const fixedKey = `${cb.toString()}-${ |
| Array.isArray(keyParts) && keyParts.join(',') |
| }` |
|
|
| const cachedCb = async (...args: any[]) => { |
| const workStore = workAsyncStorage.getStore() |
| const workUnitStore = workUnitAsyncStorage.getStore() |
|
|
| |
| const maybeIncrementalCache: |
| | import('../../lib/incremental-cache').IncrementalCache |
| | undefined = |
| workStore?.incrementalCache || (globalThis as any).__incrementalCache |
|
|
| if (!maybeIncrementalCache) { |
| throw new Error( |
| `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}` |
| ) |
| } |
| const incrementalCache = maybeIncrementalCache |
|
|
| const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null |
| if (cacheSignal) { |
| cacheSignal.beginRead() |
| } |
| try { |
| |
| |
| |
| |
| const fetchUrlPrefix = |
| workStore && workUnitStore |
| ? getFetchUrlPrefix(workStore, workUnitStore) |
| : '' |
|
|
| |
| |
| |
| const invocationKey = `${fixedKey}-${JSON.stringify(args)}` |
| const cacheKey = await incrementalCache.generateCacheKey(invocationKey) |
| |
| const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}` |
| const fetchIdx = |
| (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1 |
|
|
| const implicitTags = workUnitStore?.implicitTags |
|
|
| const innerCacheStore: UnstableCacheStore = { |
| type: 'unstable-cache', |
| phase: 'render', |
| implicitTags, |
| draftMode: |
| workUnitStore && |
| workStore && |
| getDraftModeProviderForCacheScope(workStore, workUnitStore), |
| } |
|
|
| if (workStore) { |
| workStore.nextFetchId = fetchIdx + 1 |
|
|
| |
| |
| |
|
|
| let isNestedUnstableCache = false |
|
|
| if (workUnitStore) { |
| switch (workUnitStore.type) { |
| case 'cache': |
| case 'private-cache': |
| case 'prerender': |
| case 'prerender-ppr': |
| case 'prerender-legacy': |
| |
| |
| |
| if (typeof options.revalidate === 'number') { |
| if (workUnitStore.revalidate < options.revalidate) { |
| |
| } else { |
| workUnitStore.revalidate = options.revalidate |
| } |
| } |
|
|
| |
| const collectedTags = workUnitStore.tags |
| if (collectedTags === null) { |
| workUnitStore.tags = tags.slice() |
| } else { |
| for (const tag of tags) { |
| |
| if (!collectedTags.includes(tag)) { |
| collectedTags.push(tag) |
| } |
| } |
| } |
| break |
| case 'unstable-cache': |
| isNestedUnstableCache = true |
| break |
| case 'prerender-client': |
| case 'request': |
| break |
| default: |
| workUnitStore satisfies never |
| } |
| } |
|
|
| if ( |
| |
| |
| !isNestedUnstableCache && |
| workStore.fetchCache !== 'force-no-store' && |
| !workStore.isOnDemandRevalidate && |
| !incrementalCache.isOnDemandRevalidate && |
| !workStore.isDraftMode |
| ) { |
| |
| const cacheEntry = await incrementalCache.get(cacheKey, { |
| kind: IncrementalCacheKind.FETCH, |
| revalidate: options.revalidate, |
| tags, |
| softTags: implicitTags?.tags, |
| fetchIdx, |
| fetchUrl, |
| }) |
|
|
| if (cacheEntry && cacheEntry.value) { |
| |
| if (cacheEntry.value.kind !== CachedRouteKind.FETCH) { |
| |
| |
| |
| |
| console.error( |
| `Invariant invalid cacheEntry returned for ${invocationKey}` |
| ) |
| |
| } else { |
| |
| |
| const cachedResponse = |
| cacheEntry.value.data.body !== undefined |
| ? JSON.parse(cacheEntry.value.data.body) |
| : undefined |
| if (cacheEntry.isStale) { |
| |
| if (!workStore.pendingRevalidates) { |
| workStore.pendingRevalidates = {} |
| } |
|
|
| |
| workStore.pendingRevalidates[invocationKey] = |
| workUnitAsyncStorage |
| .run(innerCacheStore, cb, ...args) |
| .then((result) => { |
| return cacheNewResult( |
| result, |
| incrementalCache, |
| cacheKey, |
| tags, |
| options.revalidate, |
| fetchIdx, |
| fetchUrl |
| ) |
| }) |
| |
| .catch((err) => |
| console.error( |
| `revalidating cache with key: ${invocationKey}`, |
| err |
| ) |
| ) |
| } |
| |
| return cachedResponse |
| } |
| } |
| } |
|
|
| |
| const result = await workUnitAsyncStorage.run( |
| innerCacheStore, |
| cb, |
| ...args |
| ) |
|
|
| if (!workStore.isDraftMode) { |
| if (!workStore.pendingRevalidates) { |
| workStore.pendingRevalidates = {} |
| } |
|
|
| |
| |
| |
| workStore.pendingRevalidates[invocationKey] = cacheNewResult( |
| result, |
| incrementalCache, |
| cacheKey, |
| tags, |
| options.revalidate, |
| fetchIdx, |
| fetchUrl |
| ) |
| } |
|
|
| return result |
| } else { |
| noStoreFetchIdx += 1 |
| |
| |
| |
| |
|
|
| if (!incrementalCache.isOnDemandRevalidate) { |
| |
| const cacheEntry = await incrementalCache.get(cacheKey, { |
| kind: IncrementalCacheKind.FETCH, |
| revalidate: options.revalidate, |
| tags, |
| fetchIdx, |
| fetchUrl, |
| softTags: implicitTags?.tags, |
| }) |
|
|
| if (cacheEntry && cacheEntry.value) { |
| |
| if (cacheEntry.value.kind !== CachedRouteKind.FETCH) { |
| |
| |
| |
| console.error( |
| `Invariant invalid cacheEntry returned for ${invocationKey}` |
| ) |
| |
| } else if (!cacheEntry.isStale) { |
| |
| return cacheEntry.value.data.body !== undefined |
| ? JSON.parse(cacheEntry.value.data.body) |
| : undefined |
| } |
| } |
| } |
|
|
| |
| const result = await workUnitAsyncStorage.run( |
| innerCacheStore, |
| cb, |
| ...args |
| ) |
|
|
| |
| |
| |
| await cacheNewResult( |
| result, |
| incrementalCache, |
| cacheKey, |
| tags, |
| options.revalidate, |
| fetchIdx, |
| fetchUrl |
| ) |
| return result |
| } |
| } finally { |
| if (cacheSignal) { |
| cacheSignal.endRead() |
| } |
| } |
| } |
| |
| return cachedCb as unknown as T |
| } |
|
|
| function getFetchUrlPrefix( |
| workStore: WorkStore, |
| workUnitStore: WorkUnitStore |
| ): string { |
| switch (workUnitStore.type) { |
| case 'request': |
| const pathname = workUnitStore.url.pathname |
| const searchParams = new URLSearchParams(workUnitStore.url.search) |
|
|
| const sortedSearch = [...searchParams.keys()] |
| .sort((a, b) => a.localeCompare(b)) |
| .map((key) => `${key}=${searchParams.get(key)}`) |
| .join('&') |
|
|
| return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}` |
| case 'prerender': |
| case 'prerender-client': |
| case 'prerender-ppr': |
| case 'prerender-legacy': |
| case 'cache': |
| case 'private-cache': |
| case 'unstable-cache': |
| return workStore.route |
| default: |
| return workUnitStore satisfies never |
| } |
| } |
|
|