Skip to content

Commit 9f0ceca

Browse files
committed
lazily update the regional cache in the background via option
1 parent f567760 commit 9f0ceca

File tree

2 files changed

+18
-14
lines changed

2 files changed

+18
-14
lines changed

examples/e2e/app-router/open-next.config.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import memoryQueue from "@opennextjs/cloudflare/memory-queue";
66
import { withRegionalCache } from "@opennextjs/cloudflare/regional-cache";
77

88
export default defineCloudflareConfig({
9-
incrementalCache: withRegionalCache(r2IncrementalCache, { mode: "long-lived" }),
9+
incrementalCache: withRegionalCache(r2IncrementalCache, {
10+
mode: "long-lived",
11+
shouldLazilyUpdateOnCacheHit: true,
12+
}),
1013
tagCache: d1TagCache,
1114
queue: memoryQueue,
1215
});

packages/cloudflare/src/api/regional-cache.ts

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const ONE_MINUTE_IN_SECONDS = 60;
99

1010
type Options = {
1111
mode: "short-lived" | "long-lived";
12+
shouldLazilyUpdateOnCacheHit?: boolean;
1213
};
1314

1415
class RegionalCache implements IncrementalCache {
@@ -28,31 +29,31 @@ class RegionalCache implements IncrementalCache {
2829
isFetch?: IsFetch
2930
): Promise<WithLastModified<CacheValue<IsFetch>> | null> {
3031
try {
31-
const storeResponse = this.store.get(key, isFetch);
32-
32+
const cache = await this.getCacheInstance();
3333
const localCacheKey = this.getCacheKey(key, isFetch);
3434

3535
// Check for a cached entry as this will be faster than the store response.
36-
const cache = await this.getCacheInstance();
3736
const cachedResponse = await cache.match(localCacheKey);
3837
if (cachedResponse) {
3938
debug("Get - cached response");
4039

41-
// Update the local cache after the R2 fetch has completed.
42-
getCloudflareContext().ctx.waitUntil(
43-
Promise.resolve(storeResponse).then(async (rawEntry) => {
44-
const { value, lastModified } = rawEntry ?? {};
40+
// Re-fetch from the store and update the regional cache in the background
41+
if (this.opts.shouldLazilyUpdateOnCacheHit) {
42+
getCloudflareContext().ctx.waitUntil(
43+
this.store.get(key, isFetch).then(async (rawEntry) => {
44+
const { value, lastModified } = rawEntry ?? {};
4545

46-
if (value && typeof lastModified === "number") {
47-
await this.putToCache(localCacheKey, { value, lastModified });
48-
}
49-
})
50-
);
46+
if (value && typeof lastModified === "number") {
47+
await this.putToCache(localCacheKey, { value, lastModified });
48+
}
49+
})
50+
);
51+
}
5152

5253
return cachedResponse.json();
5354
}
5455

55-
const rawEntry = await storeResponse;
56+
const rawEntry = await this.store.get(key, isFetch);
5657
const { value, lastModified } = rawEntry ?? {};
5758
if (!value || typeof lastModified !== "number") return null;
5859

0 commit comments

Comments
 (0)