SignerX-inference-webui / static /js /websocket-manager.js
FangSen9000
Add current contents
d6bdfb4
Raw History Blame Contribute Delete
13.2 kB
/**
* WebSocket 管理器 - 为 ControlWave 提供可靠的 WebSocket 连接
*
* 特性:
* - 自动重连
* - 连接状态管理
* - 消息队列(离线时缓存消息)
* - 事件系统
* - 错误处理
*/
class ControlWaveWebSocketManager {
constructor(options = {}) {
// 配置选项
this.options = {
url: options.url || `ws://localhost:8080/ws`,
reconnectInterval: options.reconnectInterval || 1000, // 初始重连间隔
maxReconnectInterval: options.maxReconnectInterval || 30000, // 最大重连间隔
reconnectDecay: options.reconnectDecay || 1.5, // 重连间隔增长因子
timeoutInterval: options.timeoutInterval || 2000, // 连接超时
maxReconnectAttempts: options.maxReconnectAttempts || null, // null = 无限重试
enableMessageQueue: options.enableMessageQueue !== false, // 启用消息队列
maxQueueSize: options.maxQueueSize || 100, // 最大队列大小
debug: options.debug || false
};
// 状态管理
this.ws = null;
this.forcedClose = false;
this.reconnectAttempts = 0;
this.reconnectTimer = null;
this.messageQueue = [];
// 连接状态
this.readyState = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3,
RECONNECTING: 4
};
this.state = this.readyState.CLOSED;
// 事件监听器
this.eventListeners = {
open: [],
close: [],
error: [],
message: [],
reconnecting: [],
reconnect_failed: []
};
// 自动开始连接
this.connect();
}
// 调试日志
log(...args) {
if (this.options.debug) {
console.log('[WebSocketManager]', ...args);
}
}
// 连接 WebSocket
connect() {
if (this.state === this.readyState.OPEN || this.state === this.readyState.CONNECTING) {
this.log('Already connected or connecting');
return;
}
this.log('Connecting to', this.options.url);
this.state = this.readyState.CONNECTING;
this.forcedClose = false;
try {
this.ws = new WebSocket(this.options.url);
this.setupEventHandlers();
// 连接超时处理
const timeout = setTimeout(() => {
if (this.state === this.readyState.CONNECTING) {
this.log('Connection timeout');
this.ws.close();
}
}, this.options.timeoutInterval);
this.ws.addEventListener('open', () => {
clearTimeout(timeout);
});
} catch (error) {
this.log('Connection error:', error);
this.handleReconnect();
}
}
// 设置事件处理器
setupEventHandlers() {
this.ws.onopen = (event) => {
this.log('Connected');
this.state = this.readyState.OPEN;
this.reconnectAttempts = 0;
// 发送队列中的消息
this.flushMessageQueue();
// 触发事件
this.emit('open', event);
// 触发全局事件供其他组件监听
window.dispatchEvent(new CustomEvent('websocket-connected', {
detail: {
timestamp: new Date().toISOString(),
manager: this
}
}));
};
this.ws.onclose = (event) => {
this.log('Disconnected', event.code, event.reason);
this.state = this.readyState.CLOSED;
this.ws = null;
this.emit('close', event);
if (!this.forcedClose) {
this.handleReconnect();
}
};
this.ws.onerror = (event) => {
this.log('Error:', event);
this.emit('error', event);
};
this.ws.onmessage = (event) => {
this.emit('message', event);
};
}
// 处理重连
handleReconnect() {
if (this.forcedClose) {
return;
}
// 检查最大重连次数
if (this.options.maxReconnectAttempts !== null &&
this.reconnectAttempts >= this.options.maxReconnectAttempts) {
this.log('Max reconnection attempts reached');
this.emit('reconnect_failed', {
attempts: this.reconnectAttempts
});
return;
}
this.state = this.readyState.RECONNECTING;
this.reconnectAttempts++;
// 计算重连延迟(指数退避)
const timeout = Math.min(
this.options.reconnectInterval * Math.pow(this.options.reconnectDecay, this.reconnectAttempts - 1),
this.options.maxReconnectInterval
);
this.log(`Reconnecting in ${timeout}ms (attempt ${this.reconnectAttempts})`);
this.emit('reconnecting', {
attempt: this.reconnectAttempts,
delay: timeout
});
this.reconnectTimer = setTimeout(() => {
this.connect();
}, timeout);
}
// 发送消息
send(data) {
const message = typeof data === 'string' ? data : JSON.stringify(data);
if (this.state === this.readyState.OPEN && this.ws) {
try {
this.ws.send(message);
this.log('Sent:', message);
return true;
} catch (error) {
this.log('Send error:', error);
this.queueMessage(message);
return false;
}
} else {
// 连接未就绪,加入队列
this.queueMessage(message);
return false;
}
}
// 消息入队
queueMessage(message) {
if (!this.options.enableMessageQueue) {
this.log('Message dropped (queue disabled):', message);
return;
}
if (this.messageQueue.length >= this.options.maxQueueSize) {
// 移除最旧的消息
this.messageQueue.shift();
this.log('Message queue full, dropping oldest message');
}
this.messageQueue.push(message);
this.log('Message queued:', message);
}
// 发送队列中的消息
flushMessageQueue() {
if (!this.options.enableMessageQueue || this.messageQueue.length === 0) {
return;
}
this.log(`Flushing ${this.messageQueue.length} queued messages`);
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift();
try {
this.ws.send(message);
} catch (error) {
this.log('Failed to send queued message:', error);
// 将消息放回队列前端
this.messageQueue.unshift(message);
break;
}
}
}
// 关闭连接
close(code = 1000, reason = '') {
this.forcedClose = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
this.ws.close(code, reason);
}
this.state = this.readyState.CLOSED;
this.messageQueue = [];
}
// 事件系统
on(event, callback) {
if (this.eventListeners[event]) {
this.eventListeners[event].push(callback);
}
}
off(event, callback) {
if (this.eventListeners[event]) {
const index = this.eventListeners[event].indexOf(callback);
if (index > -1) {
this.eventListeners[event].splice(index, 1);
}
}
}
emit(event, data) {
if (this.eventListeners[event]) {
this.eventListeners[event].forEach(callback => {
try {
callback(data);
} catch (error) {
console.error('Event listener error:', error);
}
});
}
}
// 获取连接状态
get isConnected() {
return this.state === this.readyState.OPEN;
}
get isReconnecting() {
return this.state === this.readyState.RECONNECTING;
}
// 兼容旧接口
get socket() {
return this.ws;
}
}
// 创建全局实例
if (typeof window !== 'undefined') {
// 创建管理器实例
const wsManager = new ControlWaveWebSocketManager({
debug: true,
enableMessageQueue: true,
maxQueueSize: 50,
reconnectInterval: 1000,
maxReconnectInterval: 10000
});
// 设置消息处理
wsManager.on('message', (event) => {
try {
const data = JSON.parse(event.data);
console.log('📨 收到 WebSocket 消息:', data.type);
// 处理不同类型的消息
switch(data.type) {
case 'viser_status':
console.log('Viser 状态:', data.active ? '活动' : '未活动', '端口:', data.port);
break;
case 'training_visualization_updated':
console.log('训练可视化已更新:', data.status);
break;
case 'plugin_response':
// plugin_response 消息由 sendRequest 的 responseHandler 处理
// 这里只做日志记录
console.log('插件响应:', data.plugin, data.action, data.status);
break;
default:
console.log('未知消息类型:', data.type);
}
} catch (error) {
console.error('处理 WebSocket 消息时出错:', error);
}
});
// 暴露到全局作用域,兼容旧代码
window.controlWaveWebSocket = {
send: (message) => wsManager.send(message),
get socket() { return wsManager.socket; },
get isConnected() { return wsManager.isConnected; },
// 新增:直接访问管理器
manager: wsManager,
// 新增:sendRequest方法
sendRequest: (pluginId, data) => {
const REQUEST_TIMEOUT_MS = 180000; // 3 minutes to accommodate long-running generations
return new Promise((resolve, reject) => {
const requestId = `${pluginId}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
// 准备消息
const message = {
type: 'plugin_message',
plugin: pluginId,
requestId: requestId,
...data
};
// 设置响应监听器
const responseHandler = (event) => {
try {
const response = JSON.parse(event.data);
// 调试日志
if (response.type === 'plugin_response') {
console.log(`🔍 收到插件响应 [${response.plugin}]:`, {
requestId: response.requestId,
expectedId: requestId,
match: response.requestId === requestId,
status: response.status
});
}
if (response.type === 'plugin_response' &&
response.requestId === requestId) {
// 清理监听器
wsManager.off('message', responseHandler);
console.log('✅ 响应匹配,返回数据:', response);
// 处理响应
if (response.status === 'success') {
resolve(response.response || response);
} else {
reject(new Error(response.message || 'Plugin error'));
}
}
} catch (error) {
// 忽略非JSON消息
}
};
// 添加响应监听器
wsManager.on('message', responseHandler);
// 发送消息
wsManager.send(message);
// 设置超时
setTimeout(() => {
wsManager.off('message', responseHandler);
reject(new Error('Request timeout (180s)'));
}, REQUEST_TIMEOUT_MS);
});
}
};
// 在页面卸载时清理
window.addEventListener('beforeunload', () => {
wsManager.close(1001, 'Page unloading');
});
}