headplane/server/ws.mjs

29 lines
862 B
JavaScript
Raw Normal View History

2024-12-30 13:48:10 +05:30
// The Websocket server is wholly responsible for ingesting messages from
// Headplane agent instances (hopefully not more than 1 is running lol)
2024-12-31 10:30:14 +05:30
import { WebSocketServer } from 'ws';
import { log } from './utils.mjs';
2024-12-30 13:48:10 +05:30
2024-12-31 10:30:14 +05:30
const wss = new WebSocketServer({ noServer: true });
2024-12-30 13:48:10 +05:30
wss.on('connection', (ws, req) => {
// On connection the agent will send its NodeID via Headers
// We store this for later use to validate and show on the UI
2024-12-31 10:30:14 +05:30
const nodeID = req.headers['x-headplane-ts-node-id'];
2024-12-30 13:48:10 +05:30
if (!nodeID) {
2024-12-31 10:30:14 +05:30
ws.close(1008, 'ERR_NO_HP_TS_NODE_ID');
return;
2024-12-30 13:48:10 +05:30
}
2024-12-31 10:30:14 +05:30
});
2024-12-30 13:48:10 +05:30
export async function registerWss(server) {
2024-12-31 10:30:14 +05:30
log('SRVX', 'INFO', 'Registering Websocket Server');
2024-12-30 13:48:10 +05:30
server.on('upgrade', (request, socket, head) => {
2024-12-31 10:30:14 +05:30
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
2024-12-30 13:48:10 +05:30
}
export function getWss() {
2024-12-31 10:30:14 +05:30
return wss;
2024-12-30 13:48:10 +05:30
}