# Docker Compose configuration for libSQL Server
# libSQL is an open-source fork of SQLite optimized for edge deployments
# Supports primary-replica replication and serverless architectures

x-defaults: &defaults
  restart: unless-stopped
  logging:
    driver: json-file
    options:
      max-size: 100m
      max-file: '3'

services:
  libsql:
    <<: *defaults
    image: ${GHCR_IO_REGISTRY:-ghcr.io}/tursodatabase/libsql-server:${LIBSQL_VERSION:-latest}
    platform: ${LIBSQL_PLATFORM:-linux/amd64}
    ports:
      - '${LIBSQL_HTTP_PORT_OVERRIDE:-8080}:8080' # HTTP/Hrana API port
      - '${LIBSQL_GRPC_PORT_OVERRIDE:-5001}:5001' # gRPC port for replication
    volumes:
      - libsql_data:/var/lib/sqld
    environment:
      - TZ=${TZ:-UTC}
      - SQLD_NODE=${LIBSQL_NODE:-primary}
      - SQLD_DB_PATH=${LIBSQL_DB_PATH:-iku.db}
      - SQLD_HTTP_LISTEN_ADDR=${LIBSQL_HTTP_LISTEN_ADDR:-0.0.0.0:8080}
      - SQLD_GRPC_LISTEN_ADDR=${LIBSQL_GRPC_LISTEN_ADDR:-0.0.0.0:5001}
      # Authentication (optional, uncomment to enable)
      # - SQLD_HTTP_AUTH=${LIBSQL_HTTP_AUTH:-}
      # - SQLD_AUTH_JWT_KEY_FILE=${LIBSQL_AUTH_JWT_KEY_FILE:-}
      # - SQLD_AUTH_JWT_KEY=${LIBSQL_AUTH_JWT_KEY:-}
    healthcheck:
      test: [CMD, wget, --quiet, --tries=1, --spider, 'http://localhost:8080/health']
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s
    deploy:
      resources:
        limits:
          cpus: ${LIBSQL_CPU_LIMIT:-1.0}
          memory: ${LIBSQL_MEMORY_LIMIT:-512M}
        reservations:
          cpus: ${LIBSQL_CPU_RESERVATION:-0.1}
          memory: ${LIBSQL_MEMORY_RESERVATION:-256M}

  # Replica instance (optional, use with profile)
  libsql-replica:
    <<: *defaults
    image: ${GHCR_IO_REGISTRY:-ghcr.io}/tursodatabase/libsql-server:${LIBSQL_VERSION:-latest}
    platform: ${LIBSQL_PLATFORM:-linux/amd64}
    profiles:
      - replica
    ports:
      - '${LIBSQL_REPLICA_HTTP_PORT_OVERRIDE:-8081}:8080'
      - '${LIBSQL_REPLICA_GRPC_PORT_OVERRIDE:-5002}:5001'
    volumes:
      - libsql_replica_data:/var/lib/sqld
    environment:
      - TZ=${TZ:-UTC}
      - SQLD_NODE=replica
      - SQLD_PRIMARY_URL=${LIBSQL_PRIMARY_URL:-http://libsql:5001}
      - SQLD_DB_PATH=${LIBSQL_DB_PATH:-iku.db}
      - SQLD_HTTP_LISTEN_ADDR=${LIBSQL_HTTP_LISTEN_ADDR:-0.0.0.0:8080}
      - SQLD_GRPC_LISTEN_ADDR=${LIBSQL_GRPC_LISTEN_ADDR:-0.0.0.0:5001}
    healthcheck:
      test: [CMD, wget, --quiet, --tries=1, --spider, 'http://localhost:8080/health']
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s
    depends_on:
      libsql:
        condition: service_healthy
    deploy:
      resources:
        limits:
          cpus: ${LIBSQL_REPLICA_CPU_LIMIT:-1.0}
          memory: ${LIBSQL_REPLICA_MEMORY_LIMIT:-512M}
        reservations:
          cpus: ${LIBSQL_REPLICA_CPU_RESERVATION:-0.1}
          memory: ${LIBSQL_REPLICA_MEMORY_RESERVATION:-256M}

volumes:
  libsql_data:
  libsql_replica_data:
