|
1 | | -import { PrismaClient } from "@prisma/client"; |
| 1 | +import { PrismaClient, Prisma } from "@prisma/client"; |
2 | 2 |
|
3 | 3 | import { env } from "@/env"; |
4 | 4 |
|
| 5 | +// Connection retry configuration |
| 6 | +const MAX_RETRIES = 3; |
| 7 | +const INITIAL_RETRY_DELAY_MS = 500; |
| 8 | + |
| 9 | +// Check if error is a connection error that should be retried |
| 10 | +const isConnectionError = (error: unknown): boolean => { |
| 11 | + if (error instanceof Prisma.PrismaClientKnownRequestError) { |
| 12 | + // P1001: Can't reach database server |
| 13 | + // P1008: Operations timed out |
| 14 | + // P1017: Server has closed the connection |
| 15 | + return ["P1001", "P1008", "P1017"].includes(error.code); |
| 16 | + } |
| 17 | + if (error instanceof Prisma.PrismaClientUnknownRequestError) { |
| 18 | + const message = error.message.toLowerCase(); |
| 19 | + return ( |
| 20 | + message.includes("can't reach database server") || |
| 21 | + message.includes("connection") || |
| 22 | + message.includes("timeout") || |
| 23 | + message.includes("econnrefused") |
| 24 | + ); |
| 25 | + } |
| 26 | + // Check for generic connection errors |
| 27 | + if (error instanceof Error) { |
| 28 | + const message = error.message.toLowerCase(); |
| 29 | + return ( |
| 30 | + message.includes("can't reach database server") || |
| 31 | + message.includes("connection") || |
| 32 | + message.includes("timeout") || |
| 33 | + message.includes("econnrefused") |
| 34 | + ); |
| 35 | + } |
| 36 | + return false; |
| 37 | +}; |
| 38 | + |
| 39 | +// Retry wrapper for database operations with exponential backoff |
| 40 | +const withRetry = async <T>( |
| 41 | + operation: () => Promise<T>, |
| 42 | + retries = MAX_RETRIES, |
| 43 | +): Promise<T> => { |
| 44 | + try { |
| 45 | + return await operation(); |
| 46 | + } catch (error) { |
| 47 | + if (retries > 0 && isConnectionError(error)) { |
| 48 | + // Exponential backoff: 500ms, 1000ms, 2000ms |
| 49 | + const attempt = MAX_RETRIES - retries + 1; |
| 50 | + const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt - 1); |
| 51 | + |
| 52 | + if (env.NODE_ENV === "development") { |
| 53 | + console.warn(`Database connection error, retrying in ${delay}ms (${attempt}/${MAX_RETRIES})`); |
| 54 | + } |
| 55 | + |
| 56 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 57 | + |
| 58 | + // Try to reconnect before retrying |
| 59 | + try { |
| 60 | + await prismaClient.$connect(); |
| 61 | + } catch { |
| 62 | + // Ignore connection errors here, let the retry handle it |
| 63 | + } |
| 64 | + |
| 65 | + return withRetry(operation, retries - 1); |
| 66 | + } |
| 67 | + throw error; |
| 68 | + } |
| 69 | +}; |
| 70 | + |
5 | 71 | const createPrismaClient = () => { |
| 72 | + // Validate DATABASE_URL is using pooled connection for Supabase |
| 73 | + const dbUrl = env.DATABASE_URL; |
| 74 | + if (dbUrl) { |
| 75 | + try { |
| 76 | + // Properly parse URL to validate hostname instead of substring matching |
| 77 | + const url = new URL(dbUrl); |
| 78 | + const hostname = url.hostname.toLowerCase(); |
| 79 | + const port = url.port ? parseInt(url.port, 10) : (url.protocol === "postgresql:" ? 5432 : null); |
| 80 | + const isSupabase = hostname.endsWith(".supabase.com") || hostname === "supabase.com"; |
| 81 | + const isPooler = hostname.includes("pooler"); |
| 82 | + const searchParams = new URLSearchParams(url.search); |
| 83 | + const hasPgbouncer = searchParams.has("pgbouncer") && searchParams.get("pgbouncer") === "true"; |
| 84 | + |
| 85 | + if (isSupabase) { |
| 86 | + if (isPooler && port === 5432) { |
| 87 | + console.error("DATABASE_URL: pooler hostname requires port 6543, not 5432"); |
| 88 | + } else if (!isPooler && port === 5432) { |
| 89 | + console.error("DATABASE_URL: use connection pooler (port 6543) for serverless"); |
| 90 | + } else if (isPooler && port === 6543 && !hasPgbouncer) { |
| 91 | + console.warn("DATABASE_URL: add ?pgbouncer=true for optimal performance"); |
| 92 | + } |
| 93 | + } |
| 94 | + } catch (error) { |
| 95 | + // If URL parsing fails, log warning but don't block initialization |
| 96 | + // Prisma will handle invalid URLs with its own error messages |
| 97 | + if (env.NODE_ENV === "development") { |
| 98 | + console.warn("Could not parse DATABASE_URL for validation:", error); |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
6 | 103 | const client = new PrismaClient({ |
7 | 104 | log: |
8 | 105 | env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"], |
9 | 106 | }); |
10 | 107 |
|
11 | | - // In serverless environments (Vercel), we want to avoid eager connection |
12 | | - // Prisma will connect lazily on first query, which is better for cold starts |
13 | | - // Don't call $connect() here - let Prisma handle connections on-demand |
14 | | - |
15 | 108 | return client; |
16 | 109 | }; |
17 | 110 |
|
18 | 111 | const globalForPrisma = globalThis as unknown as { |
19 | 112 | prisma: ReturnType<typeof createPrismaClient> | undefined; |
20 | 113 | }; |
21 | 114 |
|
22 | | -// Reuse Prisma client across invocations to optimize connection pooling |
23 | | -// In Vercel serverless, the same container may handle multiple requests |
24 | | -// Reusing the client prevents creating new connections for each request |
25 | | -export const db = |
26 | | - globalForPrisma.prisma ?? createPrismaClient(); |
| 115 | +// Create or reuse Prisma client |
| 116 | +const prismaClient = globalForPrisma.prisma ?? createPrismaClient(); |
27 | 117 |
|
28 | | -// Store in globalThis for reuse across all environments |
29 | | -// This is especially important in serverless where the same container |
30 | | -// may handle multiple requests, allowing connection reuse |
31 | 118 | if (!globalForPrisma.prisma) { |
32 | | - globalForPrisma.prisma = db; |
| 119 | + globalForPrisma.prisma = prismaClient; |
33 | 120 | } |
34 | 121 |
|
| 122 | +// Create a wrapper that adds retry logic to all Prisma operations |
| 123 | +// We'll intercept model access and wrap query methods |
| 124 | +const createRetryProxy = <T extends object>(target: T): T => { |
| 125 | + return new Proxy(target, { |
| 126 | + get(obj, prop) { |
| 127 | + const value = obj[prop as keyof T]; |
| 128 | + |
| 129 | + // If it's a model (user, wallet, etc.), wrap its methods |
| 130 | + if (value && typeof value === "object" && !prop.toString().startsWith("$")) { |
| 131 | + return createRetryProxy(value as object); |
| 132 | + } |
| 133 | + |
| 134 | + // If it's a function (query method), wrap it with retry logic |
| 135 | + if (typeof value === "function") { |
| 136 | + return (...args: unknown[]) => { |
| 137 | + return withRetry(() => { |
| 138 | + const result = value.apply(obj, args); |
| 139 | + return result instanceof Promise ? result : Promise.resolve(result); |
| 140 | + }); |
| 141 | + }; |
| 142 | + } |
| 143 | + |
| 144 | + return value; |
| 145 | + }, |
| 146 | + }) as T; |
| 147 | +}; |
| 148 | + |
| 149 | +// Export db with retry logic |
| 150 | +export const db = createRetryProxy(prismaClient); |
| 151 | + |
35 | 152 | // Graceful shutdown handling |
36 | 153 | if (typeof process !== "undefined") { |
37 | | - process.on("beforeExit", async () => { |
38 | | - await db.$disconnect(); |
39 | | - }); |
| 154 | + const disconnect = async () => { |
| 155 | + try { |
| 156 | + await prismaClient.$disconnect(); |
| 157 | + } catch (error) { |
| 158 | + // Ignore errors during shutdown |
| 159 | + } |
| 160 | + }; |
40 | 161 |
|
| 162 | + process.on("beforeExit", disconnect); |
41 | 163 | process.on("SIGINT", async () => { |
42 | | - await db.$disconnect(); |
| 164 | + await disconnect(); |
43 | 165 | process.exit(0); |
44 | 166 | }); |
45 | | - |
46 | 167 | process.on("SIGTERM", async () => { |
47 | | - await db.$disconnect(); |
| 168 | + await disconnect(); |
48 | 169 | process.exit(0); |
49 | 170 | }); |
50 | 171 | } |
0 commit comments