|
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( |
| 54 | + `Database connection error (attempt ${attempt}/${MAX_RETRIES}), retrying in ${delay}ms...`, |
| 55 | + error instanceof Error ? error.message : String(error), |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 60 | + |
| 61 | + // Try to reconnect before retrying |
| 62 | + try { |
| 63 | + await prismaClient.$connect(); |
| 64 | + } catch { |
| 65 | + // Ignore connection errors here, let the retry handle it |
| 66 | + } |
| 67 | + |
| 68 | + return withRetry(operation, retries - 1); |
| 69 | + } |
| 70 | + throw error; |
| 71 | + } |
| 72 | +}; |
| 73 | + |
5 | 74 | const createPrismaClient = () => { |
| 75 | + // Validate DATABASE_URL is using pooled connection for Supabase |
| 76 | + const dbUrl = env.DATABASE_URL; |
| 77 | + if (dbUrl && dbUrl.includes("supabase.com")) { |
| 78 | + const isPooler = dbUrl.includes("pooler"); |
| 79 | + const hasWrongPort = dbUrl.includes(":5432"); |
| 80 | + const hasCorrectPort = dbUrl.includes(":6543"); |
| 81 | + |
| 82 | + // Critical error: Using pooler hostname with direct port |
| 83 | + if (isPooler && hasWrongPort) { |
| 84 | + console.error( |
| 85 | + "❌ CRITICAL: DATABASE_URL uses pooler hostname but wrong port (5432). " + |
| 86 | + "For Supabase connection pooler, you MUST use port 6543, not 5432. " + |
| 87 | + "Fix: Replace :5432 with :6543 in your DATABASE_URL. " + |
| 88 | + "Get correct URL from: Supabase Dashboard → Settings → Database → Connection Pooling → Transaction mode", |
| 89 | + ); |
| 90 | + } |
| 91 | + // Error: Using direct connection instead of pooled |
| 92 | + else if (!isPooler && hasWrongPort) { |
| 93 | + console.error( |
| 94 | + "❌ DATABASE_URL is using direct connection (port 5432). " + |
| 95 | + "For Vercel serverless with Supabase, you MUST use the connection pooler URL (port 6543). " + |
| 96 | + "Get it from: Supabase Dashboard → Settings → Database → Connection Pooling → Transaction mode", |
| 97 | + ); |
| 98 | + } |
| 99 | + // Warning: Pooler URL missing pgbouncer parameter |
| 100 | + else if (isPooler && hasCorrectPort && !dbUrl.includes("pgbouncer=true")) { |
| 101 | + console.warn( |
| 102 | + "⚠️ DATABASE_URL uses pooler but missing pgbouncer=true parameter. " + |
| 103 | + "Add ?pgbouncer=true to your connection string for optimal performance.", |
| 104 | + ); |
| 105 | + } |
| 106 | + } |
| 107 | + |
6 | 108 | const client = new PrismaClient({ |
7 | 109 | log: |
8 | 110 | env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"], |
9 | 111 | }); |
10 | 112 |
|
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 | 113 | return client; |
16 | 114 | }; |
17 | 115 |
|
18 | 116 | const globalForPrisma = globalThis as unknown as { |
19 | 117 | prisma: ReturnType<typeof createPrismaClient> | undefined; |
20 | 118 | }; |
21 | 119 |
|
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(); |
| 120 | +// Create or reuse Prisma client |
| 121 | +const prismaClient = globalForPrisma.prisma ?? createPrismaClient(); |
27 | 122 |
|
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 | 123 | if (!globalForPrisma.prisma) { |
32 | | - globalForPrisma.prisma = db; |
| 124 | + globalForPrisma.prisma = prismaClient; |
33 | 125 | } |
34 | 126 |
|
| 127 | +// Create a wrapper that adds retry logic to all Prisma operations |
| 128 | +// We'll intercept model access and wrap query methods |
| 129 | +const createRetryProxy = <T extends object>(target: T): T => { |
| 130 | + return new Proxy(target, { |
| 131 | + get(obj, prop) { |
| 132 | + const value = obj[prop as keyof T]; |
| 133 | + |
| 134 | + // If it's a model (user, wallet, etc.), wrap its methods |
| 135 | + if (value && typeof value === "object" && !prop.toString().startsWith("$")) { |
| 136 | + return createRetryProxy(value as object); |
| 137 | + } |
| 138 | + |
| 139 | + // If it's a function (query method), wrap it with retry logic |
| 140 | + if (typeof value === "function") { |
| 141 | + return (...args: unknown[]) => { |
| 142 | + return withRetry(() => { |
| 143 | + const result = value.apply(obj, args); |
| 144 | + return result instanceof Promise ? result : Promise.resolve(result); |
| 145 | + }); |
| 146 | + }; |
| 147 | + } |
| 148 | + |
| 149 | + return value; |
| 150 | + }, |
| 151 | + }) as T; |
| 152 | +}; |
| 153 | + |
| 154 | +// Export db with retry logic |
| 155 | +export const db = createRetryProxy(prismaClient); |
| 156 | + |
35 | 157 | // Graceful shutdown handling |
36 | 158 | if (typeof process !== "undefined") { |
37 | | - process.on("beforeExit", async () => { |
38 | | - await db.$disconnect(); |
39 | | - }); |
| 159 | + const disconnect = async () => { |
| 160 | + try { |
| 161 | + await prismaClient.$disconnect(); |
| 162 | + } catch (error) { |
| 163 | + // Ignore errors during shutdown |
| 164 | + } |
| 165 | + }; |
40 | 166 |
|
| 167 | + process.on("beforeExit", disconnect); |
41 | 168 | process.on("SIGINT", async () => { |
42 | | - await db.$disconnect(); |
| 169 | + await disconnect(); |
43 | 170 | process.exit(0); |
44 | 171 | }); |
45 | | - |
46 | 172 | process.on("SIGTERM", async () => { |
47 | | - await db.$disconnect(); |
| 173 | + await disconnect(); |
48 | 174 | process.exit(0); |
49 | 175 | }); |
50 | 176 | } |
0 commit comments