talos-access / backend /entrypoint.sh
Greg
Claude Opus 4.7 (1M context)
feat(entrypoint): auto-detect db state and apply migrations
2b28dbf
Raw History Blame Contribute Delete
3.42 kB
#!/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