|
| 1 | +/* eslint-disable @typescript-eslint/no-unused-vars */ |
| 2 | +import type { KVNamespace } from "@cloudflare/workers-types"; |
| 3 | +import type { Extension } from "@opennextjs/aws/types/cache"; |
| 4 | +import type { CacheValue, IncrementalCache, WithLastModified } from "@opennextjs/aws/types/overrides"; |
| 5 | +import { IgnorableError, RecoverableError } from "@opennextjs/aws/utils/error.js"; |
| 6 | + |
| 7 | +import { getCloudflareContext } from "./get-cloudflare-context.js"; |
| 8 | + |
| 9 | +export const CACHE_ASSET_DIR = "cnd-cgi/_next_cache"; |
| 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 | + this.debug(`- From KV`); |
| 40 | + const kvKey = this.getKVKey(key, isFetch ? "fetch" : "cache"); |
| 41 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 42 | + let value: any = await this.kv?.get(kvKey, "json"); |
| 43 | + if (!value && this.assets) { |
| 44 | + const url = this.getAssetUrl(key); |
| 45 | + const response = await this.assets.fetch(url); |
| 46 | + this.debug(`- From Assets`); |
| 47 | + if (response.ok) { |
| 48 | + value = await response.json(); |
| 49 | + } |
| 50 | + } |
| 51 | + if (value) { |
| 52 | + this.debug(`-> hit`); |
| 53 | + return { value }; |
| 54 | + } |
| 55 | + } catch { |
| 56 | + throw new RecoverableError(`Failed to get cache [${key}]`); |
| 57 | + } |
| 58 | + |
| 59 | + this.debug(`-> miss`); |
| 60 | + throw new RecoverableError(`Not found [${key}]`); |
| 61 | + } |
| 62 | + |
| 63 | + async set<IsFetch extends boolean = false>( |
| 64 | + key: string, |
| 65 | + value: CacheValue<IsFetch>, |
| 66 | + isFetch?: IsFetch |
| 67 | + ): Promise<void> { |
| 68 | + if (!this.initialized) { |
| 69 | + await this.init(); |
| 70 | + } |
| 71 | + if (!this.kv) { |
| 72 | + throw new IgnorableError(`No KVNamespace`); |
| 73 | + } |
| 74 | + this.debug(`Set ${key}`); |
| 75 | + try { |
| 76 | + const kvKey = this.getKVKey(key, isFetch ? "fetch" : "cache"); |
| 77 | + // TODO: add TTL to avoid cache growing too big ? |
| 78 | + await this.kv.put(kvKey, JSON.stringify(value)); |
| 79 | + } catch { |
| 80 | + throw new RecoverableError(`Failed to set cache [${key}]`); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + async delete(key: string): Promise<void> { |
| 85 | + if (!this.initialized) { |
| 86 | + await this.init(); |
| 87 | + } |
| 88 | + if (!this.kv) { |
| 89 | + throw new IgnorableError(`No KVNamespace`); |
| 90 | + } |
| 91 | + this.debug(`Delete ${key}`); |
| 92 | + try { |
| 93 | + const kvKey = this.getKVKey(key, "cache"); |
| 94 | + await this.kv.delete(kvKey); |
| 95 | + } catch (e) { |
| 96 | + throw new RecoverableError(`Failed to delete cache [${key}]`); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + protected getKVKey(key: string, extension: Extension): string { |
| 101 | + return `${this.getBuildId()}/${key}.${extension}`; |
| 102 | + } |
| 103 | + |
| 104 | + protected getAssetUrl(key: string): string { |
| 105 | + return `http://assets.local/${CACHE_ASSET_DIR}/${this.getBuildId()}/${key}.cache`.replace(/\/\//g, "/"); |
| 106 | + } |
| 107 | + |
| 108 | + protected debug(...args: unknown[]) { |
| 109 | + if (process.env.NEXT_PRIVATE_DEBUG_CACHE) { |
| 110 | + console.log(`[Cache ${this.name}] `, ...args); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + protected getBuildId() { |
| 115 | + return process.env.NEXT_BUILD_ID ?? "no-build-id"; |
| 116 | + } |
| 117 | + |
| 118 | + protected async init() { |
| 119 | + const env = (await getCloudflareContext()).env; |
| 120 | + this.kv = env.NEXT_CACHE_WORKERS_KV; |
| 121 | + this.assets = env.ASSETS; |
| 122 | + this.initialized = true; |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +export default new Cache(); |
0 commit comments