#!/usr/bin/env bash # entrypoint.sh — boot in-container Postgres, then hand off to the CMD # (which is supervisord managing uvicorn + celery worker + celery beat). # # Runs as uid 1000 on Hugging Face Spaces. Postgres data lives in /tmp # and is wiped on every container restart — that's intentional, the user # chose this trade-off in exchange for not depending on an external DB. set -euo pipefail PG_BIN=/usr/lib/postgresql/${PG_MAJOR:-15}/bin PG_LOG=/tmp/postgres.log echo "[entrypoint] boot — uid=$(id -u) pgdata=$PGDATA" # --- 1. Initialise Postgres data dir on first boot -------------------------- if [ ! -s "$PGDATA/PG_VERSION" ]; then echo "[entrypoint] initdb on $PGDATA" "$PG_BIN/initdb" \ -D "$PGDATA" \ -U postgres \ --auth-host=md5 \ --auth-local=trust \ --encoding=UTF8 \ --locale=C.UTF-8 \ >/dev/null # Bind only to localhost — the API and Celery talk to it over the # loopback inside the same container. cat >> "$PGDATA/postgresql.conf" <<'CONF' listen_addresses = '127.0.0.1' port = 5432 # /var/run/postgresql is not writable in HF Spaces; keep the unix socket # in /tmp where uid 1000 can write. unix_socket_directories = '/tmp' # Container memory tuning. HF /dev/shm is typically small (~64MB), so # keep shared_buffers low. The API processes IFC, not OLAP queries. shared_buffers = 64MB work_mem = 4MB maintenance_work_mem = 16MB max_connections = 20 # Disable kernel features that containers usually don't grant. huge_pages = off dynamic_shared_memory_type = posix CONF fi # --- 2. Start Postgres in the background ------------------------------------ echo "[entrypoint] starting postgres" if ! "$PG_BIN/pg_ctl" -D "$PGDATA" -l "$PG_LOG" -w -t 30 start; then echo "[entrypoint] pg_ctl start FAILED. Dumping $PG_LOG:" >&2 echo "---------------- postgres.log ----------------" >&2 cat "$PG_LOG" >&2 || true echo "---------------- end log -------------------" >&2 exit 1 fi # --- 3. Ensure user / database / extension exist ---------------------------- # Idempotent: safe to run on every boot. On a fresh PGDATA they get created; # on a warm one nothing happens. psql -h /tmp -U postgres -d postgres -v ON_ERROR_STOP=1 <&2 || true exit 1 fi echo "[entrypoint] alembic OK" # --- 5. Hand off to the original CMD (supervisord) ------------------------- echo "[entrypoint] handing off to: $*" exec "$@"