Spaces:
Runtime error

File size: 3,423 Bytes
6aa6081
63ce0aa
 
6aa6081
 
 
63ce0aa
 
 
 
 
 
 
 
1f52113
63ce0aa
 
 
 
 
 
 
 
 
8381024
63ce0aa
 
6aa6081
63ce0aa
 
 
 
6aa6081
63ce0aa
 
6aa6081
63ce0aa
 
 
 
 
 
 
6aa6081
2b28dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aa6081
2b28dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aa6081
2b28dbf
6aa6081
2b28dbf
6aa6081
2b28dbf
 
 
 
 
 
 
 
6aa6081
 
 
 
 
 
 
 
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
#!/usr/bin/env sh
# Entrypoint for the Talos Access backend.
# Flujo: esperar PostgreSQL (TCP) -> migraciones opcionales -> crear esquema -> seed -> uvicorn.
set -e
cd /app

# Wait until PostgreSQL is reachable (works for both local docker-compose and Supabase).
echo "Waiting for PostgreSQL..."
python3 <<'PYEOF'
import os
import socket
import sys
import time
import urllib.parse as up

# Prefer DATABASE_URL if set (Supabase production); otherwise use POSTGRES_* vars.
url = os.environ.get("DATABASE_URL")
if url:
    parsed = up.urlparse(url)
    host = parsed.hostname
    port = parsed.port or 5432
else:
    host = os.environ.get("POSTGRES_HOST", "postgres")
    port = int(os.environ.get("POSTGRES_PORT", "5432"))

print(f"Target: {host}:{port}")
for attempt in range(60):
    try:
        with socket.create_connection((host, port), timeout=2):
            print(f"PostgreSQL reachable at {host}:{port} after {attempt+1} attempt(s)")
            sys.exit(0)
    except OSError:
        time.sleep(2)

print(f"ERROR: PostgreSQL not reachable at {host}:{port} after ~120s", file=sys.stderr)
sys.exit(1)
PYEOF

# Bail if the wait-loop failed (PYEOF exited non-zero).
if [ $? -ne 0 ]; then
    echo "Aborting startup: database is unreachable." >&2
    exit 1
fi

# Detectar estado de BD y elegir camino de inicialización.
# UPGRADE = alembic_version existe        -> alembic upgrade head + create_all (red de seguridad)
# STAMP   = hay tablas sin alembic_version -> create_all + alembic stamp head (adopción)
# INIT    = BD vacía                       -> create_all + alembic stamp head (fresh)
# Fail-fast: si alembic upgrade o stamp fallan, el container nuevo aborta.
# HF Spaces mantiene el container viejo activo si el nuevo no arranca (asunción operativa).
echo "[entrypoint] Detectando estado de BD..."
DB_STATE=$(python3 - <<'PY'
import logging
logging.disable(logging.CRITICAL)  # silencia SQLAlchemy echo antes de importar engine
from app.core.database import engine
from app.core.db_state import detect_db_state
print(detect_db_state(engine))
PY
)
echo "[entrypoint] Estado: $DB_STATE"

case "$DB_STATE" in
  UPGRADE)
    echo "[entrypoint] Aplicando migraciones (alembic upgrade head)..."
    alembic upgrade head || { echo "[entrypoint] FATAL: alembic upgrade failed" >&2; exit 1; }
    echo "[entrypoint] create_all() de seguridad para tablas nuevas sin migracion..."
    python3 - <<'PY'
from app.core.database import Base, engine
import app.models  # noqa: F401 -- registra todos los modelos
Base.metadata.create_all(bind=engine)
print("[entrypoint] create_all OK.")
PY
    ;;
  STAMP|INIT)
    echo "[entrypoint] Creando esquema desde modelos (create_all)..."
    python3 - <<'PY'
from app.core.database import Base, engine
import app.models  # noqa: F401
Base.metadata.create_all(bind=engine)
print("[entrypoint] create_all OK.")
PY
    echo "[entrypoint] Marcando alembic_version en head (alembic stamp head)..."
    alembic stamp head || { echo "[entrypoint] FATAL: alembic stamp failed" >&2; exit 1; }
    ;;
  *)
    echo "[entrypoint] FATAL: estado de BD desconocido: '$DB_STATE'" >&2
    exit 1
    ;;
esac

if [ "${SEED_DEMO:-1}" = "1" ]; then
  echo "[entrypoint] Sembrando datos demo..."
  python3 seed_demo.py || echo "[entrypoint] seed_demo termino con error (continuo)."
fi

echo "[entrypoint] Iniciando uvicorn en 0.0.0.0:8000 ..."
exec uvicorn app.main:app --host 0.0.0.0 --port 8000