# Cohorly self-host stack: Postgres, API, error worker, dashboard and a Caddy
# proxy with automatic TLS, all behind ONE domain. See the Self-hosting guide in the Cohorly docs.
#
#   cp .env.example .env     # required values, license key, release images
#   docker compose pull && docker compose up -d --no-build
#
# Run the release images we deliver: a server image without release.json
# refuses self-host mode (see "License key" in the Self-hosting guide).
#
# Only Caddy publishes ports. The dashboard is built with an empty
# NEXT_PUBLIC_COHORLY_API, so the browser calls the API with relative URLs on
# the same origin and Caddy routes them (see Caddyfile).

# Log rotation for every service: json-file capped at 3 x 10 MB per container.
x-logging: &default-logging
  driver: json-file
  options:
    max-size: "10m"
    max-file: "3"

# Settings shared by the API and the error worker (same image).
x-server-env: &server-env
  # The application role once COHORLY_DATABASE_URL is set (see db-roles
  # below and "Postgres roles" in README.md), else the superuser as before.
  DATABASE_URL: ${COHORLY_DATABASE_URL:-postgres://cohorly:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/cohorly}
  COHORLY_DEPLOYMENT_MODE: self-host
  # License key, checked at boot without network. The file wins
  # when both are set; mount it into both containers (see the Self-hosting guide).
  COHORLY_LICENSE_KEY: ${COHORLY_LICENSE_KEY:-}
  COHORLY_LICENSE_KEY_FILE: ${COHORLY_LICENSE_KEY_FILE:-}
  COHORLY_TZ: ${COHORLY_TZ:-}
  COHORLY_PG_POOL_MAX: ${COHORLY_PG_POOL_MAX:-15}
  # V8 old-space cap in MB. Empty = V8's default for the container's memory.
  COHORLY_HEAP_MB: ${COHORLY_HEAP_MB:-}
  COHORLY_DASHBOARD_ORIGIN: https://${COHORLY_DOMAIN:?set COHORLY_DOMAIN in .env}${COHORLY_PUBLIC_PORT:+:${COHORLY_PUBLIC_PORT}}
  COHORLY_SMTP_URL: ${COHORLY_SMTP_URL:-}
  COHORLY_MAIL_FROM: ${COHORLY_MAIL_FROM:-}
  COHORLY_BLOB_DRIVER: ${COHORLY_BLOB_DRIVER:-disk}
  COHORLY_S3_ENDPOINT: ${COHORLY_S3_ENDPOINT:-}
  COHORLY_S3_BUCKET: ${COHORLY_S3_BUCKET:-}
  COHORLY_S3_REGION: ${COHORLY_S3_REGION:-}
  COHORLY_S3_ACCESS_KEY_ID: ${COHORLY_S3_ACCESS_KEY_ID:-}
  COHORLY_S3_SECRET_ACCESS_KEY: ${COHORLY_S3_SECRET_ACCESS_KEY:-}
  SENTRY_DSN: ${SENTRY_DSN:-}
  LOG_LEVEL: ${LOG_LEVEL:-info}
  METRICS_PORT: "9464"

services:
  postgres:
    image: postgres:17-alpine
    restart: unless-stopped
    logging: *default-logging
    # Defaults are the "small" profile (2 GB host). Bigger hosts: see the
    # profile table in the Self-hosting guide.
    command:
      - postgres
      - -c
      - shared_buffers=${PG_SHARED_BUFFERS:-512MB}
      - -c
      - effective_cache_size=${PG_EFFECTIVE_CACHE_SIZE:-1536MB}
      - -c
      - work_mem=${PG_WORK_MEM:-8MB}
      - -c
      - max_connections=${PG_MAX_CONNECTIONS:-50}
    environment:
      POSTGRES_USER: cohorly
      POSTGRES_DB: cohorly
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
    # Docker's 64 MB default /dev/shm is too small for parallel hash joins on
    # the larger profiles.
    shm_size: ${PG_SHM_SIZE:-256mb}
    volumes:
      - selfhost-pgdata:/var/lib/postgresql/data
    healthcheck:
      # -h 127.0.0.1: the official image first runs a temporary server that
      # listens on the unix socket only; without a host pg_isready answers
      # "ready" while the TCP server the API connects to is not up yet.
      test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U cohorly -d cohorly"]
      interval: 10s
      timeout: 5s
      # The first boot runs initdb, whose final fsync of the data directory
      # took over 30 s on a busy SATA SSD. A check that passes ends the start
      # period at once, so a fast host starts no later.
      start_period: 120s
      retries: 5

  server:
    # Set COHORLY_SERVER_IMAGE=<the registry we gave you>/cohorly-server (for
    # example registry.example.com/cohorly/cohorly-server) and
    # COHORLY_IMAGE_TAG=<X.Y.Z> (tags are X.Y.Z without a "v", plus latest),
    # then run `docker compose pull && docker compose up -d --no-build`
    # (guide: "Getting the images").
    #
    # The build section is not used with the delivered images: start with
    # `--no-build`.
    build: &server-build
      context: ../..
      dockerfile: apps/server/Dockerfile
      args:
        COHORLY_LICENSE_PUBLIC_KEY: ${COHORLY_LICENSE_PUBLIC_KEY:-}
        COHORLY_RELEASE_DATE: ${COHORLY_RELEASE_DATE:-}
    image: ${COHORLY_SERVER_IMAGE:-cohorly-server}:${COHORLY_IMAGE_TAG:-local}
    restart: unless-stopped
    # On SIGTERM the API finishes in-flight requests for up to 40 s;
    # Docker's default 10 s would cut them.
    stop_grace_period: 45s
    logging: *default-logging
    environment:
      <<: *server-env
      # The schema owner: migrations and partitions run as it. Only the API
      # gets it; the worker never runs DDL.
      DATABASE_MIGRATION_URL: ${COHORLY_DATABASE_MIGRATION_URL:-}
      # The analysis queries' own pool, on top of COHORLY_PG_POOL_MAX (the
      # worker runs no analysis, so it is not in server-env); 0 shares it.
      COHORLY_QUERY_POOL_MAX: ${COHORLY_QUERY_POOL_MAX:-4}
      COHORLY_API_KEY: ${COHORLY_API_KEY:?set COHORLY_API_KEY in .env}
      BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET:?set BETTER_AUTH_SECRET in .env}
      COHORLY_MCP_JWT_SECRET: ${COHORLY_MCP_JWT_SECRET:?set COHORLY_MCP_JWT_SECRET in .env}
      # Closes the codeless onboarding path to anyone but this account.
      COHORLY_BOOTSTRAP_ADMIN_EMAIL: ${COHORLY_BOOTSTRAP_ADMIN_EMAIL:-}
      COHORLY_MCP_PUBLIC_ORIGIN: https://${COHORLY_DOMAIN:?set COHORLY_DOMAIN in .env}${COHORLY_PUBLIC_PORT:+:${COHORLY_PUBLIC_PORT}}
      GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
      GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}
      OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
      COHORLY_AI_MODELS: ${COHORLY_AI_MODELS:-}
      # COHORLY_PROXY_SECRET is deliberately NOT set: Caddy is the only edge
      # and the API reads the client IP it appends to X-Forwarded-For.
      PORT: "4000"
    volumes:
      - selfhost-blobs:/app/data/blobs
    depends_on:
      postgres:
        condition: service_healthy
      db-roles:
        condition: service_completed_successfully
    healthcheck:
      test:
        - CMD-SHELL
        - >-
          node -e "fetch('http://127.0.0.1:4000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
      interval: 30s
      timeout: 5s
      # Every migration runs on the first boot, before /health answers.
      start_period: 120s
      retries: 3

  # Postgres roles: creates or realigns cohorly_owner, cohorly_app and
  # (optional) cohorly_monitor from the URLs below, hands the schema to the
  # owner and grants the app role. Runs to completion before the API and the
  # worker on every `up`; idempotent, and a no-op that exits 0 while
  # COHORLY_DATABASE_MIGRATION_URL is unset, so an install from before the
  # split starts exactly as it did. Same image, no license check, no port.
  db-roles:
    build: *server-build
    image: ${COHORLY_SERVER_IMAGE:-cohorly-server}:${COHORLY_IMAGE_TAG:-local}
    command: ["node", "dist/db-roles-main.js"]
    restart: "no"
    logging: *default-logging
    mem_limit: 128m
    pids_limit: 32
    environment:
      COHORLY_HEAP_MB: "64"
      COHORLY_DB_ADMIN_URL: postgres://cohorly:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/cohorly
      DATABASE_MIGRATION_URL: ${COHORLY_DATABASE_MIGRATION_URL:-}
      DATABASE_URL: ${COHORLY_DATABASE_URL:-}
      COHORLY_PG_MONITOR_DSN: ${COHORLY_PG_MONITOR_DSN:-}
      LOG_LEVEL: ${LOG_LEVEL:-info}
    # The image's HEALTHCHECK probes the API port, which this never serves.
    healthcheck:
      disable: true
    depends_on:
      postgres:
        condition: service_healthy

  # The only writer of error issues; same image, own entrypoint, no port. It
  # never migrates, so it starts once the API is healthy.
  error-worker:
    # Same build as `server` (cached): without it compose would try to pull
    # the local image name from a registry.
    build: *server-build
    image: ${COHORLY_SERVER_IMAGE:-cohorly-server}:${COHORLY_IMAGE_TAG:-local}
    command: ["node", "dist/error-worker-main.js"]
    restart: unless-stopped
    logging: *default-logging
    environment:
      <<: *server-env
      # One batch holds one connection: a small pool keeps it off the API's share.
      COHORLY_PG_POOL_MAX: ${COHORLY_ERROR_WORKER_PG_POOL_MAX:-3}
    volumes:
      - selfhost-blobs:/app/data/blobs
    depends_on:
      postgres:
        condition: service_healthy
      db-roles:
        condition: service_completed_successfully
      server:
        condition: service_healthy
    healthcheck:
      test:
        - CMD-SHELL
        - >-
          node -e "fetch('http://127.0.0.1:9464/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
      interval: 30s
      timeout: 5s
      start_period: 20s
      retries: 3

  # NEXT_PUBLIC_COHORLY_API stays empty: same-origin relative URLs, nothing to
  # configure and no rebuild when the domain changes. No secrets here.
  dashboard:
    build:
      context: ../..
      dockerfile: apps/dashboard/Dockerfile
      args:
        NEXT_PUBLIC_COHORLY_API: ""
        # Optional, empty by default: dashboard error monitoring.
        NEXT_PUBLIC_SENTRY_DSN: ${DASHBOARD_SENTRY_DSN:-}
    image: ${COHORLY_DASHBOARD_IMAGE:-cohorly-dashboard}:${COHORLY_IMAGE_TAG:-local}
    restart: unless-stopped
    logging: *default-logging
    depends_on:
      server:
        condition: service_healthy
    healthcheck:
      test:
        - CMD-SHELL
        - >-
          node -e "fetch('http://127.0.0.1:3000/login').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
      interval: 30s
      timeout: 5s
      start_period: 15s
      retries: 3

  caddy:
    image: caddy:2.11.9-alpine
    restart: unless-stopped
    logging: *default-logging
    ports:
      - "${COHORLY_HTTP_PORT:-80}:80"
      - "${COHORLY_HTTPS_PORT:-443}:443"
    environment:
      COHORLY_DOMAIN: ${COHORLY_DOMAIN:?set COHORLY_DOMAIN in .env}
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - selfhost-caddy-data:/data
      - selfhost-caddy-config:/config
    depends_on:
      server:
        condition: service_healthy
      dashboard:
        condition: service_healthy
    healthcheck:
      # Caddy's admin API listens on localhost:2019 inside the container.
      test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:2019/config/ || exit 1"]
      interval: 15s
      timeout: 5s
      start_period: 10s
      retries: 3

  # Optional: `docker compose --profile monitoring up -d`. Ships host,
  # container and app metrics plus container logs to Grafana Cloud; needs the
  # GCLOUD_* values in .env. Reads the Docker API through docker-socket-proxy
  # (GET only, closed list) and a few host paths (/proc, /sys) read-only,
  # which is why it is off by default. Same mounts as the production
  # docker-compose.yml at the repo root (VEL-2091).
  alloy:
    profiles: ["monitoring"]
    image: grafana/alloy:v1.10.2
    restart: unless-stopped
    logging: *default-logging
    mem_limit: 256m
    pids_limit: 256
    command:
      - run
      - /etc/alloy/config.alloy
      - --storage.path=/var/lib/alloy/data
      - --stability.level=generally-available
    environment:
      # cohorly_monitor (pg_monitor only) once COHORLY_PG_MONITOR_DSN is set.
      COHORLY_PG_DSN: ${COHORLY_PG_MONITOR_DSN:-postgres://cohorly:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/cohorly?sslmode=disable}
      GCLOUD_PROM_URL: ${GCLOUD_PROM_URL:-}
      GCLOUD_PROM_USER: ${GCLOUD_PROM_USER:-}
      GCLOUD_LOKI_URL: ${GCLOUD_LOKI_URL:-}
      GCLOUD_LOKI_USER: ${GCLOUD_LOKI_USER:-}
      GCLOUD_RW_TOKEN: ${GCLOUD_RW_TOKEN:-}
      GOMEMLIMIT: 110MiB
      GOGC: "50"
      # Only this compose project's containers (config.alloy); empty keeps all.
      COHORLY_COMPOSE_PROJECT: ${COMPOSE_PROJECT_NAME:-}
    volumes:
      - ../monitoring/alloy/config.alloy:/etc/alloy/config.alloy:ro
      - selfhost-alloy-data:/var/lib/alloy/data
      - selfhost-docker-api:/run/docker-api:ro
      - /proc:/rootfs/proc:ro
      - /sys:/rootfs/sys:ro
      - /etc/os-release:/rootfs/etc/os-release:ro
      - /var/lib/docker/image/overlay2/layerdb/mounts:/rootfs/var/lib/docker/image/overlay2/layerdb/mounts:ro
      - /sys:/sys:ro
      - /dev/disk:/dev/disk:ro
    depends_on:
      - server
      - docker-socket-proxy

  # Read-only Docker API for Alloy; see docker-socket-proxy in the production
  # docker-compose.yml at the repo root for what it allows and why.
  docker-socket-proxy:
    profiles: ["monitoring"]
    image: wollomatic/socket-proxy:1.13.2
    restart: unless-stopped
    logging: *default-logging
    user: "0:0"
    read_only: true
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    network_mode: none
    mem_limit: 64m
    pids_limit: 64
    command:
      - -loglevel=info
      - -proxysocketendpoint=/run/docker-api/docker.sock
      - -proxysocketendpointfilemode=0600
      - -allowHEAD=(/_ping|/v1\.[0-9]+/_ping)
      - -allowGET=(/_ping|/v1\.[0-9]+/(_ping|version|info|networks|containers/json|containers/[0-9a-f]{64}/(json|logs)))
      - -watchdoginterval=60
      - -stoponwatchdog
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - selfhost-docker-api:/run/docker-api

volumes:
  selfhost-pgdata:
  selfhost-blobs:
  selfhost-caddy-data:
  selfhost-caddy-config:
  selfhost-alloy-data:
  selfhost-docker-api:
    driver: local
    driver_opts:
      type: tmpfs
      device: tmpfs
      o: "size=64k,mode=0700"
