|
| 1 | +import { debug, error } from "@opennextjs/aws/adapters/logger.js"; |
| 2 | +import type { OpenNextConfig } from "@opennextjs/aws/types/open-next.js"; |
| 3 | +import type { TagCache } from "@opennextjs/aws/types/overrides.js"; |
| 4 | + |
| 5 | +import { getCloudflareContext } from "./cloudflare-context.js"; |
| 6 | + |
| 7 | +// inlined during build |
| 8 | +const manifest = process.env.__OPENNEXT_CACHE_TAGS_MANIFEST; |
| 9 | + |
| 10 | +class D1TagCache implements TagCache { |
| 11 | + public name = "d1-tag-cache"; |
| 12 | + |
| 13 | + public async getByPath(rawPath: string): Promise<string[]> { |
| 14 | + const { isDisabled, db, table } = this.getConfig(); |
| 15 | + if (isDisabled) return []; |
| 16 | + |
| 17 | + const path = this.getCacheKey(rawPath); |
| 18 | + |
| 19 | + try { |
| 20 | + const { success, results } = await db |
| 21 | + .prepare(`SELECT tag FROM ${table} WHERE path = ?`) |
| 22 | + .bind(path) |
| 23 | + .all<{ tag: string }>(); |
| 24 | + |
| 25 | + if (!success) throw new Error(`D1 select failed for ${path}`); |
| 26 | + |
| 27 | + const tags = this.mergeTagArrays( |
| 28 | + manifest.paths[path], |
| 29 | + results?.map((item) => item.tag) |
| 30 | + ); |
| 31 | + |
| 32 | + debug("tags for path", path, tags); |
| 33 | + return tags; |
| 34 | + } catch (e) { |
| 35 | + error("Failed to get tags by path", e); |
| 36 | + return []; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public async getByTag(rawTag: string): Promise<string[]> { |
| 41 | + const { isDisabled, db, table } = this.getConfig(); |
| 42 | + if (isDisabled) return []; |
| 43 | + |
| 44 | + const tag = this.getCacheKey(rawTag); |
| 45 | + |
| 46 | + try { |
| 47 | + const { success, results } = await db |
| 48 | + .prepare(`SELECT path FROM ${table} WHERE tag = ?`) |
| 49 | + .bind(tag) |
| 50 | + .all<{ path: string }>(); |
| 51 | + |
| 52 | + if (!success) throw new Error(`D1 select failed for ${tag}`); |
| 53 | + |
| 54 | + const paths = this.mergeTagArrays( |
| 55 | + manifest.tags[tag], |
| 56 | + results?.map((item) => item.path) |
| 57 | + ); |
| 58 | + |
| 59 | + debug("paths for tag", tag, paths); |
| 60 | + return paths; |
| 61 | + } catch (e) { |
| 62 | + error("Failed to get by tag", e); |
| 63 | + return []; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + public async getLastModified(path: string, lastModified?: number): Promise<number> { |
| 68 | + const { isDisabled, db, table } = this.getConfig(); |
| 69 | + if (isDisabled) return lastModified ?? Date.now(); |
| 70 | + |
| 71 | + try { |
| 72 | + const { success, results } = await db |
| 73 | + .prepare(`SELECT tag FROM ${table} WHERE path = ? AND revalidatedAt > ?`) |
| 74 | + .bind(this.getCacheKey(path), lastModified ?? 0) |
| 75 | + .all<{ tag: string }>(); |
| 76 | + |
| 77 | + if (!success) throw new Error(`D1 select failed for ${path} - ${lastModified ?? 0}`); |
| 78 | + |
| 79 | + const tags = results?.map((item) => this.removeBuildId(item.tag)) ?? []; |
| 80 | + debug("revalidatedTags", tags); |
| 81 | + return tags.length > 0 ? -1 : (lastModified ?? Date.now()); |
| 82 | + } catch (e) { |
| 83 | + error("Failed to get revalidated tags", e); |
| 84 | + return lastModified ?? Date.now(); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + public async writeTags(tags: { tag: string; path: string; revalidatedAt?: number }[]): Promise<void> { |
| 89 | + const { isDisabled, db, table } = this.getConfig(); |
| 90 | + if (isDisabled || tags.length === 0) return; |
| 91 | + |
| 92 | + try { |
| 93 | + const results = await db.batch( |
| 94 | + tags.map(({ tag, path, revalidatedAt }) => |
| 95 | + db |
| 96 | + .prepare(`INSERT INTO ${table} (tag, path, revalidatedAt) VALUES(?, ?, ?)`) |
| 97 | + .bind(this.getCacheKey(tag), this.getCacheKey(path), revalidatedAt ?? Date.now()) |
| 98 | + ) |
| 99 | + ); |
| 100 | + |
| 101 | + const failedResults = results.filter((res) => !res.success); |
| 102 | + |
| 103 | + if (failedResults.length > 0) { |
| 104 | + throw new Error(`${failedResults.length} tags failed to write`); |
| 105 | + } |
| 106 | + } catch (e) { |
| 107 | + error("Failed to batch write tags", e); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private getConfig() { |
| 112 | + const cfEnv = getCloudflareContext().env; |
| 113 | + const db = cfEnv.NEXT_CACHE_D1; |
| 114 | + const table = cfEnv.NEXT_CACHE_D1_TABLE ?? "tags"; |
| 115 | + |
| 116 | + if (!db) debug("No D1 database found"); |
| 117 | + |
| 118 | + const isDisabled = !!(globalThis as unknown as { openNextConfig: OpenNextConfig }).openNextConfig |
| 119 | + .dangerous?.disableTagCache; |
| 120 | + |
| 121 | + if (!db || isDisabled) { |
| 122 | + return { isDisabled: true as const }; |
| 123 | + } |
| 124 | + |
| 125 | + return { isDisabled: false as const, db, table }; |
| 126 | + } |
| 127 | + |
| 128 | + protected removeBuildId(key: string) { |
| 129 | + return key.replace(`${this.getBuildId()}/`, ""); |
| 130 | + } |
| 131 | + |
| 132 | + protected getCacheKey(key: string) { |
| 133 | + return `${this.getBuildId()}/${key}`.replaceAll("//", "/"); |
| 134 | + } |
| 135 | + |
| 136 | + protected getBuildId() { |
| 137 | + return process.env.NEXT_BUILD_ID ?? "no-build-id"; |
| 138 | + } |
| 139 | + |
| 140 | + protected mergeTagArrays(...arrays: (string[] | undefined)[]) { |
| 141 | + const set = new Set<string>(); |
| 142 | + |
| 143 | + for (const arr of arrays) { |
| 144 | + arr?.forEach((v) => set.add(this.removeBuildId(v))); |
| 145 | + } |
| 146 | + |
| 147 | + return [...set.values()]; |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +export default new D1TagCache(); |
0 commit comments