Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(fetch-cache): add check for updated tags when checking same cache key #63547

Merged
merged 21 commits into from
Apr 9, 2024
Merged
Changes from 8 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions packages/next/src/server/lib/incremental-cache/fetch-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ export default class FetchCache implements CacheHandler {
private cacheEndpoint?: string
private debug: boolean

private hasMatchingTags(arr1: string[], arr2: string[]) {
if (arr1.length !== arr2.length) return false

const set1 = new Set(arr1)
const set2 = new Set(arr2)

if (set1.size !== set2.size) return false

for (let tag of set1) {
if (!set2.has(tag)) return false
}

return true
}

static isAvailable(ctx: {
_requestHeaders: CacheHandlerContext['_requestHeaders']
}) {
Expand Down Expand Up @@ -168,8 +183,13 @@ export default class FetchCache implements CacheHandler {
// on successive requests
let data = memoryCache?.get(key)

// get data from fetch cache
if (!data && this.cacheEndpoint) {
const hasFetchKindAndMatchingTags =
data?.value?.kind === 'FETCH' &&
this.hasMatchingTags(tags ?? [], data.value.tags ?? [])

// Get data from fetch cache. Also check if new tags have been
// specified with the same cache key (fetch URL)
if (this.cacheEndpoint && (!data || !hasFetchKindAndMatchingTags)) {
try {
const start = Date.now()
const fetchParams: NextFetchCacheParams = {
Expand Down Expand Up @@ -220,6 +240,11 @@ export default class FetchCache implements CacheHandler {
throw new Error(`invalid cache value`)
}

// if new tags were specified, merge those tags to the existing tags
if (cached.kind === 'FETCH') {
cached.tags = [...new Set([...(cached.tags ?? []), ...(tags ?? [])])]
samcx marked this conversation as resolved.
Show resolved Hide resolved
}

const cacheState = res.headers.get(CACHE_STATE_HEADER)
const age = res.headers.get('age')

Expand Down
Loading