# Feature Specification: Deployment & Configuration

**ID:** DEPLOY-001
**Version:** 1.0
**Status:** Planned
**Priority:** High

## Overview
Deployment options, configuration management, and operational procedures for OpenSpeak server and client.

## Server Deployment

### Deployment Options

#### 1. Standalone Binary (Recommended for MVP)
**Advantages:**
- Simple, no dependencies
- Easy to start/stop
- Works on any OS

**Process:**
```bash
# Build
go build -o openspeak-server ./cmd/openspeak-server

# Run
./openspeak-server --config config.yaml

# Or with environment variables
OPENSPEAK_PORT=50051 ./openspeak-server
```

#### 2. Docker Container (Future)
**Dockerfile:**
```dockerfile
FROM golang:1.21 AS builder
WORKDIR /build
COPY . .
RUN go build -o openspeak-server ./cmd/openspeak-server

FROM alpine:latest
COPY --from=builder /build/openspeak-server /usr/local/bin/
EXPOSE 50051
CMD ["openspeak-server"]
```

**docker-compose.yml:**
```yaml
version: '3.8'
services:
  openspeak-server:
    build: .
    ports:
      - "50051:50051"
    environment:
      OPENSPEAK_PORT: 50051
      OPENSPEAK_LOG_LEVEL: info
    volumes:
      - ./config:/etc/openspeak
    restart: unless-stopped
```

#### 3. Systemd Service (Linux)
**File:** `/etc/systemd/system/openspeak.service`
```ini
[Unit]
Description=OpenSpeak Voice Server
After=network.target

[Service]
Type=simple
User=openspeak
WorkingDirectory=/opt/openspeak
ExecStart=/opt/openspeak/openspeak-server --config /etc/openspeak/config.yaml
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
```

**Commands:**
```bash
sudo systemctl daemon-reload
sudo systemctl enable openspeak
sudo systemctl start openspeak
sudo systemctl status openspeak
sudo journalctl -u openspeak -f  # View logs
```

### System Requirements

#### Minimum (Single Channel, 10 Users)
- CPU: 1 core @ 2GHz
- RAM: 512MB
- Disk: 100MB
- Network: 1 Mbps upstream

#### Recommended (Production, 50 Users)
- CPU: 2 cores @ 2GHz
- RAM: 2GB
- Disk: 1GB (SSD preferred for logs)
- Network: 10 Mbps upstream

#### High Performance (100+ Users)
- CPU: 4+ cores
- RAM: 4GB+
- Disk: 10GB SSD
- Network: 50+ Mbps

## Configuration Management

### Configuration Sources (Priority Order)
1. Environment variables
2. Command-line flags
3. Configuration file (YAML)
4. Defaults in code

### Environment Variables
```bash
# Server
OPENSPEAK_HOST=0.0.0.0
OPENSPEAK_PORT=50051
OPENSPEAK_TLS_CERT=/etc/openspeak/server.crt
OPENSPEAK_TLS_KEY=/etc/openspeak/server.key

# Authentication
OPENSPEAK_AUTH_TOKENS_FILE=/etc/openspeak/admin_tokens.json
OPENSPEAK_AUTH_TOKEN_TTL=0

# Audio
OPENSPEAK_AUDIO_DEFAULT_BITRATE=64
OPENSPEAK_AUDIO_JITTER_BUFFER_MS=50

# Logging
OPENSPEAK_LOG_LEVEL=info
OPENSPEAK_LOG_FORMAT=json
OPENSPEAK_LOG_FILE=/var/log/openspeak/server.log

# Advanced
OPENSPEAK_GRACEFUL_SHUTDOWN_TIMEOUT=30
OPENSPEAK_MAX_CONNECTION_IDLE_SECONDS=120
```

### Configuration File (config.yaml)
```yaml
server:
  # Server network configuration
  host: 0.0.0.0              # Listen on all interfaces
  port: 50051                # gRPC port
  tls:
    enabled: false           # Disable TLS for development
    cert_file: ""
    key_file: ""
  graceful_shutdown_timeout: 30  # Seconds

authentication:
  # Token-based authentication
  tokens_file: /etc/openspeak/admin_tokens.json
  token_ttl_seconds: 0       # 0 = no expiration (for MVP)

  # Future: User authentication
  user_auth_enabled: false
  password_hash_algorithm: "bcrypt"  # bcrypt, argon2
  session_timeout_minutes: 30

audio:
  # Audio quality settings
  default_bitrate_kbps: 64
  min_bitrate_kbps: 8
  max_bitrate_kbps: 128
  sample_rate_hz: 48000
  frame_size_ms: 20
  jitter_buffer_ms: 50
  max_packet_age_ms: 500

voice_routing:
  # Voice packet routing
  max_broadcast_lag_ms: 100
  packet_buffer_size: 1000
  voice_packet_timeout_ms: 5000

presence:
  # Presence tracking
  idle_timeout_seconds: 300      # 5 minutes
  heartbeat_interval_seconds: 30
  max_connection_idle_seconds: 120

logging:
  # Logging configuration
  level: info                # debug, info, warn, error
  format: json              # json, text
  output: stdout            # stdout, file, both
  file: /var/log/openspeak/server.log
  max_size_mb: 100          # Max log file size
  max_backups: 5            # Number of backup files
  max_age_days: 7           # Retention period

metrics:
  # Metrics collection
  enabled: false
  prometheus_port: 9090
  collection_interval_seconds: 60

development:
  # Development mode
  debug_mode: false
  profiling_enabled: false
  pprof_port: 6060
```

### Admin Tokens File (admin_tokens.json)
```json
[
  {
    "token": "d4f1c2e5b7a9f3c1e5b8a2d4f7c1e4a9",
    "name": "Admin Token 1",
    "permissions": [
      "admin",
      "channels:create",
      "channels:delete",
      "users:manage"
    ],
    "created_at": "2024-01-01T00:00:00Z",
    "expires_at": null,
    "last_used": "2024-01-10T15:30:00Z",
    "revoked": false
  }
]
```

## Client Deployment

### Distribution Methods

#### 1. Standalone Executable
```bash
# Build for Windows
GOOS=windows GOARCH=amd64 go build -o openspeak-client.exe ./cmd/openspeak-client

# Build for macOS
GOOS=darwin GOARCH=amd64 go build -o openspeak-client-macos ./cmd/openspeak-client

# Build for Linux
GOOS=linux GOARCH=amd64 go build -o openspeak-client ./cmd/openspeak-client
```

#### 2. Installer (MSI for Windows)
- WiX Toolset for MSI creation
- Installs to Program Files
- Desktop shortcut
- Uninstall support

#### 3. Portable (Future)
- Single ZIP file
- No installation required
- Config stored in app directory

### System Requirements
- Go 1.21+ (for building)
- 100MB disk space
- Audio device (microphone + speakers)
- Network connection to server

## Monitoring & Observability

### Health Checks

#### Server Health Endpoint (Future)
```bash
curl http://localhost:8080/health
```

Response:
```json
{
  "status": "healthy",
  "uptime_seconds": 86400,
  "connected_users": 25,
  "active_channels": 8,
  "memory_mb": 45,
  "cpu_percent": 5.2
}
```

### Log Monitoring
```bash
# View live logs
journalctl -u openspeak -f

# View last 100 lines
journalctl -u openspeak -n 100

# View errors only
journalctl -u openspeak -p err
```

### Metrics (Prometheus, Future)
```
openspeak_connected_users
openspeak_active_channels
openspeak_voice_packets_per_second
openspeak_average_latency_ms
openspeak_memory_usage_bytes
openspeak_cpu_usage_percent
```

## Backup & Recovery

### Configuration Backup
```bash
# Backup config and tokens
tar -czf openspeak-backup.tar.gz \
  /etc/openspeak/ \
  /var/log/openspeak/
```

### Data Persistence (Future)
When database support added:
```bash
# Database backup
mysqldump openspeak > backup.sql

# Restore
mysql openspeak < backup.sql
```

## Security Considerations

### TLS Configuration (Production)
```yaml
server:
  tls:
    enabled: true
    cert_file: /etc/openspeak/server.crt
    key_file: /etc/openspeak/server.key
```

**Certificate Generation (Self-Signed):**
```bash
openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365 -nodes
```

### Firewall Rules
```bash
# Allow gRPC port
sudo ufw allow 50051/tcp

# Restrict to specific IPs (example)
sudo ufw allow from 192.168.1.0/24 to any port 50051
```

### Token Security
- Store tokens in `/etc/openspeak/` with 0600 permissions
- Never commit tokens to version control
- Use environment variables for CI/CD
- Rotate tokens regularly
- Log all token usage

## Upgrade Procedure

### Server Upgrade
```bash
# Build new version
go build -o openspeak-server ./cmd/openspeak-server

# Stop current server
sudo systemctl stop openspeak

# Backup current binary
cp /usr/local/bin/openspeak-server /usr/local/bin/openspeak-server.backup

# Replace binary
sudo cp openspeak-server /usr/local/bin/

# Restart server
sudo systemctl start openspeak

# Verify
sudo systemctl status openspeak
```

### Client Upgrade
- Check for updates on startup (future)
- Inform user of new version
- Provide upgrade link
- Auto-download and install (future)

## Troubleshooting

### Common Issues

**Port Already in Use:**
```bash
# Find process using port
lsof -i :50051

# Kill process
kill -9 <PID>
```

**High Memory Usage:**
- Check for memory leaks (with profiling)
- Reduce jitter buffer size
- Enable debug logging to identify issue

**High CPU Usage:**
- Profile with pprof (development)
- Check for busy loops
- Monitor voice packet rate

**Clients Can't Connect:**
- Check firewall rules
- Verify server is running
- Check TLS configuration
- Verify client has correct server address

## Testing Strategy
- Deployment on clean system
- Configuration file parsing tests
- Environment variable override tests
- TLS certificate validation
- Log rotation and management tests
- Graceful shutdown tests
- Multi-server load balancing tests (future)
