Files
JoyD/AutoRobot/Windows/Robot/Web/src/DockLayout/handlers/EventBusManager.js

589 lines
16 KiB
JavaScript
Raw Normal View History

/**
* 事件总线集成模块
* 统一管理所有事件处理器和功能模块
*/
2025-12-25 13:53:52 +08:00
import { eventBus, eventBusActions, EVENT_TYPES } from '../eventBus';
import { panelHandler, PANEL_EVENT_TYPES, panelActions } from './PanelHandler';
import tabPageHandler, { TABPAGE_EVENT_TYPES, tabPageActions } from './TabPageHandler';
import areaHandler, { AREA_EVENT_TYPES, areaActions } from './AreaHandler';
import globalEventManager, { GLOBAL_EVENT_TYPES, globalEventActions } from './GlobalEventManager';
import dragStateManager, { DRAG_STATE_TYPES, dragStateActions } from './DragStateManager';
import integrationTester, { testActions, TEST_CONFIG } from './IntegrationTester';
// 事件总线配置
export const EVENT_BUS_CONFIG = {
// 事件总线配置
bus: {
enableDebug: true,
enablePerformance: true,
maxHistorySize: 1000,
cleanupInterval: 30000 // 30秒清理一次
},
// 处理器配置
handlers: {
panel: {
enabled: true,
autoRegister: true,
eventBufferSize: 100
},
tabpage: {
enabled: true,
autoRegister: true,
eventBufferSize: 100
},
area: {
enabled: true,
autoRegister: true,
eventBufferSize: 100
},
global: {
enabled: true,
autoRegister: true,
routing: true
},
drag: {
enabled: true,
autoRegister: true,
conflictDetection: true
}
},
// 集成测试配置
testing: {
enabled: true,
autoRun: false,
reportInterval: 60000, // 1分钟
performanceThreshold: {
eventEmitTime: 10,
eventHandleTime: 50,
memoryUsage: 50 * 1024 * 1024
}
}
};
// 事件总线管理器类
class EventBusManager {
constructor() {
this.isInitialized = false;
this.isDestroyed = false;
this.components = new Map();
this.eventRoutes = new Map();
this.performanceMonitor = null;
this.healthCheckInterval = null;
this.initializedHandlers = new Set();
// 绑定方法
this._handleGlobalError = this._handleGlobalError.bind(this);
this._handleUnhandledRejection = this._handleUnhandledRejection.bind(this);
this._healthCheck = this._healthCheck.bind(this);
}
/**
* 初始化事件总线系统
* @param {Object} config - 配置选项
*/
async initialize(config = {}) {
if (this.isInitialized) {
console.warn('⚠️ 事件总线系统已经初始化');
return;
}
console.log('🚀 初始化事件总线系统...');
this.isInitialized = true;
try {
// 合并配置
this.config = { ...EVENT_BUS_CONFIG, ...config };
// 初始化全局错误处理
this._setupGlobalErrorHandling();
// 注册事件处理器
await this._registerAllHandlers();
// 设置事件路由
this._setupEventRoutes();
// 启动性能监控(如果启用)
if (this.config.testing.enabled && this.config.testing.autoRun) {
await this._startPerformanceMonitoring();
}
// 启动健康检查
this._startHealthCheck();
// 发布初始化完成事件
eventBus.emit(GLOBAL_EVENT_TYPES.SYSTEM_INITIALIZED, {
timestamp: Date.now(),
version: '1.0.0',
components: Array.from(this.initializedHandlers)
});
console.log('✅ 事件总线系统初始化完成');
console.log(`📋 已注册组件: ${Array.from(this.initializedHandlers).join(', ')}`);
} catch (error) {
console.error('❌ 事件总线系统初始化失败:', error);
this.isInitialized = false;
throw error;
}
}
/**
* 注册所有事件处理器
*/
async _registerAllHandlers() {
const handlers = [
{ name: 'panel', handler: panelHandler, events: PANEL_EVENT_TYPES },
{ name: 'tabpage', handler: tabPageHandler, events: TABPAGE_EVENT_TYPES },
{ name: 'area', handler: areaHandler, events: AREA_EVENT_TYPES },
{ name: 'global', handler: globalEventManager, events: GLOBAL_EVENT_TYPES },
2025-12-26 13:09:35 +08:00
{ name: 'drag', handler: dragStateManager.getInstance(), events: DRAG_STATE_TYPES, skipEventRegistration: true }
];
2025-12-26 13:09:35 +08:00
for (const { name, handler, events, skipEventRegistration = false } of handlers) {
const handlerConfig = this.config.handlers[name];
if (!handlerConfig?.enabled) {
console.log(`⏭️ 跳过禁用的事件处理器: ${name}`);
continue;
}
try {
console.log(`📝 注册事件处理器: ${name}`);
2025-12-26 13:09:35 +08:00
// 注册事件处理器到事件总线(除非跳过)
if (!skipEventRegistration) {
Object.values(events).forEach(eventType => {
if (typeof handler.handleEvent === 'function') {
eventBus.on(eventType, handler.handleEvent.bind(handler), {
priority: 1,
id: `handler-${name}`,
componentId: `handler-${name}`
});
}
});
} else {
console.log(`⏭️ 跳过事件监听器注册(内部自动注册): ${name}`);
}
// 调用初始化方法(如果存在)
if (typeof handler.initialize === 'function') {
await handler.initialize();
}
this.initializedHandlers.add(name);
this.components.set(name, {
handler,
events: Object.values(events),
config: handlerConfig,
status: 'active',
initializedAt: Date.now()
});
console.log(`✅ 事件处理器注册成功: ${name}`);
} catch (error) {
console.error(`❌ 事件处理器注册失败 [${name}]:`, error);
this.components.set(name, {
handler,
events: Object.values(events),
config: handlerConfig,
status: 'error',
error: error.message,
initializedAt: Date.now()
});
}
}
}
/**
* 设置事件路由
*/
_setupEventRoutes() {
// 设置跨组件事件路由
const routes = [
// Panel相关路由
{ from: PANEL_EVENT_TYPES.PANEL_CREATE_REQUEST, to: [GLOBAL_EVENT_TYPES.PANEL_CREATED] },
{ from: PANEL_EVENT_TYPES.PANEL_CLOSE_REQUEST, to: [GLOBAL_EVENT_TYPES.PANEL_CLOSED] },
{ from: PANEL_EVENT_TYPES.PANEL_MAXIMIZE, to: [GLOBAL_EVENT_TYPES.PANEL_STATE_CHANGED] },
// TabPage相关路由
{ from: TABPAGE_EVENT_TYPES.TABPAGE_CREATE_REQUEST, to: [GLOBAL_EVENT_TYPES.TABPAGE_CREATED] },
{ from: TABPAGE_EVENT_TYPES.TABPAGE_CLOSE_REQUEST, to: [GLOBAL_EVENT_TYPES.TABPAGE_CLOSED] },
{ from: TABPAGE_EVENT_TYPES.TABPAGE_SWITCH, to: [GLOBAL_EVENT_TYPES.TABPAGE_SWITCHED] },
// Area相关路由
{ from: AREA_EVENT_TYPES.AREA_CREATE_REQUEST, to: [GLOBAL_EVENT_TYPES.AREA_CREATED] },
{ from: AREA_EVENT_TYPES.AREA_DESTROY_REQUEST, to: [GLOBAL_EVENT_TYPES.AREA_DESTROYED] },
{ from: AREA_EVENT_TYPES.AREA_MERGE, to: [GLOBAL_EVENT_TYPES.AREA_MERGED] },
// 拖拽相关路由
{ from: 'panel.drag.start', to: [GLOBAL_EVENT_TYPES.DRAG_STARTED] },
{ from: 'panel.drag.end', to: [GLOBAL_EVENT_TYPES.DRAG_ENDED] },
{ from: 'tabpage.drag.start', to: [GLOBAL_EVENT_TYPES.DRAG_STARTED] },
{ from: 'tabpage.drag.end', to: [GLOBAL_EVENT_TYPES.DRAG_ENDED] },
{ from: 'area.drag.start', to: [GLOBAL_EVENT_TYPES.DRAG_STARTED] },
{ from: 'area.drag.end', to: [GLOBAL_EVENT_TYPES.DRAG_ENDED] }
];
routes.forEach(route => {
this.eventRoutes.set(route.from, route.to);
eventBus.on(route.from, (data) => {
// 自动路由到目标事件
route.to.forEach(targetEvent => {
eventBus.emit(targetEvent, {
...data,
sourceEvent: route.from,
routed: true,
routeTime: Date.now()
});
});
2025-12-26 13:09:35 +08:00
}, { id: 'router', priority: 0, componentId: 'event-router' });
});
console.log(`🔗 设置了 ${routes.length} 个事件路由`);
}
/**
* 设置全局错误处理
*/
_setupGlobalErrorHandling() {
// 捕获未处理的错误
window.addEventListener('error', this._handleGlobalError);
// 捕获未处理的Promise拒绝
window.addEventListener('unhandledrejection', this._handleUnhandledRejection);
console.log('🔧 全局错误处理已设置');
}
/**
* 处理全局错误
* @param {ErrorEvent} event - 错误事件
*/
_handleGlobalError(event) {
console.error('🚨 全局错误捕获:', {
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error
});
// 发布错误事件
eventBus.emit(GLOBAL_EVENT_TYPES.SYSTEM_ERROR, {
type: 'javascript_error',
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack,
timestamp: Date.now()
});
}
/**
* 处理未捕获的Promise拒绝
* @param {PromiseRejectionEvent} event - Promise拒绝事件
*/
_handleUnhandledRejection(event) {
console.error('🚨 未处理的Promise拒绝:', {
reason: event.reason,
promise: event.promise
});
// 发布错误事件
eventBus.emit(GLOBAL_EVENT_TYPES.SYSTEM_ERROR, {
type: 'unhandled_promise_rejection',
reason: event.reason?.toString(),
stack: event.reason?.stack,
timestamp: Date.now()
});
}
/**
* 启动性能监控
*/
async _startPerformanceMonitoring() {
console.log('📊 启动性能监控...');
// 运行快速性能测试
try {
const report = await testActions.runAll(['panel', 'tabpage', 'area']);
console.log('✅ 初始性能测试完成');
// 发布性能报告
eventBus.emit(GLOBAL_EVENT_TYPES.PERFORMANCE_REPORT, {
type: 'initial_test',
report,
timestamp: Date.now()
});
} catch (error) {
console.warn('⚠️ 初始性能测试失败:', error.message);
}
}
/**
* 启动健康检查
*/
_startHealthCheck() {
// 每分钟执行一次健康检查
this.healthCheckInterval = setInterval(this._healthCheck, 60000);
console.log('💚 健康检查已启动');
}
/**
* 执行健康检查
*/
_healthCheck() {
if (this.isDestroyed) return;
const healthStatus = {
timestamp: Date.now(),
components: {},
eventBus: {
isActive: eventBus.isActive(),
handlerCount: eventBus.getHandlerCount(),
queuedEvents: eventBus.getQueuedEvents()
},
memory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize,
limit: performance.memory.jsHeapSizeLimit
} : null,
issues: []
};
// 检查组件状态
for (const [name, component] of this.components) {
component.status = 'active'; // 简化实现,实际应该检查组件健康状态
healthStatus.components[name] = {
status: component.status,
error: component.error,
initializedAt: component.initializedAt
};
if (component.status === 'error') {
healthStatus.issues.push({
component: name,
type: 'component_error',
message: component.error
});
}
}
// 检查事件总线状态
if (healthStatus.eventBus.handlerCount === 0) {
healthStatus.issues.push({
component: 'eventBus',
type: 'no_handlers',
message: '事件总线没有注册的事件处理器'
});
}
// 发布健康检查结果
eventBus.emit(GLOBAL_EVENT_TYPES.HEALTH_CHECK, healthStatus);
}
/**
* 获取系统状态
* @returns {Object} 系统状态
*/
getSystemStatus() {
return {
initialized: this.isInitialized,
destroyed: this.isDestroyed,
config: this.config,
components: Object.fromEntries(this.components),
eventRoutes: Object.fromEntries(this.eventRoutes),
initializedHandlers: Array.from(this.initializedHandlers),
eventBusStats: eventBus.getStats(),
uptime: Date.now() - (this.startTime || Date.now())
};
}
/**
* 重启组件
* @param {string} componentName - 组件名称
*/
async restartComponent(componentName) {
const component = this.components.get(componentName);
if (!component) {
throw new Error(`未找到组件: ${componentName}`);
}
console.log(`🔄 重启组件: ${componentName}`);
try {
// 销毁组件
if (typeof component.handler.destroy === 'function') {
await component.handler.destroy();
}
// 重新初始化组件
if (typeof component.handler.initialize === 'function') {
await component.handler.initialize();
}
// 更新状态
component.status = 'active';
component.error = null;
component.restartedAt = Date.now();
console.log(`✅ 组件重启成功: ${componentName}`);
// 发布重启事件
eventBus.emit(GLOBAL_EVENT_TYPES.COMPONENT_RESTARTED, {
componentName,
timestamp: Date.now()
});
} catch (error) {
component.status = 'error';
component.error = error.message;
console.error(`❌ 组件重启失败 [${componentName}]:`, error);
throw error;
}
}
/**
* 销毁事件总线系统
*/
async destroy() {
if (!this.isInitialized || this.isDestroyed) {
return;
}
console.log('🗑️ 销毁事件总线系统...');
this.isDestroyed = true;
try {
// 停止健康检查
if (this.healthCheckInterval) {
clearInterval(this.healthCheckInterval);
this.healthCheckInterval = null;
}
// 移除全局错误处理
window.removeEventListener('error', this._handleGlobalError);
window.removeEventListener('unhandledrejection', this._handleUnhandledRejection);
// 销毁所有组件
for (const [name, component] of this.components) {
try {
if (typeof component.handler.destroy === 'function') {
await component.handler.destroy();
}
console.log(`✅ 组件销毁成功: ${name}`);
} catch (error) {
console.error(`❌ 组件销毁失败 [${name}]:`, error);
}
}
// 清空数据
this.components.clear();
this.eventRoutes.clear();
this.initializedHandlers.clear();
// 销毁测试器
if (typeof integrationTester.destroy === 'function') {
integrationTester.destroy();
}
console.log('✅ 事件总线系统已完全销毁');
} catch (error) {
console.error('❌ 事件总线系统销毁过程中发生错误:', error);
throw error;
}
}
}
// 创建单例实例
const eventBusManager = new EventBusManager();
// 便捷API
export const systemActions = {
/**
* 初始化事件总线系统
* @param {Object} config - 配置选项
*/
initialize: (config) => eventBusManager.initialize(config),
/**
* 获取系统状态
* @returns {Object} 系统状态
*/
getStatus: () => eventBusManager.getSystemStatus(),
/**
* 重启组件
* @param {string} componentName - 组件名称
*/
restartComponent: (componentName) => eventBusManager.restartComponent(componentName),
/**
* 运行集成测试
* @param {Array} suites - 测试套件列表
* @returns {Promise} 测试报告
*/
runTests: (suites) => testActions.runAll(suites),
/**
* 获取性能摘要
* @returns {Object} 性能摘要
*/
getPerformanceSummary: () => testActions.getPerformanceSummary(),
/**
* 销毁系统
*/
destroy: () => eventBusManager.destroy()
};
// 导出所有API
export const dockLayoutActions = {
// 事件总线API
...eventBusActions,
// Panel API
...panelActions,
// TabPage API
...tabPageActions,
// Area API
...areaActions,
// 全局事件 API
...globalEventActions,
// 拖拽状态 API
...dragStateActions,
// 系统 API
...systemActions
};
// 默认导出管理器实例
export default eventBusManager;
// 导出的常量
export {
EVENT_BUS_CONFIG,
EVENT_TYPES,
PANEL_EVENT_TYPES,
TABPAGE_EVENT_TYPES,
AREA_EVENT_TYPES,
GLOBAL_EVENT_TYPES,
DRAG_STATE_TYPES,
TEST_CONFIG
};