Shatteredvoid/STARTUP_GUIDE.md
MegaProxy e681c446b6 feat: implement comprehensive startup system and fix authentication
Major improvements:
- Created startup orchestration system with health monitoring and graceful shutdown
- Fixed user registration and login with simplified authentication flow
- Rebuilt authentication forms from scratch with direct API integration
- Implemented comprehensive debugging and error handling
- Added Redis fallback functionality for disabled environments
- Fixed CORS configuration for cross-origin frontend requests
- Simplified password validation to 6+ characters (removed complexity requirements)
- Added toast notifications at app level for better UX feedback
- Created comprehensive startup/shutdown scripts with OODA methodology
- Fixed database validation and connection issues
- Implemented TokenService memory fallback when Redis is disabled

Technical details:
- New SimpleLoginForm.tsx and SimpleRegisterForm.tsx components
- Enhanced CORS middleware with additional allowed origins
- Simplified auth validators and removed strict password requirements
- Added extensive logging and diagnostic capabilities
- Fixed authentication middleware token validation
- Implemented graceful Redis error handling throughout the stack
- Created modular startup system with configurable health checks

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-03 12:53:25 +00:00

14 KiB

Shattered Void MMO - Startup System Guide

This guide covers the comprehensive startup system for the Shattered Void MMO, providing multiple ways to launch and manage the game services.

Quick Start

The easiest way to start the game:

# Simple startup with all default settings
./start.sh

# Or using npm
npm run game

Startup Options

The start.sh script provides the most user-friendly interface:

# Development mode (default)
./start.sh

# Production mode
./start.sh --env production

# Debug mode with verbose logging
./start.sh --debug --verbose

# Backend only (no frontend)
./start.sh --no-frontend

# Custom port
./start.sh --port 8080

# Skip database checks (useful for testing)
./start.sh --no-database --skip-preflight

NPM Scripts

# Comprehensive startup with full system validation
npm run start:game

# Environment-specific startup
npm run start:dev        # Development mode
npm run start:prod       # Production mode
npm run start:staging    # Staging mode

# Quick startup (shell script)
npm run start:quick

# Debug mode
npm run start:debug

# Backend only
npm run start:backend-only

Direct Node.js

# Direct startup (bypasses some safety checks)
node start-game.js

# With environment
NODE_ENV=production node start-game.js

Configuration

Environment Variables

The startup system respects these environment variables:

# Core settings
NODE_ENV=development|production|staging|testing
PORT=3000                           # Backend port
FRONTEND_PORT=5173                  # Frontend port
HOST=0.0.0.0                       # Host binding

# Service toggles
ENABLE_FRONTEND=true|false          # Enable/disable frontend
DISABLE_DATABASE=true|false         # Skip database
DISABLE_REDIS=true|false           # Skip Redis
ENABLE_HEALTH_MONITORING=true|false # Health checks

# Startup behavior
SKIP_PREFLIGHT=true|false          # Skip system checks
VERBOSE_STARTUP=true|false         # Detailed logging
AUTO_MIGRATE=true|false            # Auto-run migrations
AUTO_SEED=true|false               # Auto-run seeds

# Visual settings
DISABLE_BANNER=true|false          # Hide startup banner
DISABLE_COLORS=true|false          # Disable colored output

Configuration File

Advanced configuration is available in config/startup.config.js:

// Example: Custom timeout settings
const config = {
  backend: {
    startupTimeout: 30000,     // 30 seconds
    healthEndpoint: '/health'
  },
  database: {
    migrationTimeout: 60000,   // 60 seconds
    autoMigrate: true
  },
  healthMonitoring: {
    interval: 30000,           // 30 seconds
    alertThresholds: {
      responseTime: 5000,      // 5 seconds
      memoryUsage: 80          // 80%
    }
  }
};

System Components

1. Pre-flight Checks (scripts/startup-checks.js)

Validates system requirements before startup:

  • Node.js version (18+)
  • NPM availability
  • Environment configuration
  • Directory structure
  • Package dependencies
  • Port availability
  • Database configuration
  • Redis configuration (optional)
  • Log directories
  • Frontend dependencies (optional)
  • System memory (1GB+ recommended)
  • Disk space (<90% usage)
  • File permissions

Test individually:

npm run system:check

2. Database Validation (scripts/database-validator.js)

Comprehensive database health checks:

  • 🔗 Connectivity testing
  • 📦 Migration status and auto-execution
  • 🏗️ Schema structure validation
  • 🌱 Seed data verification
  • 🔍 Data integrity checks
  • 📊 Performance metrics

Test individually:

npm run db:validate

3. Health Monitoring (scripts/health-monitor.js)

Real-time service monitoring:

  • 🏥 Service health checks
  • 📈 Performance metrics
  • 🚨 Alert system
  • 📊 Uptime tracking
  • 💾 System resource monitoring

Test individually:

npm run health:check

4. Main Orchestrator (start-game.js)

Central startup coordination:

  • 🎭 Phase-based startup
  • ⏱️ Timeout management
  • 🔄 Retry logic
  • 📝 Comprehensive logging
  • 🛑 Graceful shutdown
  • 📊 Performance metrics
  • 🔧 Node.js version compatibility detection
  • 📦 Automatic frontend fallback for older Node.js versions

Node.js Version Compatibility

The system automatically detects Node.js version compatibility and handles Vite development server limitations:

Vite Development Server Requirements

  • Node.js 20+: Full Vite development server support
  • Node.js 18-19: Automatic fallback to built frontend static server
  • Node.js <18: Not supported

Automatic Fallback Behavior

When Node.js version is incompatible with Vite 7.x (requires crypto.hash() from Node.js 20+):

  1. Detection: System detects Node.js version during startup
  2. Warning: Clear warning about version compatibility
  3. Fallback: Automatically serves built frontend from /frontend/dist/
  4. Status: Frontend shows as "static" mode in startup summary
# Example startup output with Node.js 18.x
Node.js version: v18.19.1
Node.js v18.19.1 is not compatible with Vite 7.x (requires Node.js 20+)
crypto.hash() function is not available in this Node.js version
Attempting to serve built frontend as fallback...
Built frontend fallback started in 5ms

║ ✅ Frontend:5173 (static)

Configuration Options

Control fallback behavior with environment variables:

# Disable frontend fallback (fail if Vite incompatible)
FRONTEND_FALLBACK=false ./start.sh

# Force use built frontend even with compatible Node.js
# (automatically happens if Vite dev server fails for any reason)

Building Frontend for Fallback

Ensure built frontend is available:

# Build frontend for production/fallback use
cd frontend
npm run build

# Verify build exists
ls -la dist/

Startup Phases

The startup system follows these phases:

  1. 🔍 Pre-flight Checks - System validation
  2. 🗄️ Database Validation - DB connectivity and migrations
  3. 🖥️ Backend Server Startup - Express server launch
  4. 🌐 Frontend Server Startup - React dev server (if enabled)
  5. 🏥 Health Monitoring - Service monitoring activation

Each phase includes:

  • ⏱️ Timing metrics
  • 🔄 Retry logic
  • Error handling
  • 📊 Progress reporting

Service Management

Starting Services

# Full stack (backend + frontend + monitoring)
./start.sh

# Backend only
./start.sh --no-frontend

# Skip health monitoring
./start.sh --no-health

# Database-free mode (for testing)
./start.sh --no-database

Stopping Services

# Graceful shutdown
Ctrl+C

# Force stop (if needed)
pkill -f start-game.js

Service Status

The startup system provides real-time status:

╔═══════════════════════════════════════════════════════════════╗
║                        STARTUP SUMMARY                       ║
╠═══════════════════════════════════════════════════════════════╣
║ Total Duration: 2847ms                                        ║
║                                                               ║
║ Services Status:                                              ║
║ ✅ Preflight                                                  ║
║ ✅ Database                                                   ║
║ ✅ Backend:3000                                               ║
║ ✅ Frontend:5173                                              ║
║ ✅ HealthMonitor                                              ║
╚═══════════════════════════════════════════════════════════════╝

Troubleshooting

Common Issues

  1. Port already in use

    # Use different port
    ./start.sh --port 8080
    
    # Or kill existing process
    lsof -ti:3000 | xargs kill
    
  2. Database connection failed

    # Check PostgreSQL status
    sudo systemctl status postgresql
    
    # Start PostgreSQL
    sudo systemctl start postgresql
    
    # Create database
    createdb shattered_void_dev
    
  3. Missing dependencies

    # Install dependencies
    npm install
    
    # Install frontend dependencies
    cd frontend && npm install
    
  4. Migration issues

    # Reset database
    npm run db:reset
    
    # Manual migration
    npm run db:migrate
    
  5. Vite development server fails (Node.js compatibility)

    # Check Node.js version
    node --version
    
    # If Node.js < 20, system will automatically fallback
    # To upgrade Node.js:
    # Using nvm:
    nvm install 20
    nvm use 20
    
    # Using package manager:
    # Ubuntu/Debian: sudo apt update && sudo apt install nodejs
    # MacOS: brew install node@20
    
    # Verify fallback works by ensuring frontend is built:
    cd frontend && npm run build
    
  6. Frontend fallback not working

    # Ensure frontend is built
    cd frontend
    npm install
    npm run build
    
    # Verify build directory exists
    ls -la dist/
    
    # Check if Express is available (should be in package.json)
    npm list express
    

Debug Mode

Enable comprehensive debugging:

# Maximum verbosity
./start.sh --debug --verbose

# Or with environment variables
DEBUG=* VERBOSE_STARTUP=true ./start.sh

Logs

Access different log streams:

# Combined logs
npm run logs

# Error logs only
npm run logs:error

# Startup logs
npm run logs:startup

# Audit logs
npm run logs:audit

Health Check Endpoints

Once running, access health information:

# Backend health
curl http://localhost:3000/health

# Health monitoring data (if debug endpoints enabled)
curl http://localhost:3000/debug/health

Production Deployment

Production Mode

# Production startup
./start.sh --env production

# Or with npm
npm run start:prod

Production mode changes:

  • 🚫 Frontend disabled (serves pre-built assets)
  • Faster health check intervals
  • 🔒 Enhanced security checks
  • 📊 Performance monitoring enabled
  • 🚨 Stricter error handling

Environment Variables for Production

NODE_ENV=production
DISABLE_FRONTEND=true          # Use nginx/CDN for frontend
ENABLE_HEALTH_MONITORING=true
LOG_LEVEL=warn
CRASH_REPORTING=true
PERFORMANCE_REPORTING=true

Docker Integration

The startup system works with Docker:

# Build Docker image
npm run docker:build

# Run with Docker Compose
npm run docker:run

Development Tips

Quick Development Cycle

# Fast startup without full checks
SKIP_PREFLIGHT=true ./start.sh --no-frontend

# Backend only with auto-restart
npm run dev

Testing the Startup System

# Test all components
npm run system:check    # Pre-flight checks
npm run db:validate     # Database validation
npm run health:check    # Health monitoring

# Test specific scenarios
./start.sh --no-database --skip-preflight  # Minimal startup
./start.sh --debug --log-file startup.log  # Full logging

Customizing the Startup

Modify config/startup.config.js for custom behavior:

module.exports = {
  backend: {
    startupTimeout: 45000,  // Longer timeout
    port: 8080             // Different default port
  },
  preflightChecks: {
    enabled: false         // Skip checks in development
  }
};

API Reference

Startup Script Options

Option Environment Variable Description
--env ENV NODE_ENV Set environment mode
--port PORT PORT Backend server port
--frontend-port PORT FRONTEND_PORT Frontend server port
--no-frontend ENABLE_FRONTEND=false Disable frontend
--no-health ENABLE_HEALTH_MONITORING=false Disable health monitoring
--no-database DISABLE_DATABASE=true Skip database
--no-redis DISABLE_REDIS=true Skip Redis
--skip-preflight SKIP_PREFLIGHT=true Skip system checks
--verbose VERBOSE_STARTUP=true Enable verbose logging
--debug DEBUG=* Enable debug mode
--no-colors DISABLE_COLORS=true Disable colored output

NPM Scripts Reference

Script Description
npm run game Quick startup (shell script)
npm run start:game Full startup with validation
npm run start:dev Development mode
npm run start:prod Production mode
npm run start:debug Debug mode
npm run start:backend-only Backend only
npm run system:check Run system checks
npm run health:check Test health monitoring
npm run db:validate Validate database

Contributing

When modifying the startup system:

  1. Test all scenarios - Test with different combinations of flags
  2. Update documentation - Keep this guide current
  3. Maintain backward compatibility - Don't break existing workflows
  4. Add comprehensive logging - Help with debugging
  5. Follow error handling patterns - Use the established error classes

The startup system is designed to be:

  • 🛡️ Robust - Handles failures gracefully
  • 🔧 Configurable - Adapts to different environments
  • 📊 Observable - Provides comprehensive monitoring
  • 🚀 Fast - Optimized startup performance
  • 🎯 User-friendly - Clear interface and error messages

For more information, see the individual component documentation or run ./start.sh --help.