Skip to content

Commit

Permalink
Add metrics names for unstable_cache
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Jan 18, 2024
1 parent 9e8e44e commit 7aa4d53
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions packages/next/src/server/web/spec-extension/unstable-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@ import {

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
revalidate: number | false | undefined,
fetchIdx: number,
fetchUrl: string
): Promise<unknown> {
await incrementalCache.set(
cacheKey,
Expand All @@ -38,6 +42,8 @@ async function cacheNewResult<T>(
revalidate,
fetchCache: true,
tags,
fetchIdx,
fetchUrl,
}
)
return
Expand Down Expand Up @@ -104,8 +110,12 @@ export function unstable_cache<T extends Callback>(
// the keyspace smaller than the execution space
const invocationKey = `${fixedKey}-${JSON.stringify(args)}`
const cacheKey = await incrementalCache.fetchCacheKey(invocationKey)
const fetchUrl = `unstable_cache ${cb.name ? ` ${cb.name}` : cacheKey}`
const fetchIdx = (store ? store.nextFetchId : noStoreFetchIdx) ?? 1

if (store) {
store.nextFetchId = fetchIdx + 1

// We are in an App Router context. We try to return the cached entry if it exists and is valid
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it.
Expand Down Expand Up @@ -156,6 +166,7 @@ export function unstable_cache<T extends Callback>(
revalidate: options.revalidate,
tags,
softTags: implicitTags,
fetchIdx,
})

if (cacheEntry && cacheEntry.value) {
Expand Down Expand Up @@ -198,7 +209,9 @@ export function unstable_cache<T extends Callback>(
incrementalCache,
cacheKey,
tags,
options.revalidate
options.revalidate,
fetchIdx,
fetchUrl
)
})
// @TODO This error handling seems wrong. We swallow the error?
Expand Down Expand Up @@ -232,10 +245,13 @@ export function unstable_cache<T extends Callback>(
incrementalCache,
cacheKey,
tags,
options.revalidate
options.revalidate,
fetchIdx,
fetchUrl
)
return result
} else {
noStoreFetchIdx += 1
// We are in Pages Router or were called outside of a render. We don't have a store
// so we just call the callback directly when it needs to run.
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
Expand Down Expand Up @@ -295,7 +311,9 @@ export function unstable_cache<T extends Callback>(
incrementalCache,
cacheKey,
tags,
options.revalidate
options.revalidate,
fetchIdx,
fetchUrl
)
return result
}
Expand Down

0 comments on commit 7aa4d53

Please sign in to comment.