### Install and Run Air for Hot Reloading Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Instructions to install the 'air' tool for automatic Go project rebuilding on file changes and then run it. ```bash # Install tools like 'air' for automatic rebuilding: go install github.com/cosmtrek/air@latest air ``` -------------------------------- ### Install and Verify Go Dependencies (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Downloads all project dependencies using `go mod download` and verifies their integrity with `go mod verify`. ```bash # Download and install all dependencies go mod download # Verify dependencies are correctly installed go mod verify ``` -------------------------------- ### Clone and Verify Project Structure (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Clones the game backend repository using Git and lists the project's top-level directories to confirm the setup. ```bash # Clone the project git clone cd prototype-game # Verify the project structure ls -la ``` -------------------------------- ### Verify Go Environment Configuration (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Checks the installed Go version and environment variables like GOPATH and GOROOT. Also shows how to verify the GOPROXY setting for module resolution. ```bash # Check Go version go version # Verify Go environment go env GOPATH go env GOROOT ``` ```bash go env GOPROXY # Should show: https://proxy.golang.org,direct ``` -------------------------------- ### Start Gateway Service (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Launches the gateway service, optionally specifying its bind address and the simulation engine's address. ```bash # Navigate to project directory cd prototype-game # Start the Gateway service ./bin/gateway # Or with custom settings ./bin/gateway -bind-addr=:9090 -sim-addr=localhost:8080 ``` -------------------------------- ### Start Simulation Engine (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Launches the simulation engine service, optionally specifying bind address and cell size. ```bash # Start the simulation engine with default settings ./bin/simulation # Or with custom configuration ./bin/simulation -bind-addr=:8081 -cell-size=1000 ``` -------------------------------- ### Start PostgreSQL with Docker Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Command to start a PostgreSQL database instance using Docker, mapping the default port and setting a root password. ```bash # Start PostgreSQL docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password postgres:15 ``` -------------------------------- ### Set Environment Variables Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Demonstrates how to create a `.env` file with development settings and load them using the 'source' command. ```bash # .env file GATEWAY_BIND_ADDR=:9090 SIMULATION_BIND_ADDR=:8080 LOG_LEVEL=debug MAX_CONNECTIONS=1000 SPATIAL_CELL_SIZE=500 Load with: source .env ./bin/gateway ``` -------------------------------- ### Format and Lint Go Code Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Commands for formatting Go code using 'gofmt' and running the 'golangci-lint' linter, with make targets provided. ```bash # Format code make fmt # Run linter make lint # Or manually: gofmt -w . golangci-lint run ``` -------------------------------- ### Change Service Port Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Example of how to restart a service using a different port to resolve 'Address already in use' conflicts. ```bash # Or use different port ./bin/simulation -bind-addr=:8081 ``` -------------------------------- ### Restart and Test Services Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Instructions to stop running services, restart affected services, and then test with the probe tool. ```bash # Stop running services (Ctrl+C) # Restart affected services ./bin/simulation & ./bin/gateway & # Test with probe ./bin/probe -gateway=localhost:9090 ``` -------------------------------- ### Start Multiple Probe Instances Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Launches multiple instances of the 'probe' tool in the background, each with a unique player ID, to test multi-client connectivity. ```bash # Start multiple probe instances ./bin/probe -gateway=localhost:9090 -player-id=player1 & ./bin/probe -gateway=localhost:9090 -player-id=player2 & ./bin/probe -gateway=localhost:9090 -player-id=player3 & # Wait a moment, then check connections jobs # Should show three running probe processes ``` -------------------------------- ### Build All Services using Makefile (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Compiles all backend services using the `make build` command, creating executables in the `./bin/` directory. ```bash # Build all services at once make build # This creates executables in the ./bin/ directory ls -la bin/ ``` -------------------------------- ### Reinstall Go Dependencies Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Commands to download and tidy Go module dependencies, helping to resolve 'module not found' or other dependency-related build issues. ```bash # Reinstall dependencies go mod download go mod tidy ``` -------------------------------- ### Connect Simulation to Database Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Shows how to configure the simulation engine to connect to a PostgreSQL database using a connection string. ```bash # Connect to database ./bin/simulation -db-url="postgres://postgres:password@localhost/gamedb" ``` -------------------------------- ### Run Project Tests Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Commands to execute all tests, tests with coverage, or tests for specific packages using Go's testing framework. ```bash # Run all tests make test # Run tests with coverage make test-coverage # Run specific package tests go test ./internal/spatial/... ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Demonstrates how to enable detailed debug logging for the simulation engine by setting the '-log-level' flag. ```bash ./bin/simulation -log-level=debug ``` -------------------------------- ### System Monitoring Tools Installation and Usage Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Installs essential system monitoring utilities like htop, iotop, and netstat-nat. Provides commands to monitor system resources such as CPU usage, disk I/O, and network connections. ```bash # Install monitoring tools sudo apt install htop iotop netstat-nat # Monitor system resources htop iotop ss -tulpn ``` -------------------------------- ### Build Individual Go Services (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Builds specific services like the Gateway, Simulation Engine, and Probe tool individually using `go build` with output flags. ```bash # Build the Gateway service go build -o bin/gateway ./cmd/gateway # Build the Simulation Engine go build -o bin/simulation ./cmd/simulation # Build the Probe tool (debugging utility) go build -o bin/probe ./cmd/probe ``` -------------------------------- ### Docker Compose Commands for Production Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Commands to start, verify, and monitor services using Docker Compose in a production environment. Includes starting services in detached mode, checking deployment status with curl, and following logs. ```bash # Start services docker-compose up -d # Verify deployment curl -f https://yourgame.com/healthz # Check logs docker-compose logs -f ``` -------------------------------- ### Rebuild Project Code Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Provides commands for rebuilding the project, either a quick build for testing or a specific service rebuild using Go. ```bash # Make your changes to source files # Then rebuild only what's needed # Quick rebuild for testing make build # Or rebuild specific service go build -o bin/gateway ./cmd/gateway ``` -------------------------------- ### Local Development with Make Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Quick start for local development using Make. Includes cloning the repository, setting up scripts, and starting/testing services. ```bash # Clone and setup git clone cd prototype-game ./scripts/setup.sh # Start services make run # Test connection make login && make wsprobe TOKEN=$(make login) ``` -------------------------------- ### Configure Gateway Service Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Lists common command-line flags for configuring the gateway, such as bind address, simulation address, connection limits, and logging. ```bash # Common flags for gateway ./bin/gateway \ -bind-addr=:9090 \ -sim-addr=localhost:8080 \ -max-connections=1000 \ -heartbeat-interval=30s \ -log-level=info ``` -------------------------------- ### Monitor Process Resources Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Uses 'watch' and 'ps' to continuously monitor the CPU and memory usage of simulation and gateway processes. ```bash watch -n 1 'ps aux | grep -E "(simulation|gateway)"' ``` -------------------------------- ### Check Service Health (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Performs a basic health check on the simulation engine service by sending an HTTP GET request to the `/health` endpoint. ```bash # Check simulation engine health curl http://localhost:8080/health ``` -------------------------------- ### Configure Simulation Engine Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Shows common command-line flags for configuring the simulation engine, including bind address, cell size, tick rate, and logging. ```bash # Common flags for simulation engine ./bin/simulation \ -bind-addr=:8080 \ -cell-size=500 \ -tick-rate=20 \ -max-entities=10000 \ -log-level=info ``` -------------------------------- ### Test Connection with Probe Tool (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Uses the probe tool to connect to the gateway service and verifies successful session establishment and player spawning. ```bash # In a third terminal window ./bin/probe -gateway=localhost:9090 ``` -------------------------------- ### Kill Process by PID Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md A bash command to forcefully terminate a process using its Process ID (PID). ```bash # Kill the process kill -9 ``` -------------------------------- ### Test WebSocket Connection Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md A JavaScript snippet to establish a WebSocket connection to the gateway, handling open, message, and error events. ```javascript // In browser console or Node.js const ws = new WebSocket('ws://localhost:9090/ws'); ws.onopen = () => console.log('Connected successfully'); ws.onmessage = (msg) => console.log('Received:', msg.data); ws.onerror = (err) => console.error('WebSocket error:', err); ``` -------------------------------- ### Development Build with Race Detection (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Creates a development build with race detection enabled and optimized for debugging by disabling optimizations (`-N -l`). ```bash # Development build with race detection make build-dev # Or manually: go build -race -gcflags="all=-N -l" -o bin/gateway-dev ./cmd/gateway ``` -------------------------------- ### Monitor System Performance Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Checks CPU and memory usage for simulation and gateway processes using 'top' and monitors the connection count via curl. ```bash # Check CPU and memory usage top -p $(pgrep -f "simulation|gateway") # Monitor connection count curl http://localhost:9090/metrics | grep connection_count ``` -------------------------------- ### Clean Go Module Cache Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Command to clean the local Go module cache, often necessary when encountering dependency errors during builds. ```bash # Clean module cache go clean -modcache ``` -------------------------------- ### Production Server Preparation Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Prepares the production server by updating the system, installing Docker and Docker Compose, and creating a dedicated application user with necessary permissions. ```bash # Update system sudo apt update && sudo apt upgrade -y # Install Docker curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh sudo usermod -aG docker $USER # Install Docker Compose sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose # Create application user sudo useradd -m -s /bin/bash gameserver sudo usermod -aG docker gameserver ``` -------------------------------- ### Check Gateway Health Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Uses curl to send a request to the gateway's /health endpoint and checks the expected JSON response. ```bash # Check gateway health curl http://localhost:9090/health # Expected: {"status":"healthy","simulation":"connected"} ``` -------------------------------- ### Local Development with Docker Compose Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Manages the development stack using Docker Compose. Allows starting, viewing logs, and stopping the services. ```bash # Start development stack docker-compose -f docker-compose.dev.yml up -d # Check logs docker-compose -f docker-compose.dev.yml logs -f # Stop services docker-compose -f docker-compose.dev.yml down ``` -------------------------------- ### Production SSL/TLS Setup Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Configures SSL/TLS for production using Certbot, obtaining certificates for specified domains and setting up automatic renewal via cron. ```bash # Install Certbot sudo apt install certbot python3-certbot-nginx # Obtain SSL certificate sudo certbot certonly --nginx -d yourgame.com -d api.yourgame.com # Auto-renewal sudo crontab -e # Add: 0 12 * * * /usr/bin/certbot renew --quiet ``` -------------------------------- ### AWS EC2 Instance Setup and Docker Deployment Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Instructions for setting up an AWS EC2 instance, configuring security groups, and deploying the application using Docker and Docker Compose. Assumes SSH access with a key pair. ```bash # Launch EC2 instance (t3.large or larger) # Configure security groups (ports 80, 443, 22) # Attach Elastic IP # Install Docker and deploy ssh -i your-key.pem ubuntu@your-ec2-ip sudo apt update && sudo apt install docker.io docker-compose # Follow production setup steps ``` -------------------------------- ### Diagnose Service Startup Issues (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Commands to help diagnose why a service might not be starting. This includes checking docker logs, resource usage, and verifying the docker-compose configuration. ```bash # Check logs docker-compose logs prototype-game # Check resource usage docker stats # Verify configuration docker-compose config ``` -------------------------------- ### Build and Run Game Backend (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Commands to clone the repository, build all Go services using Make, and start the game backend. Assumes Go 1.21+ and Make are installed. ```bash # Clone the repository git clone cd prototype-game # Build all services make build # Start the game backend make run ``` -------------------------------- ### Command Line Options (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Examples of running the compiled Gateway and Simulation binaries with specific command-line arguments for configuration. ```bash # Gateway ./bin/gateway -port 8080 -sim localhost:8081 # Simulation ./bin/sim -port 8081 -cell-size 500 -tick-rate 20 ``` -------------------------------- ### Find Process Using Port Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/getting-started.md Provides a bash command to find the process ID (PID) that is currently using a specific port, useful for troubleshooting 'Address already in use' errors. ```bash # Find process using the port lsof -i :8080 ``` -------------------------------- ### Staging Deployment Steps Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Steps for staging deployment, including creating directories, cloning the repository, checking out the staging branch, copying environment configurations, and updating Docker Compose files. Also includes obtaining SSL certificates. ```bash # Create staging directory mkdir -p /opt/prototype-game-staging cd /opt/prototype-game-staging # Clone repository git clone . git checkout staging # Copy staging configuration cp configs/.env.production .env # Edit .env with staging-specific values # Edit docker-compose.yml for staging # Update ports, volumes, and environment variables # Set up SSL certificates (Let's Encrypt) sudo apt install certbot sudo certbot certonly --standalone -d staging.yourdomain.com # Build and start services docker-compose up -d # Verify deployment curl -f http://localhost:8080/healthz # View logs docker-compose logs -f prototype-game # Monitor resources docker stats # Check metrics curl http://localhost:8080/metrics ``` -------------------------------- ### Restart Prototype Game Service (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Provides commands for gracefully restarting the prototype game service using docker-compose, or performing a force restart by stopping and then starting the services. ```bash # Graceful restart docker-compose restart prototype-game # Force restart docker-compose down && docker-compose up -d ``` -------------------------------- ### Monitor and Profile Performance (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Commands for monitoring system resources like CPU and memory, checking application metrics, and profiling the Go application using pprof. ```bash # Monitor CPU/Memory htop # Check application metrics curl http://localhost:8080/metrics | grep -E "(cpu|memory|connection)" # Profile application go tool pprof http://localhost:8080/debug/pprof/profile ``` -------------------------------- ### Production Environment Variables Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Defines critical environment variables for the production setup, including database and Redis URLs, JWT secret, CORS origins, performance tuning parameters, and logging configurations. ```bash # Database DATABASE_URL=postgres://gameuser:${DB_PASSWORD}@postgres:5432/gamedb REDIS_URL=redis://redis:6379/0 # Security JWT_SECRET=${JWT_SECRET} CORS_ORIGINS=https://yourgame.com # Performance GOMAXPROCS=8 MAX_CONNECTIONS=10000 SPATIAL_CELL_SIZE=1000 TICK_RATE=30 # Monitoring METRICS_ENABLED=true LOG_LEVEL=info LOG_FORMAT=json ``` -------------------------------- ### Production Application Deployment Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Deploys the application in production by switching to the application user, creating the application directory, cloning the repository, checking out the main branch, and setting up the production configuration. ```bash # Switch to application user sudo su - gameserver # Create application directory mkdir -p /home/gameserver/prototype-game cd /home/gameserver/prototype-game # Clone and configure git clone . git checkout main # Set up production configuration cp configs/.env.production .env # Configure production-specific settings ``` -------------------------------- ### Development Environment Variables Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Sets environment variables for the development environment to configure logging, spatial cell size, tick rate, and maximum connections. ```bash export LOG_LEVEL=debug export SPATIAL_CELL_SIZE=500 export TICK_RATE=20 export MAX_CONNECTIONS=100 ``` -------------------------------- ### Troubleshooting Connection Refused (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Steps to resolve 'Connection refused' errors by ensuring the simulation service is running before starting the gateway. ```bash # Ensure simulation is running first make run-sim # Then start gateway make run-gateway ``` -------------------------------- ### Troubleshoot Database Connection Issues (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Commands to test database connectivity and check database logs. It verifies if the application can connect to the PostgreSQL database and access its logs. ```bash # Test database connectivity docker exec -it postgres_container psql -U gameuser -d gamedb -c "SELECT 1;" # Check database logs docker-compose logs postgres ``` -------------------------------- ### Google Cloud Compute Engine Instance Creation Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Command to create a Google Cloud Compute Engine VM instance with specified machine type, zone, and operating system image. This is the first step in deploying the application to GCP. ```bash # Create VM instance gcloud compute instances create prototype-game \ --machine-type=n1-standard-4 \ --zone=us-central1-a \ --image-family=ubuntu-2004-lts \ --image-project=ubuntu-os-cloud # Deploy application # Follow production setup steps ``` -------------------------------- ### Configuration Environment Variables (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Example environment variables for configuring the game backend services, including ports, simulation settings, and logging levels. ```bash # Service ports GATEWAY_PORT=8080 SIM_PORT=8081 # Simulation settings SPATIAL_CELL_SIZE=500 TICK_RATE=20 MAX_ENTITIES=10000 # Logging LOG_LEVEL=info ``` -------------------------------- ### Google Cloud SQL PostgreSQL Instance Creation Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Command to create a Google Cloud SQL instance for PostgreSQL, specifying the database version and machine tier. This instance will serve as the game's database. ```bash # Create Cloud SQL PostgreSQL instance gcloud sql instances create game-db \ --database-version=POSTGRES_15 \ --tier=db-f1-micro \ --region=us-central1 ``` -------------------------------- ### Scale Prototype Game Services (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Command to scale the prototype game service horizontally, increasing the number of running instances. ```bash # Scale horizontally docker-compose up -d --scale prototype-game=3 ``` -------------------------------- ### Application and Database Monitoring Commands Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Commands for monitoring application logs and metrics, as well as interacting with the PostgreSQL database to check activity. This includes following Docker Compose logs, fetching metrics, and querying database connection status. ```bash # View application logs docker-compose logs -f prototype-game # Monitor metrics curl https://yourgame.com/metrics # Database monitoring docker exec -it postgres_container psql -U gameuser -d gamedb -c "SELECT * FROM pg_stat_activity;" ``` -------------------------------- ### HTTP GET /auth/validate Response Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Example JSON response for JWT token validation, confirming token validity, player ID, and expiration time. ```json { "valid": true, "player_id": "player_123", "expires_at": "2024-01-15T15:30:00Z" } ``` -------------------------------- ### Bash Script for Database and S3 Backups Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md A shell script to perform database backups using `pg_dump` and optionally upload them to an S3 bucket. It creates timestamped SQL backup files. ```bash #!/bin/bash # backup.sh # Database backup docker exec postgres_container pg_dump -U gameuser gamedb > "backup_$(date +%Y%m%d_%H%M%S).sql" # Upload to S3 (optional) aws s3 cp backup_*.sql s3://your-backup-bucket/ ``` -------------------------------- ### Rollback Prototype Game Deployment (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Steps to rollback the deployment to a previous version. This involves checking out a previous git tag, stopping the current deployment, rebuilding, and restarting. ```bash # Rollback to previous version git checkout docker-compose down docker-compose build docker-compose up -d ``` -------------------------------- ### Log Rotation Configuration using logrotate Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Configuration file for `logrotate` to manage log files generated by Docker containers. It defines rotation policies like daily rotation, keeping 7 days of logs, compression, and error handling. ```bash # Configure logrotate sudo tee /etc/logrotate.d/prototype-game << EOF /var/lib/docker/containers/*/*-json.log { daily rotate 7 compress delaycompress missingok notifempty create 0644 root root } EOF ``` -------------------------------- ### HTTP Metrics Request Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md HTTP GET request to the /metrics endpoint to retrieve server performance metrics in Prometheus format. ```http GET /metrics HTTP/1.1 Host: gateway-server:9090 ``` -------------------------------- ### Nginx Configuration for Prototype Game Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md Configures Nginx as a reverse proxy for the prototype game, handling HTTP to HTTPS redirection, SSL termination, WebSocket proxying, and API routing. It sets up upstream servers and security headers. ```nginx upstream backend { server localhost:8080; } server { listen 80; server_name yourgame.com api.yourgame.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name yourgame.com api.yourgame.com; ssl_certificate /etc/letsencrypt/live/yourgame.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/yourgame.com/privkey.pem; # Security headers add_header Strict-Transport-Security "max-age=31536000; includeSubDomains"; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; add_header Referrer-Policy "strict-origin-when-cross-origin"; # WebSocket support location /ws { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # API endpoints location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` -------------------------------- ### JavaScript WebSocket Authentication and Setup Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Handles sending an authentication message with a JWT token and processing the authentication result. It sets up the heartbeat and game loop upon successful authentication. ```javascript ws.send(JSON.stringify({ type: 'authenticate', data: { token: jwtToken } })); function handleMessage(message) { switch (message.type) { case 'authentication_result': if (message.data.success) { console.log('Authenticated as:', message.data.player_id); startHeartbeat(); setupGameLoop(); } else { console.error('Authentication failed'); ws.close(); } break; } } ``` -------------------------------- ### Kubernetes Deployment Manifest Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md YAML manifest for a Kubernetes Deployment. It defines a stateless application with 3 replicas, specifying container image, ports, environment variables (e.g., DATABASE_URL), and resource requests/limits. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: prototype-game namespace: prototype-game spec: replicas: 3 selector: matchLabels: app: prototype-game template: metadata: labels: app: prototype-game spec: containers: - name: prototype-game image: prototype-game:latest ports: - containerPort: 8080 - containerPort: 8081 env: - name: DATABASE_URL valueFrom: secretKeyRef: name: db-secret key: url resources: requests: memory: "1Gi" cpu: "500m" limits: memory: "2Gi" cpu: "1000m" ``` -------------------------------- ### HTTP POST /auth/login Response Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Example JSON response for a successful JWT token acquisition, containing the access token, its expiry, player identifier, and session identifier. ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expires_at": "2024-01-15T15:30:00Z", "player_id": "player_123", "session_id": "sess_abc123" } ``` -------------------------------- ### Kubernetes Namespace Definition Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md YAML manifest to create a Kubernetes namespace named 'prototype-game'. Namespaces are used to isolate resources within a Kubernetes cluster. ```yaml apiVersion: v1 kind: Namespace metadata: name: prototype-game ``` -------------------------------- ### GET /auth/validate Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Validate an existing JWT authentication token. ```APIDOC ## GET /auth/validate ### Description Validate an existing JWT authentication token. ### Method GET ### Endpoint /auth/validate ### Parameters #### Query Parameters - **Authorization** (string) - Required - The JWT token prefixed with "Bearer ". ### Request Example ```http GET /auth/validate HTTP/1.1 Host: gateway-server:9090 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` ### Response #### Success Response (200) - **valid** (boolean) - Indicates if the token is valid. - **player_id** (string) - The unique identifier for the player associated with the token. - **expires_at** (string) - The expiration timestamp of the token (ISO 8601). #### Response Example ```json { "valid": true, "player_id": "player_123", "expires_at": "2024-01-15T15:30:00Z" } ``` ``` -------------------------------- ### Error Codes and Handling Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Details WebSocket and HTTP error codes, their meanings, common causes, and provides examples of error response formats and client-side error handling logic. ```APIDOC ## Error Codes & Handling ### WebSocket Error Codes | Code | Name | Description | |------|--------------------|--------------------------------------| | 4000 | Invalid Message | Malformed JSON or unknown message type | | 4001 | Authentication Failed | Invalid or expired JWT token | | 4002 | Rate Limited | Too many messages sent | | 4003 | Player Not Found | Player ID not found in session | | 4004 | Invalid Action | Action not allowed in current state | | 4005 | World Full | Maximum player capacity reached | ### HTTP Error Codes | Code | Description | Common Causes | |------|--------------------------|--------------------------------------| | 400 | Bad Request | Invalid JSON, missing parameters | | 401 | Unauthorized | Missing or invalid authentication | | 403 | Forbidden | Insufficient permissions | | 404 | Not Found | Endpoint or resource not found | | 429 | Too Many Requests | Rate limit exceeded | | 500 | Internal Server Error | Server-side error | | 503 | Service Unavailable | Server overloaded or maintenance | ### Error Response Format ```json { "error": { "code": 4001, "message": "Authentication failed", "details": "JWT token has expired", "timestamp": "2024-01-15T10:30:00.000Z", "retry_after": 5000 } } ``` ### Client Error Handling #### Connection Errors ```javascript websocket.onerror = function(error) { console.error('WebSocket error:', error); // Implement exponential backoff reconnection setTimeout(() => reconnect(), getBackoffDelay()); }; websocket.onclose = function(event) { if (event.code >= 4000 && event.code < 5000) { // Server-initiated close, handle specific error handleServerError(event.code, event.reason); } else { // Network issue, attempt reconnection scheduleReconnect(); } }; ``` #### Message Errors ```javascript function handleServerMessage(message) { const data = JSON.parse(message.data); if (data.type === 'error') { switch (data.error.code) { case 4001: // Authentication failed refreshAuthToken().then(reconnect); break; case 4002: // Rate limited implementRateLimit(data.error.retry_after); break; default: console.error('Server error:', data.error); } } } ``` ``` -------------------------------- ### HTTP Debug Player Data Request Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md HTTP GET request to the /debug/players endpoint for retrieving player information. Requires an Authorization header with a bearer token. ```http GET /debug/players HTTP/1.1 Host: gateway-server:9090 Authorization: Bearer admin_token_here ``` -------------------------------- ### Go Multi-factor Authentication Configuration Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/security.md Example struct for configuring multi-factor authentication (MFA) in Go, including requirements, method, token expiry, and refresh token support. This is a basic structure and would need further implementation for actual MFA logic. ```go import "time" // Example: Multi-factor authentication type AuthConfig struct { RequireMFA bool MFAMethod string // "totp", "sms", "email" TokenExpiry time.Duration RefreshTokens bool } ``` -------------------------------- ### HTTP POST /auth/refresh Response Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Example JSON response for a JWT token refresh, providing a new token and its updated expiration time. ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expires_at": "2024-01-15T16:30:00Z" } ``` -------------------------------- ### HTTP Health Check Request Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md HTTP GET request to the /health endpoint for checking server status. Requires the gateway-server host. ```http GET /health HTTP/1.1 Host: gateway-server:9090 ``` -------------------------------- ### Go Rate Limiting Configuration Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/security.md Example struct for configuring rate limiting parameters in Go. It includes settings for requests per minute, burst size, and lists of whitelisted and blacklisted IP addresses. This structure helps define the behavior and exceptions for rate limiting. ```go // Example rate limiting configuration type RateLimitConfig struct { RequestsPerMinute int BurstSize int WhitelistedIPs []string BlacklistedIPs []string } ``` -------------------------------- ### Bash Script for Service Health Checks Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/deployment.md A shell script that performs health checks on the game's gateway and simulation services by sending HTTP requests to their health endpoints. It exits with a non-zero status if any check fails. ```bash #!/bin/bash # health-check.sh # Check service health if ! curl -f http://localhost:8080/healthz > /dev/null 2>&1; then echo "Gateway health check failed" exit 1 fi if ! curl -f http://localhost:8081/healthz > /dev/null 2>&1; then echo "Simulation health check failed" exit 1 fi echo "All services healthy" ``` -------------------------------- ### Bash Security Configuration Environment Variables Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/security.md Example environment variables for configuring various security aspects of an application, including JWT secrets and expiry, rate limiting parameters, CORS origins, and TLS certificate paths. These variables are typically used to customize security settings without modifying code. ```bash # Security Configuration JWT_SECRET=your-super-secret-jwt-key JWT_EXPIRY=1h RATE_LIMIT_REQUESTS=100 RATE_LIMIT_WINDOW=1m CORS_ORIGINS=https://yourdomain.com TLS_CERT_PATH=/path/to/cert.pem TLS_KEY_PATH=/path/to/key.pem ``` -------------------------------- ### HTTP GET /auth/validate for JWT Token Validation Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Validates a JWT token by sending a GET request to the /auth/validate endpoint with the token in the Authorization header. Returns a boolean indicating validity and associated player information. ```http GET /auth/validate HTTP/1.1 Host: gateway-server:9090 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` -------------------------------- ### Gateway Configuration via Environment Variables Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md This snippet demonstrates how to configure the gateway's behavior using environment variables. These variables mirror many of the command-line flags, allowing for flexible deployment and configuration management. ```bash # Gateway configuration via environment export GATEWAY_BIND_ADDR=":9090" export GATEWAY_SIM_ADDR="localhost:8080" export GATEWAY_MAX_CONNECTIONS="1000" export GATEWAY_JWT_SECRET="your-secret-key" export GATEWAY_LOG_LEVEL="info" ``` -------------------------------- ### Clean and Rebuild Project (Go) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Commands to clean the Go module cache, download dependencies, and build the project using Make. ```bash go clean -modcache go mod download make build ``` -------------------------------- ### Simulation Engine Command Line Flags Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Configures the simulation engine server using command-line flags. Covers network binding, spatial parameters, tick rate, entity limits, world size, logging, and database connection. ```APIDOC ## Simulation Engine Command Line Flags Configures the simulation engine server. ### Usage ```bash ./bin/simulation [flags] ``` ### Flags | Flag | Type | Default | Description | |-------------|--------|------------|----------------------------------| | `-bind-addr`| string | `:8080` | Server bind address | | `-cell-size`| int | `500` | Spatial cell size in units | | `-tick-rate`| int | `20` | Simulation updates per second | | `-max-entities`| int | `10000` | Maximum entities per shard | | `-world-size`| string | `10000x10000` | World dimensions | | `-log-level`| string | `info` | Logging level | | `-db-url` | string | - | Database connection URL (optional) | ``` -------------------------------- ### Gateway Command Line Flags Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Configures the gateway server using command-line flags. Includes settings for network addresses, connection limits, timeouts, logging, and security. ```APIDOC ## Gateway Command Line Flags Configures the gateway server. ### Usage ```bash ./bin/gateway [flags] ``` ### Flags | Flag | Type | Default | Description | |--------------------|----------|--------------|----------------------------------------| | `-bind-addr` | string | `:9090` | WebSocket server bind address | | `-sim-addr` | string | `localhost:8080` | Simulation engine address | | `-max-connections` | int | `1000` | Maximum concurrent connections | | `-heartbeat-interval` | duration | `30s` | Connection heartbeat interval | | `-read-timeout` | duration | `60s` | WebSocket read timeout | | `-write-timeout` | duration | `10s` | WebSocket write timeout | | `-log-level` | string | `info` | Logging level (debug, info, warn, error) | | `-jwt-secret` | string | - | JWT signing secret (required) | | `-cors-origins` | string | `*` | Allowed CORS origins | ``` -------------------------------- ### Gateway Command Line Flags Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md This snippet shows the basic command to run the gateway binary and lists its available command-line flags. These flags control network binding, simulation address, connection limits, timeouts, logging, JWT secrets, and CORS origins. ```bash ./bin/gateway [flags] ``` -------------------------------- ### Simulation Engine Command Line Flags Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md This snippet displays the command to execute the simulation engine binary and lists its configurable flags. These flags manage network binding, spatial cell size, tick rate, entity limits, world dimensions, logging, and database connections. ```bash ./bin/simulation [flags] ``` -------------------------------- ### Test WebSocket Connection (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Steps to obtain a development token using Make and then test the WebSocket connection to the game backend. ```bash # Get a development token TOKEN=$(make login) # Test WebSocket connection make wsprobe TOKEN=$TOKEN ``` -------------------------------- ### Complete Connection Flow Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Illustrates the client-side WebSocket connection establishment process, including authentication via JWT. ```APIDOC ## Protocol Examples ### Complete Connection Flow #### 1. Initial Connection ```javascript // Client-side connection establishment const ws = new WebSocket('ws://localhost:9090/ws', [], { headers: { 'Authorization': 'Bearer ' + jwtToken } }); ws.onopen = function() { console.log('WebSocket connected'); }; ws.onmessage = function(event) { const message = JSON.parse(event.data); handleMessage(message); }; ``` ``` -------------------------------- ### Development Commands (Bash) Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md A collection of Make commands for managing the game backend services, running tests, formatting code, and debugging. ```bash # Development make run # Start all services make stop # Stop all services make build # Build binaries make test # Run tests make test-ws # Run WebSocket integration tests # Code Quality make fmt # Format Go code make fmt-check # Check formatting make vet # Run Go vet # Testing & Debugging make login # Get development token make wsprobe TOKEN=x # Test WebSocket connection ``` -------------------------------- ### WebSocket Client Initial Connection Flow Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md This JavaScript snippet shows the client-side implementation for establishing an initial WebSocket connection. It includes setting up event listeners for connection opening and message reception, and includes authorization headers. ```javascript // Client-side connection establishment const ws = new WebSocket('ws://localhost:9090/ws', [], { headers: { 'Authorization': 'Bearer ' + jwtToken } }); ws.onopen = function() { console.log('WebSocket connected'); }; ws.onmessage = function(event) { const message = JSON.parse(event.data); handleMessage(message); }; ``` -------------------------------- ### Git Workflow for Contributing Source: https://github.com/astrosteveo/prototype-game/blob/main/README.md Standard Git commands for forking a repository, creating a feature branch, committing changes, and opening a pull request. ```bash git checkout -b feature/amazing-feature git commit -m 'Add amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### POST /auth/login Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Acquire JWT authentication tokens by providing player credentials. ```APIDOC ## POST /auth/login ### Description Acquire JWT authentication tokens by providing player credentials. ### Method POST ### Endpoint /auth/login ### Parameters #### Request Body - **username** (string) - Required - The player's username. - **password** (string) - Required - The player's password. ### Request Example ```json { "username": "player123", "password": "secure_password" } ``` ### Response #### Success Response (200) - **token** (string) - The JWT authentication token. - **expires_at** (string) - The expiration timestamp of the token (ISO 8601). - **player_id** (string) - The unique identifier for the player. - **session_id** (string) - The unique identifier for the player's session. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expires_at": "2024-01-15T15:30:00Z", "player_id": "player_123", "session_id": "sess_abc123" } ``` ``` -------------------------------- ### Client → Server: player_action Source: https://github.com/astrosteveo/prototype-game/blob/main/docs/api-reference.md Execute game-specific player actions such as using items or interacting with the environment. ```APIDOC ## Client → Server: player_action ### Description Execute game-specific player actions such as using items or interacting with the environment. ### Message Type `player_action` ### Data Payload ```json { "action": "use_item", "target": { "type": "entity", "entity_id": "entity_456" }, "parameters": { "item_id": "sword_001", "intensity": 0.8 } } ``` ### Parameters - **action** (string) - The type of action to perform. Common actions include: `"use_item"`, `"interact"`, `"attack"`, `"chat"`. - **target** (object) - The target of the action. - **type** (string) - The type of target (e.g., `"entity"`, `"object"`). - **entity_id** (string) - The ID of the target entity, if applicable. - **parameters** (object) - Additional parameters specific to the action. ```