Spaces:
3SCError404
/
Paused

File size: 4,280 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
e8ef986
 
4405ca9
e8ef986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5357920
 
 
 
e8ef986
 
 
 
36b0f72
c8fb83f
e8ef986
c8fb83f
de557ab
e8ef986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
b7980f7
 
 
 
5eb4857
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""
Async SQLAlchemy engine and session factory for PostgreSQL.
"""

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
from core.config import get_settings

settings = get_settings()

import sys
import os
from sqlalchemy.pool import NullPool

# Definitive Process Identification: 
# We inspect both environment variables and the actual command line arguments
# to ensure we never misidentify a Worker as an API (or vice versa).
def is_worker_process() -> bool:
    if os.environ.get("NEXUS_MODE") == "worker":
        return True
    # If arq or nexus_worker is in the command line, we are 100% a background worker
    for arg in sys.argv:
        if "arq" in arg.lower() or "nexus_worker" in arg.lower():
            return True
    return False

# Global state for lazy engine initialization
_engine = None
_session_factory = None

def get_engine():
    """Lazily initialize the SQLAlchemy engine with the correct pooling strategy."""
    global _engine
    if _engine is None:
        is_worker = is_worker_process()
        
        # UNIVERSAL FIX: Every process now uses NullPool (Zero-Footprint).
        # We rely 100% on the server-side PgBouncer for pooling.
        # This prevents SQLAlchemy from keeping 'warm' local connections that
        # lead to prepared statement conflicts in transaction-mode proxies.
        _engine = create_async_engine(
            settings.async_database_url,
            echo=settings.DEBUG,
            future=True,
            poolclass=NullPool,
            pool_pre_ping=True, 
            connect_args={
                "sslmode": "require", # Psycopg uses sslmode
                "prepare_threshold": None, # Disable prepared statements for Transaction Mode safety
            }
        )
    return _engine

def get_session_factory():
    """Lazily initialize the session maker."""
    global _session_factory
    if _session_factory is None:
        _session_factory = async_sessionmaker(
            get_engine(),
            class_=AsyncSession,
            expire_on_commit=False,
        )
    return _session_factory

# Proxy objects for backward compatibility with existing imports
class EngineProxy:
    def __getattr__(self, name): return getattr(get_engine(), name)
    def __await__(self): return get_engine().__await__()

class SessionFactoryProxy:
    def __call__(self, **kwargs): return get_session_factory()(**kwargs)
    def __getattr__(self, name): return getattr(get_session_factory(), name)

engine = EngineProxy()
async_session_factory = SessionFactoryProxy()


class Base(DeclarativeBase):
    """Base class for all SQLAlchemy models."""
    pass


async def get_db():
    """
    Standardize database session management.
    Yields an async session and ensures proper rollback on exceptions.
    """
    async with async_session_factory() as session:
        try:
            yield session
            # We DON'T auto-commit here anymore as it can cause issues 
            # with partial updates in complex routes. Endpoints should call await db.commit().
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()


import subprocess
from core.logging import get_logger

logger = get_logger(__name__)

async def run_migrations():
    """
    Run Alembic migrations automatically on startup.
    This replaces the hacky init_db approach.
    """
    try:
        logger.info("Running database migrations via Alembic...")
        # We run this as a subprocess to avoid event loop conflicts 
        # since alembic's env.py often calls asyncio.run()
        subprocess.run(
            ["alembic", "upgrade", "head"],
            check=True
        )
        logger.info("Database migrations completed successfully.")
    except Exception as e:
        logger.error(f"Unexpected error during migration: {e}")
        # In a real app, we might want to exit here to prevent running on old schema
        # For hackathon, we'll log it and continue.
        # raise e

async def init_db():
    """DEPRECATED: Use run_migrations instead for proper versioning."""
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)