|
| 1 | +import { debug, error } from "@opennextjs/aws/adapters/logger.js"; |
| 2 | +import type { CacheValue, IncrementalCache, WithLastModified } from "@opennextjs/aws/types/overrides.js"; |
| 3 | +import { IgnorableError } from "@opennextjs/aws/utils/error.js"; |
| 4 | + |
| 5 | +import { getCloudflareContext } from "./cloudflare-context.js"; |
| 6 | + |
| 7 | +type Entry<IsFetch extends boolean> = { |
| 8 | + value: CacheValue<IsFetch>; |
| 9 | + lastModified: number; |
| 10 | +}; |
| 11 | + |
| 12 | +const ONE_YEAR_IN_SECONDS = 31536000; |
| 13 | + |
| 14 | +/** |
| 15 | + * An instance of the Incremental Cache that uses an R2 bucket (`NEXT_CACHE_R2_BUCKET`) as it's |
| 16 | + * underlying data store. |
| 17 | + * |
| 18 | + * The directory that the cache entries are stored in can be confused with the `NEXT_CACHE_R2_DIRECTORY` |
| 19 | + * environment variable, and defaults to `incremental-cache`. |
| 20 | + * |
| 21 | + * The cache uses an instance of the Cache API (`incremental-cache`) to store a local version of the |
| 22 | + * R2 cache entry to enable fast retrieval, with the cache being updated from R2 in the background. |
| 23 | + */ |
| 24 | +class R2IncrementalCache implements IncrementalCache { |
| 25 | + readonly name = "r2-incremental-cache"; |
| 26 | + |
| 27 | + protected localCache: Cache | undefined; |
| 28 | + |
| 29 | + async get<IsFetch extends boolean = false>( |
| 30 | + key: string, |
| 31 | + isFetch?: IsFetch |
| 32 | + ): Promise<WithLastModified<CacheValue<IsFetch>> | null> { |
| 33 | + const r2 = getCloudflareContext().env.NEXT_CACHE_R2_BUCKET; |
| 34 | + if (!r2) throw new IgnorableError("No R2 bucket"); |
| 35 | + |
| 36 | + debug(`Get ${key}`); |
| 37 | + |
| 38 | + try { |
| 39 | + const r2Response = r2.get(this.getR2Key(key)); |
| 40 | + |
| 41 | + const localCacheKey = this.getLocalCacheKey(key, isFetch); |
| 42 | + |
| 43 | + // Check for a cached entry as this will be faster than R2. |
| 44 | + const cachedResponse = await this.getFromLocalCache(localCacheKey); |
| 45 | + if (cachedResponse) { |
| 46 | + debug(` -> Cached response`); |
| 47 | + // Update the local cache after the R2 fetch has completed. |
| 48 | + getCloudflareContext().ctx.waitUntil( |
| 49 | + Promise.resolve(r2Response).then(async (res) => { |
| 50 | + if (res) { |
| 51 | + const entry: Entry<IsFetch> = await res.json(); |
| 52 | + await this.putToLocalCache(localCacheKey, JSON.stringify(entry), entry.value.revalidate); |
| 53 | + } |
| 54 | + }) |
| 55 | + ); |
| 56 | + |
| 57 | + return cachedResponse.json(); |
| 58 | + } |
| 59 | + |
| 60 | + const r2Object = await r2Response; |
| 61 | + if (!r2Object) return null; |
| 62 | + const entry: Entry<IsFetch> = await r2Object.json(); |
| 63 | + |
| 64 | + // Update the locale cache after retrieving from R2. |
| 65 | + getCloudflareContext().ctx.waitUntil( |
| 66 | + this.putToLocalCache(localCacheKey, JSON.stringify(entry), entry.value.revalidate) |
| 67 | + ); |
| 68 | + |
| 69 | + return entry; |
| 70 | + } catch (e) { |
| 71 | + error(`Failed to get from cache`, e); |
| 72 | + return null; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + async set<IsFetch extends boolean = false>( |
| 77 | + key: string, |
| 78 | + value: CacheValue<IsFetch>, |
| 79 | + isFetch?: IsFetch |
| 80 | + ): Promise<void> { |
| 81 | + const r2 = getCloudflareContext().env.NEXT_CACHE_R2_BUCKET; |
| 82 | + if (!r2) throw new IgnorableError("No R2 bucket"); |
| 83 | + |
| 84 | + debug(`Set ${key}`); |
| 85 | + |
| 86 | + try { |
| 87 | + const entry: Entry<IsFetch> = { |
| 88 | + value, |
| 89 | + // Note: `Date.now()` returns the time of the last IO rather than the actual time. |
| 90 | + // See https://developers.cloudflare.com/workers/reference/security-model/ |
| 91 | + lastModified: Date.now(), |
| 92 | + }; |
| 93 | + |
| 94 | + await Promise.all([ |
| 95 | + r2.put(this.getR2Key(key, isFetch), JSON.stringify(entry)), |
| 96 | + // Update the locale cache for faster retrieval. |
| 97 | + this.putToLocalCache( |
| 98 | + this.getLocalCacheKey(key, isFetch), |
| 99 | + JSON.stringify(entry), |
| 100 | + entry.value.revalidate |
| 101 | + ), |
| 102 | + ]); |
| 103 | + } catch (e) { |
| 104 | + error(`Failed to set to cache`, e); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + async delete(key: string): Promise<void> { |
| 109 | + const r2 = getCloudflareContext().env.NEXT_CACHE_R2_BUCKET; |
| 110 | + if (!r2) throw new IgnorableError("No R2 bucket"); |
| 111 | + |
| 112 | + debug(`Delete ${key}`); |
| 113 | + |
| 114 | + try { |
| 115 | + await Promise.all([ |
| 116 | + r2.delete(this.getR2Key(key)), |
| 117 | + this.deleteFromLocalCache(this.getLocalCacheKey(key)), |
| 118 | + ]); |
| 119 | + } catch (e) { |
| 120 | + error(`Failed to delete from cache`, e); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + protected getBaseCacheKey(key: string, isFetch?: boolean): string { |
| 125 | + return `${process.env.NEXT_BUILD_ID ?? "no-build-id"}/${key}.${isFetch ? "fetch" : "cache"}`; |
| 126 | + } |
| 127 | + |
| 128 | + protected getR2Key(key: string, isFetch?: boolean): string { |
| 129 | + const directory = getCloudflareContext().env.NEXT_CACHE_R2_DIRECTORY ?? "incremental-cache"; |
| 130 | + return `${directory}/${this.getBaseCacheKey(key, isFetch)}`; |
| 131 | + } |
| 132 | + |
| 133 | + protected getLocalCacheKey(key: string, isFetch?: boolean) { |
| 134 | + return new Request(new URL(this.getBaseCacheKey(key, isFetch), "http://cache.local")); |
| 135 | + } |
| 136 | + |
| 137 | + protected async getLocalCacheInstance(): Promise<Cache> { |
| 138 | + if (this.localCache) return this.localCache; |
| 139 | + |
| 140 | + this.localCache = await caches.open("incremental-cache"); |
| 141 | + return this.localCache; |
| 142 | + } |
| 143 | + |
| 144 | + protected async getFromLocalCache(key: Request) { |
| 145 | + const cache = await this.getLocalCacheInstance(); |
| 146 | + return cache.match(key); |
| 147 | + } |
| 148 | + |
| 149 | + protected async putToLocalCache( |
| 150 | + key: Request, |
| 151 | + entry: string, |
| 152 | + revalidate: number | false | undefined |
| 153 | + ): Promise<void> { |
| 154 | + const cache = await this.getLocalCacheInstance(); |
| 155 | + await cache.put( |
| 156 | + key, |
| 157 | + new Response(entry, { |
| 158 | + headers: new Headers({ |
| 159 | + "cache-control": `max-age=${revalidate || ONE_YEAR_IN_SECONDS}`, |
| 160 | + }), |
| 161 | + }) |
| 162 | + ); |
| 163 | + } |
| 164 | + |
| 165 | + protected async deleteFromLocalCache(key: Request) { |
| 166 | + const cache = await this.getLocalCacheInstance(); |
| 167 | + await cache.delete(key); |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +export default new R2IncrementalCache(); |
0 commit comments