services:
  openalgo:
    image: openalgo:latest
    build:
      context: .
      dockerfile: Dockerfile

    container_name: openalgo-web
    ports:
      - "${FLASK_PORT:-5000}:5000"
      - "${WEBSOCKET_PORT:-8765}:8765"

    # persistent DB, strategies, logs + mount the host .env read-only so dotenv can read it
    volumes:
      - openalgo_db:/app/db
      - openalgo_log:/app/log            # Application logs (named volume)
      - openalgo_strategies:/app/strategies  # Python strategies (named volume)
      - openalgo_keys:/app/keys          # API keys/certificates (named volume)
      - openalgo_tmp:/app/tmp            # Temporary directory for numba/scipy (named volume)
      - ./.env:/app/.env:ro

    # (optional) extra env-vars that are NOT in .env
    environment:
      - FLASK_ENV=${FLASK_ENV:-production}
      - FLASK_DEBUG=${FLASK_DEBUG:-0}
      - TZ=Asia/Kolkata
      # Limit OpenBLAS/NumPy threads to prevent RLIMIT_NPROC exhaustion
      # See: https://github.com/marketcalls/openalgo/issues/822
      - OPENBLAS_NUM_THREADS=${OPENBLAS_NUM_THREADS:-2}
      - OMP_NUM_THREADS=${OMP_NUM_THREADS:-2}
      - MKL_NUM_THREADS=${MKL_NUM_THREADS:-2}
      - NUMEXPR_NUM_THREADS=${NUMEXPR_NUM_THREADS:-2}
      # Numba JIT compiler settings
      - NUMBA_NUM_THREADS=${NUMBA_NUM_THREADS:-2}
      # Strategy memory limit (MB) - reduce for low-memory containers
      # 2GB container with 5 strategies: set to 256
      - STRATEGY_MEMORY_LIMIT_MB=${STRATEGY_MEMORY_LIMIT_MB:-1024}

    # Shared memory for scipy/numba operations
    # Recommended: 25% of container RAM (min 128m, max 2g)
    # 2GB container: 256m | 4GB: 512m | 8GB: 1g | 16GB+: 2g
    shm_size: ${SHM_SIZE:-512m}

    healthcheck:
      test: ["CMD", "curl", "-f", "http://127.0.0.1:5000/auth/check-setup"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

    restart: unless-stopped

# Define named volumes for persistence
volumes:
  openalgo_db:
    driver: local
  openalgo_log:
    driver: local
  openalgo_strategies:
    driver: local
  openalgo_keys:
    driver: local
  openalgo_tmp:
    driver: local
