|
| 1 | +import { BuildExtension } from "@trigger.dev/core/v3/build"; |
| 2 | +import { syncEnvVars } from "../core.js"; |
| 3 | + |
| 4 | +type EnvVar = { name: string; value: string; isParentEnv?: boolean }; |
| 5 | + |
| 6 | +type NeonBranch = { |
| 7 | + id: string; |
| 8 | + name: string; |
| 9 | +}; |
| 10 | + |
| 11 | +type NeonEndpoint = { |
| 12 | + id: string; |
| 13 | + host: string; |
| 14 | + type: string; |
| 15 | +}; |
| 16 | + |
| 17 | +type NeonDatabase = { |
| 18 | + id: number; |
| 19 | + name: string; |
| 20 | + owner_name: string; |
| 21 | +}; |
| 22 | + |
| 23 | +type NeonRole = { |
| 24 | + name: string; |
| 25 | + password?: string; |
| 26 | +}; |
| 27 | + |
| 28 | +// List of Neon DB related environment variables to sync |
| 29 | +export const NEON_ENV_VARS = [ |
| 30 | + "PGUSER", |
| 31 | + "POSTGRES_URL_NO_SSL", |
| 32 | + "POSTGRES_HOST", |
| 33 | + "POSTGRES_URL", |
| 34 | + "POSTGRES_PRISMA_URL", |
| 35 | + "DATABASE_URL_UNPOOLED", |
| 36 | + "POSTGRES_URL_NON_POOLING", |
| 37 | + "PGHOST", |
| 38 | + "POSTGRES_USER", |
| 39 | + "DATABASE_URL", |
| 40 | + "POSTGRES_PASSWORD", |
| 41 | + "POSTGRES_DATABASE", |
| 42 | + "PGPASSWORD", |
| 43 | + "PGDATABASE", |
| 44 | + "PGHOST_UNPOOLED", |
| 45 | +]; |
| 46 | + |
| 47 | +function buildNeonEnvVarMappings(options: { |
| 48 | + user: string; |
| 49 | + password: string; |
| 50 | + database: string; |
| 51 | + host: string; |
| 52 | + poolerHost: string; |
| 53 | +}): Record<string, string> { |
| 54 | + const { user, password, database, host, poolerHost } = options; |
| 55 | + |
| 56 | + return { |
| 57 | + PGUSER: user, |
| 58 | + PGPASSWORD: password, |
| 59 | + PGDATABASE: database, |
| 60 | + PGHOST: poolerHost, |
| 61 | + PGHOST_UNPOOLED: host, |
| 62 | + POSTGRES_USER: user, |
| 63 | + POSTGRES_PASSWORD: password, |
| 64 | + POSTGRES_DATABASE: database, |
| 65 | + POSTGRES_HOST: poolerHost, |
| 66 | + DATABASE_URL: `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${poolerHost}/${database}?sslmode=require`, |
| 67 | + DATABASE_URL_UNPOOLED: `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}/${database}?sslmode=require`, |
| 68 | + POSTGRES_URL: `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${poolerHost}/${database}?sslmode=require`, |
| 69 | + POSTGRES_URL_NO_SSL: `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${poolerHost}/${database}`, |
| 70 | + POSTGRES_URL_NON_POOLING: `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}/${database}?sslmode=require`, |
| 71 | + POSTGRES_PRISMA_URL: `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${poolerHost}/${database}?sslmode=require&pgbouncer=true&connect_timeout=15`, |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +export function syncNeonEnvVars(options?: { |
| 76 | + projectId?: string; |
| 77 | + neonAccessToken?: string; |
| 78 | + branch?: string; |
| 79 | + databaseName?: string; |
| 80 | + roleName?: string; |
| 81 | + envVarPrefix?: string; |
| 82 | +}): BuildExtension { |
| 83 | + const sync = syncEnvVars(async (ctx) => { |
| 84 | + const projectId = |
| 85 | + options?.projectId ?? process.env.NEON_PROJECT_ID ?? ctx.env.NEON_PROJECT_ID; |
| 86 | + const neonAccessToken = |
| 87 | + options?.neonAccessToken ?? process.env.NEON_ACCESS_TOKEN ?? ctx.env.NEON_ACCESS_TOKEN; |
| 88 | + const branch = options?.branch ?? ctx.branch; |
| 89 | + const envVarPrefix = options?.envVarPrefix ?? ""; |
| 90 | + const outputEnvVars = NEON_ENV_VARS; |
| 91 | + |
| 92 | + // Skip the whole process for Vercel environments |
| 93 | + if (ctx.env.VERCEL) { |
| 94 | + return []; |
| 95 | + } |
| 96 | + |
| 97 | + if (!projectId) { |
| 98 | + throw new Error( |
| 99 | + "syncNeonEnvVars: you did not pass in a projectId or set the NEON_PROJECT_ID env var." |
| 100 | + ); |
| 101 | + } |
| 102 | + |
| 103 | + if (!neonAccessToken) { |
| 104 | + throw new Error( |
| 105 | + "syncNeonEnvVars: you did not pass in an neonAccessToken or set the NEON_ACCESS_TOKEN env var." |
| 106 | + ); |
| 107 | + } |
| 108 | + |
| 109 | + // Skip branch-specific logic for production environment |
| 110 | + if (ctx.environment === "prod") { |
| 111 | + return []; |
| 112 | + } |
| 113 | + |
| 114 | + if (!branch) { |
| 115 | + throw new Error( |
| 116 | + "syncNeonEnvVars: you did not pass in a branch and no branch was detected from context." |
| 117 | + ); |
| 118 | + } |
| 119 | + |
| 120 | + const environmentMap = { |
| 121 | + prod: "production", |
| 122 | + staging: "preview", |
| 123 | + dev: "development", |
| 124 | + preview: "preview", |
| 125 | + } as const; |
| 126 | + |
| 127 | + const environment = environmentMap[ctx.environment as keyof typeof environmentMap]; |
| 128 | + |
| 129 | + if (!environment) { |
| 130 | + throw new Error( |
| 131 | + `Invalid environment '${ctx.environment}'. Expected 'prod', 'staging', 'dev', or 'preview'.` |
| 132 | + ); |
| 133 | + } |
| 134 | + |
| 135 | + try { |
| 136 | + // Step 1: Search for the branch in Neon |
| 137 | + const branchSearchParams = new URLSearchParams({ search: branch }); |
| 138 | + const branchesUrl = `https://console.neon.tech/api/v2/projects/${projectId}/branches?${branchSearchParams}`; |
| 139 | + const branchesResponse = await fetch(branchesUrl, { |
| 140 | + headers: { |
| 141 | + Authorization: `Bearer ${neonAccessToken}`, |
| 142 | + }, |
| 143 | + }); |
| 144 | + |
| 145 | + if (!branchesResponse.ok) { |
| 146 | + throw new Error(`Failed to fetch Neon branches: ${branchesResponse.status}`); |
| 147 | + } |
| 148 | + |
| 149 | + const branchesData = await branchesResponse.json(); |
| 150 | + const branches: NeonBranch[] = branchesData.branches || []; |
| 151 | + |
| 152 | + if (branches.length === 0) { |
| 153 | + // No matching branch found |
| 154 | + return []; |
| 155 | + } |
| 156 | + |
| 157 | + // Neon branch names are prefixed with environment (e.g., "preview/branch-name") |
| 158 | + const expectedBranchName = `${environment}/${branch}`; |
| 159 | + const matchingBranch = branches.find( |
| 160 | + (b) => b.name === expectedBranchName || b.name === branch |
| 161 | + ); |
| 162 | + |
| 163 | + if (!matchingBranch) { |
| 164 | + // No exact match found |
| 165 | + return []; |
| 166 | + } |
| 167 | + |
| 168 | + const neonBranchId = matchingBranch.id; |
| 169 | + |
| 170 | + // Step 2: Get endpoints for the branch |
| 171 | + const endpointsUrl = `https://console.neon.tech/api/v2/projects/${projectId}/branches/${neonBranchId}/endpoints`; |
| 172 | + const endpointsResponse = await fetch(endpointsUrl, { |
| 173 | + headers: { |
| 174 | + Authorization: `Bearer ${neonAccessToken}`, |
| 175 | + }, |
| 176 | + }); |
| 177 | + |
| 178 | + if (!endpointsResponse.ok) { |
| 179 | + throw new Error(`Failed to fetch Neon branch endpoints: ${endpointsResponse.status}`); |
| 180 | + } |
| 181 | + |
| 182 | + const endpointsData = await endpointsResponse.json(); |
| 183 | + const endpoints: NeonEndpoint[] = endpointsData.endpoints || []; |
| 184 | + |
| 185 | + if (endpoints.length === 0) { |
| 186 | + return []; |
| 187 | + } |
| 188 | + |
| 189 | + // Find an endpoint with type containing 'write', or take the first one |
| 190 | + const writeEndpoint = endpoints.find((ep) => ep.type.includes("write")); |
| 191 | + const endpoint = writeEndpoint || endpoints[0]; |
| 192 | + |
| 193 | + if (!endpoint) { |
| 194 | + return []; |
| 195 | + } |
| 196 | + |
| 197 | + // Step 3: Get databases for the branch |
| 198 | + const databasesUrl = `https://console.neon.tech/api/v2/projects/${projectId}/branches/${neonBranchId}/databases`; |
| 199 | + const databasesResponse = await fetch(databasesUrl, { |
| 200 | + headers: { |
| 201 | + Authorization: `Bearer ${neonAccessToken}`, |
| 202 | + }, |
| 203 | + }); |
| 204 | + |
| 205 | + if (!databasesResponse.ok) { |
| 206 | + throw new Error(`Failed to fetch Neon branch databases: ${databasesResponse.status}`); |
| 207 | + } |
| 208 | + |
| 209 | + const databasesData = await databasesResponse.json(); |
| 210 | + const databases: NeonDatabase[] = databasesData.databases || []; |
| 211 | + |
| 212 | + if (databases.length === 0) { |
| 213 | + return []; |
| 214 | + } |
| 215 | + |
| 216 | + // Find the specified database or use the first one |
| 217 | + const targetDatabase = options?.databaseName |
| 218 | + ? databases.find((db) => db.name === options.databaseName) |
| 219 | + : databases[0]; |
| 220 | + |
| 221 | + if (!targetDatabase) { |
| 222 | + throw new Error( |
| 223 | + `syncNeonEnvVars: Database '${options?.databaseName}' not found in branch.` |
| 224 | + ); |
| 225 | + } |
| 226 | + |
| 227 | + // Step 4: Get the role (user) and password |
| 228 | + const targetRoleName = options?.roleName ?? targetDatabase.owner_name; |
| 229 | + const rolePasswordUrl = `https://console.neon.tech/api/v2/projects/${projectId}/branches/${neonBranchId}/roles/${targetRoleName}/reveal_password`; |
| 230 | + const rolePasswordResponse = await fetch(rolePasswordUrl, { |
| 231 | + headers: { |
| 232 | + Authorization: `Bearer ${neonAccessToken}`, |
| 233 | + }, |
| 234 | + }); |
| 235 | + |
| 236 | + if (!rolePasswordResponse.ok) { |
| 237 | + throw new Error( |
| 238 | + `Failed to fetch Neon role password: ${rolePasswordResponse.status}. Make sure the role '${targetRoleName}' exists and has a password.` |
| 239 | + ); |
| 240 | + } |
| 241 | + |
| 242 | + const rolePasswordData: NeonRole = await rolePasswordResponse.json(); |
| 243 | + const password = rolePasswordData.password; |
| 244 | + |
| 245 | + if (!password) { |
| 246 | + throw new Error( |
| 247 | + `syncNeonEnvVars: No password found for role '${targetRoleName}'. The role may not have a password set.` |
| 248 | + ); |
| 249 | + } |
| 250 | + |
| 251 | + // Step 5: Build new environment variables based on the endpoint host |
| 252 | + const newHost = endpoint.host; |
| 253 | + const poolerHost = newHost.replace(/^([^.]+)\./, "$1-pooler."); |
| 254 | + |
| 255 | + const envVarMappings = buildNeonEnvVarMappings({ |
| 256 | + user: targetRoleName, |
| 257 | + password, |
| 258 | + database: targetDatabase.name, |
| 259 | + host: newHost, |
| 260 | + poolerHost, |
| 261 | + }); |
| 262 | + |
| 263 | + // Build output env vars |
| 264 | + const newEnvVars: EnvVar[] = []; |
| 265 | + |
| 266 | + for (const neonEnvVar of outputEnvVars) { |
| 267 | + const prefixedKey = `${envVarPrefix}${neonEnvVar}`; |
| 268 | + if (envVarMappings[neonEnvVar]) { |
| 269 | + newEnvVars.push({ |
| 270 | + name: prefixedKey, |
| 271 | + value: envVarMappings[neonEnvVar], |
| 272 | + }); |
| 273 | + } |
| 274 | + } |
| 275 | + |
| 276 | + return newEnvVars; |
| 277 | + } catch (error) { |
| 278 | + console.error("Error fetching Neon branch environment variables:", error); |
| 279 | + throw error; |
| 280 | + } |
| 281 | + }); |
| 282 | + |
| 283 | + return { |
| 284 | + name: "SyncNeonEnvVarsExtension", |
| 285 | + async onBuildComplete(context, manifest) { |
| 286 | + await sync.onBuildComplete?.(context, manifest); |
| 287 | + }, |
| 288 | + }; |
| 289 | +} |
0 commit comments