# syntax=docker/dockerfile:1
#
# MTUSI Messenger, lab4 — PostgreSQL + Redis/Valkey HTTP API.
# Base image is pinned by tag *and* digest (multi-arch manifest list), so a rebuild
# on another machine with the same platform yields the same layers.
#
# Runtime dependencies: psycopg2-binary for PostgreSQL, redis for the session cache.
# Development-only tooling lives in requirements-dev.txt and never enters this image.
FROM python:3.12-slim-bookworm@sha256:392307d22300de8b5986851a12d9176dfc0fc073e65bf6523ebd7dcbeb23564e

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONPATH=/app/src

# Pinned runtime dependencies (versions fixed for reproducible builds).
RUN pip install --no-cache-dir \
        psycopg2-binary==2.9.11 \
        redis==7.0.1 \
        bcrypt==4.0.1 \
        boto3==1.42.97 \
        Pillow==12.3.0

# Unprivileged runtime account; the image's default root user is never used at runtime.
RUN groupadd --gid 10001 app \
 && useradd --uid 10001 --gid 10001 --create-home --shell /usr/sbin/nologin app

ARG APP_REVISION=local
ENV APP_REVISION=$APP_REVISION

WORKDIR /app
COPY --chown=10001:10001 src/ /app/src/
COPY --chown=10001:10001 migrations/ /app/migrations/

USER 10001:10001

# Configuration comes from the environment; secrets are read from files at runtime.
ENV APP_HOST=0.0.0.0 \
    APP_PORT=8080 \
    APP_ENV=lab \
    LOG_LEVEL=info \
    SHUTDOWN_GRACE_SECONDS=8 \
    SESSION_TTL_SECONDS=3600 \
    SESSION_STORE=redis \
    DB_POOL_MIN=2 \
    DB_POOL_MAX=10 \
    DB_CONNECT_TIMEOUT=5 \
    DB_STATEMENT_TIMEOUT=10

EXPOSE 8080

# Python (not curl) keeps the image slim; /health/ready is the synchronous-path probe.
HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \
    CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/health/ready' % os.environ.get('APP_PORT', '8080'), timeout=2)"]

STOPSIGNAL SIGTERM

# The HTTP process is PID 1 and handles SIGTERM itself (graceful drain, exit code 0).
CMD ["python", "-m", "messenger"]
