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(cache): remove cached value when revalidation results in an error… #2611

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
Changes from all commits
Commits
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
38 changes: 28 additions & 10 deletions src/runtime/internal/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,22 @@ export function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(
entry.mtime = Date.now();
entry.integrity = integrity;
delete pending[key];
if (validate(entry) !== false) {
const promise = useStorage()
.setItem(cacheKey, entry)
.catch((error) => {
console.error(`[nitro] [cache] Cache write error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
if (event?.waitUntil) {
event.waitUntil(promise);
}
const promise =
validate(entry) === false
? useStorage()
.removeItem(cacheKey)
.catch((error) => {
console.error(`[nitro] [cache] Cache write error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
})
: useStorage()
.setItem(cacheKey, entry)
.catch((error) => {
console.error(`[nitro] [cache] Cache write error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
if (event?.waitUntil) {
event.waitUntil(promise);
}
}
};
Expand All @@ -137,6 +143,18 @@ export function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(
_resolvePromise.catch((error) => {
console.error(`[nitro] [cache] SWR handler error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });

// SWR revalidation failed, remove existing entry so we do
// not continue to return the cached value indefinitely.
const promise = useStorage()
.removeItem(cacheKey)
.catch((error) => {
console.error(`[nitro] [cache] Cache write error.`, error);
useNitroApp().captureError(error, { event, tags: ["cache"] });
});
if (event?.waitUntil) {
event.waitUntil(promise);
}
});
return entry;
}
Expand Down