Spaces:
Paused

File size: 7,492 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
e8ef986
 
cf96a4f
0509823
cf96a4f
 
 
 
e8ef986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5357920
 
0509823
 
 
8c62622
 
 
0509823
8c62622
0509823
 
e8ef986
 
 
 
0509823
cf96a4f
0509823
e8ef986
dbc31e7
 
 
 
de557ab
882eb03
e8ef986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
b7980f7
 
 
 
5eb4857
 
 
b7980f7
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
6ba1c48
 
5eb4857
6ba1c48
 
 
 
 
213ab14
 
6ba1c48
 
 
 
 
 
5eb4857
6ba1c48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
6ba1c48
 
 
 
 
1049d57
 
 
 
6ba1c48
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
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
import json
from sqlalchemy.pool import NullPool, AsyncAdaptedQueuePool
from fastapi.encoders import jsonable_encoder

def custom_json_serializer(obj):
    return json.dumps(jsonable_encoder(obj))

# 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.
        
        pool_class = NullPool if is_worker else AsyncAdaptedQueuePool
        pool_kwargs = {} if is_worker else {
            "pool_size": 25,      # base resident connections
            "max_overflow": 45,   # burst headroom β€” total cap = 70 connections
            "pool_timeout": 10,   # fail fast: surface overload quickly vs. hang for 45s
            "pool_recycle": 300,
            "pool_pre_ping": True,
        }

        _engine = create_async_engine(
            settings.async_database_url,
            echo=settings.DEBUG,
            future=True,
            poolclass=pool_class,
            json_serializer=custom_json_serializer,
            **pool_kwargs,
            connect_args={
                # Use SSL only for cloud/remote databases; local Postgres rarely has SSL enabled
                "sslmode": "require" if (settings.DATABASE_URL and any(
                    x in settings.DATABASE_URL for x in ("supabase", "neon.tech", "render.com", "railway.app")
                )) else "prefer",
                "prepare_threshold": None, # Disable prepared statements for Transaction Mode safety
                "options": "-c statement_timeout=60000", # Protect pool but allow for AI synthesis
            }
        )
    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)

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 with a Distributed Redis Lock.
    Ensures only one instance executes migrations in multi-pod deployments.
    """
    import asyncio
    import uuid
    from core.cache import get_redis_client
    
    lock_key = "nexus:infra:migration_lock"
    # 300s (5m) lock is safer for production migrations
    lock_ttl = 300 
    max_retries = 5
    retry_delay = 2
    
    redis = get_redis_client()
    lock_id = str(uuid.uuid4())
    
    try:
        for attempt in range(max_retries):
            try:
                # 1. Acquire Lock with Unique ID
                acquired = await redis.set(lock_key, lock_id, ex=lock_ttl, nx=True)
                if acquired:
                    logger.info("πŸ” Database Migration Lock ACQUIRED.")
                    try:
                        logger.info("Running Alembic upgrade head...")
                        
                        # Use asyncio.create_subprocess_exec to keep the event loop responsive
                        process = await asyncio.create_subprocess_exec(
                            "alembic", "upgrade", "head",
                            stdout=asyncio.subprocess.PIPE,
                            stderr=asyncio.subprocess.PIPE
                        )
                        
                        stdout, stderr = await process.communicate()
                        
                        if process.returncode == 0:
                            logger.info("βœ… Database migrations completed successfully.")
                        else:
                            logger.error(f"❌ Migration failed with exit code {process.returncode}:\n{stderr.decode()}")
                    finally:
                        # 2. RELEASE LOCK: Only if we still own it (Safe Cleanup)
                        current_val = await redis.get(lock_key)
                        if current_val == lock_id:
                            await redis.delete(lock_key)
                            logger.info("πŸ”“ Database Migration Lock RELEASED.")
                        else:
                            logger.warning("⚠️ Could not release lock: Lock was stolen or expired.")
                    return

                logger.warning(f"⏳ Migration Lock busy, retrying ({attempt+1}/{max_retries})...")
                await asyncio.sleep(retry_delay)
            except Exception as e:
                logger.error(f"❌ Migration Lock Error: {e}")
                await asyncio.sleep(retry_delay)

        logger.error("🚫 Failed to acquire Migration Lock after multiple attempts.")
            
    except Exception as e:
        logger.error(f"⚠️ Unexpected error during distributed migration: {e}")
        # Relinquish the lock if we own it
        # NOTE: In extremely slow migrations, the lock might auto-expire. 
        # This is safer than a permanent deadlock.
        try:
            current_val = await redis.get(lock_key)
            if current_val == lock_id:
                await redis.delete(lock_key)
                logger.info("πŸ”“ Migration Lock released.")
        except Exception:
            pass

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)