fosrl.pangolin/server/routers/ws.ts

426 lines
14 KiB
TypeScript
Raw Permalink Normal View History

2024-11-10 17:34:07 -05:00
import { Router, Request, Response } from "express";
import { Server as HttpServer } from "http";
import { WebSocket, WebSocketServer } from "ws";
import { IncomingMessage } from "http";
import { Socket } from "net";
2025-06-04 12:02:07 -04:00
import { Newt, newts, NewtSession } from "@server/db";
2024-11-10 17:34:07 -05:00
import { eq } from "drizzle-orm";
2025-06-04 12:02:07 -04:00
import { db } from "@server/db";
2025-01-01 21:41:31 -05:00
import { validateNewtSessionToken } from "@server/auth/sessions/newt";
2024-11-10 21:06:36 -05:00
import { messageHandlers } from "./messageHandlers";
2024-11-15 21:53:58 -05:00
import logger from "@server/logger";
2025-05-28 20:59:06 -04:00
import redisManager from "@server/db/redis";
import { v4 as uuidv4 } from "uuid";
2024-11-04 00:29:25 -05:00
// Custom interfaces
interface WebSocketRequest extends IncomingMessage {
2024-11-10 17:08:11 -05:00
token?: string;
2024-11-04 00:29:25 -05:00
}
interface AuthenticatedWebSocket extends WebSocket {
2024-11-10 17:08:11 -05:00
newt?: Newt;
2025-05-28 20:59:06 -04:00
connectionId?: string;
2024-11-04 00:29:25 -05:00
}
interface TokenPayload {
2024-11-10 17:08:11 -05:00
newt: Newt;
session: NewtSession;
2024-11-04 00:29:25 -05:00
}
2024-11-10 17:34:07 -05:00
interface WSMessage {
type: string;
data: any;
}
interface HandlerResponse {
message: WSMessage;
broadcast?: boolean;
excludeSender?: boolean;
targetNewtId?: string;
}
interface HandlerContext {
message: WSMessage;
senderWs: WebSocket;
2024-11-15 21:53:58 -05:00
newt: Newt | undefined;
2025-05-28 20:59:06 -04:00
sendToClient: (newtId: string, message: WSMessage) => Promise<boolean>;
broadcastToAllExcept: (message: WSMessage, excludeNewtId?: string) => Promise<void>;
2024-11-10 17:34:07 -05:00
connectedClients: Map<string, WebSocket[]>;
}
2025-05-28 20:59:06 -04:00
interface RedisMessage {
type: 'direct' | 'broadcast';
targetNewtId?: string;
excludeNewtId?: string;
message: WSMessage;
fromNodeId: string;
}
2024-11-10 17:34:07 -05:00
export type MessageHandler = (context: HandlerContext) => Promise<HandlerResponse | void>;
2024-11-04 00:29:25 -05:00
const router: Router = Router();
const wss: WebSocketServer = new WebSocketServer({ noServer: true });
2025-05-28 20:59:06 -04:00
// Generate unique node ID for this instance
const NODE_ID = uuidv4();
const REDIS_CHANNEL = 'websocket_messages';
// Client tracking map (local to this node)
2024-11-10 17:34:07 -05:00
let connectedClients: Map<string, AuthenticatedWebSocket[]> = new Map();
2025-05-28 20:59:06 -04:00
// Redis keys
const getConnectionsKey = (newtId: string) => `ws:connections:${newtId}`;
const getNodeConnectionsKey = (nodeId: string, newtId: string) => `ws:node:${nodeId}:${newtId}`;
// Initialize Redis subscription for cross-node messaging
const initializeRedisSubscription = async (): Promise<void> => {
if (!redisManager.isRedisEnabled()) return;
await redisManager.subscribe(REDIS_CHANNEL, async (channel: string, message: string) => {
try {
const redisMessage: RedisMessage = JSON.parse(message);
// Ignore messages from this node
if (redisMessage.fromNodeId === NODE_ID) return;
if (redisMessage.type === 'direct' && redisMessage.targetNewtId) {
// Send to specific client on this node
await sendToClientLocal(redisMessage.targetNewtId, redisMessage.message);
} else if (redisMessage.type === 'broadcast') {
// Broadcast to all clients on this node except excluded
await broadcastToAllExceptLocal(redisMessage.message, redisMessage.excludeNewtId);
}
} catch (error) {
logger.error('Error processing Redis message:', error);
}
});
};
2024-11-10 17:34:07 -05:00
// Helper functions for client management
2025-05-28 20:59:06 -04:00
const addClient = async (newtId: string, ws: AuthenticatedWebSocket): Promise<void> => {
// Generate unique connection ID
const connectionId = uuidv4();
ws.connectionId = connectionId;
// Add to local tracking
2024-11-10 17:34:07 -05:00
const existingClients = connectedClients.get(newtId) || [];
existingClients.push(ws);
connectedClients.set(newtId, existingClients);
2025-05-28 20:59:06 -04:00
// Add to Redis tracking if enabled
if (redisManager.isRedisEnabled()) {
// Add this node to the set of nodes handling this newt
await redisManager.sadd(getConnectionsKey(newtId), NODE_ID);
// Track specific connection on this node
await redisManager.hset(getNodeConnectionsKey(NODE_ID, newtId), connectionId, Date.now().toString());
}
logger.info(`Client added to tracking - Newt ID: ${newtId}, Connection ID: ${connectionId}, Total connections: ${existingClients.length}`);
2024-11-10 17:34:07 -05:00
};
2025-05-28 20:59:06 -04:00
const removeClient = async (newtId: string, ws: AuthenticatedWebSocket): Promise<void> => {
// Remove from local tracking
2024-11-10 17:34:07 -05:00
const existingClients = connectedClients.get(newtId) || [];
const updatedClients = existingClients.filter(client => client !== ws);
2025-01-01 21:41:31 -05:00
2024-11-10 17:34:07 -05:00
if (updatedClients.length === 0) {
connectedClients.delete(newtId);
2025-05-28 20:59:06 -04:00
// Remove from Redis tracking if enabled
if (redisManager.isRedisEnabled()) {
await redisManager.srem(getConnectionsKey(newtId), NODE_ID);
await redisManager.del(getNodeConnectionsKey(NODE_ID, newtId));
}
2024-11-15 21:53:58 -05:00
logger.info(`All connections removed for Newt ID: ${newtId}`);
2024-11-10 17:34:07 -05:00
} else {
connectedClients.set(newtId, updatedClients);
2025-05-28 20:59:06 -04:00
// Update Redis tracking if enabled
if (redisManager.isRedisEnabled() && ws.connectionId) {
await redisManager.hdel(getNodeConnectionsKey(NODE_ID, newtId), ws.connectionId);
}
2024-11-15 21:53:58 -05:00
logger.info(`Connection removed - Newt ID: ${newtId}, Remaining connections: ${updatedClients.length}`);
2024-11-10 17:34:07 -05:00
}
};
2025-05-28 20:59:06 -04:00
// Local message sending (within this node)
const sendToClientLocal = async (newtId: string, message: WSMessage): Promise<boolean> => {
2024-11-10 17:34:07 -05:00
const clients = connectedClients.get(newtId);
if (!clients || clients.length === 0) {
return false;
}
const messageString = JSON.stringify(message);
clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(messageString);
}
});
return true;
};
2025-05-28 20:59:06 -04:00
const broadcastToAllExceptLocal = async (message: WSMessage, excludeNewtId?: string): Promise<void> => {
2024-11-10 17:34:07 -05:00
connectedClients.forEach((clients, newtId) => {
if (newtId !== excludeNewtId) {
clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
}
});
};
2025-05-28 20:59:06 -04:00
// Cross-node message sending (via Redis)
const sendToClient = async (newtId: string, message: WSMessage): Promise<boolean> => {
// Try to send locally first
const localSent = await sendToClientLocal(newtId, message);
// If Redis is enabled, also send via Redis pub/sub to other nodes
if (redisManager.isRedisEnabled()) {
const redisMessage: RedisMessage = {
type: 'direct',
targetNewtId: newtId,
message,
fromNodeId: NODE_ID
};
await redisManager.publish(REDIS_CHANNEL, JSON.stringify(redisMessage));
}
return localSent;
};
const broadcastToAllExcept = async (message: WSMessage, excludeNewtId?: string): Promise<void> => {
// Broadcast locally
await broadcastToAllExceptLocal(message, excludeNewtId);
// If Redis is enabled, also broadcast via Redis pub/sub to other nodes
if (redisManager.isRedisEnabled()) {
const redisMessage: RedisMessage = {
type: 'broadcast',
excludeNewtId,
message,
fromNodeId: NODE_ID
};
await redisManager.publish(REDIS_CHANNEL, JSON.stringify(redisMessage));
}
};
// Check if a newt has active connections across all nodes
const hasActiveConnections = async (newtId: string): Promise<boolean> => {
if (!redisManager.isRedisEnabled()) {
// Fallback to local check
const clients = connectedClients.get(newtId);
return !!(clients && clients.length > 0);
}
const activeNodes = await redisManager.smembers(getConnectionsKey(newtId));
return activeNodes.length > 0;
};
// Get all active nodes for a newt
const getActiveNodes = async (newtId: string): Promise<string[]> => {
if (!redisManager.isRedisEnabled()) {
const clients = connectedClients.get(newtId);
return (clients && clients.length > 0) ? [NODE_ID] : [];
}
return await redisManager.smembers(getConnectionsKey(newtId));
};
2024-11-10 17:34:07 -05:00
// Token verification middleware (unchanged)
2024-11-04 00:29:25 -05:00
const verifyToken = async (token: string): Promise<TokenPayload | null> => {
2024-11-10 17:08:11 -05:00
try {
2024-11-10 17:34:07 -05:00
const { session, newt } = await validateNewtSessionToken(token);
2024-11-10 17:08:11 -05:00
if (!session || !newt) {
return null;
}
const existingNewt = await db
.select()
.from(newts)
.where(eq(newts.newtId, newt.newtId));
if (!existingNewt || !existingNewt[0]) {
return null;
}
return { newt: existingNewt[0], session };
} catch (error) {
2024-12-07 22:07:13 -05:00
logger.error("Token verification failed:", error);
2024-11-10 17:08:11 -05:00
return null;
}
2024-11-04 00:29:25 -05:00
};
2025-05-28 20:59:06 -04:00
const setupConnection = async (ws: AuthenticatedWebSocket, newt: Newt): Promise<void> => {
2024-12-07 22:07:13 -05:00
logger.info("Establishing websocket connection");
2024-11-04 00:29:25 -05:00
2024-12-07 22:07:13 -05:00
if (!newt) {
logger.error("Connection attempt without newt");
2024-11-10 17:34:07 -05:00
return ws.terminate();
}
2024-12-07 22:07:13 -05:00
ws.newt = newt;
2024-11-10 17:08:11 -05:00
2024-12-07 22:07:13 -05:00
// Add client to tracking
2025-05-28 20:59:06 -04:00
await addClient(newt.newtId, ws);
2024-11-10 17:08:11 -05:00
2024-11-10 17:34:07 -05:00
ws.on("message", async (data) => {
2024-11-10 17:08:11 -05:00
try {
const message: WSMessage = JSON.parse(data.toString());
2025-01-01 21:41:31 -05:00
2024-11-10 17:34:07 -05:00
// Validate message format
if (!message.type || typeof message.type !== "string") {
throw new Error("Invalid message format: missing or invalid type");
}
2025-01-01 21:41:31 -05:00
2024-11-10 17:34:07 -05:00
// Get the appropriate handler for the message type
const handler = messageHandlers[message.type];
if (!handler) {
throw new Error(`Unsupported message type: ${message.type}`);
}
2025-01-01 21:41:31 -05:00
2024-11-10 17:34:07 -05:00
// Process the message and get response
const response = await handler({
message,
senderWs: ws,
2024-11-15 21:53:58 -05:00
newt: ws.newt,
2024-11-10 17:34:07 -05:00
sendToClient,
broadcastToAllExcept,
connectedClients
});
2025-01-01 21:41:31 -05:00
2024-11-10 17:34:07 -05:00
// Send response if one was returned
if (response) {
if (response.broadcast) {
// Broadcast to all clients except sender if specified
2025-05-28 20:59:06 -04:00
await broadcastToAllExcept(response.message, response.excludeSender ? newt.newtId : undefined);
2024-11-10 17:34:07 -05:00
} else if (response.targetNewtId) {
// Send to specific client if targetNewtId is provided
2025-05-28 20:59:06 -04:00
await sendToClient(response.targetNewtId, response.message);
2024-11-10 17:34:07 -05:00
} else {
// Send back to sender
ws.send(JSON.stringify(response.message));
}
}
2024-12-07 22:07:13 -05:00
2024-11-10 17:08:11 -05:00
} catch (error) {
2024-12-07 22:07:13 -05:00
logger.error("Message handling error:", error);
2024-11-10 17:08:11 -05:00
ws.send(JSON.stringify({
2024-11-10 17:34:07 -05:00
type: "error",
data: {
message: error instanceof Error ? error.message : "Unknown error occurred",
originalMessage: data.toString()
}
2024-11-10 17:08:11 -05:00
}));
}
2025-01-01 21:41:31 -05:00
});
2025-05-28 20:59:06 -04:00
ws.on("close", async () => {
await removeClient(newt.newtId, ws);
2024-12-07 22:07:13 -05:00
logger.info(`Client disconnected - Newt ID: ${newt.newtId}`);
2024-11-10 17:08:11 -05:00
});
2025-01-01 21:41:31 -05:00
2024-11-10 17:34:07 -05:00
ws.on("error", (error: Error) => {
2024-12-07 22:07:13 -05:00
logger.error(`WebSocket error for Newt ID ${newt.newtId}:`, error);
2024-11-10 17:08:11 -05:00
});
2024-12-07 22:07:13 -05:00
2025-05-28 20:59:06 -04:00
logger.info(`WebSocket connection established - Newt ID: ${newt.newtId}, Node ID: ${NODE_ID}`);
2024-12-07 22:07:13 -05:00
};
// Router endpoint (unchanged)
router.get("/ws", (req: Request, res: Response) => {
res.status(200).send("WebSocket endpoint");
2024-11-04 00:29:25 -05:00
});
2024-12-07 22:07:13 -05:00
// WebSocket upgrade handler
const handleWSUpgrade = (server: HttpServer): void => {
server.on("upgrade", async (request: WebSocketRequest, socket: Socket, head: Buffer) => {
try {
const token = request.url?.includes("?")
? new URLSearchParams(request.url.split("?")[1]).get("token") || ""
: request.headers["sec-websocket-protocol"];
if (!token) {
logger.warn("Unauthorized connection attempt: no token...");
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
const tokenPayload = await verifyToken(token);
if (!tokenPayload) {
logger.warn("Unauthorized connection attempt: invalid token...");
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
2025-05-28 20:59:06 -04:00
wss.handleUpgrade(request, socket, head, async (ws: AuthenticatedWebSocket) => {
await setupConnection(ws, tokenPayload.newt);
2024-12-07 22:07:13 -05:00
});
} catch (error) {
logger.error("WebSocket upgrade error:", error);
socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n");
socket.destroy();
}
});
};
2025-05-28 20:59:06 -04:00
// Initialize Redis subscription when the module is loaded
if (redisManager.isRedisEnabled()) {
initializeRedisSubscription().catch(error => {
logger.error('Failed to initialize Redis subscription:', error);
});
logger.info(`WebSocket handler initialized with Redis support - Node ID: ${NODE_ID}`);
} else {
logger.info('WebSocket handler initialized in local mode (Redis disabled)');
}
// Cleanup function for graceful shutdown
const cleanup = async (): Promise<void> => {
try {
// Close all WebSocket connections
connectedClients.forEach((clients) => {
clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.terminate();
}
});
});
// Clean up Redis tracking for this node
if (redisManager.isRedisEnabled()) {
const keys = await redisManager.getClient()?.keys(`ws:node:${NODE_ID}:*`) || [];
if (keys.length > 0) {
await Promise.all(keys.map(key => redisManager.del(key)));
}
}
logger.info('WebSocket cleanup completed');
} catch (error) {
logger.error('Error during WebSocket cleanup:', error);
}
};
// Handle process termination
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
2024-11-04 00:29:25 -05:00
export {
2024-11-10 17:08:11 -05:00
router,
2024-11-10 17:34:07 -05:00
handleWSUpgrade,
sendToClient,
broadcastToAllExcept,
2025-05-28 20:59:06 -04:00
connectedClients,
hasActiveConnections,
getActiveNodes,
NODE_ID,
cleanup
};