Spaces:
Sleeping
Sleeping
fix: replace psycopg2-binary with pg8000 (pure Python) to avoid Vercel Lambda 250MB native dep crash
Browse files- backend/api/index.py +34 -23
- backend/requirements.txt +2 -1
- backend/storage.py +19 -24
backend/api/index.py
CHANGED
|
@@ -1,42 +1,53 @@
|
|
| 1 |
"""
|
| 2 |
Minimal Vercel serverless entry point for OpenCouncil backend.
|
| 3 |
|
| 4 |
-
|
| 5 |
-
avoiding cold-start crashes from missing or incompatible dependencies.
|
| 6 |
"""
|
| 7 |
|
|
|
|
| 8 |
import os
|
| 9 |
import sys
|
| 10 |
from pathlib import Path
|
| 11 |
-
from typing import Any
|
| 12 |
|
| 13 |
# Signal to storage.py that we're on Vercel (use /tmp for SQLite)
|
| 14 |
os.environ["VERCEL"] = "1"
|
| 15 |
|
| 16 |
-
# Ensure the backend root is on sys.path
|
| 17 |
_backend_root = Path(__file__).parent.parent
|
| 18 |
if str(_backend_root) not in sys.path:
|
| 19 |
sys.path.insert(0, str(_backend_root))
|
| 20 |
|
| 21 |
-
# Change working directory to backend root
|
| 22 |
os.chdir(str(_backend_root))
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
return handler(environ, start_response)
|
|
|
|
| 1 |
"""
|
| 2 |
Minimal Vercel serverless entry point for OpenCouncil backend.
|
| 3 |
|
| 4 |
+
Uses Mangum to wrap FastAPI. If imports fail, returns a JSON error response.
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
+
import json
|
| 8 |
import os
|
| 9 |
import sys
|
| 10 |
from pathlib import Path
|
|
|
|
| 11 |
|
| 12 |
# Signal to storage.py that we're on Vercel (use /tmp for SQLite)
|
| 13 |
os.environ["VERCEL"] = "1"
|
| 14 |
|
| 15 |
+
# Ensure the backend root is on sys.path
|
| 16 |
_backend_root = Path(__file__).parent.parent
|
| 17 |
if str(_backend_root) not in sys.path:
|
| 18 |
sys.path.insert(0, str(_backend_root))
|
| 19 |
|
| 20 |
+
# Change working directory to backend root
|
| 21 |
os.chdir(str(_backend_root))
|
| 22 |
|
| 23 |
+
_app = None
|
| 24 |
+
|
| 25 |
+
def _get_app():
|
| 26 |
+
global _app
|
| 27 |
+
if _app is not None:
|
| 28 |
+
return _app
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from mangum import Mangum
|
| 32 |
+
from api.server import app as fastapi_app
|
| 33 |
+
_app = Mangum(fastapi_app, lifespan="off")
|
| 34 |
+
return _app
|
| 35 |
+
except Exception as e:
|
| 36 |
+
import traceback
|
| 37 |
+
# Return a simple WSGI app that shows the error
|
| 38 |
+
error_msg = json.dumps({
|
| 39 |
+
"error": f"Backend initialization failed: {str(e)}",
|
| 40 |
+
"traceback": traceback.format_exc(),
|
| 41 |
+
})
|
| 42 |
+
def error_app(environ, start_response):
|
| 43 |
+
start_response("500 Internal Server Error", [
|
| 44 |
+
("Content-Type", "application/json"),
|
| 45 |
+
("Content-Length", str(len(error_msg))),
|
| 46 |
+
])
|
| 47 |
+
return [error_msg.encode()]
|
| 48 |
+
_app = error_app
|
| 49 |
+
return _app
|
| 50 |
+
|
| 51 |
+
def app(environ, start_response):
|
| 52 |
+
handler = _get_app()
|
| 53 |
return handler(environ, start_response)
|
backend/requirements.txt
CHANGED
|
@@ -14,7 +14,8 @@ openai>=1.0.0
|
|
| 14 |
cryptography>=42.0.0
|
| 15 |
|
| 16 |
# Database — PostgreSQL for Vercel, SQLite for local
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
# Vercel serverless adapter
|
| 20 |
mangum>=0.17.0
|
|
|
|
| 14 |
cryptography>=42.0.0
|
| 15 |
|
| 16 |
# Database — PostgreSQL for Vercel, SQLite for local
|
| 17 |
+
# Pure-Python driver (no native deps) for Lambda compatibility
|
| 18 |
+
pg8000>=1.30.0
|
| 19 |
|
| 20 |
# Vercel serverless adapter
|
| 21 |
mangum>=0.17.0
|
backend/storage.py
CHANGED
|
@@ -51,34 +51,29 @@ if USE_POSTGRES:
|
|
| 51 |
from urllib.parse import urlparse, unquote
|
| 52 |
|
| 53 |
def _get_pg_conn():
|
| 54 |
-
"""Get a PostgreSQL connection.
|
| 55 |
|
| 56 |
-
Parses DATABASE_URL manually to handle special characters in passwords
|
| 57 |
-
(e.g. Supabase Transaction Pooler connection strings with `]`, `@`, etc.).
|
| 58 |
"""
|
| 59 |
-
import
|
| 60 |
-
import psycopg2.extras
|
| 61 |
raw_url = os.environ["DATABASE_URL"]
|
| 62 |
parsed = urlparse(raw_url)
|
| 63 |
|
| 64 |
-
# Build kwargs from parsed URL — this avoids psycopg2's own URL parser
|
| 65 |
-
# which can choke on special characters in the password.
|
| 66 |
kwargs = {
|
| 67 |
"host": parsed.hostname,
|
| 68 |
"port": parsed.port or 6543,
|
| 69 |
-
"
|
| 70 |
"user": parsed.username,
|
| 71 |
"password": unquote(parsed.password) if parsed.password else "",
|
| 72 |
}
|
| 73 |
|
| 74 |
-
# Handle SSL
|
| 75 |
if parsed.query:
|
| 76 |
qs = dict(q.split("=", 1) for q in parsed.query.split("&") if "=" in q)
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
kwargs["sslmode"] = sslmode
|
| 80 |
|
| 81 |
-
conn =
|
| 82 |
conn.autocommit = False
|
| 83 |
return conn
|
| 84 |
|
|
@@ -450,7 +445,7 @@ def _get_minutes_pg(minutes_id: str) -> Optional[Minutes]:
|
|
| 450 |
|
| 451 |
conn = _get_pg_conn()
|
| 452 |
try:
|
| 453 |
-
with conn.cursor(cursor_factory=
|
| 454 |
cur.execute(
|
| 455 |
"SELECT * FROM minutes WHERE id = %s", (minutes_id,)
|
| 456 |
)
|
|
@@ -518,7 +513,7 @@ def _list_minutes_pg(limit: int = 10) -> list[dict]:
|
|
| 518 |
"""List minutes from PostgreSQL."""
|
| 519 |
conn = _get_pg_conn()
|
| 520 |
try:
|
| 521 |
-
with conn.cursor(cursor_factory=
|
| 522 |
cur.execute(
|
| 523 |
"""SELECT id, city, state, meeting_date, meeting_type, title, url,
|
| 524 |
document_url, source
|
|
@@ -669,7 +664,7 @@ def _get_minutes_summary_pg(minutes_id: str) -> Optional[SummaryResponse]:
|
|
| 669 |
|
| 670 |
conn = _get_pg_conn()
|
| 671 |
try:
|
| 672 |
-
with conn.cursor(cursor_factory=
|
| 673 |
cur.execute(
|
| 674 |
"SELECT * FROM minutes_summaries WHERE minutes_id = %s", (minutes_id,)
|
| 675 |
)
|
|
@@ -816,7 +811,7 @@ def _save_summary_sqlite(summary: Summary) -> str:
|
|
| 816 |
def _save_summary_pg(summary: Summary) -> str:
|
| 817 |
conn = _get_pg_conn()
|
| 818 |
try:
|
| 819 |
-
with conn.cursor(cursor_factory=
|
| 820 |
cur.execute(
|
| 821 |
"""INSERT INTO summaries
|
| 822 |
(minutes_id, summary, key_decisions, budget_items,
|
|
@@ -904,7 +899,7 @@ def _get_summary_sqlite(summary_id: str) -> Optional[Summary]:
|
|
| 904 |
def _get_summary_pg(summary_id: str) -> Optional[Summary]:
|
| 905 |
conn = _get_pg_conn()
|
| 906 |
try:
|
| 907 |
-
with conn.cursor(cursor_factory=
|
| 908 |
cur.execute(
|
| 909 |
"SELECT * FROM summaries WHERE id = %s", (summary_id,)
|
| 910 |
)
|
|
@@ -955,7 +950,7 @@ def _list_pending_summaries_sqlite() -> list[dict]:
|
|
| 955 |
def _list_pending_summaries_pg() -> list[dict]:
|
| 956 |
conn = _get_pg_conn()
|
| 957 |
try:
|
| 958 |
-
with conn.cursor(cursor_factory=
|
| 959 |
cur.execute(
|
| 960 |
"""SELECT s.id, s.summary, s.category, s.neighborhood_impact,
|
| 961 |
s.status, s.created_at,
|
|
@@ -1199,7 +1194,7 @@ def _get_volunteer_sqlite(user_id: str) -> Optional[Volunteer]:
|
|
| 1199 |
def _get_volunteer_pg(user_id: str) -> Optional[Volunteer]:
|
| 1200 |
conn = _get_pg_conn()
|
| 1201 |
try:
|
| 1202 |
-
with conn.cursor(cursor_factory=
|
| 1203 |
cur.execute(
|
| 1204 |
"SELECT * FROM volunteers WHERE user_id = %s", (user_id,)
|
| 1205 |
)
|
|
@@ -1249,7 +1244,7 @@ def _get_volunteer_by_email_sqlite(email: str) -> Optional[Volunteer]:
|
|
| 1249 |
def _get_volunteer_by_email_pg(email: str) -> Optional[Volunteer]:
|
| 1250 |
conn = _get_pg_conn()
|
| 1251 |
try:
|
| 1252 |
-
with conn.cursor(cursor_factory=
|
| 1253 |
cur.execute(
|
| 1254 |
"SELECT * FROM volunteers WHERE email = %s", (email,)
|
| 1255 |
)
|
|
@@ -1329,7 +1324,7 @@ def _create_verification_session_sqlite(volunteer_id: str, summary_id: str) -> s
|
|
| 1329 |
def _create_verification_session_pg(volunteer_id: str, summary_id: str) -> str:
|
| 1330 |
conn = _get_pg_conn()
|
| 1331 |
try:
|
| 1332 |
-
with conn.cursor(cursor_factory=
|
| 1333 |
cur.execute(
|
| 1334 |
"""INSERT INTO verification_sessions
|
| 1335 |
(volunteer_id, summary_id)
|
|
@@ -1443,7 +1438,7 @@ def _get_volunteer_sessions_sqlite(user_id: str) -> list[dict]:
|
|
| 1443 |
def _get_volunteer_sessions_pg(user_id: str) -> list[dict]:
|
| 1444 |
conn = _get_pg_conn()
|
| 1445 |
try:
|
| 1446 |
-
with conn.cursor(cursor_factory=
|
| 1447 |
cur.execute(
|
| 1448 |
"""SELECT vs.id, vs.started_at, vs.ended_at, vs.duration_seconds,
|
| 1449 |
vs.action, vs.notes,
|
|
@@ -1564,7 +1559,7 @@ def _backfill_summaries_sqlite() -> dict:
|
|
| 1564 |
def _backfill_summaries_pg() -> dict:
|
| 1565 |
conn = _get_pg_conn()
|
| 1566 |
try:
|
| 1567 |
-
with conn.cursor(cursor_factory=
|
| 1568 |
cur.execute(
|
| 1569 |
"""SELECT ms.*, m.raw_text
|
| 1570 |
FROM minutes_summaries ms
|
|
|
|
| 51 |
from urllib.parse import urlparse, unquote
|
| 52 |
|
| 53 |
def _get_pg_conn():
|
| 54 |
+
"""Get a PostgreSQL connection using pg8000 (pure Python driver).
|
| 55 |
|
| 56 |
+
Parses DATABASE_URL manually to handle special characters in passwords.
|
|
|
|
| 57 |
"""
|
| 58 |
+
import pg8000
|
|
|
|
| 59 |
raw_url = os.environ["DATABASE_URL"]
|
| 60 |
parsed = urlparse(raw_url)
|
| 61 |
|
|
|
|
|
|
|
| 62 |
kwargs = {
|
| 63 |
"host": parsed.hostname,
|
| 64 |
"port": parsed.port or 6543,
|
| 65 |
+
"database": parsed.path.lstrip("/"),
|
| 66 |
"user": parsed.username,
|
| 67 |
"password": unquote(parsed.password) if parsed.password else "",
|
| 68 |
}
|
| 69 |
|
| 70 |
+
# Handle SSL from query params (e.g. ?sslmode=require)
|
| 71 |
if parsed.query:
|
| 72 |
qs = dict(q.split("=", 1) for q in parsed.query.split("&") if "=" in q)
|
| 73 |
+
if qs.get("sslmode") in ("require", "verify-full", "verify-ca"):
|
| 74 |
+
kwargs["ssl_context"] = True
|
|
|
|
| 75 |
|
| 76 |
+
conn = pg8000.connect(**kwargs)
|
| 77 |
conn.autocommit = False
|
| 78 |
return conn
|
| 79 |
|
|
|
|
| 445 |
|
| 446 |
conn = _get_pg_conn()
|
| 447 |
try:
|
| 448 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 449 |
cur.execute(
|
| 450 |
"SELECT * FROM minutes WHERE id = %s", (minutes_id,)
|
| 451 |
)
|
|
|
|
| 513 |
"""List minutes from PostgreSQL."""
|
| 514 |
conn = _get_pg_conn()
|
| 515 |
try:
|
| 516 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 517 |
cur.execute(
|
| 518 |
"""SELECT id, city, state, meeting_date, meeting_type, title, url,
|
| 519 |
document_url, source
|
|
|
|
| 664 |
|
| 665 |
conn = _get_pg_conn()
|
| 666 |
try:
|
| 667 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 668 |
cur.execute(
|
| 669 |
"SELECT * FROM minutes_summaries WHERE minutes_id = %s", (minutes_id,)
|
| 670 |
)
|
|
|
|
| 811 |
def _save_summary_pg(summary: Summary) -> str:
|
| 812 |
conn = _get_pg_conn()
|
| 813 |
try:
|
| 814 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 815 |
cur.execute(
|
| 816 |
"""INSERT INTO summaries
|
| 817 |
(minutes_id, summary, key_decisions, budget_items,
|
|
|
|
| 899 |
def _get_summary_pg(summary_id: str) -> Optional[Summary]:
|
| 900 |
conn = _get_pg_conn()
|
| 901 |
try:
|
| 902 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 903 |
cur.execute(
|
| 904 |
"SELECT * FROM summaries WHERE id = %s", (summary_id,)
|
| 905 |
)
|
|
|
|
| 950 |
def _list_pending_summaries_pg() -> list[dict]:
|
| 951 |
conn = _get_pg_conn()
|
| 952 |
try:
|
| 953 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 954 |
cur.execute(
|
| 955 |
"""SELECT s.id, s.summary, s.category, s.neighborhood_impact,
|
| 956 |
s.status, s.created_at,
|
|
|
|
| 1194 |
def _get_volunteer_pg(user_id: str) -> Optional[Volunteer]:
|
| 1195 |
conn = _get_pg_conn()
|
| 1196 |
try:
|
| 1197 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 1198 |
cur.execute(
|
| 1199 |
"SELECT * FROM volunteers WHERE user_id = %s", (user_id,)
|
| 1200 |
)
|
|
|
|
| 1244 |
def _get_volunteer_by_email_pg(email: str) -> Optional[Volunteer]:
|
| 1245 |
conn = _get_pg_conn()
|
| 1246 |
try:
|
| 1247 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 1248 |
cur.execute(
|
| 1249 |
"SELECT * FROM volunteers WHERE email = %s", (email,)
|
| 1250 |
)
|
|
|
|
| 1324 |
def _create_verification_session_pg(volunteer_id: str, summary_id: str) -> str:
|
| 1325 |
conn = _get_pg_conn()
|
| 1326 |
try:
|
| 1327 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 1328 |
cur.execute(
|
| 1329 |
"""INSERT INTO verification_sessions
|
| 1330 |
(volunteer_id, summary_id)
|
|
|
|
| 1438 |
def _get_volunteer_sessions_pg(user_id: str) -> list[dict]:
|
| 1439 |
conn = _get_pg_conn()
|
| 1440 |
try:
|
| 1441 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 1442 |
cur.execute(
|
| 1443 |
"""SELECT vs.id, vs.started_at, vs.ended_at, vs.duration_seconds,
|
| 1444 |
vs.action, vs.notes,
|
|
|
|
| 1559 |
def _backfill_summaries_pg() -> dict:
|
| 1560 |
conn = _get_pg_conn()
|
| 1561 |
try:
|
| 1562 |
+
with conn.cursor(cursor_factory=pg8000.dbapi.PgCursor) as cur:
|
| 1563 |
cur.execute(
|
| 1564 |
"""SELECT ms.*, m.raw_text
|
| 1565 |
FROM minutes_summaries ms
|