arnavam commited on
Commit
4e1faa9
·
1 Parent(s): b9ca729

Graceful DB connection with retries and SSL for Supabase

Browse files
Files changed (1) hide show
  1. app/database.py +34 -4
app/database.py CHANGED
@@ -483,10 +483,40 @@ class PostgresDocumentDatabase:
483
 
484
  async def connect_db():
485
  global client, db
486
- client = await asyncpg.create_pool(settings.postgres_uri, min_size=1, max_size=10)
487
- db = PostgresDocumentDatabase(client)
488
- await db.initialize()
489
- print("Connected to PostgreSQL")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
 
491
 
492
  async def close_db():
 
483
 
484
  async def connect_db():
485
  global client, db
486
+ import asyncio
487
+ import logging
488
+
489
+ logger = logging.getLogger(__name__)
490
+ uri = settings.postgres_uri
491
+
492
+ # Ensure SSL for remote connections (required by Supabase)
493
+ if "supabase" in uri and "sslmode" not in uri:
494
+ separator = "&" if "?" in uri else "?"
495
+ uri = f"{uri}{separator}sslmode=require"
496
+
497
+ max_retries = 3
498
+ for attempt in range(1, max_retries + 1):
499
+ try:
500
+ client = await asyncpg.create_pool(
501
+ uri, min_size=1, max_size=10,
502
+ command_timeout=30, timeout=30,
503
+ )
504
+ db = PostgresDocumentDatabase(client)
505
+ await db.initialize()
506
+ logger.info("Connected to PostgreSQL")
507
+ return
508
+ except Exception as e:
509
+ logger.warning(f"DB connection attempt {attempt}/{max_retries} failed: {e}")
510
+ if attempt < max_retries:
511
+ await asyncio.sleep(2 * attempt)
512
+ else:
513
+ logger.error(
514
+ "Could not connect to PostgreSQL after %d attempts. "
515
+ "App will start but database features will be unavailable.",
516
+ max_retries,
517
+ )
518
+ # Don't crash the app — let it start for health checks
519
+ return
520
 
521
 
522
  async def close_db():