# SAP LLM Gateway - Docker Compose Configuration
#
# This configuration supports both local builds and pulling pre-built images from a container registry.
#
# Image Configuration:
#   - DOCKER_REGISTRY: Container registry (default: ghcr.io)
#   - DOCKER_ORGANIZATION: Registry organization (default: st-gr)
#   - DOCKER_TAG: Image version tag (default: latest)
#
# These can be set via:
#   1. .env.docker file in this directory
#   2. Environment variables: export DOCKER_TAG=1.2.3
#   3. Inline: DOCKER_TAG=1.2.3 docker-compose up
#
# Usage Modes:
#   Local builds (default):   docker-compose up --build
#   Pull from registry:       DOCKER_BUILDKIT=0 docker-compose pull && docker-compose up
#   Registry-only mode:       docker-compose -f docker-compose.yml -f docker-compose.registry.yml up
#
services:
  gateway:
    image: ${DOCKER_REGISTRY:-ghcr.io}/${DOCKER_ORGANIZATION:-st-gr}/sail-proxy-gateway:${DOCKER_TAG:-latest}
    build:
      context: ..
      dockerfile: docker/gateway.Dockerfile
    ports:
      - "3000:3000"
    env_file:
      - ../services/gateway/.env
      # FILE_SEARCH_DATABASE_URL lives here (see
      # docker/configs/shared/.env.filesearch-runtime), generated by
      # setup-docker.js from the same secrets that configure the postgres
      # service below, so the password has exactly one source of truth
      # (this file) instead of a second literal. A compose ${VAR} substitution
      # cannot do this: it resolves only from the shell/docker/.env, never from
      # another service's `environment:` block, so it would silently fall back to
      # its own hardcoded default instead of the real postgres password.
      # `required: false` so a fresh clone that hasn't run setup-docker.js yet
      # still starts the gateway (file_search just reports unavailable).
      #
      # Deliberately NOT `.env.postgres`: that file carries
      # FILE_SEARCH_MIGRATION_DATABASE_URL, the privileged DDL credential —
      # the whole point of the split is that the long-running gateway
      # process never holds it, not even unused in its own environment (an
      # RCE in the internet-facing gateway must not be able to read a
      # superuser DSN out of process.env). Only the one-shot
      # `gateway-migrate` service below gets that file.
      - path: .env.filesearch-runtime
        required: false
    environment:
      - DEPLOY_TARGET=docker
      - NODE_ENV=production
      - PORT=3000
      # Override localhost URLs for Docker networking
      - VALKEY_URL=redis://valkey:6379
      - ADMIN_SERVICE_URL=http://nginx:8080/admin
      # Enable unified token authentication system
      - UNIFIED_TOKEN_SYSTEM_ENABLED=true
      # Override debug settings for docker
      - DEBUG=false
    volumes:
      - ../logs/gateway:/app/services/gateway/logs
      - ../services/gateway/api_config.json:/app/services/gateway/api_config.json
    networks:
      - sap-llm-network
    depends_on:
      postgres:
        condition: service_started
      valkey:
        condition: service_started
      admin:
        condition: service_started
      # Ensures the schema (and the restricted runtime role this service's
      # own FILE_SEARCH_DATABASE_URL points at) exist before the gateway's
      # own boot-time runMigration() ever runs — see gateway-migrate below.
      gateway-migrate:
        condition: service_completed_successfully
    restart: unless-stopped

  # One-shot: applies the file_search schema migration and provisions the
  # `gateway` service's DML-only runtime role, then exits. This is the ONLY
  # place FILE_SEARCH_MIGRATION_DATABASE_URL (a bootstrap-superuser DSN) is
  # used or even present in this compose file's containers — see
  # services/gateway/src/fileSearch/migrateCli.ts and
  # cli-tools/file-search-migrate.js for the same logic run outside Docker.
  gateway-migrate:
    image: ${DOCKER_REGISTRY:-ghcr.io}/${DOCKER_ORGANIZATION:-st-gr}/sail-proxy-gateway:${DOCKER_TAG:-latest}
    build:
      context: ..
      dockerfile: docker/gateway.Dockerfile
    env_file:
      - ../services/gateway/.env
      - path: .env.postgres
        required: false
      - path: .env.filesearch-runtime
        required: false
    environment:
      - DEPLOY_TARGET=docker
      - NODE_ENV=production
      # ../services/gateway/.env sets GATEWAY_STANDALONE=false for the real
      # gateway service; `environment:` here overrides that env_file-sourced
      # value (compose gives `environment:` precedence) so migrateCli.ts's
      # isStandaloneMode() check takes the synchronous, local-file config
      # path instead of awaiting Valkey/admin-service events this
      # short-lived one-shot step has no other reason to depend on. Without
      # this override, getFileSearchConfig() falls back to a synchronous
      # getConfig() call while non-standalone mode is still "waiting for
      # admin events", which throws (caught, logged, and silently
      # substitutes FILE_SEARCH_DEFAULTS) instead of reading the real
      # configured embedding_dimensions from api_config.json — verified
      # against a live docker-compose run of this exact service. (Kyma's
      # migrate-file-search initContainer takes the opposite approach —
      # see that manifest — because Admin/Valkey genuinely are reachable
      # there by the time it runs.)
      - GATEWAY_STANDALONE=true
      # CONFIG_FILE_PATH as an absolute path: this container's cwd (WORKDIR
      # /app, per gateway.Dockerfile) does not match where the api_config.json
      # volume below is mounted, so the default cwd-relative `./api_config.json`
      # would silently miss it.
      - CONFIG_FILE_PATH=/app/services/gateway/api_config.json
      # Never let a migration failure block the `gateway` service below from
      # starting (compose's `service_completed_successfully` condition on
      # this service otherwise requires exit code 0 unconditionally). Before
      # this migration step existed, a broken migration cost file_search a
      # 503 and nothing else; this flag keeps that exact blast radius —
      # see migrateCli.ts's own doc comment for the full reasoning. The
      # failure is still logged loudly (docker compose logs gateway-migrate).
      - FILE_SEARCH_MIGRATE_NEVER_BLOCK=true
    command: >
      sh -c "
        echo 'Waiting for PostgreSQL to be ready...'
        while ! nc -z postgres 5432; do sleep 1; done
        echo 'PostgreSQL is ready!'
        node services/gateway/dist/services/gateway/src/fileSearch/migrateCli.js
      "
    volumes:
      - ../services/gateway/api_config.json:/app/services/gateway/api_config.json
    networks:
      - sap-llm-network
    depends_on:
      - postgres
    restart: "no"

  admin:
    image: ${DOCKER_REGISTRY:-ghcr.io}/${DOCKER_ORGANIZATION:-st-gr}/sail-proxy-admin:${DOCKER_TAG:-latest}
    build:
      context: ..
      dockerfile: docker/admin.Dockerfile
    ports:
      # Loopback only (A5): admin trusts X-Auth-Request-Email/Groups, which
      # nginx is supposed to set from its own auth_request result. Publishing
      # this on 0.0.0.0 lets anyone on the network set those headers directly
      # and claim the admin role. Still reachable from the host for debugging.
      - "127.0.0.1:4004:4004"
    env_file:
      - ../services/admin/.env
      - .env.postgres  # Add PostgreSQL configuration for Docker
      - .env.auth
    environment:
      - DEPLOY_TARGET=docker
      - NODE_ENV=production
      - PORT=4004
      - CDS_ENV=pg
      - NODE_CONFIG_ENV=pg
      # Override SQLite DB_PATH from .env file for Docker deployment
      - DB_PATH=
      # Override localhost URLs for Docker networking
      - VALKEY_URL=redis://valkey:6379
      - GATEWAY_URL=http://gateway:3000
      # JWT Authentication Configuration
      - OAUTH2_PROXY_OIDC_ISSUER_URL=http://localhost:8080/dex
    command: >
      sh -c "
        echo 'Waiting for PostgreSQL to be ready...'
        while ! nc -z postgres 5432; do sleep 1; done
        echo 'PostgreSQL is ready!'
        echo 'Deploying schema using cds-deploy (required for @cap-js/postgres)...'
        cd /app/services/admin && /app/node_modules/.bin/cds-deploy --profile pg || { echo 'ERROR: cds-deploy failed; refusing to start with unmigrated schema'; exit 1; }
        echo 'Starting CAP service with custom startup logic...'
        exec node dist/services/admin/src/index.js
      "
    volumes:
      - ../logs/admin:/app/services/admin/logs
      - ../services/admin/api_config.json:/app/services/admin/api_config.json
    networks:
      - sap-llm-network
    depends_on:
      - postgres
      - valkey
      - oauth2-proxy
    restart: unless-stopped

  ollama:
    image: ${DOCKER_REGISTRY:-ghcr.io}/${DOCKER_ORGANIZATION:-st-gr}/sail-proxy-ollama:${DOCKER_TAG:-latest}
    build:
      context: ..
      dockerfile: docker/ollama.Dockerfile
    ports:
      - "11434:11434"
    env_file:
      - ../services/ollama/.env
    environment:
      - NODE_ENV=production
      - PORT=11434
      # Must be here, not only as an ENV in ollama.Dockerfile: `environment:`
      # outranks `env_file:`, and ../services/ollama/.env carries
      # OLLAMA_HOST=localhost (correct for a dev host, wrong in a container).
      # With localhost the app bound ::1 only and the published port above
      # reached nothing, while the app served fine inside the container.
      - OLLAMA_HOST=0.0.0.0
      # Same class of problem as OLLAMA_HOST above: ../services/ollama/.env sets
      # MAIN_PROXY_URL=http://localhost:3000, which is right on a dev host and
      # wrong in a container — there `localhost` is the OLLAMA container, not the
      # gateway, so every /api/chat, /api/generate and streaming call failed with
      # "Cannot connect to main proxy at http://localhost:3000. Is it running?"
      # while the gateway was healthy the whole time. `gateway` is the compose
      # service name on the shared network, and `environment:` outranks env_file.
      - MAIN_PROXY_URL=http://gateway:3000
    networks:
      - sap-llm-network
    depends_on:
      - gateway
    restart: unless-stopped
    profiles:
      - ollama

  valkey:
    image: valkey/valkey:8
    ports:
      # Loopback only (A5): no auth, and cache keys/entries are otherwise
      # readable to anyone who can reach it on the network.
      - "127.0.0.1:6379:6379"
    volumes:
      - valkey_data:/data
    networks:
      - sap-llm-network
    restart: unless-stopped

  dex:
    image: ghcr.io/dexidp/dex:v2.46.1
    ports:
      # Loopback only (A5): nginx already proxies /dex/ at its public port;
      # this direct port is internal wiring, not a client-facing endpoint.
      - "127.0.0.1:5556:5556"      # HTTP OIDC endpoints
    volumes:
      - ./dex.config.yaml:/etc/dex/config.yaml:ro
      - ./okta-saml-ca.pem:/etc/dex/saml-ca.pem:ro
    env_file:
      - .env.auth
    networks:
      - sap-llm-network
    depends_on:
      postgres:
        condition: service_started  
    command: >
      sh -c "
        echo 'Waiting for postgres to be ready...' &&
        while ! nc -z postgres 5432; do sleep 1; done &&
        echo 'PostgreSQL is ready, starting Dex...' &&
        exec dex serve /etc/dex/config.yaml
      "
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:5556/dex/.well-known/openid-configuration"]
      interval: 5s
      timeout: 3s
      retries: 20
      start_period: 10s

  oauth2-proxy:
    image: quay.io/oauth2-proxy/oauth2-proxy:v7.6.0
    depends_on:
      dex:
        condition: service_healthy
    env_file:
      - .env.auth
    ports:
      # Loopback only (A5): nginx already proxies /auth/ and /oauth2/ at its
      # public port; this direct port is internal wiring, not client-facing.
      - "127.0.0.1:4180:4180"
    networks:
      sap-llm-network:
        aliases:
          - oauth2-proxy
    restart: unless-stopped

  postgres:
    # pgvector/pgvector:pg16-trixie is postgres:16 plus the pgvector extension.
    # file_search runs `CREATE EXTENSION IF NOT EXISTS vector` at startup; without
    # this image it fails closed (feature reports unavailable, never throws).
    #
    # Pinned to the "-trixie" variant deliberately, not plain "pg16": plain
    # `postgres:16` and `pgvector/pgvector:pg16` currently build on different
    # Debian releases (trixie/glibc 2.41 vs bookworm/glibc 2.36). An existing
    # install upgrading in place — same volume, image swap only — would keep
    # postgres text-collation data (including admin's CAP schema, which shares
    # this database) built under one glibc and read under another: a silent
    # wrong-results/index-corruption hazard, not a startup failure. "-trixie"
    # matches plain postgres:16's base exactly, so an in-place upgrade never
    # crosses a glibc boundary and this class of problem cannot occur. See
    # docs/developer/release.md for the remediation if a
    # differently-based pgvector image is ever substituted here.
    image: pgvector/pgvector:pg16-trixie
    ports:
      # Loopback only (A5): holds API keys, credentials and usage data for
      # every service; no reason for it to be reachable from the network.
      - "127.0.0.1:5432:5432"
    environment:
      - POSTGRES_DB=sap_llm_gateway
      # Substituted from docker/.env (gitignored), falling back to these
      # placeholders so a fresh clone still starts. setup-docker.js used to
      # rewrite the literals in THIS tracked file with the real generated
      # credentials, which meant every setup run planted a live database
      # password in a file staged for commit.
      #
      # ${VAR} works here specifically because docker/.env is one of the two
      # sources compose substitutes from (the other being the shell). It would
      # NOT work from an env_file: — see the note on the gateway service above,
      # which is why an earlier attempt at this failed.
      - POSTGRES_USER=${POSTGRES_USER:-admin_user}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-admin_password}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - sap-llm-network
    restart: unless-stopped

  nginx:
    image: ${DOCKER_REGISTRY:-ghcr.io}/${DOCKER_ORGANIZATION:-st-gr}/sail-proxy-nginx:${DOCKER_TAG:-latest}
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "${NGINX_PORT:-8080}:${NGINX_PORT:-8080}"
      - "443:443"
    env_file:
      - .env.nginx  # Generated by setup-docker.js with BASE_URL
    environment:
      # Basic configuration
      - NGINX_PORT=${NGINX_PORT:-8080}
      - SERVER_NAME=${SERVER_NAME:-localhost}
      - BASE_URL=${BASE_URL:-http://localhost:8080}
      # Logout configuration
      - LOGOUT_REDIRECT_URL=${LOGOUT_REDIRECT_URL:-http://localhost:8080/admin/app/shell/}
      # Service discovery (uses Docker Compose service names)
      - OAUTH2_PROXY_HOST=oauth2-proxy
      - OAUTH2_PROXY_PORT=4180
      - DEX_HOST=dex
      - DEX_PORT=5556
      - ADMIN_HOST=admin
      - ADMIN_PORT=4004
      - GATEWAY_HOST=gateway
      - GATEWAY_PORT=3000
      # Configuration mode
      - CONFIG_MODE=${CONFIG_MODE:-template}
      # Request timeout configuration
      - REQUEST_TIMEOUT_SECONDS=${REQUEST_TIMEOUT_SECONDS:-900}
    depends_on:
      - oauth2-proxy
      - gateway
      - admin
    networks:
      - sap-llm-network
    restart: unless-stopped

  # S3-compatible storage for local trials of the file_search s3 blob backend. Not started by
  # default, and no credentials here: set both in your shell first (the password at least 8 chars),
  #   MINIO_ROOT_USER=<access-key> MINIO_ROOT_PASSWORD=<secret-key> docker compose --profile minio up -d minio
  # Inside the network the endpoint is http://minio:9000; from the host http://127.0.0.1:59100 (not
  # 59000, which the CI helper ci/scripts/file-search-test-s3.js uses). Same pinned image as the CI.
  minio:
    image: pgsty/minio:RELEASE.2026-08-04T00-00-00Z@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372
    # Refuses to start without both variables: MinIO would otherwise fall back to its well-known
    # default credentials. (A required ${VAR:?} would break `docker compose up` without the profile.)
    entrypoint: ["sh", "-c", "[ -n \"$$MINIO_ROOT_USER\" ] && [ -n \"$$MINIO_ROOT_PASSWORD\" ] || { echo 'set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD' >&2; exit 1; }; exec /usr/bin/docker-entrypoint.sh minio server /data"]
    environment:
      - MINIO_ROOT_USER=${MINIO_ROOT_USER:-}
      - MINIO_ROOT_PASSWORD=${MINIO_ROOT_PASSWORD:-}
    ports:
      # Loopback only, console unpublished.
      - "127.0.0.1:59100:9000"
    volumes:
      - file_search_minio_data:/data
    networks:
      - sap-llm-network
    profiles:
      - minio

networks:
  sap-llm-network:
    driver: bridge

volumes:
  valkey_data:
  postgres_data:
  file_search_minio_data:
