/**
 * 监控插件
 * 
 * 提供请求监控能力，包括耗时、错误率、上报等
 */ import { PluginPriority } from "./RequestPlugin";
import { logger } from "../../utils/logger";
import { getMonitoring } from "../../utils/monitoring";
import { errorUtils } from "../../utils/errors";
/**
 * 监控事件类型
 */ export var MonitoringEventType = /*#__PURE__*/ function(MonitoringEventType) {
    /**
   * 请求开始
   */ MonitoringEventType["REQUEST_START"] = "request_start";
    /**
   * 请求成功
   */ MonitoringEventType["REQUEST_SUCCESS"] = "request_success";
    /**
   * 请求失败
   */ MonitoringEventType["REQUEST_ERROR"] = "request_error";
    /**
   * 请求完成（无论成功或失败）
   */ MonitoringEventType["REQUEST_COMPLETE"] = "request_complete";
    return MonitoringEventType;
}({});
/**
 * 创建监控插件
 * 
 * @param config - 监控插件配置
 * @returns 监控插件实例
 */ export function createMonitoringPlugin(config = {}) {
    const { enabled = true, reporter, recordStart = true, recordSuccess = true, recordError = true, recordComplete = true, slowRequestThreshold = 3000 } = config;
    // 如果没有提供上报函数，使用默认的 logger 输出
    const defaultReporter = (event)=>{
        logger.debug('[Request Monitoring]', event);
    };
    const report = reporter || defaultReporter;
    return {
        name: 'monitoring',
        priority: PluginPriority.LOW,
        async onBeforeRequest (context) {
            if (!enabled) {
                return;
            }
            if (recordStart) {
                const event = {
                    type: "request_start",
                    url: context.request.url,
                    method: context.request.method || 'GET',
                    tags: context.request.tags,
                    timestamp: Date.now()
                };
                try {
                    await report(event);
                } catch (error) {
                    logger.error('监控上报失败:', error);
                    // 上报错误到监控服务
                    const monitoring = getMonitoring();
                    monitoring.captureError(error, {
                        type: 'monitoring_report_failed',
                        event: 'request_start'
                    });
                }
            }
        },
        async onAfterRequest (context) {
            if (!enabled || !context.response) {
                return;
            }
            const duration = context.duration || 0;
            const isSlow = duration > slowRequestThreshold;
            if (recordSuccess) {
                const event = {
                    type: "request_success",
                    url: context.request.url,
                    method: context.request.method || 'GET',
                    duration,
                    status: context.response.status,
                    tags: context.request.tags,
                    timestamp: Date.now()
                };
                try {
                    await report(event);
                } catch (error) {
                    logger.error('监控上报失败:', error);
                    // 上报错误到监控服务
                    const monitoring = getMonitoring();
                    monitoring.captureError(error, {
                        type: 'monitoring_report_failed',
                        event: 'request_start'
                    });
                }
            }
            if (recordComplete) {
                const event = {
                    type: "request_complete",
                    url: context.request.url,
                    method: context.request.method || 'GET',
                    duration,
                    status: context.response.status,
                    tags: context.request.tags,
                    timestamp: Date.now()
                };
                try {
                    await report(event);
                } catch (error) {
                    logger.error('监控上报失败:', error);
                    // 上报错误到监控服务
                    const monitoring = getMonitoring();
                    monitoring.captureError(error, {
                        type: 'monitoring_report_failed',
                        event: 'request_start'
                    });
                }
            }
            // 如果是慢请求，额外记录
            if (isSlow) {
                logger.warn(`[Slow Request] ${context.request.method || 'GET'} ${context.request.url} took ${duration}ms`);
                // 上报慢请求到监控服务
                const monitoring = getMonitoring();
                monitoring.captureError(new Error(`慢请求: ${context.request.method || 'GET'} ${context.request.url} 耗时 ${duration}ms`), {
                    type: 'slow_request',
                    duration,
                    method: context.request.method || 'GET',
                    url: context.request.url
                });
            }
        },
        async onError (context) {
            if (!enabled || !context.error) {
                return;
            }
            const duration = context.duration || 0;
            if (recordError) {
                const error = context.error;
                const event = {
                    type: "request_error",
                    url: context.request.url,
                    method: context.request.method || 'GET',
                    duration,
                    status: error.status,
                    error: {
                        type: error.type,
                        code: error.code,
                        message: error.message
                    },
                    tags: context.request.tags,
                    timestamp: Date.now()
                };
                // 上报错误到监控服务
                const monitoring = getMonitoring();
                const normalizedError = errorUtils.normalizeError(error);
                monitoring.captureError(normalizedError, {
                    type: 'request_error',
                    url: context.request.url,
                    method: context.request.method || 'GET',
                    duration,
                    status: error.status,
                    errorType: error.type,
                    errorCode: error.code
                });
                try {
                    await report(event);
                } catch (reportError) {
                    logger.error('监控上报失败:', reportError);
                    // 上报上报失败错误到监控服务
                    monitoring.captureError(reportError, {
                        type: 'monitoring_report_failed',
                        event: 'request_error'
                    });
                }
            }
            if (recordComplete) {
                const error = context.error;
                const event = {
                    type: "request_complete",
                    url: context.request.url,
                    method: context.request.method || 'GET',
                    duration,
                    status: error.status,
                    error: {
                        type: error.type,
                        code: error.code,
                        message: error.message
                    },
                    tags: context.request.tags,
                    timestamp: Date.now()
                };
                try {
                    await report(event);
                } catch (reportError) {
                    logger.error('监控上报失败:', reportError);
                    // 上报错误到监控服务
                    const monitoring = getMonitoring();
                    monitoring.captureError(reportError, {
                        type: 'monitoring_report_failed',
                        event: context.error ? 'request_error' : 'request_complete'
                    });
                }
            }
        }
    };
}

//# sourceMappingURL=monitoring.js.map