maestri-remote/src/relay/server.js

234 lines
7.3 KiB
JavaScript

import http from 'node:http';
import path from 'node:path';
import { WebSocketServer } from 'ws';
import { SessionManager } from './session-manager.js';
import { PushService } from './push-service.js';
import { OtaService } from './ota-service.js';
import { IntentClassifier } from './intent-classifier.js';
import { TelemetryService } from './telemetry-service.js';
import { DbService } from './db-service.js';
import { AuthService } from './auth-service.js';
import { createRelayHttpHandler } from './http-handler.js';
import { handleClientWsMessage } from './client-message-handler.js';
import { handleGatewayWsMessage } from './gateway-message-handler.js';
const PORT = parseInt(process.env.PORT || '3000', 10);
const PUBLIC_DIR = path.resolve('public');
const sessionManager = new SessionManager();
const pushService = new PushService();
const otaService = new OtaService();
const intentClassifier = new IntentClassifier();
const telemetryService = new TelemetryService();
const dbService = new DbService();
const authService = new AuthService({ dbService });
if (dbService.isConfigured()) {
dbService.ensureSchema().catch((err) => {
console.error('[Relay:DB] Falha ao inicializar schema Postgres:', err.message);
});
}
// Quando um prompt é criado pelo Gateway, envia Push aos clientes da sessão
sessionManager.on('promptPending', ({ pin, prompt }) => {
pushService.sendNotification(pin, {
title: `Prompt de ${prompt.agentName}`,
body: prompt.prompt?.slice(0, 100) || 'Novo comando ou confirmação aguardando resposta.',
data: { requestId: prompt.requestId, agentName: prompt.agentName, type: 'prompt_pending' }
});
});
sessionManager.on('taskCompleted', ({ pin, agentName }) => {
pushService.sendNotification(pin, {
title: `⚡ ${agentName}: Execução concluída`,
body: 'O terminal parou e está pronto para nova instrução.',
data: { agentName, type: 'task_completed' }
});
});
sessionManager.on('chatResponse', ({ pin, agentName, response }) => {
const cleanSnippet = (response || 'Resposta pronta.').replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').slice(0, 120);
pushService.sendNotification(pin, {
title: `💬 Resposta de ${agentName}`,
body: cleanSnippet,
data: { agentName, type: 'chat_response' }
});
});
sessionManager.on('agentPaused', ({ pin, agentName, pauseResetTime }) => {
pushService.sendNotification(pin, {
title: `⏸️ ${agentName}: Limite de cota atingido`,
body: pauseResetTime ? `Agente pausado até ${pauseResetTime}.` : 'Agente pausado aguardando liberação de cota.',
data: { agentName, type: 'agent_paused' }
});
});
sessionManager.on('agentInteractiveMenu', ({ pin, agentName, menuTitle }) => {
pushService.sendNotification(pin, {
title: `🎛️ ${agentName}: Menu interativo ativo`,
body: menuTitle ? `Aguardando seleção: ${menuTitle}` : 'Aguardando seleção de opções no terminal.',
data: { agentName, type: 'interactive_menu' }
});
});
const server = http.createServer(createRelayHttpHandler({
publicDir: PUBLIC_DIR,
pushService,
otaService,
intentClassifier,
telemetryService,
authService,
dbService
}));
// Setup dos Servidores WebSocket
const wssGateway = new WebSocketServer({ noServer: true });
const wssClient = new WebSocketServer({ noServer: true });
server.on('upgrade', (request, socket, head) => {
const { pathname } = new URL(request.url, `http://${request.headers.host}`);
if (pathname === '/ws/gateway') {
wssGateway.handleUpgrade(request, socket, head, (ws) => {
wssGateway.emit('connection', ws, request);
});
} else if (pathname === '/ws/client') {
wssClient.handleUpgrade(request, socket, head, (ws) => {
wssClient.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
// Heartbeat a cada 25s para detectar notebooks/máquinas desligadas ou desconectadas
const heartbeatInterval = setInterval(() => {
wssGateway.clients.forEach((ws) => {
if (ws.isAlive === false) {
console.log('[Relay:GatewayWS] Conexão inativa detectada (sem pong). Encerrando socket...');
return ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
wssClient.clients.forEach((ws) => {
if (ws.isAlive === false) {
return ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
}, 25000);
server.on('close', () => clearInterval(heartbeatInterval));
// Gateway WebSocket Handler
wssGateway.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
let sessionPin = null;
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString());
if (msg.type === 'AUTH_GATEWAY') {
sessionPin = msg.pin;
sessionManager.registerGateway(sessionPin, ws, msg.machineName);
ws.send(JSON.stringify({ type: 'AUTH_SUCCESS', pin: sessionPin }));
return;
}
if (!sessionPin) return;
handleGatewayWsMessage({
sessionPin,
msg,
sessionManager,
telemetryService,
intentClassifier
});
} catch (err) {
console.error('[Relay:GatewayWS] Erro ao processar mensagem:', err.message);
}
});
});
// Mobile Client WebSocket Handler
wssClient.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
let sessionPin = null;
ws.on('message', (data) => {
try {
const msg = JSON.parse(data.toString());
if (msg.type === 'AUTH_CLIENT') {
sessionPin = msg.pin;
const result = sessionManager.registerClient(sessionPin, ws);
if (!result.success) {
ws.send(JSON.stringify({ type: 'AUTH_ERROR', message: result.error }));
sessionPin = null;
} else {
ws.send(JSON.stringify({
type: 'AUTH_SUCCESS',
pin: sessionPin,
gatewayConnected: Boolean(result.isGatewayReady)
}));
}
return;
}
if (!sessionPin) return;
handleClientWsMessage({
ws,
sessionPin,
msg,
sessionManager,
telemetryService
});
} catch (err) {
console.error('[Relay:ClientWS] Erro ao processar mensagem:', err.message);
}
});
});
server.listen(PORT, '0.0.0.0', () => {
const manifest = otaService.getManifest();
console.log(`[Maestri Remote Relay] Versão: v${manifest.version || '1.0.9'} (build: ${manifest.buildId || 'local'})`);
console.log(`[Maestri Remote Relay] Servidor rodando na porta ${PORT}`);
console.log(`[Maestri Remote Relay] Health: http://localhost:${PORT}/api/health`);
console.log(`[Maestri Remote Relay] OTA Updates: http://localhost:${PORT}/api/updates/latest`);
});
const gracefulShutdown = (signal) => {
console.log(`[Relay] Recebido sinal ${signal}. Encerrando conexões graciosamente...`);
const notifyAndClose = (wss) => {
wss.clients.forEach(client => {
try {
client.close(1001, 'Servidor reiniciando para atualização (rollout)');
} catch {}
});
};
notifyAndClose(wssGateway);
notifyAndClose(wssClient);
server.close(() => {
console.log('[Relay] Servidor HTTP/WS encerrado com sucesso.');
process.exit(0);
});
setTimeout(() => {
console.warn('[Relay] Forçando encerramento após timeout.');
process.exit(0);
}, 10000).unref();
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));