File size: 2,348 Bytes
a77ba8b
 
 
909accc
 
 
 
a77ba8b
909accc
 
a77ba8b
909accc
1ff5f67
909accc
 
 
 
68b786c
 
 
 
f3060d7
909accc
 
 
f3060d7
 
 
a77ba8b
909accc
a77ba8b
909accc
a77ba8b
 
909accc
 
 
 
 
 
 
 
c0881b0
909accc
 
c0881b0
909accc
 
 
 
 
a77ba8b
c0881b0
 
 
 
909accc
a77ba8b
 
c0881b0
 
 
 
 
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
#!/usr/bin/env bash
set -euo pipefail

# 1. Configuration
PGDATA="/tmp/postgres"
PGHOST="/tmp"
PG_PORT="5432"
SEKAI_DB_URL="postgresql://sekai:sekai@/sekai?host=${PGHOST}&port=${PG_PORT}"
BACKUP_DIR="/data/db_backups"
BACKUP_FILE="${BACKUP_DIR}/sekai_backup.sql"

mkdir -p "${BACKUP_DIR}"

# 2. Initialize a fresh, ephemeral database
echo "Initializing ephemeral PostgreSQL in ${PGDATA}..."
mkdir -p "${PGDATA}"
chmod 700 "${PGDATA}"

if [ ! -f "${PGDATA}/PG_VERSION" ]; then
    initdb --auth=trust --no-locale --encoding=UTF8 "${PGDATA}" >/dev/null
fi

# 3. Start Postgres
echo "Starting PostgreSQL..."
pg_ctl start -l "${PGDATA}/postgres.log" -o "-k ${PGHOST} -p ${PG_PORT}" -w >/dev/null || {
    cat "${PGDATA}/postgres.log"
    exit 1
}

# 4. Create sekai user and database
if ! psql -h "${PGHOST}" -p "${PG_PORT}" -U sekai -d sekai -c '\q' 2>/dev/null; then
    psql -h "${PGHOST}" -p "${PG_PORT}" -d postgres -c "CREATE DATABASE sekai OWNER sekai;" >/dev/null
fi

# 5. Restore from persistent backup if it exists
if [ -f "${BACKUP_FILE}" ]; then
    echo "Found persistent backup! Restoring database state..."
    psql -h "${PGHOST}" -p "${PG_PORT}" -d sekai < "${BACKUP_FILE}" >/dev/null
else
    echo "No existing backup found. Starting fresh."
fi

# 6. Start Background Auto-Backup Process (Every 5 mins)
(
    while true; do
        sleep 300
        pg_dump -h "${PGHOST}" -p "${PG_PORT}" -U sekai -d sekai --clean --if-exists > "${BACKUP_FILE}.tmp"
        mv "${BACKUP_FILE}.tmp" "${BACKUP_FILE}"
        echo "[Backup] Database automatically saved to persistent storage."
    done
) &

# ── NEW: Graceful Shutdown Trap ──────────────────────────────────────
# If Hugging Face restarts or puts the Space to sleep, force a backup instantly.
trap 'echo "Container stopping! Forcing a final database backup..."; pg_dump -h "${PGHOST}" -p "${PG_PORT}" -U sekai -d sekai --clean --if-exists > "${BACKUP_FILE}.tmp"; mv "${BACKUP_FILE}.tmp" "${BACKUP_FILE}"; echo "Final backup saved! Goodbye."; exit 0' SIGTERM SIGINT

export SEKAI_DATABASE_URL="${SEKAI_DB_URL}"
echo "PostgreSQL ready at ${PGHOST}:${PG_PORT}"

# 7. Start the app (Removed 'exec' so the trap works)
uv run python main.py &

# Wait for the python app to finish or receive a kill signal
wait $!