|
| 1 | +import type { KVNamespace } from "@cloudflare/workers-types"; |
| 2 | +import type { CacheValue, IncrementalCache, WithLastModified } from "@opennextjs/aws/types/overrides"; |
| 3 | +import { IgnorableError, RecoverableError } from "@opennextjs/aws/utils/error.js"; |
| 4 | + |
| 5 | +import { getCloudflareContext } from "./get-cloudflare-context.js"; |
| 6 | + |
| 7 | +export const CACHE_ASSET_DIR = "cnd-cgi/_next_cache"; |
| 8 | + |
| 9 | +export const STATUS_DELETED = 1; |
| 10 | + |
| 11 | +/** |
| 12 | + * Open Next cache based on cloudflare KV and Assets. |
| 13 | + * |
| 14 | + * Note: The class is instantiated outside of the request context. |
| 15 | + * The cloudflare context and process.env are not initialzed yet |
| 16 | + * when the constructor is called. |
| 17 | + */ |
| 18 | +class Cache implements IncrementalCache { |
| 19 | + readonly name = "cloudflare-kv"; |
| 20 | + protected initialized = false; |
| 21 | + protected kv: KVNamespace | undefined; |
| 22 | + protected assets: Fetcher | undefined; |
| 23 | + |
| 24 | + async get<IsFetch extends boolean = false>( |
| 25 | + key: string, |
| 26 | + isFetch?: IsFetch |
| 27 | + ): Promise<WithLastModified<CacheValue<IsFetch>>> { |
| 28 | + if (!this.initialized) { |
| 29 | + await this.init(); |
| 30 | + } |
| 31 | + |
| 32 | + if (!(this.kv || this.assets)) { |
| 33 | + throw new IgnorableError(`No KVNamespace nor Fetcher`); |
| 34 | + } |
| 35 | + |
| 36 | + this.debug(`Get ${key}`); |
| 37 | + |
| 38 | + try { |
| 39 | + let entry: { |
| 40 | + value?: CacheValue<IsFetch>; |
| 41 | + lastModified?: number; |
| 42 | + status?: number; |
| 43 | + } | null = null; |
| 44 | + |
| 45 | + if (this.kv) { |
| 46 | + this.debug(`- From KV`); |
| 47 | + const kvKey = this.getKVKey(key, isFetch); |
| 48 | + entry = await this.kv.get(kvKey, "json"); |
| 49 | + if (entry?.status === STATUS_DELETED) { |
| 50 | + return {}; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if (!entry && this.assets) { |
| 55 | + this.debug(`- From Assets`); |
| 56 | + const url = this.getAssetUrl(key, isFetch); |
| 57 | + const response = await this.assets.fetch(url); |
| 58 | + if (response.ok) { |
| 59 | + // TODO: consider populating KV with the asset value if faster. |
| 60 | + // This could be optional as KV writes are $$. |
| 61 | + // See https://github.com/opennextjs/opennextjs-cloudflare/pull/194#discussion_r1893166026 |
| 62 | + entry = { |
| 63 | + value: await response.json(), |
| 64 | + // __BUILD_TIMESTAMP_MS__ is injected by ESBuild. |
| 65 | + lastModified: (globalThis as { __BUILD_TIMESTAMP_MS__?: number }).__BUILD_TIMESTAMP_MS__, |
| 66 | + }; |
| 67 | + } |
| 68 | + } |
| 69 | + this.debug(entry ? `-> hit` : `-> miss`); |
| 70 | + return { value: entry?.value, lastModified: entry?.lastModified }; |
| 71 | + } catch { |
| 72 | + throw new RecoverableError(`Failed to get cache [${key}]`); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + async set<IsFetch extends boolean = false>( |
| 77 | + key: string, |
| 78 | + value: CacheValue<IsFetch>, |
| 79 | + isFetch?: IsFetch |
| 80 | + ): Promise<void> { |
| 81 | + if (!this.initialized) { |
| 82 | + await this.init(); |
| 83 | + } |
| 84 | + if (!this.kv) { |
| 85 | + throw new IgnorableError(`No KVNamespace`); |
| 86 | + } |
| 87 | + this.debug(`Set ${key}`); |
| 88 | + try { |
| 89 | + const kvKey = this.getKVKey(key, isFetch); |
| 90 | + // Note: We can not set a TTL as we might fallback to assets, |
| 91 | + // still removing old data (old BUILD_ID) could help avoiding |
| 92 | + // the cache growing too big. |
| 93 | + await this.kv.put( |
| 94 | + kvKey, |
| 95 | + JSON.stringify({ |
| 96 | + value, |
| 97 | + // Note: `Date.now()` returns the time of the last IO rather than the actual time. |
| 98 | + // See https://developers.cloudflare.com/workers/reference/security-model/ |
| 99 | + lastModified: Date.now(), |
| 100 | + }) |
| 101 | + ); |
| 102 | + } catch { |
| 103 | + throw new RecoverableError(`Failed to set cache [${key}]`); |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + async delete(key: string): Promise<void> { |
| 108 | + if (!this.initialized) { |
| 109 | + await this.init(); |
| 110 | + } |
| 111 | + if (!this.kv) { |
| 112 | + throw new IgnorableError(`No KVNamespace`); |
| 113 | + } |
| 114 | + this.debug(`Delete ${key}`); |
| 115 | + try { |
| 116 | + const kvKey = this.getKVKey(key, /* isFetch= */ false); |
| 117 | + // Do not delete the key as we would then fallback to the assets. |
| 118 | + await this.kv.put(kvKey, JSON.stringify({ status: STATUS_DELETED })); |
| 119 | + } catch { |
| 120 | + throw new RecoverableError(`Failed to delete cache [${key}]`); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + protected getKVKey(key: string, isFetch?: boolean): string { |
| 125 | + return `${this.getBuildId()}/${key}.${isFetch ? "fetch" : "cache"}`; |
| 126 | + } |
| 127 | + |
| 128 | + protected getAssetUrl(key: string, isFetch?: boolean): string { |
| 129 | + return isFetch |
| 130 | + ? `http://assets.local/${CACHE_ASSET_DIR}/__fetch/${this.getBuildId()}/${key}` |
| 131 | + : `http://assets.local/${CACHE_ASSET_DIR}/${this.getBuildId()}/${key}.cache`; |
| 132 | + } |
| 133 | + |
| 134 | + protected debug(...args: unknown[]) { |
| 135 | + if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { |
| 136 | + console.log(`[Cache ${this.name}] `, ...args); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + protected getBuildId() { |
| 141 | + return process.env.NEXT_BUILD_ID ?? "no-build-id"; |
| 142 | + } |
| 143 | + |
| 144 | + protected async init() { |
| 145 | + const env = (await getCloudflareContext()).env; |
| 146 | + this.kv = env.NEXT_CACHE_WORKERS_KV; |
| 147 | + this.assets = env.ASSETS; |
| 148 | + this.initialized = true; |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +export default new Cache(); |
0 commit comments