2
0

socket.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // socket.ts
  2. import { Server, Socket } from 'socket.io';
  3. import * as http from 'http';
  4. import chalk from 'chalk';
  5. import { isElectron } from './utils';
  6. export let io: Server;
  7. export let clients = new Map<string, Socket>();
  8. export const logWebSocketRequest = (
  9. socket: Socket,
  10. event: string,
  11. message?: any,
  12. direction: 'in' | 'out' = 'in'
  13. ) => {
  14. if (isElectron()) {
  15. return;
  16. }
  17. const clientId = socket.handshake.query['milvus-client-id'] as string;
  18. const remoteAddress =
  19. socket.handshake.address === '::1' ? '127.0.0.1' : socket.handshake.address;
  20. const timestamp = new Date().toLocaleTimeString();
  21. const directionLabel = direction === 'in' ? '←' : '→';
  22. const mes =
  23. process.env.ATTU_LOG_LEVEL === 'debug'
  24. ? JSON.stringify(message)
  25. : message
  26. ? JSON.stringify(message).length
  27. : '';
  28. const logMessage = [
  29. chalk.blue.bold('WS'),
  30. chalk.magenta.bold(event),
  31. chalk.green.bold(`Client: ${clientId}`),
  32. chalk.yellow(remoteAddress),
  33. chalk.gray(`@ ${timestamp}`),
  34. direction === 'in'
  35. ? chalk.cyan(directionLabel)
  36. : chalk.magenta(directionLabel),
  37. message ? chalk.white(mes) : '',
  38. ]
  39. .filter(Boolean)
  40. .join(' ');
  41. console.log(logMessage);
  42. };
  43. export const initWebSocket = (server: http.Server) => {
  44. io = new Server(server, {
  45. cors: {
  46. origin: '*',
  47. methods: ['GET', 'POST'],
  48. },
  49. });
  50. io.on('connection', (socket: Socket) => {
  51. const clientId = socket.handshake.query['milvus-client-id'] as string;
  52. if (clientId) {
  53. clients.set(clientId, socket);
  54. // Log connection event
  55. logWebSocketRequest(socket, 'CONNECT');
  56. socket.on('disconnect', () => {
  57. // Log disconnect event
  58. logWebSocketRequest(socket, 'DISCONNECT');
  59. clients.delete(clientId);
  60. });
  61. socket.on('error', (error: Error) => {
  62. // Log error event
  63. logWebSocketRequest(socket, 'error', error.message);
  64. });
  65. // Log custom events
  66. socket.onAny((event, ...args) => {
  67. logWebSocketRequest(socket, event, args);
  68. });
  69. }
  70. });
  71. io.use((socket, next) => {
  72. const originalEmit = socket.emit;
  73. // Convert the assigned function to an arrow function
  74. socket.emit = (event: string, ...args: any[]) => {
  75. logWebSocketRequest(socket, event, args, 'out');
  76. // Use .apply() with the correct context (socket)
  77. return originalEmit.apply(socket, [event, ...args]);
  78. };
  79. next();
  80. });
  81. // Handle server-level errors
  82. io.on('error', (error: Error) => {
  83. if (!isElectron()) {
  84. console.error(chalk.red(`ws server error: ${error.message}`));
  85. }
  86. });
  87. };