Spaces:
Running

File size: 2,637 Bytes
f7bc54e
 
 
 
 
35d2e8f
f7bc54e
f5c6732
f7bc54e
 
f5c6732
f7bc54e
 
 
 
 
f5c6732
f7bc54e
f5c6732
 
 
 
 
 
 
 
f7bc54e
 
f5c6732
f7bc54e
 
 
f5c6732
 
 
f7bc54e
f5c6732
 
 
 
 
 
 
35d2e8f
f5c6732
 
 
35d2e8f
f5c6732
 
f7bc54e
 
 
f5c6732
f7bc54e
 
 
 
f5c6732
f7bc54e
 
 
 
 
 
f65fb07
f7bc54e
 
f5c6732
f7bc54e
 
f5c6732
 
 
 
 
 
 
 
 
 
 
f7bc54e
 
 
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
import subprocess
import os
import sys
import logging
import time
import traceback

# Configure logging
logging.basicConfig(
    level=logging.INFO, 
    format='[%(asctime)s] %(levelname)s: %(message)s',
    handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)

def run_command(command, shell=True):
    logger.info(f"πŸ‘‰ Running: {command}")
    try:
        result = subprocess.run(
            command, 
            shell=shell, 
            check=True,
            stdout=sys.stdout,
            stderr=sys.stderr
        )
        return result
    except subprocess.CalledProcessError as e:
        logger.error(f"❌ Command failed with exit code {e.returncode}")
        time.sleep(1)
        sys.exit(e.returncode)

def main():
    logger.info("πŸš€ STARTUP SCRIPT INITIALIZED")
    logger.info(f"πŸ“‚ CWD: {os.getcwd()}")
    logger.info(f"🐍 Python: {sys.version}")
    
    # 0. Debug Check: Can we trace the app?
    logger.info("πŸ” Checking if 'app.main' is importable...")
    try:
        import app.main
        logger.info("βœ… 'app.main' imported successfully!")
    except ImportError as e:
        logger.error(f"❌ Failed to import app.main: {e}")
        logger.error(traceback.format_exc())
        sys.exit(1)
    except Exception as e:
        logger.error(f"❌ Unexpected error importing app.main: {e}")
        logger.error(traceback.format_exc())
        sys.exit(1)

    # 1. Run Migrations
    logger.info("πŸ› οΈ Running Database Migrations...")
    run_command("python -m alembic upgrade head")
    logger.info("βœ… Migrations done.")

    # 2. Start Uvicorn
    host = "0.0.0.0"
    port = os.environ.get("PORT", "8000")
    logger.info(f"πŸ”Œ Starting Server on {host}:{port}...")
    
    uvicorn_cmd = [
        "python", "-m", "uvicorn", 
        "app.main:app", 
        "--host", host, 
        "--port", port,
        "--log-level", "info"  # Production level logging
    ]
    
    logger.info(f"▢️ Executing: {' '.join(uvicorn_cmd)}")
    sys.stdout.flush()
    
    # Use subprocess.run instead of exec to catch the exit
    try:
        proc = subprocess.run(uvicorn_cmd, check=False)
        logger.info(f"πŸ›‘ Uvicorn exited with code: {proc.returncode}")
        # If it exits cleanly (0), that's actually bad for a server (it should run forever)
        if proc.returncode == 0:
             logger.error("⚠️ Uvicorn exited with 0, but it should have kept running!")
    except Exception as e:
        logger.error(f"❌ Error running uvicorn: {e}")

    logger.info("πŸ‘‹ Startup script finishing.")

if __name__ == "__main__":
    main()