Spaces:
Sleeping

File size: 11,649 Bytes
3d827f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# Optimized for Hugging Face Spaces (Single-Stage, Non-Root, Persistent Services)
# Database Configuration: PostgreSQL (ledgersg_dev) + Redis (localhost:6379)
FROM python:3.13-trixie

# ──────────────────────────────────────────────────────────────────────────────
# 1. Environment Configuration
# ──────────────────────────────────────────────────────────────────────────────
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PIP_NO_CACHE_DIR=1
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
ENV DEBIAN_FRONTEND=noninteractive
ENV APP_PORT=7860
ENV XDG_RUNTIME_DIR=/tmp/runtime-user
ENV PATH="/home/user/.local/bin:/usr/local/bin:${PATH}"
ENV PGDATA=/var/lib/postgresql/data
ENV PGHOST=/tmp
ENV PGPORT=5432

# Database Configuration (from .env)
ENV DB_NAME=ledgersg_dev
ENV DB_USER=ledgersg
ENV DB_PASSWORD=ledgersg_secret_to_change
ENV DB_HOST=localhost
ENV DB_PORT=5432
ENV REDIS_URL=redis://localhost:6379/0

# ──────────────────────────────────────────────────────────────────────────────
# 2. System Dependencies (Database + Dev Tools)
# ──────────────────────────────────────────────────────────────────────────────
RUN apt-get update && apt-get install -y \
    bash coreutils ca-certificates cron curl wget git less procps sudo vim tar zip unzip tmux openssh-client rsync \
    build-essential gcc gnupg cmake pkg-config \
    libpq-dev libjson-c-dev libssl-dev libwebsockets-dev \
    libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz0b libffi-dev libjpeg-dev libopenjp2-7-dev \
    # Database Servers
    postgresql postgresql-contrib redis-server \
    # Cleanup
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# ──────────────────────────────────────────────────────────────────────────────
# 3. Toolchain Installation (UV, Bun)
# ──────────────────────────────────────────────────────────────────────────────
# SECURITY NOTE: Downloading binaries from raw GitHub URLs is a supply-chain risk.
# Ensure you trust the source 'nordeim/HF-Space'.
RUN cd /usr/bin && \
    wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/bun && \
    wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/uv && \
    wget -q https://github.com/nordeim/HF-Space/raw/refs/heads/main/uvx && \
    chmod a+x /usr/bin/bun /usr/bin/uv*

# ──────────────────────────────────────────────────────────────────────────────
# 4. Python Dependencies
# ──────────────────────────────────────────────────────────────────────────────
RUN pip install --upgrade pip && \
    pip install django-celery-beat && \
    pip install -U django djangorestframework djangorestframework-simplejwt django-cors-headers django-filter && \
    pip install psycopg[binary] celery[redis] redis py-moneyed pydantic weasyprint lxml python-decouple whitenoise gunicorn structlog sentry-sdk[django] pytest pytest-django pytest-cov pytest-xdist model-bakery factory-boy faker httpx ruff mypy django-stubs djangorestframework-stubs pre-commit ipython django-debug-toolbar django-extensions && \
    pip install fastapi uvicorn httpx pydantic python-multipart sqlalchemy alembic aiofiles jinja2

# ──────────────────────────────────────────────────────────────────────────────
# 5. Node.js Installation (Corrected to LTS 20.x)
# ──────────────────────────────────────────────────────────────────────────────
# Node 24.x does not exist. Using 20.x LTS for stability with Next.js/Tooling.
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
    apt-get install -y nodejs && \
    rm -rf /var/lib/apt/lists/* && \
    node --version && \
    npm --version

# ──────────────────────────────────────────────────────────────────────────────
# 6. User & Permission Setup (Hugging Face Requirement)
# ──────────────────────────────────────────────────────────────────────────────
RUN groupadd -g 1000 user && \
    useradd -m -u 1000 -g user -d /home/user user && \
    echo "user ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/user && \
    chmod 0440 /etc/sudoers.d/user && \
    mkdir -p ${XDG_RUNTIME_DIR} /data /app /var/run/postgresql && \
    chown -R user:user ${XDG_RUNTIME_DIR} /data /app /var/run/postgresql

# ──────────────────────────────────────────────────────────────────────────────
# 7. Global NPM & Playwright
# ──────────────────────────────────────────────────────────────────────────────
RUN npm install -g --omit=dev pnpm@latest vite@latest vitest@latest && \
    npx playwright install chromium && \
    npx playwright install-deps chromium

# ──────────────────────────────────────────────────────────────────────────────
# 8. Database & Server Bootstrap Scripts (Embedded)
# ──────────────────────────────────────────────────────────────────────────────
# Create a minimal FastAPI app to satisfy Healthcheck & Keep-Alive
RUN mkdir -p /app/core && \
    chown -R user:user /app

COPY <<EOF /app/core/boot.py
from fastapi import FastAPI
import uvicorn
import os

app = FastAPI()

@app.get("/")
def read_root():
    return {"status": "alive", "service": "LedgerSG Dev Space"}

@app.get("/health")
def health():
    return {"status": "healthy"}

if __name__ == "__main__":
    port = int(os.getenv("APP_PORT", 7860))
    uvicorn.run(app, host="0.0.0.0", port=port)
EOF

# Create Entrypoint Script to manage Postgres, Redis, and Web Server
COPY <<EOF /usr/local/bin/entrypoint.sh
#!/bin/bash
set -e

echo "=== LedgerSG Development Space Starting ==="

# Ensure Postgres data directory exists and is owned by user
mkdir -p \$PGDATA
chown -R user:user \$PGDATA
chown -R user:user /var/run/postgresql

# Initialize Postgres if not exists (as user)
if [ ! -f "\$PGDATA/PG_VERSION" ]; then
    echo "Initializing PostgreSQL cluster..."
    su - user -c "initdb -D \$PGDATA"
    
    # Configure PostgreSQL for password authentication
    echo "Configuring PostgreSQL authentication..."
    
    # Allow local connections with password
    cat >> \$PGDATA/pg_hba.conf << 'PGHBA'
# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             all                                     trust
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5
PGHBA

    # Configure listen addresses
    sed -i "s/#listen_addresses = 'localhost'/listen_addresses = 'localhost'/" \$PGDATA/postgresql.conf
    echo "listen_addresses = 'localhost'" >> \$PGDATA/postgresql.conf
fi

# Start Redis in background
echo "Starting Redis on port 6379..."
redis-server --daemonize yes

# Start Postgres in background (as user)
echo "Starting PostgreSQL on port 5432..."
su - user -c "pg_ctl -D \$PGDATA -l /tmp/postgres.log start"

# Wait for Postgres to be ready
echo "Waiting for PostgreSQL to accept connections..."
for i in {1..30}; do
    if su - user -c "pg_isready -h localhost -p 5432" > /dev/null 2>&1; then
        echo "βœ“ PostgreSQL is ready"
        break
    fi
    if [ \$i -eq 30 ]; then
        echo "βœ— PostgreSQL failed to start within 30 seconds"
        cat /tmp/postgres.log
        exit 1
    fi
    sleep 1
done

# Create database user and database if not exists
echo "Setting up database user and database..."
su - user -c "psql -h localhost -p 5432 -d postgres -c \"SELECT 1 FROM pg_roles WHERE rolname='\$DB_USER'\" | grep -q 1 || psql -h localhost -p 5432 -d postgres -c \"CREATE ROLE \$DB_USER WITH LOGIN PASSWORD '\$DB_PASSWORD';\""

su - user -c "psql -h localhost -p 5432 -d postgres -c \"SELECT 1 FROM pg_database WHERE datname='\$DB_NAME'\" | grep -q 1 || psql -h localhost -p 5432 -d postgres -c \"CREATE DATABASE \$DB_NAME OWNER \$DB_USER;\""

# Grant all privileges
su - user -c "psql -h localhost -p 5432 -d \$DB_NAME -c \"GRANT ALL PRIVILEGES ON DATABASE \$DB_NAME TO \$DB_USER;\""

echo "βœ“ Database setup complete: \$DB_NAME (user: \$DB_USER)"

# Verify Redis is running
echo "Verifying Redis connection..."
if redis-cli ping > /dev/null 2>&1; then
    echo "βœ“ Redis is ready on localhost:6379"
else
    echo "βœ— Redis failed to start"
    exit 1
fi

# Execute the main command (Web Server)
echo "=== Starting Web Server on port \$APP_PORT ==="
exec "\$@"
EOF

RUN chmod +x /usr/local/bin/entrypoint.sh && \
    chown -R user:user /app/core

# ──────────────────────────────────────────────────────────────────────────────
# 9. Finalization
# ──────────────────────────────────────────────────────────────────────────────
USER user
WORKDIR /app
COPY --chown=user:user . /app

# Ensure .env file exists (create empty if not provided)
RUN touch /app/.env && chown user:user /app/.env

EXPOSE ${APP_PORT}

# Healthcheck against the boot.py server
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:${APP_PORT}/health || exit 1

# Use Entrypoint to start DBs, then run the boot.py server
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["python", "/app/core/boot.py"]