Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 26x 26x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 34x 34x 34x 2x 36x 2x 2x 2x 3x 3x 3x 13x 2x 2x 2x 3x 13x 13x 13x 1x 1x 1x 12x 12x 12x 12x 11x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 2x 2x 2x 2x 11x 11x 11x 11x 11x 2x 13x 13x 13x 12x 1x 1x 2x 2x 1x 2x 2x 2x 11x 11x 9x 11x 11x 11x 11x 11x 8x 8x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 19x 19x 10x 10x 2x 2x 2x 2x 2x 12x 12x 8x 8x 4x 4x 5x 5x 5x 4x 5x 5x 5x 2x 3x 3x 3x 5x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 3x 3x 2x 2x 10x 4x 2x 2x 4x 2x 2x 2x 2x 2x 4x 3x 2x 2x 4x 4x 2x 2x 4x 2x 2x 2x 2x 2x 26x | // src/services/websocketService.server.ts
/**
* WebSocket service for real-time notifications
* Manages WebSocket connections and broadcasts messages to connected clients
*/
import { WebSocketServer, WebSocket } from 'ws';
import type { Server as HTTPServer } from 'http';
import jwt from 'jsonwebtoken';
import type { Logger } from 'pino';
import { logger as globalLogger } from './logger.server';
import {
createWebSocketMessage,
type WebSocketMessage,
type DealNotificationData,
type SystemMessageData,
} from '../types/websocket';
import type { IncomingMessage } from 'http';
const JWT_SECRET = process.env.JWT_SECRET || 'test-secret';
Iif (!process.env.JWT_SECRET) {
console.warn('[WebSocket] JWT_SECRET not set in environment, using fallback');
}
/**
* Extended WebSocket with user context
*/
interface AuthenticatedWebSocket extends WebSocket {
userId?: string;
isAlive?: boolean;
}
/**
* JWT payload structure
*/
interface JWTPayload {
user_id: string;
email: string;
role: string;
}
export class WebSocketService {
private wss: WebSocketServer | null = null;
private clients: Map<string, Set<AuthenticatedWebSocket>> = new Map();
private pingInterval: NodeJS.Timeout | null = null;
constructor(private logger: Logger) {}
/**
* Initialize the WebSocket server and attach it to an HTTP server
*/
initialize(server: HTTPServer): void {
this.wss = new WebSocketServer({
server,
path: '/ws',
});
this.logger.info('WebSocket server initialized on path /ws');
this.wss.on('connection', (ws: AuthenticatedWebSocket, request: IncomingMessage) => {
this.handleConnection(ws, request);
});
// Start heartbeat ping/pong to detect dead connections
this.startHeartbeat();
}
/**
* Handle new WebSocket connection
*/
private handleConnection(ws: AuthenticatedWebSocket, request: IncomingMessage): void {
const connectionLogger = this.logger.child({ context: 'ws-connection' });
// Extract JWT token from query string or cookie
const token = this.extractToken(request);
if (!token) {
connectionLogger.warn('WebSocket connection rejected: No token provided');
ws.close(1008, 'Authentication required');
return;
}
// Verify JWT token
let payload: JWTPayload;
try {
const verified = jwt.verify(token, JWT_SECRET);
connectionLogger.debug({ verified, type: typeof verified }, 'JWT verification result');
Iif (!verified || typeof verified === 'string') {
connectionLogger.warn(
'WebSocket connection rejected: JWT verification returned invalid payload',
);
ws.close(1008, 'Invalid token');
return;
}
payload = verified as JWTPayload;
} catch (error) {
connectionLogger.warn({ error }, 'WebSocket connection rejected: Invalid token');
ws.close(1008, 'Invalid token');
return;
}
// Attach user ID to the WebSocket connection
ws.userId = payload.user_id;
ws.isAlive = true;
// Register the client
this.registerClient(ws);
connectionLogger.info(
{ userId: ws.userId },
`WebSocket client connected for user ${ws.userId}`,
);
// Send connection confirmation
const confirmationMessage = createWebSocketMessage.connectionEstablished({
user_id: ws.userId,
message: 'Connected to real-time notification service',
});
this.sendToClient(ws, confirmationMessage);
// Handle incoming messages
ws.on('message', (data: Buffer) => {
this.handleMessage(ws, data);
});
// Handle pong responses (heartbeat)
ws.on('pong', () => {
ws.isAlive = true;
});
// Handle disconnection
ws.on('close', () => {
this.unregisterClient(ws);
connectionLogger.info({ userId: ws.userId }, 'WebSocket client disconnected');
});
// Handle errors
ws.on('error', (error: Error) => {
connectionLogger.error({ error, userId: ws.userId }, 'WebSocket error');
});
}
/**
* Extract JWT token from request (query string or cookie)
*/
private extractToken(request: IncomingMessage): string | null {
// Try to extract from query string (?token=xxx)
const url = new URL(request.url || '', `http://${request.headers.host}`);
const tokenFromQuery = url.searchParams.get('token');
if (tokenFromQuery) {
return tokenFromQuery;
}
// Try to extract from cookie
const cookieHeader = request.headers.cookie;
Iif (cookieHeader) {
const cookies = cookieHeader.split(';').reduce(
(acc, cookie) => {
const [key, value] = cookie.trim().split('=');
acc[key] = value;
return acc;
},
{} as Record<string, string>,
);
return cookies['accessToken'] || null;
}
return null;
}
/**
* Register a WebSocket client
*/
private registerClient(ws: AuthenticatedWebSocket): void {
Iif (!ws.userId) return;
if (!this.clients.has(ws.userId)) {
this.clients.set(ws.userId, new Set());
}
this.clients.get(ws.userId)!.add(ws);
this.logger.info(
{ userId: ws.userId, totalConnections: this.clients.get(ws.userId)!.size },
'Client registered',
);
}
/**
* Unregister a WebSocket client
*/
private unregisterClient(ws: AuthenticatedWebSocket): void {
Iif (!ws.userId) return;
const userClients = this.clients.get(ws.userId);
if (userClients) {
userClients.delete(ws);
if (userClients.size === 0) {
this.clients.delete(ws.userId);
}
}
}
/**
* Handle incoming messages from clients
*/
private handleMessage(ws: AuthenticatedWebSocket, data: Buffer): void {
try {
const message = JSON.parse(data.toString()) as WebSocketMessage;
// Handle ping messages
if (message.type === 'ping') {
const pongMessage = createWebSocketMessage.pong();
this.sendToClient(ws, pongMessage);
}
// Log other message types for debugging
this.logger.debug(
{ userId: ws.userId, messageType: message.type },
'Received WebSocket message',
);
} catch (error) {
this.logger.error({ error }, 'Failed to parse WebSocket message');
}
}
/**
* Send a message to a specific WebSocket client
*/
private sendToClient(ws: AuthenticatedWebSocket, message: WebSocketMessage): void {
Eif (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message));
}
}
/**
* Broadcast a deal notification to a specific user
*/
broadcastDealNotification(userId: string, data: DealNotificationData): void {
const message = createWebSocketMessage.dealNotification(data);
this.broadcastToUser(userId, message);
}
/**
* Broadcast a system message to a specific user
*/
broadcastSystemMessage(userId: string, data: SystemMessageData): void {
const message = createWebSocketMessage.systemMessage(data);
this.broadcastToUser(userId, message);
}
/**
* Broadcast a message to all connections of a specific user
*/
private broadcastToUser(userId: string, message: WebSocketMessage): void {
const userClients = this.clients.get(userId);
if (!userClients || userClients.size === 0) {
this.logger.debug({ userId }, 'No active WebSocket connections for user');
return;
}
let sentCount = 0;
userClients.forEach((client) => {
Eif (client.readyState === WebSocket.OPEN) {
this.sendToClient(client, message);
sentCount++;
}
});
this.logger.info(
{ userId, messageType: message.type, sentCount, totalConnections: userClients.size },
'Broadcast message to user',
);
}
/**
* Broadcast a system message to all connected clients
*/
broadcastToAll(data: SystemMessageData): void {
const message = createWebSocketMessage.systemMessage(data);
let sentCount = 0;
this.clients.forEach((userClients) => {
userClients.forEach((client) => {
Eif (client.readyState === WebSocket.OPEN) {
this.sendToClient(client, message);
sentCount++;
}
});
});
this.logger.info(
{ messageType: message.type, sentCount, totalUsers: this.clients.size },
'Broadcast message to all users',
);
}
/**
* Start heartbeat ping/pong to detect dead connections
*/
private startHeartbeat(): void {
this.pingInterval = setInterval(() => {
if (!this.wss) return;
this.wss.clients.forEach((ws) => {
const authWs = ws as AuthenticatedWebSocket;
if (authWs.isAlive === false) {
this.logger.debug({ userId: authWs.userId }, 'Terminating dead connection');
return authWs.terminate();
}
authWs.isAlive = false;
authWs.ping();
});
}, 30000); // Ping every 30 seconds
this.logger.info('WebSocket heartbeat started (30s interval)');
}
/**
* Get count of active connections
*/
getConnectionStats(): { totalUsers: number; totalConnections: number } {
let totalConnections = 0;
this.clients.forEach((userClients) => {
totalConnections += userClients.size;
});
return {
totalUsers: this.clients.size,
totalConnections,
};
}
/**
* Shutdown the WebSocket server gracefully
*/
shutdown(): void {
if (this.pingInterval) {
clearInterval(this.pingInterval);
this.pingInterval = null;
}
if (this.wss) {
this.logger.info('Shutting down WebSocket server');
// Notify all clients about shutdown
this.broadcastToAll({
message: 'Server is shutting down. Please reconnect.',
severity: 'warning',
});
// Close all connections
this.wss.clients.forEach((client) => {
client.close(1001, 'Server shutting down');
});
this.wss.close(() => {
this.logger.info('WebSocket server closed');
});
this.clients.clear();
}
}
}
// Singleton instance
export const websocketService = new WebSocketService(globalLogger);
|