traces.ts
5.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
* @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;