onilib
Version:
A modular Node.js library for real-time online integration in games and web applications
272 lines (207 loc) • 6.76 kB
Markdown
# ONILib (Online Integration Library)
🚀 **Uma biblioteca Node.js completa para integração online em tempo real para jogos e aplicações web.**
A ONILib é uma solução modular e escalável que fornece todos os recursos necessários para criar aplicações online em tempo real, incluindo autenticação, comunicação WebSocket, matchmaking, P2P WebRTC, armazenamento persistente e ferramentas de administração.
## ✨ Características Principais
- 🔐 **Autenticação Robusta**: Suporte a JWT e API Keys com estratégias customizáveis
- 🔄 **Comunicação em Tempo Real**: Servidor WebSocket com salas e middlewares
- 🎮 **Sistema de Matchmaking**: Filas inteligentes com critérios de pareamento
- 🔗 **Suporte P2P**: WebRTC signaling com fallback relay opcional
- 💾 **Armazenamento Flexível**: Adaptadores para Memory, SQLite, PostgreSQL e Cloudflare D1/KV
- 📊 **Painel Administrativo**: API REST para métricas, sessões e gerenciamento
- 🧪 **Ferramentas de Teste**: Harness completo para testes P2P, latência e throughput
- 🛠️ **CLI Integrada**: Comandos para scaffolding, desenvolvimento e deploy
## 🚀 Instalação Rápida
```bash
# Instalar globalmente
npm install -g onilib
# Criar novo projeto
onilib init meu-jogo-online
cd meu-jogo-online
# Instalar dependências
npm install
# Iniciar servidor de desenvolvimento
onilib start --dev
```
## 📋 Comandos CLI
| Comando | Descrição |
|---------|----------|
| `onilib init [nome]` | Cria scaffolding inicial do projeto |
| `onilib start [--dev]` | Inicia servidor (--dev para hot reload) |
| `onilib test` | Executa suíte de testes |
| `onilib test p2p --nodes=N --duration=Xs` | Teste de stress P2P |
| `onilib build` | Prepara projeto para produção |
## 🏗️ Arquitetura Modular
### Core Modules
```javascript
const { NodeOnlineIntegration } = require('onilib');
const noi = new NodeOnlineIntegration({
// Configuração dos módulos
auth: { /* configurações de autenticação */ },
realtime: { /* configurações WebSocket */ },
storage: { /* configurações de armazenamento */ },
matchmaking: { /* configurações de matchmaking */ },
p2p: { /* configurações WebRTC */ },
admin: { /* configurações do painel admin */ }
});
await noi.start();
```
### Módulos Disponíveis
- **`core`**: Gerenciamento de ciclo de vida e configuração
- **`auth`**: Autenticação JWT e API Key
- **`realtime`**: Servidor WebSocket com salas
- **`storage`**: Adaptadores de armazenamento
- **`matchmaking`**: Sistema de filas e pareamento
- **`p2p`**: Signaling WebRTC
- **`admin`**: API REST para administração
## 💡 Exemplo Básico
### Servidor
```javascript
const { NodeOnlineIntegration } = require('onilib');
const config = {
name: 'meu-jogo',
port: 3000,
auth: {
jwtSecret: 'seu-secret-jwt',
apiKeys: ['sua-api-key']
},
realtime: {
port: 8080,
authRequired: true
},
storage: {
type: 'sqlite',
path: './data/game.db'
},
matchmaking: {
maxPlayersPerMatch: 2,
enableSkillMatching: true
}
};
async function main() {
const noi = new NodeOnlineIntegration(config);
await noi.start();
// Obter referências dos módulos
const realtime = noi.getModule('realtime');
const matchmaking = noi.getModule('matchmaking');
// Registrar handlers customizados
realtime.registerHandler('game_action', (client, message) => {
console.log('Ação do jogo:', message.data);
// Broadcast para outros jogadores na sala
realtime.broadcastToRoom(client.currentRoom, {
type: 'player_action',
data: message.data
}, client.id);
});
// Eventos de matchmaking
matchmaking.on('match:started', (match) => {
console.log('Partida iniciada:', match.id);
// Criar sala dedicada para a partida
const roomId = `match_${match.id}`;
for (const player of match.players) {
realtime.joinRoom(player.client, roomId);
realtime.sendToClient(player.client, {
type: 'game_start',
data: { matchId: match.id, roomId }
});
}
});
}
main().catch(console.error);
```
## 🔧 Configuração
Edit `noi.config.js` to customize your application settings:
- **Authentication**: Configure JWT secrets and API keys
- **WebSocket**: Set ports and connection limits
- **Storage**: Choose between memory, SQLite, or PostgreSQL
- **Matchmaking**: Configure queue settings and match criteria
- **P2P**: Set up WebRTC STUN/TURN servers
## 📡 API WebSocket
### Mensagens de Autenticação
```javascript
// Autenticação com API Key
{
type: 'auth',
data: {
strategy: 'apikey',
credentials: { apiKey: 'sua-api-key' }
}
}
// Autenticação com JWT
{
type: 'auth',
data: {
strategy: 'jwt',
credentials: { token: 'seu-jwt-token' }
}
}
```
### Mensagens de Salas
```javascript
// Entrar em sala
{
type: 'join_room',
data: { roomId: 'lobby' }
}
// Sair de sala
{
type: 'leave_room',
data: { roomId: 'lobby' }
}
```
### Mensagens de Matchmaking
```javascript
// Entrar na fila
{
type: 'join_queue',
data: {
queueType: 'ranked',
criteria: { skill: 1200, region: 'BR' }
}
}
// Aceitar partida
{
type: 'accept_match',
data: { matchId: 'match-123' }
}
```
### Admin REST API
Access the admin panel at `http://localhost:3001`:
- `GET /health` - Health check
- `GET /api/system/stats` - System statistics
- `GET /api/realtime/clients` - Connected clients
- `GET /api/matchmaking/queues` - Active queues
- `GET /api/p2p/rooms` - P2P rooms
## 🧪 Testes
### Executar Testes
```bash
# Todos os testes
npm test
# Testes específicos
npm test -- --testNamePattern="Auth Module"
# Testes P2P com múltiplos nós
onilib test p2p --nodes=10 --duration=60s
# Teste de carga
onilib test load --connections=100 --duration=30s
```
## 🚀 Deploy
### Railway/Render
```bash
# Preparar para deploy
onilib build
# Variáveis de ambiente necessárias
export NODE_ENV=production
export JWT_SECRET=seu-secret-super-seguro
export API_KEY=sua-api-key-producao
export STORAGE_TYPE=postgres
export DATABASE_URL=sua-connection-string
```
## Environment Variables
- `NODE_ENV` - Environment (development/production)
- `PORT` - HTTP server port
- `WS_PORT` - WebSocket server port
- `JWT_SECRET` - JWT signing secret
- `API_KEY` - Default API key
- `STORAGE_TYPE` - Storage adapter (memory/sqlite/postgres)
- `STORAGE_PATH` - Database file path (for SQLite)
## License
MIT