Spaces:
Running
Running
Download db.py from StudentCompanion/alu-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/StudentCompanion/alu-chatbot/resolve/main/db.py
- Command line
-
hf download hf://spaces/StudentCompanion/alu-chatbot/db.py
-
curl -L -o db.py https://huggingface.co/spaces/StudentCompanion/alu-chatbot/resolve/main/db.py
13.2 kB
| """ | |
| Amazon Aurora PostgreSQL connection pool β the structured data layer. | |
| This sits ALONGSIDE the RAG path (ChromaDB + Sheet + Claude), which is | |
| untouched. Aurora holds the relational product data: organizations, users, | |
| opportunities, curators, bookings, conversations/messages, inquiries β and | |
| the analytics views the admin dashboard reads. See schema.sql for the model. | |
| One pool per process (avoids serverless connection exhaustion). The pool is | |
| opened lazily so the app still boots when the database is not configured β | |
| the data-layer routes then return 503 instead of crashing the whole Space. | |
| ---------------------------------------------------------------------------- | |
| AUTH β two supported modes | |
| ---------------------------------------------------------------------------- | |
| This cluster (studentcompanionai) authenticates with IAM, not a static | |
| password (Secrets Manager holds no retrievable secret). So we support both: | |
| 1. PASSWORD mode β set DATABASE_URL to a full libpq URL: | |
| postgresql://USER:PASSWORD@<endpoint>:5432/postgres?sslmode=require | |
| Used as-is. Simplest, if a master password ever gets set. | |
| 2. IAM mode (this cluster) β set these instead of DATABASE_URL: | |
| DB_HOST = studentcompanionai.cluster-xxxx.us-east-1.rds.amazonaws.com | |
| DB_USER = postgres | |
| DB_NAME = postgres (optional, defaults to 'postgres') | |
| DB_REGION = us-east-1 (optional, defaults to AWS_REGION) | |
| AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (HF Space secrets) | |
| A fresh 15-min RDS auth token is generated as the password EACH TIME a | |
| physical connection is opened (pool `configure` hook), so token expiry | |
| never breaks the long-lived pool. Requires, once, on the DB: | |
| GRANT rds_iam TO postgres; | |
| Mode is auto-selected: if DATABASE_URL is set we use PASSWORD mode, else if | |
| DB_HOST is set we use IAM mode, else the data layer is disabled. | |
| """ | |
| import os | |
| import logging | |
| logger = logging.getLogger("db") | |
| _pool = None # lazily-initialised psycopg_pool.ConnectionPool | |
| _init_attempted = False | |
| def _iam_configured() -> bool: | |
| return bool(os.environ.get("DB_HOST", "").strip()) | |
| def _password_configured() -> bool: | |
| return bool(os.environ.get("DATABASE_URL", "").strip()) | |
| def _region() -> str: | |
| return ( | |
| os.environ.get("DB_REGION") | |
| or os.environ.get("AWS_REGION") | |
| or os.environ.get("AWS_DEFAULT_REGION") | |
| or "us-east-1" | |
| ).strip() | |
| def _build_password_pool(): | |
| """PASSWORD mode: DATABASE_URL used verbatim as the connection string.""" | |
| from psycopg_pool import ConnectionPool | |
| from psycopg.rows import dict_row | |
| dsn = os.environ["DATABASE_URL"].strip() | |
| pool = ConnectionPool( | |
| dsn, | |
| min_size=1, | |
| max_size=10, | |
| kwargs={"row_factory": dict_row}, | |
| open=True, | |
| ) | |
| pool.wait(timeout=10.0) | |
| return pool | |
| def _build_iam_pool(): | |
| """ | |
| IAM mode: connect with a freshly-minted RDS auth token as the password. | |
| psycopg_pool has no per-connection password hook, so we subclass | |
| psycopg.Connection and override `connect` to inject a fresh 15-min RDS | |
| auth token at the moment each physical connection is opened. The pool | |
| calls this on initial fill AND on every reconnect, so a token never | |
| outlives the connection that used it β long-lived pools keep working. | |
| """ | |
| import boto3 | |
| from psycopg_pool import ConnectionPool | |
| from psycopg.rows import dict_row | |
| import psycopg | |
| host = os.environ["DB_HOST"].strip() | |
| user = os.environ.get("DB_USER", "postgres").strip() | |
| dbname = os.environ.get("DB_NAME", "postgres").strip() | |
| port = int(os.environ.get("DB_PORT", "5432")) | |
| region = _region() | |
| rds = boto3.client("rds", region_name=region) | |
| class _IAMConnection(psycopg.Connection): | |
| def connect(cls, conninfo="", **kwargs): | |
| token = rds.generate_db_auth_token( | |
| DBHostname=host, Port=port, DBUsername=user, Region=region | |
| ) | |
| kwargs.update( | |
| host=host, | |
| port=port, | |
| dbname=dbname, | |
| user=user, | |
| password=token, | |
| sslmode="require", | |
| ) | |
| return super().connect("", **kwargs) | |
| pool = ConnectionPool( | |
| connection_class=_IAMConnection, | |
| kwargs={"row_factory": dict_row}, | |
| min_size=1, | |
| max_size=10, | |
| # This Serverless v2 cluster auto-pauses (min 0 ACUs); a cold resume | |
| # can take 30s+. Allow generous time for the first connection and a | |
| # long checkout window before a request gives up. | |
| timeout=60.0, | |
| open=True, | |
| ) | |
| # Try to warm the pool, but DON'T fail the whole data layer if the cluster | |
| # is mid-resume β keep the pool so later requests succeed once it's warm. | |
| try: | |
| pool.wait(timeout=45.0) | |
| logger.info("[db] IAM pool warm") | |
| except Exception as e: | |
| logger.warning("[db] pool not warm yet (cluster resuming?): %s", e) | |
| return pool | |
| def _build_pool(): | |
| """Create the connection pool, or return None if it can't be built.""" | |
| if not _password_configured() and not _iam_configured(): | |
| logger.error( | |
| "[db] No DB config β set DATABASE_URL (password) or DB_HOST (IAM). " | |
| "Aurora data-layer routes will 503." | |
| ) | |
| return None | |
| try: | |
| if _password_configured(): | |
| pool = _build_password_pool() | |
| logger.info("[db] Aurora pool ready (password mode)") | |
| else: | |
| pool = _build_iam_pool() | |
| logger.info("[db] Aurora pool ready (IAM-token mode)") | |
| return pool | |
| except ImportError as e: | |
| logger.error('[db] Missing dependency: %s β need "psycopg[binary,pool]" and boto3', e) | |
| return None | |
| except Exception as e: | |
| logger.error("[db] Failed to open Aurora pool: %s", e) | |
| return None | |
| def get_pool(): | |
| """ | |
| Return the process-wide connection pool, building it on first use. | |
| Returns None if no DB is configured or the pool can't be opened; callers | |
| should treat None as "data layer unavailable" and raise 503. | |
| """ | |
| global _pool, _init_attempted | |
| if _pool is None and not _init_attempted: | |
| _init_attempted = True | |
| _pool = _build_pool() | |
| return _pool | |
| def db_enabled() -> bool: | |
| return get_pool() is not None | |
| def get_org_by_domain(domain: str) -> dict | None: | |
| """ | |
| Look up an active organization by email domain (e.g. "alustudent.com"). | |
| Returns the organization row as a dict ({"id", "name", "email_domain"}) | |
| or None if no active organization matches or the data layer is unavailable. | |
| Callers decide what "not found" means for them (401 vs. 403 vs. a | |
| single-tenant fallback) β this function never raises for a normal miss. | |
| """ | |
| pool = get_pool() | |
| if pool is None: | |
| return None | |
| with pool.connection() as conn: | |
| row = conn.execute( | |
| "SELECT id, name, email_domain FROM organizations " | |
| "WHERE email_domain = %s AND is_active", | |
| (domain.lower().strip(),), | |
| ).fetchone() | |
| return dict(row) if row else None | |
| def list_organizations_with_sheets() -> list[dict]: | |
| """ | |
| Every active organization that has its own Google Sheet configured. | |
| Drives the per-organization sheet sync: each row's Sheet is fetched and | |
| written into that organization's OWN collection. Organizations without a | |
| sheet_url are simply absent from this list β having no Sheet is a normal | |
| state (their knowledge base can still be filled by document upload), not | |
| an error. | |
| Returns an empty list when the data layer isn't configured, so the caller | |
| can degrade to the legacy single-Sheet path rather than crash. | |
| """ | |
| pool = get_pool() | |
| if pool is None: | |
| return [] | |
| with pool.connection() as conn: | |
| rows = conn.execute( | |
| "SELECT id, name, email_domain, sheet_url FROM organizations " | |
| "WHERE is_active AND sheet_url IS NOT NULL AND sheet_url <> '' " | |
| "ORDER BY name" | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def set_organization_sheet_url(organization_id: str, sheet_url: str | None) -> bool: | |
| """ | |
| Set (or clear, with None) one organization's Sheet URL. | |
| Returns False if the data layer isn't configured or no such active | |
| organization exists, so the caller can surface a real error instead of | |
| silently appearing to succeed. | |
| """ | |
| pool = get_pool() | |
| if pool is None: | |
| return False | |
| cleaned = (sheet_url or "").strip() or None | |
| with pool.connection() as conn: | |
| cur = conn.execute( | |
| "UPDATE organizations SET sheet_url = %s WHERE id = %s AND is_active", | |
| (cleaned, organization_id), | |
| ) | |
| return cur.rowcount > 0 | |
| def get_admin_organization(email: str) -> str | None: | |
| """ | |
| Return the single organization_id `email` is authorized to administer, | |
| or None if it isn't an active admin for any organization. | |
| This is the real per-organization replacement for the old flat | |
| ADMIN_EMAILS env var: an admin email is tied to exactly ONE | |
| organization_id in the organization_admins table (UNIQUE(email) enforces | |
| this at the database level), so there is no request path where an | |
| admin's identity could resolve to an org other than the one they were | |
| actually granted. Callers must use the org_id THIS FUNCTION RETURNS β | |
| never re-derive an org from the admin's own email domain, which is what | |
| the code this replaces did (see auth.py / admin_routes.py history) and | |
| which breaks for an admin whose personal email domain doesn't match | |
| their organization's). | |
| """ | |
| pool = get_pool() | |
| if pool is None: | |
| return None | |
| with pool.connection() as conn: | |
| row = conn.execute( | |
| "SELECT organization_id FROM organization_admins " | |
| "WHERE email = %s AND is_active", | |
| (email.lower().strip(),), | |
| ).fetchone() | |
| return row["organization_id"] if row else None | |
| def seed_admin_emails_from_env_once(legacy_admin_emails: set[str], org_email_domain: str) -> None: | |
| """ | |
| One-time migration: if organization_admins is completely empty and the | |
| legacy ADMIN_EMAILS env var still has values, seed each of those emails | |
| as an admin of the organization matching `org_email_domain` (ALU, in | |
| practice β this is the migration path for the deployment that already | |
| exists, not a general mechanism for onboarding new admins). | |
| Deliberately does nothing if organization_admins already has ANY rows β | |
| this only ever runs once, on the first boot after this table exists, and | |
| never overwrites or duplicates what's already been migrated or added | |
| since. Called at startup (see app.py); failures are logged, not raised, | |
| so a migration hiccup never prevents the app from booting. | |
| """ | |
| if not legacy_admin_emails: | |
| return | |
| pool = get_pool() | |
| if pool is None: | |
| return | |
| try: | |
| with pool.connection() as conn: | |
| existing_count = conn.execute( | |
| "SELECT count(*) AS n FROM organization_admins" | |
| ).fetchone()["n"] | |
| if existing_count > 0: | |
| return | |
| org = conn.execute( | |
| "SELECT id FROM organizations WHERE email_domain = %s", | |
| (org_email_domain.lower().strip(),), | |
| ).fetchone() | |
| if org is None: | |
| logger.warning( | |
| "[db] Cannot seed organization_admins: no organization " | |
| "found for domain %s", org_email_domain, | |
| ) | |
| return | |
| for email in legacy_admin_emails: | |
| conn.execute( | |
| "INSERT INTO organization_admins (organization_id, email) " | |
| "VALUES (%s, %s) ON CONFLICT (email) DO NOTHING", | |
| (org["id"], email.lower().strip()), | |
| ) | |
| logger.info( | |
| "[db] Seeded %d admin email(s) from legacy ADMIN_EMAILS into " | |
| "organization_admins for domain %s", | |
| len(legacy_admin_emails), org_email_domain, | |
| ) | |
| except Exception as e: | |
| logger.error("[db] organization_admins seed migration failed: %s", e) | |
| def get_status() -> dict: | |
| """ | |
| Health snapshot for /api/services/status. Actually probes a connection so | |
| the status reflects whether queries work right now β not just whether the | |
| pool object exists (it may be mid-resume on this auto-pausing cluster). | |
| """ | |
| mode = "password" if _password_configured() else ("iam" if _iam_configured() else "unconfigured") | |
| pool = get_pool() | |
| if pool is None: | |
| return {"enabled": False, "mode": mode, "reachable": False} | |
| reachable = False | |
| detail = None | |
| try: | |
| with pool.connection(timeout=60.0) as conn: | |
| conn.execute("SELECT 1") | |
| reachable = True | |
| except Exception as e: | |
| detail = str(e)[:200] | |
| out = {"enabled": True, "mode": mode, "reachable": reachable} | |
| if detail: | |
| out["error"] = detail | |
| return out | |