1100 lines
30 KiB
JavaScript
1100 lines
30 KiB
JavaScript
/**
|
||
* 全局事件管理器
|
||
* 统一管理所有事件处理器,提供事件路由、分发、监控和调试功能
|
||
*/
|
||
|
||
import { eventBus } from '../eventBus.js';
|
||
import { panelHandler, PANEL_EVENT_TYPES, panelActions } from './PanelHandler.js';
|
||
import tabPageHandler, { TABPAGE_EVENT_TYPES, tabPageActions } from './TabPageHandler.js';
|
||
import areaHandler, { AREA_EVENT_TYPES, areaActions } from './AreaHandler.js';
|
||
|
||
// 全局事件类型常量
|
||
export const GLOBAL_EVENT_TYPES = {
|
||
// 系统级事件
|
||
SYSTEM_INIT: 'system.init',
|
||
SYSTEM_READY: 'system.ready',
|
||
SYSTEM_DESTROY: 'system.destroy',
|
||
SYSTEM_ERROR: 'system.error',
|
||
SYSTEM_PERFORMANCE: 'system.performance',
|
||
|
||
// 事件路由
|
||
EVENT_ROUTE_START: 'event.route.start',
|
||
EVENT_ROUTE_SUCCESS: 'event.route.success',
|
||
EVENT_ROUTE_ERROR: 'event.route.error',
|
||
EVENT_ROUTE_FALLBACK: 'event.route.fallback',
|
||
|
||
// 跨组件通信
|
||
CROSS_COMPONENT_BROADCAST: 'cross.component.broadcast',
|
||
CROSS_COMPONENT_REQUEST: 'cross.component.request',
|
||
CROSS_COMPONENT_RESPONSE: 'cross.component.response',
|
||
|
||
// 事件链
|
||
EVENT_CHAIN_START: 'event.chain.start',
|
||
EVENT_CHAIN_PROGRESS: 'event.chain.progress',
|
||
EVENT_CHAIN_COMPLETE: 'event.chain.complete',
|
||
EVENT_CHAIN_ERROR: 'event.chain.error',
|
||
|
||
// 性能监控
|
||
PERFORMANCE_MONITOR_START: 'performance.monitor.start',
|
||
PERFORMANCE_MONITOR_END: 'performance.monitor.end',
|
||
PERFORMANCE_THRESHOLD_EXCEEDED: 'performance.threshold.exceeded',
|
||
|
||
// 调试和日志
|
||
DEBUG_EVENT_EMIT: 'debug.event.emit',
|
||
DEBUG_EVENT_HANDLE: 'debug.event.handle',
|
||
DEBUG_PERFORMANCE: 'debug.performance',
|
||
DEBUG_MEMORY: 'debug.memory'
|
||
};
|
||
|
||
// 事件路由配置
|
||
const EVENT_ROUTES = {
|
||
// Panel事件路由
|
||
[PANEL_EVENT_TYPES.PANEL_DRAG_START]: {
|
||
handlers: ['panelHandler', 'areaHandler'],
|
||
priority: 1,
|
||
timeout: 5000
|
||
},
|
||
[PANEL_EVENT_TYPES.PANEL_MAXIMIZE]: {
|
||
handlers: ['panelHandler', 'areaHandler'],
|
||
priority: 1,
|
||
timeout: 3000
|
||
},
|
||
[PANEL_EVENT_TYPES.PANEL_CLOSE_REQUEST]: {
|
||
handlers: ['panelHandler', 'tabPageHandler'],
|
||
priority: 2,
|
||
timeout: 5000
|
||
},
|
||
|
||
// TabPage事件路由
|
||
[TABPAGE_EVENT_TYPES.TABPAGE_DRAG_START]: {
|
||
handlers: ['tabPageHandler', 'areaHandler'],
|
||
priority: 1,
|
||
timeout: 5000
|
||
},
|
||
[TABPAGE_EVENT_TYPES.TABPAGE_SWITCH]: {
|
||
handlers: ['tabPageHandler', 'panelHandler'],
|
||
priority: 2,
|
||
timeout: 3000
|
||
},
|
||
[TABPAGE_EVENT_TYPES.TABPAGE_CLOSE_REQUEST]: {
|
||
handlers: ['tabPageHandler', 'panelHandler'],
|
||
priority: 2,
|
||
timeout: 5000
|
||
},
|
||
|
||
// Area事件路由
|
||
[AREA_EVENT_TYPES.AREA_DRAG_START]: {
|
||
handlers: ['areaHandler', 'tabPageHandler'],
|
||
priority: 1,
|
||
timeout: 5000
|
||
},
|
||
[AREA_EVENT_TYPES.AREA_MERGE]: {
|
||
handlers: ['areaHandler', 'tabPageHandler', 'panelHandler'],
|
||
priority: 1,
|
||
timeout: 10000
|
||
},
|
||
[AREA_EVENT_TYPES.AREA_DOCK_CENTER]: {
|
||
handlers: ['areaHandler', 'tabPageHandler'],
|
||
priority: 1,
|
||
timeout: 8000
|
||
}
|
||
};
|
||
|
||
// 事件执行监控
|
||
class EventExecutionMonitor {
|
||
constructor() {
|
||
this.executionMap = new Map();
|
||
this.performanceHistory = [];
|
||
this.errorHistory = [];
|
||
this.maxHistorySize = 200;
|
||
}
|
||
|
||
/**
|
||
* 开始事件监控
|
||
* @param {string} eventId - 事件ID
|
||
* @param {Object} eventData - 事件数据
|
||
*/
|
||
startMonitoring(eventId, eventData) {
|
||
const execution = {
|
||
eventId,
|
||
eventType: eventData.eventType || eventData.type,
|
||
startTime: Date.now(),
|
||
handlers: [],
|
||
status: 'running',
|
||
eventData: { ...eventData }
|
||
};
|
||
|
||
this.executionMap.set(eventId, execution);
|
||
return execution;
|
||
}
|
||
|
||
/**
|
||
* 记录处理器开始
|
||
* @param {string} eventId - 事件ID
|
||
* @param {string} handlerName - 处理器名称
|
||
*/
|
||
recordHandlerStart(eventId, handlerName) {
|
||
const execution = this.executionMap.get(eventId);
|
||
if (execution) {
|
||
execution.handlers.push({
|
||
name: handlerName,
|
||
startTime: Date.now(),
|
||
status: 'running'
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 记录处理器完成
|
||
* @param {string} eventId - 事件ID
|
||
* @param {string} handlerName - 处理器名称
|
||
* @param {boolean} success - 是否成功
|
||
* @param {number} duration - 执行时长
|
||
* @param {Error} error - 错误信息
|
||
*/
|
||
recordHandlerComplete(eventId, handlerName, success, duration, error = null) {
|
||
const execution = this.executionMap.get(eventId);
|
||
if (execution) {
|
||
const handler = execution.handlers.find(h => h.name === handlerName);
|
||
if (handler) {
|
||
handler.endTime = Date.now();
|
||
handler.duration = duration;
|
||
handler.status = success ? 'completed' : 'error';
|
||
handler.error = error;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 完成事件监控
|
||
* @param {string} eventId - 事件ID
|
||
*/
|
||
completeMonitoring(eventId) {
|
||
const execution = this.executionMap.get(eventId);
|
||
if (execution) {
|
||
execution.endTime = Date.now();
|
||
execution.status = 'completed';
|
||
execution.totalDuration = execution.endTime - execution.startTime;
|
||
|
||
// 记录性能历史
|
||
this.performanceHistory.push({
|
||
eventId,
|
||
eventType: execution.eventType,
|
||
totalDuration: execution.totalDuration,
|
||
handlerCount: execution.handlers.length,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
// 限制历史大小
|
||
if (this.performanceHistory.length > this.maxHistorySize) {
|
||
this.performanceHistory.shift();
|
||
}
|
||
|
||
// 检查性能阈值
|
||
if (execution.totalDuration > 1000) { // 超过1秒
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.PERFORMANCE_THRESHOLD_EXCEEDED, {
|
||
eventId,
|
||
eventType: execution.eventType,
|
||
duration: execution.totalDuration,
|
||
threshold: 1000
|
||
});
|
||
}
|
||
}
|
||
|
||
return execution;
|
||
}
|
||
|
||
/**
|
||
* 记录错误
|
||
* @param {string} eventId - 事件ID
|
||
* @param {Error} error - 错误信息
|
||
*/
|
||
recordError(eventId, error) {
|
||
const execution = this.executionMap.get(eventId);
|
||
if (execution) {
|
||
execution.status = 'error';
|
||
execution.error = error;
|
||
execution.endTime = Date.now();
|
||
execution.totalDuration = execution.endTime - execution.startTime;
|
||
|
||
// 记录错误历史
|
||
this.errorHistory.push({
|
||
eventId,
|
||
eventType: execution.eventType,
|
||
error: error.message,
|
||
stack: error.stack,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
// 限制错误历史大小
|
||
if (this.errorHistory.length > this.maxHistorySize) {
|
||
this.errorHistory.shift();
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取执行统计
|
||
* @returns {Object} 执行统计
|
||
*/
|
||
getExecutionStats() {
|
||
const running = Array.from(this.executionMap.values()).filter(e => e.status === 'running');
|
||
const completed = Array.from(this.executionMap.values()).filter(e => e.status === 'completed');
|
||
const errors = Array.from(this.executionMap.values()).filter(e => e.status === 'error');
|
||
|
||
return {
|
||
running: running.length,
|
||
completed: completed.length,
|
||
errors: errors.length,
|
||
total: this.executionMap.size,
|
||
averageDuration: completed.length > 0 ?
|
||
completed.reduce((sum, e) => sum + e.totalDuration, 0) / completed.length : 0,
|
||
recentPerformance: this.performanceHistory.slice(-10),
|
||
recentErrors: this.errorHistory.slice(-10)
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取事件执行详情
|
||
* @param {string} eventId - 事件ID
|
||
* @returns {Object} 执行详情
|
||
*/
|
||
getExecutionDetail(eventId) {
|
||
return this.executionMap.get(eventId);
|
||
}
|
||
|
||
/**
|
||
* 清理过期记录
|
||
* @param {number} maxAge - 最大年龄(毫秒)
|
||
*/
|
||
cleanup(maxAge = 3600000) { // 1小时
|
||
const now = Date.now();
|
||
|
||
this.performanceHistory = this.performanceHistory.filter(record =>
|
||
(now - record.timestamp) < maxAge);
|
||
|
||
this.errorHistory = this.errorHistory.filter(record =>
|
||
(now - record.timestamp) < maxAge);
|
||
|
||
// 清理已完成的执行记录
|
||
Array.from(this.executionMap.entries()).forEach(([eventId, execution]) => {
|
||
if (execution.status !== 'running' && (now - execution.endTime) > maxAge) {
|
||
this.executionMap.delete(eventId);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 全局事件管理器类
|
||
*/
|
||
class GlobalEventManager {
|
||
constructor() {
|
||
this.eventHandlers = new Map();
|
||
this.eventRoutes = new Map(Object.entries(EVENT_ROUTES));
|
||
this.executionMonitor = new EventExecutionMonitor();
|
||
this.eventChains = new Map();
|
||
this.crossComponentChannels = new Map();
|
||
this.isInitialized = false;
|
||
this.debugMode = false;
|
||
|
||
// 处理器映射
|
||
this.handlerMap = {
|
||
panelHandler,
|
||
tabPageHandler,
|
||
areaHandler
|
||
};
|
||
|
||
// 绑定方法
|
||
this._onGlobalEvent = this._onGlobalEvent.bind(this);
|
||
this._onSystemError = this._handleSystemError.bind(this);
|
||
this._cleanupExpiredData = this._cleanupExpiredData.bind(this);
|
||
|
||
this._initialize();
|
||
}
|
||
|
||
/**
|
||
* 初始化事件管理器
|
||
*/
|
||
_initialize() {
|
||
// 注册全局事件监听器
|
||
this._registerGlobalEventListeners();
|
||
|
||
// 启动定期清理
|
||
this._startCleanupScheduler();
|
||
|
||
// 启动调试模式监听
|
||
this._startDebugMode();
|
||
|
||
this.isInitialized = true;
|
||
console.log('✅ 全局事件管理器初始化完成');
|
||
|
||
// 触发系统就绪事件
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.SYSTEM_READY, {
|
||
manager: 'globalEventManager',
|
||
timestamp: Date.now(),
|
||
handlers: Object.keys(this.handlerMap)
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 注册全局事件监听器
|
||
*/
|
||
_registerGlobalEventListeners() {
|
||
const globalEvents = Object.values(GLOBAL_EVENT_TYPES);
|
||
globalEvents.forEach(eventType => {
|
||
eventBus.on(eventType, this._onGlobalEvent, {
|
||
priority: 0, // 最高优先级
|
||
deduplication: { type: 'TTL_BASED', ttl: 50 }
|
||
});
|
||
});
|
||
|
||
// 注册所有组件事件监听器
|
||
this._registerComponentEventListeners();
|
||
}
|
||
|
||
/**
|
||
* 注册组件事件监听器
|
||
*/
|
||
_registerComponentEventListeners() {
|
||
// Panel事件监听
|
||
Object.values(PANEL_EVENT_TYPES).forEach(eventType => {
|
||
eventBus.on(eventType, (data) => {
|
||
this._routeEvent(eventType, data, 'panel');
|
||
}, { priority: 1 });
|
||
});
|
||
|
||
// TabPage事件监听
|
||
Object.values(TABPAGE_EVENT_TYPES).forEach(eventType => {
|
||
eventBus.on(eventType, (data) => {
|
||
this._routeEvent(eventType, data, 'tabPage');
|
||
}, { priority: 1 });
|
||
});
|
||
|
||
// Area事件监听
|
||
Object.values(AREA_EVENT_TYPES).forEach(eventType => {
|
||
eventBus.on(eventType, (data) => {
|
||
this._routeEvent(eventType, data, 'area');
|
||
}, { priority: 1 });
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 路由事件到相应的处理器
|
||
* @param {string} eventType - 事件类型
|
||
* @param {Object} eventData - 事件数据
|
||
* @param {string} source - 事件源
|
||
*/
|
||
async _routeEvent(eventType, eventData, source) {
|
||
const eventId = `${eventType}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||
const routeConfig = this.eventRoutes.get(eventType);
|
||
|
||
// 开始监控
|
||
this.executionMonitor.startMonitoring(eventId, { ...eventData, eventType });
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_ROUTE_START, {
|
||
eventId,
|
||
eventType,
|
||
source,
|
||
routeConfig
|
||
});
|
||
|
||
try {
|
||
if (routeConfig) {
|
||
// 使用配置的路由
|
||
await this._executeRoutedHandlers(eventId, eventType, eventData, routeConfig);
|
||
} else {
|
||
// 默认路由到相应组件处理器
|
||
await this._executeDefaultHandler(eventId, eventType, eventData, source);
|
||
}
|
||
|
||
// 完成监控
|
||
this.executionMonitor.completeMonitoring(eventId);
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_ROUTE_SUCCESS, {
|
||
eventId,
|
||
eventType,
|
||
source,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
} catch (error) {
|
||
// 记录错误
|
||
this.executionMonitor.recordError(eventId, error);
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_ROUTE_ERROR, {
|
||
eventId,
|
||
eventType,
|
||
source,
|
||
error: error.message,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
// 触发系统错误事件
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.SYSTEM_ERROR, {
|
||
eventId,
|
||
eventType,
|
||
source,
|
||
error,
|
||
timestamp: Date.now()
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 执行路由的处理器
|
||
* @param {string} eventId - 事件ID
|
||
* @param {string} eventType - 事件类型
|
||
* @param {Object} eventData - 事件数据
|
||
* @param {Object} routeConfig - 路由配置
|
||
*/
|
||
async _executeRoutedHandlers(eventId, eventType, eventData, routeConfig) {
|
||
const { handlers, priority, timeout = 5000 } = routeConfig;
|
||
const handlerPromises = handlers.map(async (handlerName) => {
|
||
const startTime = Date.now();
|
||
this.executionMonitor.recordHandlerStart(eventId, handlerName);
|
||
|
||
try {
|
||
const handler = this.handlerMap[handlerName];
|
||
if (!handler) {
|
||
throw new Error(`Handler ${handlerName} not found`);
|
||
}
|
||
|
||
// 执行处理器
|
||
const result = await this._executeHandlerWithTimeout(
|
||
handler,
|
||
eventType,
|
||
eventData,
|
||
timeout
|
||
);
|
||
|
||
const duration = Date.now() - startTime;
|
||
this.executionMonitor.recordHandlerComplete(eventId, handlerName, true, duration);
|
||
|
||
return { handlerName, result, duration };
|
||
|
||
} catch (error) {
|
||
const duration = Date.now() - startTime;
|
||
this.executionMonitor.recordHandlerComplete(eventId, handlerName, false, duration, error);
|
||
throw error;
|
||
}
|
||
});
|
||
|
||
// 等待所有处理器完成
|
||
const results = await Promise.allSettled(handlerPromises);
|
||
|
||
// 检查是否有失败的处理器
|
||
const failures = results.filter(result => result.status === 'rejected');
|
||
if (failures.length > 0) {
|
||
throw new Error(`Handler execution failed: ${failures.map(f => f.reason.message).join(', ')}`);
|
||
}
|
||
|
||
return results.map(result => result.value);
|
||
}
|
||
|
||
/**
|
||
* 执行默认处理器
|
||
* @param {string} eventId - 事件ID
|
||
* @param {string} eventType - 事件类型
|
||
* @param {Object} eventData - 事件数据
|
||
* @param {string} source - 事件源
|
||
*/
|
||
async _executeDefaultHandler(eventId, eventType, eventData, source) {
|
||
const handlerName = `${source}Handler`;
|
||
const handler = this.handlerMap[handlerName];
|
||
|
||
if (!handler) {
|
||
throw new Error(`Default handler ${handlerName} not found`);
|
||
}
|
||
|
||
this.executionMonitor.recordHandlerStart(eventId, handlerName);
|
||
|
||
try {
|
||
const result = await this._executeHandlerWithTimeout(handler, eventType, eventData, 5000);
|
||
const duration = Date.now() - this.executionMonitor.getExecutionDetail(eventId).startTime;
|
||
this.executionMonitor.recordHandlerComplete(eventId, handlerName, true, duration);
|
||
return result;
|
||
} catch (error) {
|
||
const duration = Date.now() - this.executionMonitor.getExecutionDetail(eventId).startTime;
|
||
this.executionMonitor.recordHandlerComplete(eventId, handlerName, false, duration, error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 带超时的处理器执行
|
||
* @param {Object} handler - 处理器对象
|
||
* @param {string} eventType - 事件类型
|
||
* @param {Object} eventData - 事件数据
|
||
* @param {number} timeout - 超时时间
|
||
* @returns {Promise} 执行结果
|
||
*/
|
||
async _executeHandlerWithTimeout(handler, eventType, eventData, timeout) {
|
||
return new Promise((resolve, reject) => {
|
||
const timer = setTimeout(() => {
|
||
reject(new Error(`Handler execution timeout after ${timeout}ms`));
|
||
}, timeout);
|
||
|
||
try {
|
||
// 假设处理器有处理事件的方法
|
||
if (typeof handler._onEvent === 'function') {
|
||
const result = handler._onEvent({ eventType, ...eventData });
|
||
if (result instanceof Promise) {
|
||
result.then(resolve).catch(reject).finally(() => clearTimeout(timer));
|
||
} else {
|
||
resolve(result);
|
||
clearTimeout(timer);
|
||
}
|
||
} else {
|
||
// 如果处理器没有_onEvent方法,直接解析
|
||
resolve(true);
|
||
clearTimeout(timer);
|
||
}
|
||
} catch (error) {
|
||
reject(error);
|
||
clearTimeout(timer);
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 处理全局事件
|
||
* @param {Object} data - 事件数据
|
||
*/
|
||
async _onGlobalEvent(data) {
|
||
const { eventType } = data;
|
||
|
||
try {
|
||
switch (eventType) {
|
||
case GLOBAL_EVENT_TYPES.SYSTEM_INIT:
|
||
await this._handleSystemInit(data);
|
||
break;
|
||
case GLOBAL_EVENT_TYPES.SYSTEM_ERROR:
|
||
await this._handleSystemError(data);
|
||
break;
|
||
case GLOBAL_EVENT_TYPES.PERFORMANCE_THRESHOLD_EXCEEDED:
|
||
await this._handlePerformanceThresholdExceeded(data);
|
||
break;
|
||
case GLOBAL_EVENT_TYPES.CROSS_COMPONENT_REQUEST:
|
||
await this._handleCrossComponentRequest(data);
|
||
break;
|
||
default:
|
||
if (this.debugMode) {
|
||
console.log(`🌐 全局事件: ${eventType}`, data);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.error(`❌ 全局事件处理错误 (${eventType}):`, error);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 处理系统初始化事件
|
||
* @param {Object} data - 事件数据
|
||
*/
|
||
async _handleSystemInit(data) {
|
||
console.log('🚀 系统初始化开始...', data);
|
||
|
||
// 检查所有处理器是否就绪
|
||
const handlersStatus = {};
|
||
for (const [name, handler] of Object.entries(this.handlerMap)) {
|
||
handlersStatus[name] = {
|
||
ready: typeof handler === 'object',
|
||
methods: Object.getOwnPropertyNames(Object.getPrototypeOf(handler))
|
||
};
|
||
}
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.SYSTEM_READY, {
|
||
manager: 'globalEventManager',
|
||
handlersStatus,
|
||
timestamp: Date.now()
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 处理系统错误事件
|
||
* @param {Object} data - 事件数据
|
||
*/
|
||
async _handleSystemError(data) {
|
||
console.error('💥 系统错误:', data);
|
||
|
||
// 记录错误详情
|
||
this.errorHistory = this.errorHistory || [];
|
||
this.errorHistory.push({
|
||
...data,
|
||
timestamp: Date.now(),
|
||
type: 'system_error'
|
||
});
|
||
|
||
// 限制错误历史大小
|
||
if (this.errorHistory.length > 100) {
|
||
this.errorHistory.shift();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 处理性能阈值超限事件
|
||
* @param {Object} data - 事件数据
|
||
*/
|
||
async _handlePerformanceThresholdExceeded(data) {
|
||
console.warn('⚡ 性能阈值超限:', data);
|
||
|
||
// 可以在这里添加性能优化建议
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.DEBUG_PERFORMANCE, {
|
||
type: 'threshold_exceeded',
|
||
data,
|
||
recommendations: this._generatePerformanceRecommendations(data),
|
||
timestamp: Date.now()
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 生成性能优化建议
|
||
* @param {Object} performanceData - 性能数据
|
||
* @returns {Array} 建议列表
|
||
*/
|
||
_generatePerformanceRecommendations(performanceData) {
|
||
const recommendations = [];
|
||
|
||
if (performanceData.duration > 2000) {
|
||
recommendations.push('考虑将长时间运行的操作分解为更小的任务');
|
||
recommendations.push('检查是否有阻塞主线程的操作');
|
||
}
|
||
|
||
if (performanceData.handlerCount > 3) {
|
||
recommendations.push('减少事件处理器的数量以提高性能');
|
||
}
|
||
|
||
return recommendations;
|
||
}
|
||
|
||
/**
|
||
* 处理跨组件请求
|
||
* @param {Object} data - 请求数据
|
||
*/
|
||
async _handleCrossComponentRequest(data) {
|
||
const { requestId, targetComponent, action, payload } = data;
|
||
|
||
try {
|
||
// 查找目标组件的处理器
|
||
const handler = this.handlerMap[`${targetComponent}Handler`];
|
||
if (!handler) {
|
||
throw new Error(`Target component handler ${targetComponent}Handler not found`);
|
||
}
|
||
|
||
// 执行请求
|
||
const result = await handler[action](payload);
|
||
|
||
// 发送响应
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_RESPONSE, {
|
||
requestId,
|
||
targetComponent,
|
||
action,
|
||
result,
|
||
success: true,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
} catch (error) {
|
||
// 发送错误响应
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_RESPONSE, {
|
||
requestId,
|
||
targetComponent,
|
||
action,
|
||
error: error.message,
|
||
success: false,
|
||
timestamp: Date.now()
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 启动调试模式
|
||
*/
|
||
_startDebugMode() {
|
||
// 监听调试命令
|
||
eventBus.on('debug.toggle', () => {
|
||
this.debugMode = !this.debugMode;
|
||
console.log(`🔧 调试模式${this.debugMode ? '开启' : '关闭'}`);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 启动清理调度器
|
||
*/
|
||
_startCleanupScheduler() {
|
||
setInterval(() => {
|
||
this._cleanupExpiredData();
|
||
}, 60000); // 每分钟清理一次
|
||
}
|
||
|
||
/**
|
||
* 清理过期数据
|
||
*/
|
||
_cleanupExpiredData() {
|
||
this.executionMonitor.cleanup();
|
||
|
||
// 清理事件链
|
||
const now = Date.now();
|
||
Array.from(this.eventChains.entries()).forEach(([chainId, chain]) => {
|
||
if (chain.status === 'completed' && (now - chain.endTime) > 300000) { // 5分钟
|
||
this.eventChains.delete(chainId);
|
||
}
|
||
});
|
||
|
||
// 清理跨组件频道
|
||
this.crossComponentChannels.forEach((channel, channelId) => {
|
||
if (channel.lastActivity && (now - channel.lastActivity) > 600000) { // 10分钟
|
||
this.crossComponentChannels.delete(channelId);
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 启动性能监控
|
||
* @param {string} operation - 操作名称
|
||
* @returns {string} 监控ID
|
||
*/
|
||
startPerformanceMonitor(operation) {
|
||
const monitorId = `perf-${operation}-${Date.now()}`;
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.PERFORMANCE_MONITOR_START, {
|
||
monitorId,
|
||
operation,
|
||
startTime: Date.now()
|
||
});
|
||
|
||
return monitorId;
|
||
}
|
||
|
||
/**
|
||
* 结束性能监控
|
||
* @param {string} monitorId - 监控ID
|
||
* @param {Object} metadata - 元数据
|
||
*/
|
||
endPerformanceMonitor(monitorId, metadata = {}) {
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.PERFORMANCE_MONITOR_END, {
|
||
monitorId,
|
||
endTime: Date.now(),
|
||
metadata
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 创建事件链
|
||
* @param {string} chainName - 链名称
|
||
* @param {Array} events - 事件列表
|
||
* @returns {string} 链ID
|
||
*/
|
||
createEventChain(chainName, events) {
|
||
const chainId = `chain-${chainName}-${Date.now()}`;
|
||
|
||
const chain = {
|
||
id: chainId,
|
||
name: chainName,
|
||
events,
|
||
currentIndex: 0,
|
||
status: 'pending',
|
||
startTime: Date.now(),
|
||
results: []
|
||
};
|
||
|
||
this.eventChains.set(chainId, chain);
|
||
|
||
// 触发链开始事件
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_CHAIN_START, {
|
||
chainId,
|
||
chainName,
|
||
eventCount: events.length
|
||
});
|
||
|
||
// 开始执行链
|
||
this._executeEventChain(chainId);
|
||
|
||
return chainId;
|
||
}
|
||
|
||
/**
|
||
* 执行事件链
|
||
* @param {string} chainId - 链ID
|
||
*/
|
||
async _executeEventChain(chainId) {
|
||
const chain = this.eventChains.get(chainId);
|
||
if (!chain || chain.currentIndex >= chain.events.length) {
|
||
this._completeEventChain(chainId);
|
||
return;
|
||
}
|
||
|
||
const currentEvent = chain.events[chain.currentIndex];
|
||
chain.status = 'running';
|
||
|
||
try {
|
||
// 触发进度事件
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_CHAIN_PROGRESS, {
|
||
chainId,
|
||
currentIndex: chain.currentIndex,
|
||
totalEvents: chain.events.length,
|
||
currentEvent
|
||
});
|
||
|
||
// 执行当前事件
|
||
const result = await this._executeSingleEvent(currentEvent);
|
||
chain.results.push(result);
|
||
|
||
// 移动到下一个事件
|
||
chain.currentIndex++;
|
||
|
||
// 继续执行链
|
||
setTimeout(() => this._executeEventChain(chainId), 100);
|
||
|
||
} catch (error) {
|
||
chain.status = 'error';
|
||
chain.error = error;
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_CHAIN_ERROR, {
|
||
chainId,
|
||
error: error.message,
|
||
currentIndex: chain.currentIndex
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 执行单个事件
|
||
* @param {Object} event - 事件对象
|
||
* @returns {Promise} 执行结果
|
||
*/
|
||
async _executeSingleEvent(event) {
|
||
const { type, data, delay = 0 } = event;
|
||
|
||
if (delay > 0) {
|
||
await new Promise(resolve => setTimeout(resolve, delay));
|
||
}
|
||
|
||
return new Promise((resolve, reject) => {
|
||
eventBus.emit(type, {
|
||
...data,
|
||
chainExecution: true,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
// 简单的等待机制(在实际应用中可能需要更复杂的协调)
|
||
setTimeout(() => resolve({ type, data, executedAt: Date.now() }), 100);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 完成事件链
|
||
* @param {string} chainId - 链ID
|
||
*/
|
||
_completeEventChain(chainId) {
|
||
const chain = this.eventChains.get(chainId);
|
||
if (chain) {
|
||
chain.status = 'completed';
|
||
chain.endTime = Date.now();
|
||
chain.duration = chain.endTime - chain.startTime;
|
||
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.EVENT_CHAIN_COMPLETE, {
|
||
chainId,
|
||
chainName: chain.name,
|
||
eventCount: chain.events.length,
|
||
duration: chain.duration,
|
||
results: chain.results
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 发送跨组件广播
|
||
* @param {string} message - 消息内容
|
||
* @param {Object} data - 附加数据
|
||
* @param {Array} targetComponents - 目标组件列表
|
||
*/
|
||
broadcast(message, data = {}, targetComponents = null) {
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_BROADCAST, {
|
||
message,
|
||
data,
|
||
targetComponents,
|
||
sender: 'globalEventManager',
|
||
timestamp: Date.now()
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 发送跨组件请求
|
||
* @param {string} targetComponent - 目标组件
|
||
* @param {string} action - 操作名称
|
||
* @param {Object} payload - 请求数据
|
||
* @returns {Promise} 响应Promise
|
||
*/
|
||
request(targetComponent, action, payload) {
|
||
const requestId = `req-${targetComponent}-${action}-${Date.now()}`;
|
||
|
||
return new Promise((resolve, reject) => {
|
||
// 设置响应处理器
|
||
const responseHandler = (responseData) => {
|
||
if (responseData.requestId === requestId) {
|
||
eventBus.off(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_RESPONSE, responseHandler);
|
||
|
||
if (responseData.success) {
|
||
resolve(responseData);
|
||
} else {
|
||
reject(new Error(responseData.error));
|
||
}
|
||
}
|
||
};
|
||
|
||
eventBus.on(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_RESPONSE, responseHandler);
|
||
|
||
// 发送请求
|
||
eventBus.emit(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_REQUEST, {
|
||
requestId,
|
||
targetComponent,
|
||
action,
|
||
payload,
|
||
timestamp: Date.now()
|
||
});
|
||
|
||
// 设置超时
|
||
setTimeout(() => {
|
||
eventBus.off(GLOBAL_EVENT_TYPES.CROSS_COMPONENT_RESPONSE, responseHandler);
|
||
reject(new Error(`Request timeout: ${targetComponent}.${action}`));
|
||
}, 10000);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取执行统计
|
||
* @returns {Object} 执行统计
|
||
*/
|
||
getExecutionStats() {
|
||
return {
|
||
...this.executionMonitor.getExecutionStats(),
|
||
eventChains: this.eventChains.size,
|
||
crossComponentChannels: this.crossComponentChannels.size,
|
||
debugMode: this.debugMode,
|
||
initialized: this.isInitialized
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取事件链状态
|
||
* @returns {Array} 事件链状态列表
|
||
*/
|
||
getEventChainStatus() {
|
||
return Array.from(this.eventChains.values()).map(chain => ({
|
||
id: chain.id,
|
||
name: chain.name,
|
||
status: chain.status,
|
||
progress: chain.events.length > 0 ? (chain.currentIndex / chain.events.length) * 100 : 0,
|
||
duration: chain.endTime ? chain.duration : Date.now() - chain.startTime
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 销毁事件管理器
|
||
*/
|
||
destroy() {
|
||
// 清理所有事件监听器
|
||
const globalEvents = Object.values(GLOBAL_EVENT_TYPES);
|
||
globalEvents.forEach(eventType => {
|
||
eventBus.off(eventType, this._onGlobalEvent);
|
||
});
|
||
|
||
// 销毁各个处理器
|
||
Object.values(this.handlerMap).forEach(handler => {
|
||
if (typeof handler.destroy === 'function') {
|
||
handler.destroy();
|
||
}
|
||
});
|
||
|
||
// 清理数据
|
||
this.eventHandlers.clear();
|
||
this.eventChains.clear();
|
||
this.crossComponentChannels.clear();
|
||
|
||
this.isInitialized = false;
|
||
console.log('🗑️ 全局事件管理器已销毁');
|
||
}
|
||
}
|
||
|
||
// 创建单例实例
|
||
const globalEventManager = new GlobalEventManager();
|
||
|
||
// 全局便捷API
|
||
export const globalEventActions = {
|
||
/**
|
||
* 启动性能监控
|
||
* @param {string} operation - 操作名称
|
||
* @returns {string} 监控ID
|
||
*/
|
||
startMonitor: (operation) => {
|
||
return globalEventManager.startPerformanceMonitor(operation);
|
||
},
|
||
|
||
/**
|
||
* 结束性能监控
|
||
* @param {string} monitorId - 监控ID
|
||
* @param {Object} metadata - 元数据
|
||
*/
|
||
endMonitor: (monitorId, metadata = {}) => {
|
||
globalEventManager.endPerformanceMonitor(monitorId, metadata);
|
||
},
|
||
|
||
/**
|
||
* 创建事件链
|
||
* @param {string} chainName - 链名称
|
||
* @param {Array} events - 事件列表
|
||
* @returns {string} 链ID
|
||
*/
|
||
createChain: (chainName, events) => {
|
||
return globalEventManager.createEventChain(chainName, events);
|
||
},
|
||
|
||
/**
|
||
* 发送跨组件广播
|
||
* @param {string} message - 消息
|
||
* @param {Object} data - 数据
|
||
* @param {Array} targets - 目标组件
|
||
*/
|
||
broadcast: (message, data = {}, targets = null) => {
|
||
globalEventManager.broadcast(message, data, targets);
|
||
},
|
||
|
||
/**
|
||
* 发送跨组件请求
|
||
* @param {string} component - 组件名
|
||
* @param {string} action - 操作
|
||
* @param {Object} payload - 数据
|
||
* @returns {Promise} 响应
|
||
*/
|
||
request: (component, action, payload) => {
|
||
return globalEventManager.request(component, action, payload);
|
||
},
|
||
|
||
/**
|
||
* 切换调试模式
|
||
*/
|
||
toggleDebug: () => {
|
||
eventBus.emit('debug.toggle');
|
||
},
|
||
|
||
/**
|
||
* 获取统计信息
|
||
* @returns {Object} 统计信息
|
||
*/
|
||
getStats: () => {
|
||
return globalEventManager.getExecutionStats();
|
||
},
|
||
|
||
/**
|
||
* 获取事件链状态
|
||
* @returns {Array} 链状态
|
||
*/
|
||
getChainStatus: () => {
|
||
return globalEventManager.getEventChainStatus();
|
||
}
|
||
};
|
||
|
||
// 导出事件管理器和相关API
|
||
export default globalEventManager; |