fix: queue issue

This commit is contained in:
2026-07-31 07:33:12 +02:00
parent e7628ac44c
commit 10ef590242
10 changed files with 283 additions and 352 deletions

View File

@@ -99,6 +99,27 @@ MockWebSocket.CLOSED = 3;
// For testing, we'll load the actual file
let WebSocketClient;
// Load the WebSocket client source (used by multiple describe blocks)
function loadWebSocketClientSource() {
const fs = require('node:fs');
const path = require('node:path');
const src = fs.readFileSync(
path.resolve(__dirname, '../../../src/server/web/static/js/shared/websocket-client.js'),
'utf8'
);
// eslint-disable-next-line no-eval
(0, eval)(src);
// Provide a Socket.IO-like io() factory for tests that use it
if (typeof globalThis.io === 'undefined') {
globalThis.io = function (url) {
const client = new globalThis.WebSocketClient(url);
client.connect();
return client;
};
}
return globalThis.WebSocketClient;
}
describe('WebSocket Client - Initialization', () => {
beforeEach(() => {
// Mock global WebSocket
@@ -106,174 +127,9 @@ describe('WebSocket Client - Initialization', () => {
// Clear any timers
vi.useFakeTimers();
// Load WebSocketClient class by evaluating the source
// In a real setup, this would be imported
const sourceCode = `
class WebSocketClient {
constructor(url, options = {}) {
this.url = url;
this.ws = null;
this.isConnected = false;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = options.maxReconnectAttempts || 5;
this.reconnectDelay = options.reconnectDelay || 1000;
this.autoReconnect = options.autoReconnect !== false;
this.eventHandlers = new Map();
this.messageQueue = [];
this.rooms = new Set();
}
getWebSocketUrl() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
return \`\${protocol}//\${host}\${this.url}\`;
}
connect() {
try {
const wsUrl = this.getWebSocketUrl();
this.ws = new WebSocket(wsUrl);
this.ws.onopen = (event) => {
this.isConnected = true;
this.reconnectAttempts = 0;
this.emit('connect');
this.rejoinRooms();
this.processMessageQueue();
};
this.ws.onmessage = (event) => {
this.handleMessage(event);
};
this.ws.onerror = (event) => {
console.error('WebSocket error:', event);
this.emit('error', event.error || new Error('WebSocket error'));
};
this.ws.onclose = (event) => {
this.isConnected = false;
this.emit('disconnect', event.reason);
if (this.autoReconnect && !event.wasClean &&
this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = this.reconnectDelay * this.reconnectAttempts;
console.log(\`Reconnecting in \${delay}ms (attempt \${this.reconnectAttempts}/\${this.maxReconnectAttempts})...\`);
setTimeout(() => this.connect(), delay);
} else if (this.reconnectAttempts >= this.maxReconnectAttempts) {
this.emit('reconnect_failed');
}
};
} catch (error) {
console.error('Failed to create WebSocket:', error);
this.emit('error', error);
}
}
disconnect() {
if (this.ws) {
this.autoReconnect = false;
this.ws.close(1000, 'Client disconnect');
}
}
handleMessage(event) {
try {
const message = JSON.parse(event.data);
const { type, ...data } = message;
if (type) {
this.emit(type, data);
}
} catch (error) {
console.error('Failed to parse message:', error);
this.emit('error', error);
}
}
on(event, handler) {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, []);
}
this.eventHandlers.get(event).push(handler);
}
off(event, handler) {
if (this.eventHandlers.has(event)) {
const handlers = this.eventHandlers.get(event);
const index = handlers.indexOf(handler);
if (index !== -1) {
handlers.splice(index, 1);
}
}
}
emit(event, data) {
if (this.eventHandlers.has(event)) {
this.eventHandlers.get(event).forEach(handler => {
try {
handler(data);
} catch (error) {
console.error(\`Error in event handler for '\${event}':\`, error);
}
});
}
}
send(action, data) {
const message = JSON.stringify({ action, ...data });
if (this.connected()) {
this.ws.send(message);
} else {
this.messageQueue.push(message);
}
}
join(room) {
this.rooms.add(room);
if (this.connected()) {
this.send('join', { room });
}
}
leave(room) {
this.rooms.delete(room);
if (this.connected()) {
this.send('leave', { room });
}
}
rejoinRooms() {
this.rooms.forEach(room => {
this.send('join', { room });
});
}
processMessageQueue() {
while (this.messageQueue.length > 0 && this.connected()) {
const message = this.messageQueue.shift();
this.ws.send(message);
}
}
connected() {
return this.isConnected && this.ws && this.ws.readyState === WebSocket.OPEN;
}
}
function io(url) {
const client = new WebSocketClient(url);
client.connect();
return client;
}
globalThis.WebSocketClient = WebSocketClient;
globalThis.io = io;
`;
eval(sourceCode);
WebSocketClient = globalThis.WebSocketClient;
// Load WebSocketClient class from the real source
WebSocketClient = loadWebSocketClientSource();
});
afterEach(() => {
@@ -340,9 +196,8 @@ describe('WebSocket Client - Connection', () => {
}
};
const sourceCode = `${/* Same source as above */}`;
eval(sourceCode);
WebSocketClient = globalThis.WebSocketClient;
// Load WebSocketClient class from the real source
WebSocketClient = loadWebSocketClientSource();
});
afterEach(() => {