# Runtime image for the lab3 API.  The base tag is pinned; dependencies are
# installed from requirements.txt, never from a mutable latest tag.
#
# Every replica runs exactly the same image.  The replica alias is its
# container hostname (see app/config.py), so no container_name is needed and
# Compose can scale the service freely.

FROM python:3.12.7-slim-bookworm

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

WORKDIR /app

RUN groupadd --system --gid 10001 app \
    && useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app

COPY requirements.txt ./
RUN python -m pip install --requirement requirements.txt

COPY app ./app
COPY migrations ./migrations
COPY student-tests ./student-tests

USER app
EXPOSE 8080

HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=6 \
    CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).read()"]

# One worker with a bounded thread pool per replica: the unit of horizontal
# scaling is the container, which keeps instance ids and CPU limits legible.
# Gunicorn stops accepting on SIGTERM and drains in-flight requests for at most
# 8 seconds; Docker's stop_grace_period gives it room to finish.
STOPSIGNAL SIGTERM
CMD ["gunicorn", "--bind=0.0.0.0:8080", "--workers=1", "--threads=8", "--timeout=30", "--graceful-timeout=8", "--keep-alive=5", "--worker-tmp-dir=/dev/shm", "--access-logfile=-", "--error-logfile=-", "app.main:app"]
