# Deployment Guide

Production deployment guide for WarpDrive.

## Quick Start - Docker Compose

**1. Build the image:**
```bash
docker build -t warpdrive:0.1.0-rc1 .
```

**2. Configure environment:**
```bash
cp .env.production.example .env
nano .env  # Edit configuration
```

**3. Start services:**
```bash
docker-compose -f docker-compose.production.yml up -d
```

**4. Verify deployment:**
```bash
# Check services are running
docker-compose -f docker-compose.production.yml ps

# Check logs
docker-compose -f docker-compose.production.yml logs warpdrive

# Test HTTP endpoint
curl http://localhost/

# Test HTTPS endpoint (self-signed)
curl -k https://localhost/

# Check metrics
curl http://localhost:9090/metrics
```

## Server Deployment (orbsuite or any VPS)

### Prerequisites

- Docker and Docker Compose installed
- Ports 80, 443 available (or configure different ports)
- (Optional) PostgreSQL and Redis if not using Docker
- (Optional) Domain name for ACME/Let's Encrypt

### Step-by-Step Deployment

**1. Clone or copy WarpDrive to server:**
```bash
# Via git
git clone https://github.com/seuros/warpdrive.git
cd warpdrive

# Or via rsync/scp
rsync -avz warpdrive/ user@orbsuite:/opt/warpdrive/
ssh user@orbsuite
cd /opt/warpdrive
```

**2. Build Docker image:**
```bash
docker build -t warpdrive:0.1.0-rc1 .
```

**3. Configure environment:**
```bash
# Copy example config
cp .env.production.example .env

# Edit with your settings
nano .env
```

**Required changes in `.env`:**
```bash
# Your upstream application
TARGET_HOST=localhost  # or your app's hostname
TARGET_PORT=3000

# Strong database password
POSTGRES_PASSWORD=your_strong_password_here

# (Optional) Redis password
REDIS_PASSWORD=another_strong_password
```

**For ACME/Let's Encrypt certificates:**
```bash
# Uncomment in .env
TLS_DOMAINS=yourdomain.com,www.yourdomain.com

# Make sure DNS points to your server
dig +short yourdomain.com  # Should return your server IP
```

**4. Create database schema file:**
```bash
mkdir -p deployments
cat > deployments/schema.sql << 'EOF'
-- WarpDrive cache invalidation schema

-- Cache invalidation events channel
-- Use: LISTEN warpdrive_cache_invalidation
-- Send: NOTIFY warpdrive_cache_invalidation, '{"key": "cache_key"}'

-- Example trigger for cache invalidation
-- CREATE OR REPLACE FUNCTION notify_cache_invalidation()
-- RETURNS trigger AS $$
-- BEGIN
--   PERFORM pg_notify('warpdrive_cache_invalidation', json_build_object('key', NEW.id)::text);
--   RETURN NEW;
-- END;
-- $$ LANGUAGE plpgsql;

-- Add your application tables and triggers here
EOF
```

**5. Start services:**
```bash
docker-compose -f docker-compose.production.yml up -d
```

**6. Verify deployment:**
```bash
# Check all services are running
docker-compose -f docker-compose.production.yml ps

# Should show:
# warpdrive         running   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp, 0.0.0.0:9090->9090/tcp
# warpdrive-postgres running (healthy)
# warpdrive-redis    running (healthy)

# Check logs
docker-compose -f docker-compose.production.yml logs -f warpdrive

# Test endpoints
curl http://localhost/
curl -k https://localhost/  # -k for self-signed
curl http://localhost:9090/metrics
```

**7. Monitor health:**
```bash
# WarpDrive health check
docker-compose -f docker-compose.production.yml exec warpdrive sh -c "curl -f http://localhost/ || echo 'FAILED'"

# PostgreSQL health
docker-compose -f docker-compose.production.yml exec postgres pg_isready -U warpdrive

# Redis health
docker-compose -f docker-compose.production.yml exec redis redis-cli ping
```

### Firewall Configuration

**Allow HTTP/HTTPS traffic:**
```bash
# UFW (Ubuntu/Debian)
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 9090/tcp  # Metrics (optional, restrict to monitoring IPs)

# firewalld (CentOS/RHEL)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-port=9090/tcp
sudo firewall-cmd --reload

# iptables
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 9090 -j ACCEPT
```

### TLS/ACME Configuration

**Option 1: Self-Signed Certificates (Default)**

Self-signed certificates are automatically generated during Docker build. No configuration needed.

**Good for:** Internal networks, testing, development

**Option 2: ACME/Let's Encrypt (Production)**

**Requirements:**
- Domain name with DNS pointing to server
- Ports 80 and 443 accessible from internet

**Configuration:**
```bash
# Edit .env
TLS_DOMAINS=example.com,www.example.com

# Uncomment in docker-compose.production.yml:
# - acme_certs:/var/lib/warpdrive

# Restart
docker-compose -f docker-compose.production.yml restart warpdrive
```

**Verify ACME provisioning:**
```bash
docker-compose -f docker-compose.production.yml logs warpdrive | grep -i acme

# Should see:
# Provisioning certificate for domain: example.com
# Certificate issued successfully!
```

**Option 3: Custom Certificates**

```bash
# Create certs directory
mkdir -p certs
cp /path/to/your/cert.pem certs/
cp /path/to/your/key.pem certs/

# Uncomment in docker-compose.production.yml:
# volumes:
#   - ./certs/cert.pem:/etc/warpdrive/certs/cert.pem:ro
#   - ./certs/key.pem:/etc/warpdrive/certs/key.pem:ro

# Restart
docker-compose -f docker-compose.production.yml restart warpdrive
```

### Monitoring & Operations

**View logs:**
```bash
# All services
docker-compose -f docker-compose.production.yml logs -f

# Just WarpDrive
docker-compose -f docker-compose.production.yml logs -f warpdrive

# Last 100 lines
docker-compose -f docker-compose.production.yml logs --tail=100 warpdrive
```

**Prometheus metrics:**
```bash
# Scrape metrics
curl http://localhost:9090/metrics

# Request rate
curl -s http://localhost:9090/metrics | grep http_requests_total

# Cache hit ratio
curl -s http://localhost:9090/metrics | grep cache_hits_total
curl -s http://localhost:9090/metrics | grep cache_misses_total

# Circuit breaker state
curl -s http://localhost:9090/metrics | grep circuit_breaker_state
```

**Common operations:**
```bash
# Restart WarpDrive
docker-compose -f docker-compose.production.yml restart warpdrive

# Reload configuration (if using volumes)
docker-compose -f docker-compose.production.yml restart warpdrive

# View resource usage
docker stats warpdrive warpdrive-postgres warpdrive-redis

# Backup PostgreSQL data
docker-compose -f docker-compose.production.yml exec postgres \
  pg_dump -U warpdrive warpdrive > backup_$(date +%Y%m%d).sql

# Restore PostgreSQL data
docker-compose -f docker-compose.production.yml exec -T postgres \
  psql -U warpdrive warpdrive < backup_20241004.sql
```

### Troubleshooting

**Issue: Connection refused to upstream**

```bash
# Check upstream is accessible
docker-compose -f docker-compose.production.yml exec warpdrive curl http://${TARGET_HOST}:${TARGET_PORT}/

# If upstream is on host machine
# Add to docker-compose.production.yml under warpdrive service:
extra_hosts:
  - "host.docker.internal:host-gateway"

# Then set in .env:
TARGET_HOST=host.docker.internal
```

**Issue: PostgreSQL connection errors**

```bash
# Check PostgreSQL is running
docker-compose -f docker-compose.production.yml ps postgres

# Test connection
docker-compose -f docker-compose.production.yml exec warpdrive sh -c \
  'psql $WARPDRIVE_DATABASE_URL -c "SELECT 1"'

# Check logs
docker-compose -f docker-compose.production.yml logs postgres
```

**Issue: Redis connection errors**

```bash
# Check Redis is running
docker-compose -f docker-compose.production.yml ps redis

# Test connection
docker-compose -f docker-compose.production.yml exec redis redis-cli ping

# If password protected
docker-compose -f docker-compose.production.yml exec redis redis-cli -a ${REDIS_PASSWORD} ping
```

**Issue: ACME certificate provisioning fails**

```bash
# Check domain DNS
dig +short yourdomain.com

# Verify HTTP-01 challenge is accessible
curl http://yourdomain.com/.well-known/acme-challenge/test

# Check logs
docker-compose -f docker-compose.production.yml logs warpdrive | grep -i acme

# Common issues:
# - DNS not pointing to server
# - Ports 80/443 not accessible
# - Firewall blocking traffic
# - Using staging server (check ACME_DIRECTORY)
```

**Issue: High memory usage**

```bash
# Check cache size configuration
docker-compose -f docker-compose.production.yml exec warpdrive env | grep CACHE

# Reduce cache size in .env:
CACHE_SIZE=33554432  # 32MB instead of 64MB

# Restart
docker-compose -f docker-compose.production.yml restart warpdrive
```

### Updating WarpDrive

```bash
# Pull latest changes
git pull origin master

# Rebuild image
docker build -t warpdrive:0.1.0-rc1 .

# Restart services
docker-compose -f docker-compose.production.yml up -d

# Verify
docker-compose -f docker-compose.production.yml logs -f warpdrive
```

### Production Checklist

- [ ] Strong passwords set for PostgreSQL and Redis
- [ ] TLS certificates configured (ACME or custom)
- [ ] Firewall rules configured
- [ ] Monitoring set up (Prometheus/Grafana)
- [ ] Log aggregation configured
- [ ] Backup strategy for PostgreSQL data
- [ ] Health check endpoints tested
- [ ] Rate limiting configured for traffic patterns
- [ ] Upstream application accessible
- [ ] DNS configured (if using ACME)
- [ ] Resource limits set (if needed)
- [ ] Auto-restart configured (default: unless-stopped)

### systemd Service (Optional)

For auto-start on system boot:

```bash
sudo cat > /etc/systemd/system/warpdrive.service << 'EOF'
[Unit]
Description=WarpDrive Proxy
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/opt/warpdrive
ExecStart=/usr/bin/docker-compose -f docker-compose.production.yml up -d
ExecStop=/usr/bin/docker-compose -f docker-compose.production.yml down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable warpdrive
sudo systemctl start warpdrive
```

### Performance Tuning

**High traffic scenarios:**
```bash
# In .env, increase:
CACHE_SIZE=134217728          # 128MB
RATE_LIMIT_RPS=500           # Higher RPS
MAX_CONCURRENT_REQUESTS=1000  # Limit concurrent

# Docker resource limits in docker-compose.production.yml:
deploy:
  resources:
    limits:
      cpus: '2.0'
      memory: 2G
    reservations:
      memory: 512M
```

**Low latency requirements:**
```bash
# Use Unix sockets for upstream if possible (30% faster than TCP)
# Configure in TOML config instead of env vars

# Disable compression if not needed
GZIP_COMPRESSION=false

# Reduce logging
LOG_REQUESTS=false
LOG_LEVEL=warn
```

## Next Steps

After successful deployment:
1. Monitor metrics at http://yourserver:9090/metrics
2. Set up Prometheus + Grafana for visualization
3. Configure alerts for circuit breaker state changes
4. Test failover scenarios
5. Load test to verify capacity
6. Document your specific configuration
