|
| 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 | +import { RecoverableError } from "@opennextjs/aws/utils/error.js"; |
| 5 | + |
| 6 | +import { getCloudflareContext } from "./cloudflare-context.js"; |
| 7 | + |
| 8 | +/** |
| 9 | + * An instance of the Tag Cache that uses a D1 binding (`NEXT_CACHE_D1`) as it's underlying data store. |
| 10 | + * |
| 11 | + * **Tag/path mappings table** |
| 12 | + * |
| 13 | + * Information about the relation between tags and paths is stored in a `tags` table that contains |
| 14 | + * two columns; `tag`, and `path`. The table name can be configured with `NEXT_CACHE_D1_TAGS_TABLE` |
| 15 | + * environment variable. |
| 16 | + * |
| 17 | + * This table should be populated using an SQL file that is generated during the build process. |
| 18 | + * |
| 19 | + * **Tag revalidations table** |
| 20 | + * |
| 21 | + * Revalidation times for tags are stored in a `revalidations` table that contains two columns; `tags`, |
| 22 | + * and `revalidatedAt`. The table name can be configured with `NEXT_CACHE_D1_REVALIDATIONS_TABLE` |
| 23 | + * environment variable. |
| 24 | + */ |
| 25 | +class D1TagCache implements TagCache { |
| 26 | + public readonly name = "d1-tag-cache"; |
| 27 | + |
| 28 | + public async getByPath(rawPath: string): Promise<string[]> { |
| 29 | + const { isDisabled, db, tables } = this.getConfig(); |
| 30 | + if (isDisabled) return []; |
| 31 | + |
| 32 | + const path = this.getCacheKey(rawPath); |
| 33 | + |
| 34 | + try { |
| 35 | + const { success, results } = await db |
| 36 | + .prepare(`SELECT tag FROM ${JSON.stringify(tables.tags)} WHERE path = ?`) |
| 37 | + .bind(path) |
| 38 | + .all<{ tag: string }>(); |
| 39 | + |
| 40 | + if (!success) throw new RecoverableError(`D1 select failed for ${path}`); |
| 41 | + |
| 42 | + const tags = results?.map((item) => this.removeBuildId(item.tag)); |
| 43 | + |
| 44 | + debug("tags for path", path, tags); |
| 45 | + return tags; |
| 46 | + } catch (e) { |
| 47 | + error("Failed to get tags by path", e); |
| 48 | + return []; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public async getByTag(rawTag: string): Promise<string[]> { |
| 53 | + const { isDisabled, db, tables } = this.getConfig(); |
| 54 | + if (isDisabled) return []; |
| 55 | + |
| 56 | + const tag = this.getCacheKey(rawTag); |
| 57 | + |
| 58 | + try { |
| 59 | + const { success, results } = await db |
| 60 | + .prepare(`SELECT path FROM ${JSON.stringify(tables.tags)} WHERE tag = ?`) |
| 61 | + .bind(tag) |
| 62 | + .all<{ path: string }>(); |
| 63 | + |
| 64 | + if (!success) throw new RecoverableError(`D1 select failed for ${tag}`); |
| 65 | + |
| 66 | + const paths = results?.map((item) => this.removeBuildId(item.path)); |
| 67 | + |
| 68 | + debug("paths for tag", tag, paths); |
| 69 | + return paths; |
| 70 | + } catch (e) { |
| 71 | + error("Failed to get by tag", e); |
| 72 | + return []; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + public async getLastModified(path: string, lastModified?: number): Promise<number> { |
| 77 | + const { isDisabled, db, tables } = this.getConfig(); |
| 78 | + if (isDisabled) return lastModified ?? Date.now(); |
| 79 | + |
| 80 | + try { |
| 81 | + const { success, results } = await db |
| 82 | + .prepare( |
| 83 | + `SELECT ${JSON.stringify(tables.revalidations)}.tag FROM ${JSON.stringify(tables.revalidations)} |
| 84 | + INNER JOIN ${JSON.stringify(tables.tags)} ON ${JSON.stringify(tables.revalidations)}.tag = ${JSON.stringify(tables.tags)}.tag |
| 85 | + WHERE ${JSON.stringify(tables.tags)}.path = ? AND ${JSON.stringify(tables.revalidations)}.revalidatedAt > ?;` |
| 86 | + ) |
| 87 | + .bind(this.getCacheKey(path), lastModified ?? 0) |
| 88 | + .all<{ tag: string }>(); |
| 89 | + |
| 90 | + if (!success) throw new RecoverableError(`D1 select failed for ${path} - ${lastModified ?? 0}`); |
| 91 | + |
| 92 | + debug("revalidatedTags", results); |
| 93 | + return results?.length > 0 ? -1 : (lastModified ?? Date.now()); |
| 94 | + } catch (e) { |
| 95 | + error("Failed to get revalidated tags", e); |
| 96 | + return lastModified ?? Date.now(); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + public async writeTags(tags: { tag: string; path: string; revalidatedAt?: number }[]): Promise<void> { |
| 101 | + const { isDisabled, db, tables } = this.getConfig(); |
| 102 | + if (isDisabled || tags.length === 0) return; |
| 103 | + |
| 104 | + try { |
| 105 | + const uniqueTags = new Set<string>(); |
| 106 | + const results = await db.batch( |
| 107 | + tags |
| 108 | + .map(({ tag, path, revalidatedAt }) => { |
| 109 | + if (revalidatedAt === 1) { |
| 110 | + // new tag/path mapping from set |
| 111 | + return db |
| 112 | + .prepare(`INSERT INTO ${JSON.stringify(tables.tags)} (tag, path) VALUES (?, ?)`) |
| 113 | + .bind(this.getCacheKey(tag), this.getCacheKey(path)); |
| 114 | + } |
| 115 | + |
| 116 | + if (!uniqueTags.has(tag) && revalidatedAt !== -1) { |
| 117 | + // tag was revalidated |
| 118 | + uniqueTags.add(tag); |
| 119 | + return db |
| 120 | + .prepare( |
| 121 | + `INSERT INTO ${JSON.stringify(tables.revalidations)} (tag, revalidatedAt) VALUES (?, ?)` |
| 122 | + ) |
| 123 | + .bind(this.getCacheKey(tag), revalidatedAt ?? Date.now()); |
| 124 | + } |
| 125 | + }) |
| 126 | + .filter((stmt) => !!stmt) |
| 127 | + ); |
| 128 | + |
| 129 | + const failedResults = results.filter((res) => !res.success); |
| 130 | + |
| 131 | + if (failedResults.length > 0) { |
| 132 | + throw new RecoverableError(`${failedResults.length} tags failed to write`); |
| 133 | + } |
| 134 | + } catch (e) { |
| 135 | + error("Failed to batch write tags", e); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private getConfig() { |
| 140 | + const cfEnv = getCloudflareContext().env; |
| 141 | + const db = cfEnv.NEXT_CACHE_D1; |
| 142 | + |
| 143 | + if (!db) debug("No D1 database found"); |
| 144 | + |
| 145 | + const isDisabled = !!(globalThis as unknown as { openNextConfig: OpenNextConfig }).openNextConfig |
| 146 | + .dangerous?.disableTagCache; |
| 147 | + |
| 148 | + if (!db || isDisabled) { |
| 149 | + return { isDisabled: true as const }; |
| 150 | + } |
| 151 | + |
| 152 | + return { |
| 153 | + isDisabled: false as const, |
| 154 | + db, |
| 155 | + tables: { |
| 156 | + tags: cfEnv.NEXT_CACHE_D1_TAGS_TABLE ?? "tags", |
| 157 | + revalidations: cfEnv.NEXT_CACHE_D1_REVALIDATIONS_TABLE ?? "revalidations", |
| 158 | + }, |
| 159 | + }; |
| 160 | + } |
| 161 | + |
| 162 | + protected removeBuildId(key: string) { |
| 163 | + return key.replace(`${this.getBuildId()}/`, ""); |
| 164 | + } |
| 165 | + |
| 166 | + protected getCacheKey(key: string) { |
| 167 | + return `${this.getBuildId()}/${key}`.replaceAll("//", "/"); |
| 168 | + } |
| 169 | + |
| 170 | + protected getBuildId() { |
| 171 | + return process.env.NEXT_BUILD_ID ?? "no-build-id"; |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +export default new D1TagCache(); |
0 commit comments