docs: Complete production documentation and deployment guide
- Add comprehensive DEPLOYMENT.md with Docker and CI/CD details - Update README.md with production URLs and architecture diagrams - Document v0.0.9-alpha changes in CHANGELOG.md with full feature list - Enhance CLAUDE.md with production architecture and security practices - Document SSE optimizations, URL separation, and monitoring setup - Include troubleshooting guides and maintenance commands - Add network architecture diagrams and communication flows
This commit is contained in:
77
CHANGELOG.md
77
CHANGELOG.md
@@ -15,6 +15,83 @@ y este proyecto adhiere a [Semantic Versioning](https://semver.org/spec/v2.0.0.h
|
|||||||
- PWA support
|
- PWA support
|
||||||
- Multi-idioma
|
- Multi-idioma
|
||||||
|
|
||||||
|
## [0.0.9-alpha] - 2025-07-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **🐳 Docker Production Environment**: Sistema completo de containerización
|
||||||
|
- Dockerfiles individuales para server, client y admin
|
||||||
|
- Docker Compose con orquestación completa
|
||||||
|
- Health checks automáticos para todos los servicios
|
||||||
|
- Restart policies para alta disponibilidad
|
||||||
|
- **⚙️ Gitea Actions CI/CD Pipeline**: Automatización completa de deployment
|
||||||
|
- Build automático de imágenes Docker
|
||||||
|
- Push a registry interno gitea.interno.com/nucleo000
|
||||||
|
- Conditional building basado en archivos modificados
|
||||||
|
- Deploy automático en main branch
|
||||||
|
- **🌐 Production Network Architecture**: Arquitectura de redes optimizada
|
||||||
|
- Red "principal" para Nginx Proxy Manager
|
||||||
|
- Red interna "snatchgame-network" para comunicación entre servicios
|
||||||
|
- Separación de URLs internas (HTTP) y externas (HTTPS)
|
||||||
|
- **🔧 Environment-based URL Configuration**: URLs dinámicas según ambiente
|
||||||
|
- SERVER_URL para comunicación interna entre contenedores
|
||||||
|
- PUBLIC_SERVER_URL para comunicación frontend-backend
|
||||||
|
- Configuración automática via /api/config endpoints
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **⚡ SSE Performance Optimizations**: Comunicación admin optimizada
|
||||||
|
- Polling reducido de 500ms a 250ms para updates más rápidos
|
||||||
|
- Headers anti-buffering (X-Accel-Buffering, Content-Encoding)
|
||||||
|
- Heartbeat mechanism cada 30 segundos
|
||||||
|
- Auto-reconexión cliente cada 5 segundos en caso de error
|
||||||
|
- **🏗️ Production URLs**: Configuración de producción completa
|
||||||
|
- snatchGame.interno.com (Cliente UI)
|
||||||
|
- snatchGameServer.interno.com (Servidor Colyseus)
|
||||||
|
- snatchgGameAdmin.interno.com (Admin UI)
|
||||||
|
- **📦 Build Process**: Optimización del proceso de build
|
||||||
|
- build:prod script para omitir generación de tipos en Docker
|
||||||
|
- npm ci para instalaciones más rápidas y reproducibles
|
||||||
|
- Multi-stage builds para imágenes más pequeñas
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **🔌 SSL Certificate Issues**: Separación URLs interna/externa
|
||||||
|
- URLs HTTPS para comunicación navegador-servidor (frontend)
|
||||||
|
- URLs HTTP para comunicación contenedor-contenedor (backend)
|
||||||
|
- Resuelve errores de certificado SSL en comunicación interna
|
||||||
|
- **🎯 Admin Service URL Configuration**: URLs dinámicas basadas en ambiente
|
||||||
|
- AdminService obtiene URL desde /api/config en lugar de hardcoded localhost
|
||||||
|
- Soporte completo para desarrollo y producción
|
||||||
|
- Inicialización async de URLs antes de llamadas API
|
||||||
|
- **📊 SSE Connection Stability**: Mejoras en estabilidad de conexión
|
||||||
|
- Manejo mejorado de heartbeat messages
|
||||||
|
- Logging detallado para debugging
|
||||||
|
- Cleanup apropiado de intervalos en disconnection
|
||||||
|
|
||||||
|
### Technical
|
||||||
|
- **🐳 Docker Configuration**:
|
||||||
|
- Puertos de producción: 3067 (server), 3010 (client), 3011 (admin)
|
||||||
|
- Alpine Linux base images para menor tamaño
|
||||||
|
- wget para health checks (más ligero que curl)
|
||||||
|
- **📡 Network Communication**:
|
||||||
|
- Separación limpia entre comunicación interna y externa
|
||||||
|
- Optimización de headers SSE para mejor performance
|
||||||
|
- Express middleware optimizado para SSE endpoints
|
||||||
|
- **🔧 Environment Management**:
|
||||||
|
- Variables de entorno separadas por servicio
|
||||||
|
- Runtime configuration via API endpoints
|
||||||
|
- Support para development y production environments
|
||||||
|
|
||||||
|
### Infrastructure
|
||||||
|
- **🏗️ Complete Production Setup**: Sistema listo para producción
|
||||||
|
- Docker registry interno configurado
|
||||||
|
- CI/CD pipeline completamente automático
|
||||||
|
- High availability con health checks y restart policies
|
||||||
|
- Network isolation y security best practices
|
||||||
|
- **📊 Monitoring & Debugging**: Herramientas de monitoreo mejoradas
|
||||||
|
- Logging estructurado con timestamps
|
||||||
|
- Connection tracking para SSE
|
||||||
|
- Performance metrics para fetch requests
|
||||||
|
- Detailed error handling y reporting
|
||||||
|
|
||||||
## [0.0.8-alpha] - 2025-07-04
|
## [0.0.8-alpha] - 2025-07-04
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
123
CLAUDE.md
123
CLAUDE.md
@@ -67,16 +67,23 @@ nginx-proxy-manager # Proxy reverso y balanceador
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Enrutamiento Producción:**
|
**Enrutamiento Producción:**
|
||||||
- `/` → Cliente UI
|
- `https://snatchGame.interno.com` → Cliente UI
|
||||||
- `/admin` → Admin UI
|
- `https://snatchgGameAdmin.interno.com` → Admin UI
|
||||||
- `/server` → API Servidor Colyseus
|
- `https://snatchGameServer.interno.com` → API Servidor Colyseus
|
||||||
|
|
||||||
|
**Puertos de Producción:**
|
||||||
|
- Cliente: Puerto 3010 (externo) → 3000 (interno)
|
||||||
|
- Admin: Puerto 3011 (externo) → 3001 (interno)
|
||||||
|
- Servidor: Puerto 3067 (externo) → 2567 (interno)
|
||||||
|
|
||||||
## UI de Administración
|
## UI de Administración
|
||||||
**Arquitectura:**
|
**Arquitectura:**
|
||||||
- Servidor Express independiente (Puerto 3001)
|
- Servidor Express independiente (Puerto 3001)
|
||||||
- Comunicación SSE con servidor Colyseus
|
- Comunicación SSE con servidor Colyseus
|
||||||
- Actualización de estado cada 500ms (polling)
|
- Actualización de estado cada 250ms (polling optimizado)
|
||||||
- Una interfaz principal (múltiples conexiones opcionales)
|
- Una interfaz principal (múltiples conexiones opcionales)
|
||||||
|
- Separación URLs: HTTP interna, HTTPS externa
|
||||||
|
- Auto-reconexión y heartbeat para estabilidad
|
||||||
|
|
||||||
**Funcionalidades principales:**
|
**Funcionalidades principales:**
|
||||||
- Dashboard con estadísticas en tiempo real:
|
- Dashboard con estadísticas en tiempo real:
|
||||||
@@ -128,17 +135,25 @@ nginx-proxy-manager # Proxy reverso y balanceador
|
|||||||
- ⚠️ **Si servicios no arrancan** probablemente el usuario los levantó manualmente
|
- ⚠️ **Si servicios no arrancan** probablemente el usuario los levantó manualmente
|
||||||
- ⚠️ **Verificar puertos** antes de iniciar servicios para evitar conflictos
|
- ⚠️ **Verificar puertos** antes de iniciar servicios para evitar conflictos
|
||||||
|
|
||||||
### Producción
|
### Producción Local
|
||||||
- **Build Server**: `cd server && npm run build`
|
- **Build Server**: `cd server && npm run build`
|
||||||
- **Start Server**: `cd server && npm run start`
|
- **Start Server**: `cd server && npm run start`
|
||||||
- **Start Client**: `cd client && npm run start`
|
- **Start Client**: `cd client && npm run start`
|
||||||
- **Start Admin**: `cd admin && npm run start`
|
- **Start Admin**: `cd admin && npm run start`
|
||||||
|
|
||||||
### Docker (Producción)
|
### Docker (Producción)
|
||||||
- **Build**: `docker-compose build`
|
- **Build todas las imágenes**: `docker-compose build`
|
||||||
- **Start**: `docker-compose up -d`
|
- **Start en producción**: `docker-compose up -d`
|
||||||
- **Stop**: `docker-compose down`
|
- **Stop servicios**: `docker-compose down`
|
||||||
- **Logs**: `docker-compose logs -f [service]`
|
- **Logs en tiempo real**: `docker-compose logs -f`
|
||||||
|
- **Logs de servicio específico**: `docker-compose logs -f [snatchgame-server|snatchgame-client|snatchgame-admin]`
|
||||||
|
- **Rebuild tras cambios**: `docker-compose down && docker-compose up -d --build`
|
||||||
|
- **Ver estado de contenedores**: `docker-compose ps`
|
||||||
|
|
||||||
|
### CI/CD (Gitea Actions)
|
||||||
|
- **Push automático**: `git push gitea main` (triggerea build y deploy automático)
|
||||||
|
- **Ver logs de CI/CD**: Revisar en Gitea Actions tab
|
||||||
|
- **Conditional builds**: Solo builds los servicios con cambios detectados
|
||||||
|
|
||||||
### Variables de Entorno
|
### Variables de Entorno
|
||||||
- Desarrollo: `.env.development`
|
- Desarrollo: `.env.development`
|
||||||
@@ -251,3 +266,93 @@ client/src/types/
|
|||||||
- **Logging**: Detallado para debugging profesional
|
- **Logging**: Detallado para debugging profesional
|
||||||
- **Tipos TypeScript**: Auto-generación con schema-codegen + copiar tipos auxiliares manualmente
|
- **Tipos TypeScript**: Auto-generación con schema-codegen + copiar tipos auxiliares manualmente
|
||||||
- **Admin Dashboard**: Completamente funcional con control total del juego
|
- **Admin Dashboard**: Completamente funcional con control total del juego
|
||||||
|
- **Separación URLs**: HTTP para comunicación interna, HTTPS para navegadores
|
||||||
|
- **CI/CD Automático**: Gitea Actions con conditional building y deploy automático
|
||||||
|
- **SSE Optimizado**: Anti-buffering, polling 250ms, heartbeat y auto-reconexión
|
||||||
|
|
||||||
|
## Arquitectura de Producción
|
||||||
|
|
||||||
|
### Flujo de Comunicación
|
||||||
|
|
||||||
|
```
|
||||||
|
Browser Nginx Proxy Docker Containers
|
||||||
|
Manager
|
||||||
|
┌─────────────┐ ┌─────────────┐ ┌─────────────────┐
|
||||||
|
│ HTTPS │ ────────► │ Routes │ ────────► │ HTTP (interno) │
|
||||||
|
│ Requests │ │ Traffic │ │ Entre servicios │
|
||||||
|
└─────────────┘ └─────────────┘ └─────────────────┘
|
||||||
|
|
||||||
|
Frontend (Vue) ──HTTPS──► Nginx ──HTTP──► Express Server ──HTTP──► Colyseus
|
||||||
|
↓
|
||||||
|
SSE Stream ──HTTP──► Admin Service
|
||||||
|
```
|
||||||
|
|
||||||
|
### Separación de Responsabilidades
|
||||||
|
|
||||||
|
**Nginx Proxy Manager:**
|
||||||
|
- Terminación SSL/TLS
|
||||||
|
- Enrutamiento por dominio
|
||||||
|
- Balance de carga
|
||||||
|
- Certificados automáticos
|
||||||
|
|
||||||
|
**Docker Network "principal":**
|
||||||
|
- Comunicación con Nginx
|
||||||
|
- Acceso externo controlado
|
||||||
|
- Isolation de otros servicios
|
||||||
|
|
||||||
|
**Docker Network "snatchgame-network":**
|
||||||
|
- Comunicación interna entre servicios
|
||||||
|
- Sin acceso externo directo
|
||||||
|
- Optimizada para velocidad
|
||||||
|
|
||||||
|
### URLs y Configuración
|
||||||
|
|
||||||
|
**Externa (HTTPS - Navegador):**
|
||||||
|
```javascript
|
||||||
|
// Frontend usa PUBLIC_SERVER_URL
|
||||||
|
const serverUrl = config.serverUrl // https://snatchGameServer.interno.com
|
||||||
|
this.client = new Client(serverUrl.replace('https://', 'wss://'))
|
||||||
|
```
|
||||||
|
|
||||||
|
**Interna (HTTP - Contenedores):**
|
||||||
|
```javascript
|
||||||
|
// Backend usa SERVER_URL
|
||||||
|
const gameServerUrl = process.env.SERVER_URL // http://snatchgame-server:2567
|
||||||
|
const response = await fetch(`${gameServerUrl}/api/admin/stats`)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Health Checks y Monitoring
|
||||||
|
|
||||||
|
**Health Endpoints:**
|
||||||
|
- `/health` en todos los servicios
|
||||||
|
- Respuesta JSON con status y metadata
|
||||||
|
- Usado por Docker y monitoring
|
||||||
|
|
||||||
|
**Logging Estructurado:**
|
||||||
|
```javascript
|
||||||
|
console.log(`[SSE] Connection #${connectionId} established. Total: ${sseConnections}`)
|
||||||
|
console.log(`[SSE] Stats fetched successfully in ${fetchTime}ms`)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Métricas de Performance:**
|
||||||
|
- SSE polling: 250ms (4 updates/segundo)
|
||||||
|
- Heartbeat: 30 segundos
|
||||||
|
- Auto-reconnect: 5 segundos
|
||||||
|
- Health check: 30 segundos
|
||||||
|
|
||||||
|
### Security Best Practices
|
||||||
|
|
||||||
|
**Network Isolation:**
|
||||||
|
- Servicios en red interna Docker
|
||||||
|
- Solo puertos necesarios expuestos
|
||||||
|
- Nginx como único punto de entrada
|
||||||
|
|
||||||
|
**SSL/TLS:**
|
||||||
|
- HTTPS/WSS para comunicación externa
|
||||||
|
- HTTP interno (rápido y seguro en Docker)
|
||||||
|
- Certificados manejados por Nginx
|
||||||
|
|
||||||
|
**Environment Variables:**
|
||||||
|
- Configuración sensitive via env vars
|
||||||
|
- Separación desarrollo/producción
|
||||||
|
- Runtime configuration endpoints
|
||||||
426
DEPLOYMENT.md
Normal file
426
DEPLOYMENT.md
Normal file
@@ -0,0 +1,426 @@
|
|||||||
|
# 🚀 Guía de Deployment - SnatchGame
|
||||||
|
|
||||||
|
## 📋 Resumen
|
||||||
|
|
||||||
|
Este documento detalla el proceso completo de deployment de SnatchGame en producción usando Docker, Gitea Actions y Nginx Proxy Manager.
|
||||||
|
|
||||||
|
## 🏗️ Arquitectura de Producción
|
||||||
|
|
||||||
|
### Componentes del Sistema
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Nginx Proxy Manager │
|
||||||
|
│ (Red "principal") │
|
||||||
|
├────────────────────────────────────────────────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ 🌐 snatchGame.interno.com ──► snatchgame-client:3000 │
|
||||||
|
│ 🎯 snatchGameServer.interno.com ──► snatchgame-server:2567 │
|
||||||
|
│ 📊 snatchgGameAdmin.interno.com ──► snatchgame-admin:3001 │
|
||||||
|
│ │
|
||||||
|
└────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Servicios Docker
|
||||||
|
|
||||||
|
| Servicio | Imagen | Puerto Interno | Puerto Externo | Descripción |
|
||||||
|
|----------|--------|----------------|----------------|-------------|
|
||||||
|
| `snatchgame-server` | `gitea.interno.com/nucleo000/snatchgame-server:latest` | 2567 | 3067 | Servidor Colyseus |
|
||||||
|
| `snatchgame-client` | `gitea.interno.com/nucleo000/snatchgame-client:latest` | 3000 | 3010 | Cliente Vue + Express |
|
||||||
|
| `snatchgame-admin` | `gitea.interno.com/nucleo000/snatchgame-admin:latest` | 3001 | 3011 | Admin Vue + Express |
|
||||||
|
|
||||||
|
## 🔧 Configuración de URLs
|
||||||
|
|
||||||
|
### Separación Interna/Externa
|
||||||
|
|
||||||
|
El sistema utiliza una arquitectura de **doble URL** para optimizar la comunicación:
|
||||||
|
|
||||||
|
#### URLs Externas (HTTPS)
|
||||||
|
- **Propósito**: Comunicación navegador ↔ servicios
|
||||||
|
- **Protocolo**: HTTPS/WSS (seguro)
|
||||||
|
- **Destino**: Nginx Proxy Manager
|
||||||
|
|
||||||
|
```
|
||||||
|
Cliente Frontend → https://snatchGameServer.interno.com (WebSocket)
|
||||||
|
Admin Frontend → https://snatchGameServer.interno.com (Fetch API)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### URLs Internas (HTTP)
|
||||||
|
- **Propósito**: Comunicación contenedor ↔ contenedor
|
||||||
|
- **Protocolo**: HTTP (rápido, sin SSL)
|
||||||
|
- **Destino**: Directo entre contenedores
|
||||||
|
|
||||||
|
```
|
||||||
|
Admin Server → http://snatchgame-server:2567 (SSE, Control API)
|
||||||
|
Client Server → http://snatchgame-server:2567 (Health checks)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Variables de Entorno
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# En docker-compose.yml
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- SERVER_URL=http://snatchgame-server:2567 # URL interna
|
||||||
|
- PUBLIC_SERVER_URL=https://snatchGameServer.interno.com # URL externa
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🐳 Docker Configuration
|
||||||
|
|
||||||
|
### Dockerfiles
|
||||||
|
|
||||||
|
#### Servidor (server/Dockerfile)
|
||||||
|
```dockerfile
|
||||||
|
FROM node:20-alpine
|
||||||
|
RUN apk add --no-cache git wget
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm ci --only=production
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build && npm prune --production
|
||||||
|
EXPOSE 2567
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=40s \
|
||||||
|
CMD wget --no-verbose --tries=1 --spider http://localhost:2567/health || exit 1
|
||||||
|
CMD ["npm", "start"]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Cliente y Admin (client/Dockerfile, admin/Dockerfile)
|
||||||
|
```dockerfile
|
||||||
|
FROM node:20-alpine
|
||||||
|
RUN apk add --no-cache git wget
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build:prod # Skips type generation in Docker
|
||||||
|
EXPOSE 3000
|
||||||
|
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=40s \
|
||||||
|
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
|
||||||
|
CMD ["npm", "start"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker Compose
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
snatchgame-server:
|
||||||
|
image: gitea.interno.com/nucleo000/snatchgame-server:latest
|
||||||
|
container_name: snatchgame-server
|
||||||
|
ports:
|
||||||
|
- "3067:2567"
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- PORT=2567
|
||||||
|
networks:
|
||||||
|
- principal
|
||||||
|
- snatchgame-network
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
snatchgame-client:
|
||||||
|
image: gitea.interno.com/nucleo000/snatchgame-client:latest
|
||||||
|
container_name: snatchgame-client
|
||||||
|
ports:
|
||||||
|
- "3010:3000"
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- PORT=3000
|
||||||
|
- SERVER_URL=http://snatchgame-server:2567
|
||||||
|
- PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
|
||||||
|
depends_on:
|
||||||
|
- snatchgame-server
|
||||||
|
networks:
|
||||||
|
- principal
|
||||||
|
- snatchgame-network
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
snatchgame-admin:
|
||||||
|
image: gitea.interno.com/nucleo000/snatchgame-admin:latest
|
||||||
|
container_name: snatchgame-admin
|
||||||
|
ports:
|
||||||
|
- "3011:3001"
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
|
- PORT=3001
|
||||||
|
- SERVER_URL=http://snatchgame-server:2567
|
||||||
|
- PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
|
||||||
|
depends_on:
|
||||||
|
- snatchgame-server
|
||||||
|
networks:
|
||||||
|
- principal
|
||||||
|
- snatchgame-network
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
networks:
|
||||||
|
principal:
|
||||||
|
external: true
|
||||||
|
snatchgame-network:
|
||||||
|
driver: bridge
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️ CI/CD Pipeline
|
||||||
|
|
||||||
|
### Gitea Actions (.gitea/workflows/build-and-deploy.yml)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
name: Build and Deploy SnatchGame
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-server:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: contains(github.event.head_commit.modified, 'server/') || github.event_name == 'pull_request'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build and push server image
|
||||||
|
run: |
|
||||||
|
docker build -t gitea.interno.com/nucleo000/snatchgame-server:latest ./server
|
||||||
|
docker push gitea.interno.com/nucleo000/snatchgame-server:latest
|
||||||
|
|
||||||
|
build-client:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: contains(github.event.head_commit.modified, 'client/') || github.event_name == 'pull_request'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build and push client image
|
||||||
|
run: |
|
||||||
|
docker build -t gitea.interno.com/nucleo000/snatchgame-client:latest ./client
|
||||||
|
docker push gitea.interno.com/nucleo000/snatchgame-client:latest
|
||||||
|
|
||||||
|
build-admin:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: contains(github.event.head_commit.modified, 'admin/') || github.event_name == 'pull_request'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build and push admin image
|
||||||
|
run: |
|
||||||
|
docker build -t gitea.interno.com/nucleo000/snatchgame-admin:latest ./admin
|
||||||
|
docker push gitea.interno.com/nucleo000/snatchgame-admin:latest
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build-server, build-client, build-admin]
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Deploy to production
|
||||||
|
run: |
|
||||||
|
docker-compose down
|
||||||
|
docker-compose pull
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### Conditional Building
|
||||||
|
|
||||||
|
El pipeline utiliza **conditional building** basado en archivos modificados:
|
||||||
|
|
||||||
|
- **server/** → Builds `snatchgame-server`
|
||||||
|
- **client/** → Builds `snatchgame-client`
|
||||||
|
- **admin/** → Builds `snatchgame-admin`
|
||||||
|
- **Pull requests** → Builds todo pero no deploya
|
||||||
|
|
||||||
|
## 🔄 Optimizaciones SSE
|
||||||
|
|
||||||
|
### Problema Identificado
|
||||||
|
La comunicación SSE entre el navegador y los contenedores Docker presentaba latencia alta (~10 segundos entre actualizaciones).
|
||||||
|
|
||||||
|
### Solución Implementada
|
||||||
|
|
||||||
|
#### Headers Anti-Buffering
|
||||||
|
```javascript
|
||||||
|
// admin/server.js
|
||||||
|
res.writeHead(200, {
|
||||||
|
'Content-Type': 'text/event-stream',
|
||||||
|
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||||
|
'Connection': 'keep-alive',
|
||||||
|
'X-Accel-Buffering': 'no', // Disable nginx buffering
|
||||||
|
'Content-Encoding': 'identity' // Disable compression
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Polling Optimizado
|
||||||
|
```javascript
|
||||||
|
// Reducido de 500ms a 250ms para updates más rápidos
|
||||||
|
const pollInterval = setInterval(async () => {
|
||||||
|
// Fetch game stats...
|
||||||
|
}, 250);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Heartbeat Mechanism
|
||||||
|
```javascript
|
||||||
|
// Keepalive cada 30 segundos
|
||||||
|
const heartbeatInterval = setInterval(() => {
|
||||||
|
res.write(': heartbeat\n\n');
|
||||||
|
}, 30000);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Auto-reconexión Cliente
|
||||||
|
```javascript
|
||||||
|
// admin/src/services/adminService.ts
|
||||||
|
this.eventSource.onerror = (error) => {
|
||||||
|
// Auto-reconnect after 5 seconds
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!this.isConnected) {
|
||||||
|
this.connect(this.callback!);
|
||||||
|
}
|
||||||
|
}, 5000);
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 Proceso de Deployment
|
||||||
|
|
||||||
|
### 1. Push a Main Branch
|
||||||
|
```bash
|
||||||
|
git add .
|
||||||
|
git commit -m "feature: new functionality"
|
||||||
|
git push gitea main
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Automatic CI/CD
|
||||||
|
- Gitea Actions detecta cambios
|
||||||
|
- Builds las imágenes necesarias
|
||||||
|
- Push al registry interno
|
||||||
|
- Deploy automático en producción
|
||||||
|
|
||||||
|
### 3. Verificación
|
||||||
|
```bash
|
||||||
|
# Verificar estado de contenedores
|
||||||
|
docker-compose ps
|
||||||
|
|
||||||
|
# Ver logs en tiempo real
|
||||||
|
docker-compose logs -f
|
||||||
|
|
||||||
|
# Health check manual
|
||||||
|
curl -f http://localhost:3067/health
|
||||||
|
curl -f http://localhost:3010/health
|
||||||
|
curl -f http://localhost:3011/health
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Rollback si es Necesario
|
||||||
|
```bash
|
||||||
|
# Rollback a versión anterior
|
||||||
|
docker-compose down
|
||||||
|
git checkout <previous-commit>
|
||||||
|
docker-compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🔧 Comandos de Mantenimiento
|
||||||
|
|
||||||
|
### Development to Production
|
||||||
|
```bash
|
||||||
|
# Build local para testing
|
||||||
|
docker-compose build
|
||||||
|
|
||||||
|
# Deploy en producción
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Rebuild completo tras cambios
|
||||||
|
docker-compose down && docker-compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Monitoring
|
||||||
|
```bash
|
||||||
|
# Logs de servicio específico
|
||||||
|
docker-compose logs -f snatchgame-server
|
||||||
|
docker-compose logs -f snatchgame-client
|
||||||
|
docker-compose logs -f snatchgame-admin
|
||||||
|
|
||||||
|
# Estadísticas de recursos
|
||||||
|
docker stats
|
||||||
|
|
||||||
|
# Estado de redes
|
||||||
|
docker network ls
|
||||||
|
docker network inspect snatchgame_principal
|
||||||
|
```
|
||||||
|
|
||||||
|
### Troubleshooting
|
||||||
|
```bash
|
||||||
|
# Verificar conectividad entre contenedores
|
||||||
|
docker exec snatchgame-admin curl http://snatchgame-server:2567/health
|
||||||
|
|
||||||
|
# Reiniciar servicio específico
|
||||||
|
docker-compose restart snatchgame-admin
|
||||||
|
|
||||||
|
# Limpiar imágenes antiguas
|
||||||
|
docker image prune -f
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📊 Monitoring y Salud del Sistema
|
||||||
|
|
||||||
|
### Health Checks
|
||||||
|
Todos los servicios incluyen health checks automáticos:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:2567/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 40s
|
||||||
|
```
|
||||||
|
|
||||||
|
### Logs Estructurados
|
||||||
|
```javascript
|
||||||
|
// Logs con timestamps y prefijos para debugging
|
||||||
|
console.log(`[SSE] Connection #${connectionId} established. Total: ${sseConnections}`);
|
||||||
|
console.log(`[SSE] Stats fetched successfully in ${fetchTime}ms`);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Métricas de Rendimiento
|
||||||
|
- **SSE Update Frequency**: 250ms
|
||||||
|
- **Heartbeat Interval**: 30s
|
||||||
|
- **Auto-reconnect Delay**: 5s
|
||||||
|
- **Health Check Interval**: 30s
|
||||||
|
|
||||||
|
## 🔒 Seguridad
|
||||||
|
|
||||||
|
### HTTPS/WSS
|
||||||
|
- Todas las comunicaciones externas usan HTTPS/WSS
|
||||||
|
- Certificados SSL manejados por Nginx Proxy Manager
|
||||||
|
- Comunicación interna HTTP (rápida y segura dentro de Docker)
|
||||||
|
|
||||||
|
### Network Isolation
|
||||||
|
- Red `principal`: Comunicación con Nginx
|
||||||
|
- Red `snatchgame-network`: Comunicación interna entre servicios
|
||||||
|
- Puertos expuestos mínimos
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
- Configuración sensitive via variables de entorno
|
||||||
|
- Separación clara desarrollo/producción
|
||||||
|
- No secrets hardcoded en código
|
||||||
|
|
||||||
|
## 📈 Escalabilidad
|
||||||
|
|
||||||
|
### Horizontal Scaling
|
||||||
|
```yaml
|
||||||
|
# Múltiples instancias del mismo servicio
|
||||||
|
snatchgame-server-1:
|
||||||
|
image: gitea.interno.com/nucleo000/snatchgame-server:latest
|
||||||
|
# ...
|
||||||
|
snatchgame-server-2:
|
||||||
|
image: gitea.interno.com/nucleo000/snatchgame-server:latest
|
||||||
|
# ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Load Balancing
|
||||||
|
- Nginx Proxy Manager puede distribuir carga
|
||||||
|
- Health checks aseguran disponibilidad
|
||||||
|
- Auto-restart en caso de fallas
|
||||||
|
|
||||||
|
## 🎯 Próximos Pasos
|
||||||
|
|
||||||
|
1. **Monitoring Avanzado**: Prometheus + Grafana
|
||||||
|
2. **Backup Automático**: Estrategia de backups de datos
|
||||||
|
3. **Blue-Green Deployment**: Deploy sin downtime
|
||||||
|
4. **Resource Limits**: CPU/Memory limits por contenedor
|
||||||
|
5. **Log Aggregation**: ELK Stack o similar
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> 📝 **Nota**: Esta documentación refleja el estado actual del sistema al 2025-07-05. Actualizar tras modificaciones significativas.
|
||||||
91
README.md
91
README.md
@@ -129,13 +129,25 @@ npm run dev
|
|||||||
- **Admin Dashboard**: http://localhost:3001
|
- **Admin Dashboard**: http://localhost:3001
|
||||||
- **Monitor Colyseus**: http://localhost:2567/monitor
|
- **Monitor Colyseus**: http://localhost:2567/monitor
|
||||||
|
|
||||||
### Producción
|
### Producción con Docker
|
||||||
```bash
|
|
||||||
# Build
|
|
||||||
npm run build
|
|
||||||
|
|
||||||
# Deploy con Docker
|
**URLs de Producción:**
|
||||||
|
- **Cliente**: https://snatchGame.interno.com
|
||||||
|
- **Servidor**: https://snatchGameServer.interno.com
|
||||||
|
- **Admin Dashboard**: https://snatchgGameAdmin.interno.com
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build todas las imágenes
|
||||||
|
docker-compose build
|
||||||
|
|
||||||
|
# Deploy en producción
|
||||||
docker-compose up -d
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Ver logs en tiempo real
|
||||||
|
docker-compose logs -f
|
||||||
|
|
||||||
|
# Rebuild y redeploy tras cambios
|
||||||
|
docker-compose down && docker-compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🎮 Interfaz del Juego
|
## 🎮 Interfaz del Juego
|
||||||
@@ -196,6 +208,8 @@ El **Admin Dashboard** proporciona control completo y monitoreo en tiempo real d
|
|||||||
- **Comunicación Bidireccional**: SSE para updates, HTTP para control
|
- **Comunicación Bidireccional**: SSE para updates, HTTP para control
|
||||||
- **Sin Variables Globales**: Implementación limpia y mantenible
|
- **Sin Variables Globales**: Implementación limpia y mantenible
|
||||||
- **Type Safety**: Sincronización completa de tipos TypeScript
|
- **Type Safety**: Sincronización completa de tipos TypeScript
|
||||||
|
- **Separación URLs**: URLs internas HTTP para contenedores, HTTPS para clientes
|
||||||
|
- **Optimización SSE**: Anti-buffering headers, polling optimizado (250ms), heartbeat
|
||||||
|
|
||||||
## ⚙️ Configuración
|
## ⚙️ Configuración
|
||||||
|
|
||||||
@@ -210,9 +224,15 @@ PORT=2567
|
|||||||
|
|
||||||
**Producción** (`.env.production`):
|
**Producción** (`.env.production`):
|
||||||
```env
|
```env
|
||||||
VITE_SERVER_URL=wss://your-domain.com
|
|
||||||
NODE_ENV=production
|
NODE_ENV=production
|
||||||
|
# Servidor
|
||||||
PORT=2567
|
PORT=2567
|
||||||
|
# Cliente
|
||||||
|
SERVER_URL=http://snatchgame-server:2567
|
||||||
|
PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
|
||||||
|
# Admin
|
||||||
|
SERVER_URL=http://snatchgame-server:2567
|
||||||
|
PUBLIC_SERVER_URL=https://snatchGameServer.interno.com
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuración de Logs
|
### Configuración de Logs
|
||||||
@@ -222,25 +242,59 @@ PORT=2567
|
|||||||
|
|
||||||
## 🏗️ Arquitectura
|
## 🏗️ Arquitectura
|
||||||
|
|
||||||
|
### Desarrollo
|
||||||
```
|
```
|
||||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||||
│ Client UI │ │ Colyseus │ │ Admin UI │
|
│ Client UI │ │ Colyseus │ │ Admin UI │
|
||||||
│ (Vue 3) │◄──►│ Server │◄──►│ (Vue 3 + SSE) │
|
│ (Vue 3) │◄──►│ Server │◄──►│ (Vue 3 + SSE) │
|
||||||
│ Port 3000 │ │ Port 2567 │ │ Port 3001 │
|
│ Port 3000 │ │ Port 2567 │ │ Port 3001 │
|
||||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||||
│ │ │
|
|
||||||
└───────────────────────┼───────────────────────┘
|
|
||||||
│
|
|
||||||
┌─────────────────┐
|
|
||||||
│ Docker + │
|
|
||||||
│ Nginx Proxy │
|
|
||||||
└─────────────────┘
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Producción con Docker
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Nginx Proxy Manager │
|
||||||
|
│ Red "principal" │
|
||||||
|
├────────────────────────────────────────────────────────────────┤
|
||||||
|
│ https://snatchGame.interno.com │
|
||||||
|
│ ↓ (Puerto 3010) │
|
||||||
|
│ ┌─────────────────┐ ┌─────────────────┐ │
|
||||||
|
│ │ snatchgame- │ │ snatchgame- │ │
|
||||||
|
│ │ client │◄────┤ server │ │
|
||||||
|
│ │ (Vue + Express) │ │ (Colyseus) │ │
|
||||||
|
│ │ Puerto 3000 │ │ Puerto 2567 │ │
|
||||||
|
│ └─────────────────┘ └─────────────────┘ │
|
||||||
|
│ ▲ ▲ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ┌─────────────────┐ │
|
||||||
|
│ └───────────────┤ snatchgame- │ │
|
||||||
|
│ │ admin │ │
|
||||||
|
│ │ (Vue + Express) │ │
|
||||||
|
│ https://snatchgGameAdmin.interno.com │ │
|
||||||
|
│ │ Puerto 3001 │ │
|
||||||
|
│ └─────────────────┘ │
|
||||||
|
│ ↑ (Puerto 3011) │
|
||||||
|
└────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Separación de URLs en Producción
|
||||||
|
|
||||||
|
**URLs Externas (HTTPS - Navegador → Nginx):**
|
||||||
|
- Cliente: `https://snatchGame.interno.com`
|
||||||
|
- Servidor: `https://snatchGameServer.interno.com`
|
||||||
|
- Admin: `https://snatchgGameAdmin.interno.com`
|
||||||
|
|
||||||
|
**URLs Internas (HTTP - Contenedor → Contenedor):**
|
||||||
|
- Servidor: `http://snatchgame-server:2567`
|
||||||
|
- Cliente API: `http://snatchgame-client:3000`
|
||||||
|
- Admin API: `http://snatchgame-admin:3001`
|
||||||
|
|
||||||
### Comunicación Admin
|
### Comunicación Admin
|
||||||
- **SSE (Server-Sent Events)**: Servidor → Admin UI
|
- **SSE (Server-Sent Events)**: Servidor → Admin UI
|
||||||
- **Polling**: Actualización cada 500ms
|
- **Polling**: Actualización cada 250ms (optimizado)
|
||||||
- **Control**: Admin → Servidor (HTTP endpoints)
|
- **Control**: Admin → Servidor (HTTP endpoints)
|
||||||
|
- **Heartbeat**: Keepalive cada 30 segundos
|
||||||
|
|
||||||
### Sincronización de Tipos
|
### Sincronización de Tipos
|
||||||
```bash
|
```bash
|
||||||
@@ -395,8 +449,15 @@ npm run start
|
|||||||
- [x] Control de rondas globales
|
- [x] Control de rondas globales
|
||||||
- [x] Información detallada de jugadores con tokens
|
- [x] Información detallada de jugadores con tokens
|
||||||
- [x] Notificaciones automáticas a clientes
|
- [x] Notificaciones automáticas a clientes
|
||||||
|
- [x] Optimización SSE (250ms polling, heartbeat, anti-buffering)
|
||||||
- [ ] Historial de partidas anteriores
|
- [ ] Historial de partidas anteriores
|
||||||
- [ ] 🐳 Docker en producción
|
- [x] 🐳 Docker en producción
|
||||||
|
- [x] Dockerfiles para todos los servicios
|
||||||
|
- [x] Docker Compose con orquestación completa
|
||||||
|
- [x] Gitea Actions CI/CD pipeline
|
||||||
|
- [x] Separación URLs internas/externas para SSL
|
||||||
|
- [x] Red principal para Nginx Proxy Manager
|
||||||
|
- [x] Health checks y restart policies
|
||||||
- [ ] 📱 PWA support
|
- [ ] 📱 PWA support
|
||||||
- [ ] 🌍 Multi-idioma (EN/ES)
|
- [ ] 🌍 Multi-idioma (EN/ES)
|
||||||
- [ ] 🔒 Sistema de salas privadas
|
- [ ] 🔒 Sistema de salas privadas
|
||||||
|
|||||||
Reference in New Issue
Block a user