openreplay/utilities/servers/websocket.js
Taha Yassine Kraiem 57213e202e feat(utilities): WS don't keep status in memory
feat(utilities): WS return full QUERY
2022-02-06 13:50:07 +01:00

219 lines
No EOL
9.1 KiB
JavaScript

const _io = require('socket.io');
var express = require('express');
var {extractPeerId} = require('./peerjs-server');
var wsRouter = express.Router();
const IDENTITIES = {agent: 'agent', session: 'session'};
const NEW_AGENT_MESSAGE = "NEW_AGENT";
const NO_AGENTS = "NO_AGENT";
const NO_SESSIONS = "SESSION_DISCONNECTED";
const SESSION_ALREADY_CONNECTED = "SESSION_ALREADY_CONNECTED";
// const wsReconnectionTimeout = process.env.wsReconnectionTimeout | 10 * 1000;
let io;
wsRouter.get(`/${process.env.S3_KEY}/sockets-list`, function (req, res) {
console.log("[WS]looking for all available sessions");
let liveSessions = {};
for (let peerId of io.sockets.adapter.rooms.keys()) {
let {projectKey, sessionId} = extractPeerId(peerId);
if (projectKey !== undefined) {
liveSessions[projectKey] = liveSessions[projectKey] || [];
liveSessions[projectKey].push(sessionId);
}
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({"data": liveSessions}));
});
wsRouter.get(`/${process.env.S3_KEY}/sockets-list/:projectKey`, function (req, res) {
console.log(`[WS]looking for available sessions for ${req.params.projectKey}`);
let liveSessions = {};
for (let peerId of io.sockets.adapter.rooms.keys()) {
let {projectKey, sessionId} = extractPeerId(peerId);
if (projectKey === req.params.projectKey) {
liveSessions[projectKey] = liveSessions[projectKey] || [];
liveSessions[projectKey].push(sessionId);
}
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({"data": liveSessions[req.params.projectKey] || []}));
});
wsRouter.get(`/${process.env.S3_KEY}/sockets-live`, async function (req, res) {
console.log("[WS]looking for all available LIVE sessions");
let liveSessions = {};
for (let peerId of io.sockets.adapter.rooms.keys()) {
let {projectKey, sessionId} = extractPeerId(peerId);
if (projectKey !== undefined) {
let connected_sockets = await io.in(peerId).fetchSockets();
for (let item of connected_sockets) {
if (item.handshake.query.identity === IDENTITIES.session) {
liveSessions[projectKey] = liveSessions[projectKey] || [];
liveSessions[projectKey].push(item.handshake.query);
}
}
}
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({"data": liveSessions}));
});
wsRouter.get(`/${process.env.S3_KEY}/sockets-live/:projectKey`, async function (req, res) {
console.log(`[WS]looking for available LIVE sessions for ${req.params.projectKey}`);
let liveSessions = {};
for (let peerId of io.sockets.adapter.rooms.keys()) {
let {projectKey, sessionId} = extractPeerId(peerId);
if (projectKey === req.params.projectKey) {
let connected_sockets = await io.in(peerId).fetchSockets();
for (let item of connected_sockets) {
if (item.handshake.query.identity === IDENTITIES.session) {
liveSessions[projectKey] = liveSessions[projectKey] || [];
liveSessions[projectKey].push(item.handshake.query);
}
}
}
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({"data": liveSessions[req.params.projectKey] || []}));
});
const findSessionSocketId = async (io, peerId) => {
const connected_sockets = await io.in(peerId).fetchSockets();
for (let item of connected_sockets) {
if (item.handshake.query.identity === IDENTITIES.session) {
return item.id;
}
}
return null;
};
async function sessions_agents_count(io, socket) {
let c_sessions = 0, c_agents = 0;
if (io.sockets.adapter.rooms.get(socket.peerId)) {
const connected_sockets = await io.in(socket.peerId).fetchSockets();
for (let item of connected_sockets) {
if (item.handshake.query.identity === IDENTITIES.session) {
c_sessions++;
} else {
c_agents++;
}
}
} else {
c_agents = -1;
c_sessions = -1;
}
return {c_sessions, c_agents};
}
async function extract_live(io, socket) {
if (io.sockets.adapter.rooms.get(socket.peerId)) {
const connected_sockets = await io.in(socket.peerId).fetchSockets();
for (let item of connected_sockets) {
if (item.handshake.query.identity === IDENTITIES.session) {
c_sessions++;
} else {
c_agents++;
}
}
} else {
c_agents = -1;
c_sessions = -1;
}
return {c_sessions, c_agents};
}
module.exports = {
wsRouter,
start: (server) => {
io = _io(server, {
maxHttpBufferSize: 7e6,
cors: {
origin: "*",
methods: ["GET", "POST", "PUT"]
},
path: '/socket'
});
io.on('connection', async (socket) => {
console.log(`WS started:${socket.id}, Query:${JSON.stringify(socket.handshake.query)}`);
socket.peerId = socket.handshake.query.peerId;
socket.identity = socket.handshake.query.identity;
const {projectKey, sessionId} = extractPeerId(socket.peerId);
socket.sessionId = sessionId;
socket.projectKey = projectKey;
socket.lastMessageReceivedAt = Date.now();
let {c_sessions, c_agents} = await sessions_agents_count(io, socket);
if (socket.identity === IDENTITIES.session) {
if (c_sessions > 0) {
console.log(`session already connected, refusing new connexion`);
io.to(socket.id).emit(SESSION_ALREADY_CONNECTED);
return socket.disconnect();
}
if (c_agents > 0) {
console.log(`notifying new session about agent-existance`);
io.to(socket.id).emit(NEW_AGENT_MESSAGE);
}
} else if (c_sessions <= 0) {
console.log(`notifying new agent about no SESSIONS`);
io.to(socket.id).emit(NO_SESSIONS);
}
socket.join(socket.peerId);
if (io.sockets.adapter.rooms.get(socket.peerId)) {
console.log(`${socket.id} joined room:${socket.peerId}, as:${socket.identity}, size:${io.sockets.adapter.rooms.get(socket.peerId).size}`);
}
socket.on('disconnect', async () => {
// console.log(`${socket.id} disconnected from ${socket.peerId}, waiting ${wsReconnectionTimeout / 1000}s before checking remaining`);
console.log(`${socket.id} disconnected from ${socket.peerId}`);
// wait a little bit before notifying everyone
// setTimeout(async () => {
console.log("checking for number of connected agents and sessions");
let {c_sessions, c_agents} = await sessions_agents_count(io, socket);
if (c_sessions === -1 && c_agents === -1) {
console.log(`room not found: ${socket.peerId}`);
return removeSession(socket.projectKey, socket.sessionId);
}
if (c_sessions === 0) {
console.log(`notifying everyone in ${socket.peerId} about no SESSIONS`);
socket.to(socket.peerId).emit(NO_SESSIONS);
removeSession(socket.projectKey, socket.sessionId);
}
if (c_agents === 0) {
console.log(`notifying everyone in ${socket.peerId} about no AGENTS`);
socket.to(socket.peerId).emit(NO_AGENTS);
}
// }, wsReconnectionTimeout);
});
socket.onAny(async (eventName, ...args) => {
socket.lastMessageReceivedAt = Date.now();
if (socket.identity === IDENTITIES.session) {
console.log(`received event:${eventName}, from:${socket.identity}, sending message to room:${socket.peerId}, size: ${io.sockets.adapter.rooms.get(socket.peerId).size}`);
socket.to(socket.peerId).emit(eventName, args[0]);
} else {
console.log(`received event:${eventName}, from:${socket.identity}, sending message to session of room:${socket.peerId}, size:${io.sockets.adapter.rooms.get(socket.peerId).size}`);
let socketId = await findSessionSocketId(io, socket.peerId);
if (socketId === null) {
console.log(`session not found for:${socket.peerId}`);
io.to(socket.id).emit(NO_SESSIONS);
} else {
console.log("message sent");
io.to(socketId).emit(eventName, args[0]);
}
}
});
if (socket.identity === IDENTITIES.agent) {
socket.to(socket.peerId).emit(NEW_AGENT_MESSAGE);
}
});
}
};