Skip to content

Commit

Permalink
fix(cache): remove cached value when revalidation results in an error…
Browse files Browse the repository at this point in the history
… or invalid value
  • Loading branch information
cjpearson committed Jul 12, 2024
1 parent eaffb9a commit 4b3438c
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions src/runtime/internal/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,16 +109,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 @@ -135,6 +141,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

0 comments on commit 4b3438c

Please sign in to comment.