Deployment Guide
This guide covers production deployment of PadawanForge to Cloudflare Workers, including CI/CD setup, monitoring, and maintenance procedures.
Production Deployment
Prerequisites
Cloudflare Account Setup
- Cloudflare Account: Active account with Workers enabled
- Domain: Custom domain for production (optional but recommended)
- Wrangler CLI: Latest version installed and authenticated
- Environment Variables: All production secrets configured
Required Permissions
- Workers deployment permissions
- D1 database access
- KV namespace management
- R2 bucket access
- Custom domain management (if applicable)
Environment Configuration
Production Environment Variables
# Core application settings
NODE_ENV=production
ENVIRONMENT=production
API_TOKEN=your_production_api_token
APP_NAME=PadawanForge
# Session configuration
SESSION_DURATION=420
SESSION_SECRET=your_production_session_secret
SESSION_COOKIE_SECURE=true
SESSION_COOKIE_HTTPONLY=true
SESSION_COOKIE_SAMESITE=strict
# Performance settings
ENABLE_COMPRESSION=true
ENABLE_CACHING=true
CACHE_TTL=3600
LOG_LEVEL=warn
DEBUG_MODE=false
OAuth Provider Configuration
# Google OAuth
OAUTH_GOOGLE_CLIENT_ID=your_production_google_client_id
OAUTH_GOOGLE_CLIENT_SECRET=your_production_google_client_secret
OAUTH_GOOGLE_REDIRECT_URI=https://your-domain.com/api/auth/callback/google
# Discord OAuth
OAUTH_DISCORD_CLIENT_ID=your_production_discord_client_id
OAUTH_DISCORD_CLIENT_SECRET=your_production_discord_client_secret
OAUTH_DISCORD_REDIRECT_URI=https://your-domain.com/api/auth/callback/discord
AI Configuration
# Default AI provider
DEFAULT_AI_PROVIDER=cloudflare
DEFAULT_AI_MODEL=@cf/meta/llama-3.1-8b-instruct
AI_TEMPERATURE=0.7
AI_MAX_TOKENS=150
AI_TIMEOUT=30000
Database Deployment
Production Database Setup
# Create production database
npm run wrangler d1 create padawan-db-prod
# Update wrangler.jsonc with production database ID
# Run migrations
npm run db:migrate:remote
Database Migration Strategy
# Create migration
npm run db:migrate:create add_new_feature
# Test migration locally
npm run db:migrate
# Deploy migration to production
npm run db:migrate:remote
# Verify migration
npm run wrangler d1 execute padawan-db-prod --command "SELECT name FROM sqlite_master WHERE type='table';"
Storage Deployment
KV Namespaces
# Create production KV namespaces
npm run wrangler kv:namespace create "PADAWAN_KV_PROD"
npm run wrangler kv:namespace create "PADAWAN_SESSIONS_PROD"
# Update wrangler.jsonc with production namespace IDs
R2 Bucket
# Create production R2 bucket
npm run wrangler r2 bucket create padawanforge-prod-assets
# Configure CORS for production
npm run wrangler r2 bucket cors put padawanforge-prod-assets --file cors-prod.json
Build and Deploy
Production Build
# Build for production
npm run build
# Verify build output
ls -la dist/
# Test production build locally
npm run preview
Deploy to Cloudflare
# Deploy to production
npm run deploy
# Or use wrangler directly
npm run wrangler deploy --env production
Deployment Verification
# Check deployment status
npm run wrangler deployments list
# Test production endpoints
curl -X GET https://your-domain.com/api/health
# Verify database connectivity
npm run wrangler d1 execute padawan-db-prod --command "SELECT 1;"
CI/CD Pipeline
GitHub Actions Setup
Workflow Configuration
# .github/workflows/deploy.yml
name: Deploy to Production
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm run test:all
- run: npm run build
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm run build
- uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: deploy
Required Secrets
# GitHub repository secrets
CLOUDFLARE_API_TOKEN=your_cloudflare_api_token
CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id
DATABASE_URL=your_production_database_url
API_TOKEN=your_production_api_token
Automated Testing
Pre-deployment Tests
# Run full test suite
npm run test:all
# Run production-specific tests
npm run test:all:prod
# Test database migrations
npm run db:migrate
# Test API endpoints
curl -X GET http://localhost:4321/api/health
Post-deployment Verification
# Health check
curl -X GET https://your-domain.com/api/health
# Database connectivity
npm run wrangler d1 execute padawan-db-prod --command "SELECT 1;"
# OAuth provider connectivity
curl -X GET https://your-domain.com/api/auth/available-providers
Monitoring and Observability
Health Monitoring
Health Check Endpoints
# Basic health check
GET /api/health
# Detailed health check
GET /api/health/detailed
# Database health
GET /api/health/database
# AI provider health
GET /api/health/ai
Monitoring Setup
# Set up uptime monitoring
# Configure alerts for:
# - Response time > 2s
# - Error rate > 5%
# - Database connection failures
# - AI provider failures
Logging Configuration
Production Logging
# Structured logging
LOG_FORMAT=json
LOG_LEVEL=warn
LOG_SAMPLING_RATE=0.1
# Error tracking
ENABLE_ERROR_TRACKING=true
ERROR_SAMPLE_RATE=1.0
Log Analysis
# View recent logs
npm run wrangler tail --format pretty
# Filter error logs
npm run wrangler tail --format json | jq 'select(.level == "error")'
# Monitor specific endpoints
npm run wrangler tail --format json | jq 'select(.message | contains("/api/"))'
Performance Monitoring
Key Metrics
- Response Time: Average and 95th percentile
- Throughput: Requests per second
- Error Rate: Percentage of failed requests
- Database Performance: Query execution time
- AI Response Time: Model inference latency
Performance Alerts
# Configure alerts for:
# - Response time > 1s (p95)
# - Error rate > 1%
# - Database query time > 500ms
# - AI response time > 5s
Security Configuration
Security Headers
# Enable security headers
ENABLE_HSTS=true
HSTS_MAX_AGE=31536000
ENABLE_CSP=true
CSP_POLICY="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
# Additional headers
X_FRAME_OPTIONS=DENY
X_CONTENT_TYPE_OPTIONS=nosniff
REFERRER_POLICY=strict-origin-when-cross-origin
Rate Limiting
# Configure rate limiting
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW=60000
RATE_LIMIT_BURST=10
# API-specific limits
API_RATE_LIMIT_REQUESTS=1000
API_RATE_LIMIT_WINDOW=60000
Authentication Security
# Session security
SESSION_SECRET=your_strong_session_secret
SESSION_COOKIE_SECURE=true
SESSION_COOKIE_HTTPONLY=true
SESSION_COOKIE_SAMESITE=strict
SESSION_MAX_AGE=86400000
Backup and Recovery
Database Backup
# Create database backup
npm run wrangler d1 execute padawan-db-prod --local --file backup.sql
# Automated backup schedule
# Daily backups at 2 AM UTC
0 2 * * * /usr/local/bin/npm run wrangler d1 execute padawan-db-prod --local --file /backups/backup-$(date +%Y%m%d).sql
Recovery Procedures
# Restore from backup
npm run wrangler d1 execute padawan-db-prod --file backup.sql
# Verify restoration
npm run wrangler d1 execute padawan-db-prod --command "SELECT COUNT(*) FROM players;"
Maintenance Procedures
Regular Maintenance
Weekly Tasks
# Review error logs
npm run wrangler tail --format json | jq 'select(.level == "error")' > weekly-errors.json
# Check database performance
npm run wrangler d1 execute padawan-db-prod --command "ANALYZE;"
# Review security logs
npm run wrangler tail --format json | jq 'select(.message | contains("security"))'
Monthly Tasks
# Update dependencies
npm update
# Review and rotate secrets
# Update API tokens and session secrets
# Performance review
# Analyze response times and error rates
Emergency Procedures
Incident Response
- Identify Issue: Check logs and monitoring
- Assess Impact: Determine affected users
- Implement Fix: Deploy hotfix if necessary
- Communicate: Update status page and users
- Post-mortem: Document incident and lessons learned
Rollback Procedure
# Rollback to previous deployment
npm run wrangler deployments rollback previous-deployment-id
# Verify rollback
curl -X GET https://your-domain.com/api/health
# Check database integrity
npm run wrangler d1 execute padawan-db-prod --command "SELECT COUNT(*) FROM players;"
Scaling Considerations
Performance Optimization
# Enable caching
ENABLE_CACHING=true
CACHE_TTL=3600
# Optimize database queries
# Use indexes for frequently accessed data
# Implement query optimization
# CDN configuration
# Configure Cloudflare CDN for static assets
Capacity Planning
- Concurrent Users: Monitor peak usage patterns
- Database Growth: Plan for data volume increases
- Storage Requirements: Monitor R2 usage
- AI Usage: Track model inference costs
Troubleshooting
Common Production Issues
High Response Times
# Check database performance
npm run wrangler d1 execute padawan-db-prod --command "EXPLAIN QUERY PLAN SELECT * FROM players;"
# Monitor AI provider latency
curl -X POST https://your-domain.com/api/ai/test-connection
# Check external dependencies
curl -X GET https://your-domain.com/api/health/detailed
Database Issues
# Check database connectivity
npm run wrangler d1 execute padawan-db-prod --command "SELECT 1;"
# Review recent migrations
npm run wrangler d1 execute padawan-db-prod --command "SELECT * FROM migrations ORDER BY created_at DESC LIMIT 5;"
# Check for locks
npm run wrangler d1 execute padawan-db-prod --command "PRAGMA busy_timeout = 5000;"
OAuth Issues
# Test OAuth providers
curl -X GET https://your-domain.com/api/auth/available-providers
# Check redirect URIs
# Verify OAuth configuration in provider dashboards
# Review OAuth logs
npm run wrangler tail --format json | jq 'select(.message | contains("oauth"))'
This deployment guide ensures reliable, secure, and scalable production deployment of PadawanForge. Regular monitoring and maintenance are essential for optimal performance.