traces.ts 5.46 KB
/*
 * @Description: 跟踪URL管理模块
 * @version: 3.0.0
 * @Author: limin
 * @Date: 2025-09-09 09:49:02
 * @LastEditors: limin
 * @LastEditTime: 2025-09-19 21:06:54
 * @FilePath: \glsk-fetch\src\monitoring\traces.ts
 */

import { simpleGet } from '../utils/http';

/**
 * 配置选项接口
 */
export interface TraceConfig {
  /** 配置中心URL */
  url: string;
  /** 请求失败重试次数 */
  retryCount: number;
  /** 重试延迟(毫秒) */
  retryDelay: number;
  /** 返回数据中URL列表的字段名 */
  urlField: string;
}

/**
 * 缓存状态接口
 */
interface TraceCache {
  /** 缓存的URL列表 */
  urls: string[] | null;
  /** 进行中的请求Promise */
  promise: Promise<string[]> | null;
}

/**
 * 配置中心响应数据接口
 */
interface ConfigResponse {
  /** URL白名单列表,字段名由配置决定 */
  [key: string]: string[];
}

/**
 * 跟踪URL管理类
 * 提供URL列表获取、缓存管理和自定义配置功能
 */
/** 白名单是否已预加载 */
export let isPreloaded = false;

export class TraceManager {
  /** 默认配置 */
  static readonly DEFAULT_CONFIG: TraceConfig = {
    url: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common',
    retryCount: 3,      // 重试次数
    retryDelay: 1000,   // 重试延迟(ms)
    urlField: 'whiteUrl' // 返回数据中URL列表的字段名
  };
  
  /** 白名单是否已预加载 */
  isPreloaded: boolean = false;

  /** 当前配置 */
  private config: TraceConfig;
  /** 缓存状态 */
  private cache: TraceCache;

  /**
   * 构造函数
   * @param options - 配置选项
   */
  constructor(options: Partial<TraceConfig> = {}) {
    this.config = { ...TraceManager.DEFAULT_CONFIG, ...options };
    this.cache = {
      urls: null,
      promise: null
    };
  }

  /**
   * 处理URL列表,移除协议前缀
   * @param urls - URL列表
   * @returns 处理后的URL列表
   * @private
   */
  private _processUrls(urls: string[] = []): string[] {
    if (!Array.isArray(urls)) return [];
    return urls.map(url => url.replace(/^https?:/, ''));
  }



  /**
   * 获取配置数据(带重试机制)
   * @private
   */
  private async _fetchWithRetry(): Promise<string[]> {
    let lastError: Error | unknown;
    
    for (let attempt = 0; attempt < this.config.retryCount; attempt++) {
      try {
        const result = await simpleGet(this.config.url) as ConfigResponse;
        const urls = result[this.config.urlField] || [];
        return this._processUrls(urls);
      } catch (error) {
        lastError = error;
        console.warn('\x1b[33m⚠️  %s\x1b[0m', `获取配置失败 (尝试 ${attempt + 1}/${this.config.retryCount}):`, error);
        
        // 最后一次尝试不需要等待
        if (attempt < this.config.retryCount - 1) {
          await new Promise(resolve => setTimeout(resolve, this.config.retryDelay));
        }
      }
    }
    
    // 所有重试都失败了
    console.error('\x1b[31m❌ %s\x1b[0m', '获取配置最终失败:', lastError);
    return [];
  }

  /**
   * 获取跟踪URL列表
   * @param forceRefresh - 是否强制刷新缓存
   * @returns 跟踪URL列表
   */
  async getTraceUrls(forceRefresh = false): Promise<string[]> {
    // 如果缓存存在且不强制刷新,直接返回缓存
    if (this.cache.urls && !forceRefresh) {
      return this.cache.urls;
    }
    
    // 如果已经有一个请求在进行中,返回该Promise
    if (this.cache.promise) {
      return this.cache.promise;
    }
    
    // 创建新的Promise并保存引用
    this.cache.promise = this._fetchWithRetry()
      .then(urls => {
        // 更新缓存
        this.cache.urls = urls;
        // 设置预加载状态为成功
        isPreloaded = true;
        return urls;
      })
      .catch(error => {
        // 设置预加载状态为失败
        isPreloaded = false;
        throw error; // 继续抛出错误
      })
      .finally(() => {
        this.cache.promise = null;
      });
    
    return this.cache.promise;
  }

  /**
   * 清除URL缓存
   * @returns 操作成功返回true
   */
  clearCache(): boolean {
    this.cache.urls = null;
    this.cache.promise = null;
    return true;
  }

  /**
   * 更新配置
   * @param options - 新的配置选项
   * @returns 更新后的配置
   */
  updateConfig(options: Partial<TraceConfig> = {}): TraceConfig {
    this.config = { ...this.config, ...options };
    return this.config;
  }

  /**
   * 获取当前配置
   * @returns 当前配置
   */
  getConfig(): Readonly<TraceConfig> {
    return { ...this.config };
  }

  /**
   * 预加载白名单URL列表
   * 在应用初始化时调用,避免首次请求时才加载白名单
   * @returns 预加载的Promise
   */
  async preloadTraceUrls(): Promise<string[]> {
    try {
      const urls = await this.getTraceUrls(true); // 强制刷新缓存
      isPreloaded = true;
      console.log('\x1b[32m✅ %s\x1b[0m', '白名单URL预加载成功:', urls.length);
      return urls;
    } catch (error) {
      isPreloaded = false;
      console.error('\x1b[31m❌ %s\x1b[0m', '白名单URL预加载失败:', error);
      return [];
    }
  }
}



// 创建默认实例
const Trace = new TraceManager();

// 将 isPreloaded 属性添加到 Trace 实例上
Object.defineProperty(Trace, 'isPreloaded', {
  get: () => isPreloaded,
  set: (value) => { isPreloaded = value; }
});

// 添加类型定义扩展
declare module './traces' {
  interface TraceManager {
    isPreloaded: boolean;
  }
}

export default Trace;