File size: 1,528 Bytes
1d7d958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskBrokerWebSocketServer = void 0;
const ws_1 = require("ws");
const app_config_1 = require("../config/app.config");
const logger_1 = require("../utils/logger");
class TaskBrokerWebSocketServer {
    wss;
    handler;
    constructor(server, handler) {
        this.handler = handler;
        this.wss = new ws_1.WebSocketServer({ server, path: app_config_1.CONFIG.WS.PATH });
        this.init();
    }
    init() {
        logger_1.logger.info(`WebSocket Server initialized on endpoint path [${app_config_1.CONFIG.WS.PATH}]`);
        this.wss.on('connection', (ws) => {
            this.handler.handleConnection(ws);
        });
        // Send periodic pings to keep connections alive through cloud proxies/load balancers
        const pingInterval = setInterval(() => {
            this.wss.clients.forEach((client) => {
                if (client.readyState === ws_1.WebSocket.OPEN) {
                    client.ping();
                }
            });
        }, app_config_1.CONFIG.WS.PING_INTERVAL_MS);
        this.wss.on('close', () => {
            clearInterval(pingInterval);
        });
    }
    sendToWorker(workerId, message) {
        const ws = this.handler.getSocketForWorker(workerId);
        if (ws && ws.readyState === ws_1.WebSocket.OPEN) {
            ws.send(JSON.stringify(message));
            return true;
        }
        return false;
    }
}
exports.TaskBrokerWebSocketServer = TaskBrokerWebSocketServer;