qwenproxy-cli 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +14 -14
- package/README.md +906 -906
- package/bin/qwenproxy.js +5 -1
- package/package.json +78 -78
- package/src/api/error-classifier.ts +159 -159
- package/src/api/error-helpers.ts +118 -118
- package/src/api/models.ts +261 -261
- package/src/api/server.ts +860 -859
- package/src/cache/memory-cache.ts +385 -385
- package/src/clean-cache.ts +204 -204
- package/src/core/account-concurrency.ts +671 -671
- package/src/core/account-manager.ts +301 -297
- package/src/core/account-priority.ts +163 -163
- package/src/core/accounts.ts +186 -186
- package/src/core/config.ts +383 -383
- package/src/core/crypto-utils.ts +79 -79
- package/src/core/database.ts +276 -276
- package/src/core/errors.ts +118 -118
- package/src/core/logger.ts +269 -269
- package/src/core/memory-usage.ts +84 -84
- package/src/core/metrics.ts +291 -291
- package/src/core/model-alias.ts +77 -77
- package/src/core/model-registry.ts +544 -544
- package/src/core/mutex.ts +119 -119
- package/src/core/paths.ts +199 -199
- package/src/core/prompt-limits.ts +214 -214
- package/src/core/reasoning-effort.ts +102 -102
- package/src/core/stream-registry.ts +96 -96
- package/src/core/waf-isolation.ts +117 -117
- package/src/core/watchdog.ts +195 -195
- package/src/delete-chats.ts +23 -23
- package/src/index.ts +65 -64
- package/src/login.ts +147 -147
- package/src/reset-cooldowns.ts +11 -11
- package/src/routes/anthropic/index.ts +355 -355
- package/src/routes/anthropic/translate.ts +522 -522
- package/src/routes/anthropic/types.ts +154 -154
- package/src/routes/anthropic/validation.ts +144 -144
- package/src/routes/chat/account.ts +1817 -1817
- package/src/routes/chat/context.ts +241 -241
- package/src/routes/chat/errors.ts +85 -85
- package/src/routes/chat/helpers.ts +268 -268
- package/src/routes/chat/index.ts +618 -618
- package/src/routes/chat/media.ts +285 -285
- package/src/routes/chat/retry-policy.ts +754 -754
- package/src/routes/chat/stop.ts +98 -98
- package/src/routes/chat/streaming.ts +2710 -2710
- package/src/routes/chat/validation.ts +526 -526
- package/src/routes/chat.ts +2 -2
- package/src/routes/completions.ts +290 -290
- package/src/routes/images.ts +139 -139
- package/src/routes/responses/adapter.ts +503 -503
- package/src/routes/responses/index.ts +405 -405
- package/src/routes/responses/state.ts +230 -230
- package/src/routes/responses/streaming.ts +528 -528
- package/src/routes/responses/types.ts +285 -285
- package/src/routes/responses/validation.ts +202 -202
- package/src/routes/upload.ts +731 -731
- package/src/routes/videos.ts +214 -214
- package/src/services/auth-playwright.ts +173 -173
- package/src/services/captcha-coordinator.ts +161 -161
- package/src/services/captcha-solver.ts +553 -553
- package/src/services/chat-cleanup.ts +80 -80
- package/src/services/context-meter.ts +317 -317
- package/src/services/fingerprint.ts +242 -242
- package/src/services/human-behavior.ts +173 -173
- package/src/services/media-generation.ts +1748 -1748
- package/src/services/playwright.ts +2800 -2800
- package/src/services/qwen-chat-pool.ts +345 -345
- package/src/services/qwen-errors.ts +133 -133
- package/src/services/qwen-headers.ts +79 -79
- package/src/services/qwen-thread-state.ts +393 -393
- package/src/services/qwen-url.ts +19 -19
- package/src/services/qwen.ts +3126 -3126
- package/src/services/session-keeper.ts +88 -88
- package/src/services/token-estimation-metrics.ts +118 -118
- package/src/sync/claude-code.ts +75 -75
- package/src/sync/codex.ts +123 -123
- package/src/sync/index.ts +362 -362
- package/src/sync/omp.ts +105 -105
- package/src/sync/opencode.ts +214 -214
- package/src/sync/types.ts +53 -53
- package/src/sync/utils.ts +27 -27
- package/src/sync-clients.ts +189 -189
- package/src/tools/instructions.ts +137 -137
- package/src/tools/manifest.ts +81 -81
- package/src/tools/parser.ts +2989 -2989
- package/src/tools/toolcall-tags.ts +142 -142
- package/src/tui/app.ts +264 -264
- package/src/tui/index.ts +61 -61
- package/src/tui/markdown.ts +258 -258
- package/src/tui/proxy-client.ts +331 -326
- package/src/tui/screen.ts +294 -278
- package/src/tui/server-manager.ts +270 -270
- package/src/tui/theme.ts +432 -432
- package/src/tui/types.ts +33 -33
- package/src/tui/views/accounts-view.ts +656 -656
- package/src/tui/views/chat-view.ts +1018 -823
- package/src/tui/views/logs-view.ts +479 -413
- package/src/tui/views/status-view.ts +204 -204
- package/src/tui/views/storage-view.ts +304 -291
- package/src/tui/views/sync-view.ts +409 -409
- package/src/types/ali-oss.d.ts +32 -32
- package/src/utils/context-truncation.ts +84 -84
- package/src/utils/json.ts +380 -380
- package/src/utils/session-id.ts +37 -37
- package/src/utils/tool-call-guard.ts +84 -84
- package/src/utils/types.ts +109 -109
package/src/core/metrics.ts
CHANGED
|
@@ -1,291 +1,291 @@
|
|
|
1
|
-
import { EventEmitter } from "events";
|
|
2
|
-
import { config } from "./config.js";
|
|
3
|
-
import { getHeapUsageSnapshot, getRssUsageSnapshot } from "./memory-usage.js";
|
|
4
|
-
|
|
5
|
-
interface MetricPoint {
|
|
6
|
-
value: number;
|
|
7
|
-
timestamp: number;
|
|
8
|
-
labels?: Record<string, string>;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
type MetricType = "counter" | "gauge" | "histogram" | "summary";
|
|
12
|
-
|
|
13
|
-
interface MetricDefinition {
|
|
14
|
-
name: string;
|
|
15
|
-
type: MetricType;
|
|
16
|
-
help: string;
|
|
17
|
-
values: Map<string, MetricPoint>;
|
|
18
|
-
histogramBuckets?: number[];
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export class Metrics extends EventEmitter {
|
|
22
|
-
private metrics: Map<string, MetricDefinition> = new Map();
|
|
23
|
-
private collectionInterval: NodeJS.Timeout | null = null;
|
|
24
|
-
|
|
25
|
-
constructor() {
|
|
26
|
-
super();
|
|
27
|
-
this.registerDefaults();
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
private registerDefaults(): void {
|
|
31
|
-
const defaults: Array<[string, MetricType, string]> = [
|
|
32
|
-
// Core request metrics
|
|
33
|
-
["requests.total", "counter", "Total requests processed"],
|
|
34
|
-
["requests.errors", "counter", "Total request errors"],
|
|
35
|
-
["latency.request", "histogram", "Request latency (ms)"],
|
|
36
|
-
|
|
37
|
-
// Stream metrics
|
|
38
|
-
["streams.active", "gauge", "Active SSE streams"],
|
|
39
|
-
["streams.errors", "counter", "Stream errors"],
|
|
40
|
-
|
|
41
|
-
// CAPTCHA / anti-bot metrics
|
|
42
|
-
["captcha.challenges.detected", "counter", "Detected CAPTCHA challenges"],
|
|
43
|
-
["captcha.solves.succeeded", "counter", "Successful CAPTCHA solves"],
|
|
44
|
-
["captcha.solves.failed", "counter", "Failed CAPTCHA solves"],
|
|
45
|
-
["captcha.solve.duration", "histogram", "CAPTCHA solve duration (ms)"],
|
|
46
|
-
|
|
47
|
-
// Memory metrics
|
|
48
|
-
["memory.heap.used", "gauge", "Heap memory used (bytes)"],
|
|
49
|
-
["memory.heap.total", "gauge", "Heap memory total (bytes)"],
|
|
50
|
-
[
|
|
51
|
-
"memory.heap.limit",
|
|
52
|
-
"gauge",
|
|
53
|
-
"V8 heap_size_limit used for RAM pressure (bytes)",
|
|
54
|
-
],
|
|
55
|
-
[
|
|
56
|
-
"memory.heap.usage_percent",
|
|
57
|
-
"gauge",
|
|
58
|
-
"Heap used percent vs heap_size_limit",
|
|
59
|
-
],
|
|
60
|
-
["memory.rss", "gauge", "Resident set size (bytes)"],
|
|
61
|
-
[
|
|
62
|
-
"memory.rss.usage_percent",
|
|
63
|
-
"gauge",
|
|
64
|
-
"RSS as percent of total system memory (RAM pressure signal)",
|
|
65
|
-
],
|
|
66
|
-
|
|
67
|
-
// Cache metrics
|
|
68
|
-
["cache.set", "counter", "Cache set operations"],
|
|
69
|
-
["cache.hit", "counter", "Cache hits"],
|
|
70
|
-
["cache.miss", "counter", "Cache misses"],
|
|
71
|
-
["cache.deleted", "counter", "Cache deletions"],
|
|
72
|
-
["cache.flushed", "counter", "Cache flushes"],
|
|
73
|
-
["cache.value.size", "histogram", "Cache value size (bytes)"],
|
|
74
|
-
["cache.get.latency", "histogram", "Cache get latency (ms)"],
|
|
75
|
-
["cache.hit.ratio", "gauge", "Cache hit ratio (hits / (hits + misses))"],
|
|
76
|
-
[
|
|
77
|
-
"cache.compression.ratio",
|
|
78
|
-
"histogram",
|
|
79
|
-
"Compression ratio (original / compressed)",
|
|
80
|
-
],
|
|
81
|
-
[
|
|
82
|
-
"cache.compression.bytes.saved",
|
|
83
|
-
"counter",
|
|
84
|
-
"Total bytes saved by compression",
|
|
85
|
-
],
|
|
86
|
-
[
|
|
87
|
-
"cache.topic.invalidation",
|
|
88
|
-
"counter",
|
|
89
|
-
"Cache entries invalidated by topic change",
|
|
90
|
-
],
|
|
91
|
-
[
|
|
92
|
-
"cache.memory.usage.bytes",
|
|
93
|
-
"gauge",
|
|
94
|
-
"Estimated cache memory usage (bytes)",
|
|
95
|
-
],
|
|
96
|
-
["cache.entries.count", "gauge", "Current number of cache entries"],
|
|
97
|
-
[
|
|
98
|
-
"topic.change.detected",
|
|
99
|
-
"counter",
|
|
100
|
-
"Detected conversation topic changes",
|
|
101
|
-
],
|
|
102
|
-
|
|
103
|
-
// Watchdog metrics
|
|
104
|
-
[
|
|
105
|
-
"watchdog.ram.status",
|
|
106
|
-
"gauge",
|
|
107
|
-
"Watchdog RAM status (0=ok, 1=warning, 2=critical)",
|
|
108
|
-
],
|
|
109
|
-
[
|
|
110
|
-
"watchdog.overall",
|
|
111
|
-
"gauge",
|
|
112
|
-
"Watchdog overall status (0=healthy, 1=degraded, 2=unhealthy)",
|
|
113
|
-
],
|
|
114
|
-
["watchdog.recovery.triggered", "counter", "Recovery attempts triggered"],
|
|
115
|
-
["watchdog.recovery.success", "counter", "Successful recoveries"],
|
|
116
|
-
["watchdog.recovery.failed", "counter", "Failed recoveries"],
|
|
117
|
-
];
|
|
118
|
-
|
|
119
|
-
for (const [name, type, help] of defaults) {
|
|
120
|
-
this.metrics.set(name, {
|
|
121
|
-
name,
|
|
122
|
-
type,
|
|
123
|
-
help,
|
|
124
|
-
values: new Map(),
|
|
125
|
-
histogramBuckets:
|
|
126
|
-
type === "histogram"
|
|
127
|
-
? [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000]
|
|
128
|
-
: undefined,
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
increment(
|
|
134
|
-
name: string,
|
|
135
|
-
value: number = 1,
|
|
136
|
-
labels?: Record<string, string>,
|
|
137
|
-
): void {
|
|
138
|
-
const metric = this.metrics.get(name);
|
|
139
|
-
if (!metric || metric.type !== "counter") return;
|
|
140
|
-
|
|
141
|
-
const key = labels ? JSON.stringify(labels) : "default";
|
|
142
|
-
// Mutate in place to avoid reallocating a MetricPoint on every increment.
|
|
143
|
-
const point = metric.values.get(key);
|
|
144
|
-
if (point) {
|
|
145
|
-
point.value += value;
|
|
146
|
-
point.timestamp = Date.now();
|
|
147
|
-
} else {
|
|
148
|
-
metric.values.set(key, { value, timestamp: Date.now(), labels });
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
gauge(name: string, value: number, labels?: Record<string, string>): void {
|
|
153
|
-
const metric = this.metrics.get(name);
|
|
154
|
-
if (!metric || metric.type !== "gauge") return;
|
|
155
|
-
|
|
156
|
-
const key = labels ? JSON.stringify(labels) : "default";
|
|
157
|
-
const point = metric.values.get(key);
|
|
158
|
-
if (point) {
|
|
159
|
-
point.value = value;
|
|
160
|
-
point.timestamp = Date.now();
|
|
161
|
-
} else {
|
|
162
|
-
metric.values.set(key, { value, timestamp: Date.now(), labels });
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
histogram(
|
|
167
|
-
name: string,
|
|
168
|
-
value: number,
|
|
169
|
-
labels?: Record<string, string>,
|
|
170
|
-
): void {
|
|
171
|
-
const metric = this.metrics.get(name);
|
|
172
|
-
if (!metric || metric.type !== "histogram") return;
|
|
173
|
-
|
|
174
|
-
const key = labels ? JSON.stringify(labels) : "default";
|
|
175
|
-
const existing = metric.values.get(key);
|
|
176
|
-
// Reuse the stored aggregate object instead of re-wrapping it each call.
|
|
177
|
-
let data: { count: number; sum: number; buckets: Map<number, number> };
|
|
178
|
-
if (existing && typeof existing.value === "object" && existing.value !== null) {
|
|
179
|
-
data = existing.value as { count: number; sum: number; buckets: Map<number, number> };
|
|
180
|
-
} else {
|
|
181
|
-
data = { count: 0, sum: 0, buckets: new Map<number, number>() };
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
data.count++;
|
|
185
|
-
data.sum += value;
|
|
186
|
-
const buckets = metric.histogramBuckets;
|
|
187
|
-
if (buckets) {
|
|
188
|
-
for (let i = 0; i < buckets.length; i++) {
|
|
189
|
-
const bucket = buckets[i];
|
|
190
|
-
if (value <= bucket) {
|
|
191
|
-
data.buckets.set(bucket, (data.buckets.get(bucket) || 0) + 1);
|
|
192
|
-
} else if (!data.buckets.has(bucket)) {
|
|
193
|
-
// Keep every bucket present for stable output, but skip redundant writes.
|
|
194
|
-
data.buckets.set(bucket, 0);
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
if (existing) {
|
|
200
|
-
existing.value = data as any;
|
|
201
|
-
existing.timestamp = Date.now();
|
|
202
|
-
} else {
|
|
203
|
-
metric.values.set(key, { value: data as any, timestamp: Date.now(), labels });
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
startCollection(): void {
|
|
208
|
-
if (this.collectionInterval) return;
|
|
209
|
-
|
|
210
|
-
this.collectionInterval = setInterval(() => {
|
|
211
|
-
this.collectSystemMetrics();
|
|
212
|
-
}, config.metrics.interval);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
private collectSystemMetrics(): void {
|
|
216
|
-
const heap = getHeapUsageSnapshot();
|
|
217
|
-
const rss = getRssUsageSnapshot();
|
|
218
|
-
this.gauge("memory.heap.used", heap.heapUsed);
|
|
219
|
-
this.gauge("memory.heap.total", heap.heapTotal);
|
|
220
|
-
this.gauge("memory.heap.limit", heap.heapSizeLimit);
|
|
221
|
-
this.gauge("memory.heap.usage_percent", heap.usagePercent);
|
|
222
|
-
this.gauge("memory.rss", heap.rss);
|
|
223
|
-
this.gauge("memory.rss.usage_percent", rss.usagePercent);
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
get(name: string, labels?: Record<string, string>): MetricPoint | null {
|
|
227
|
-
const metric = this.metrics.get(name);
|
|
228
|
-
if (!metric) return null;
|
|
229
|
-
const key = labels ? JSON.stringify(labels) : "default";
|
|
230
|
-
return metric.values.get(key) || null;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
formatPrometheus(): string {
|
|
234
|
-
let output = "";
|
|
235
|
-
for (const metric of this.metrics.values()) {
|
|
236
|
-
output += `# HELP ${metric.name} ${metric.help}\n`;
|
|
237
|
-
output += `# TYPE ${metric.name} ${metric.type}\n`;
|
|
238
|
-
|
|
239
|
-
for (const point of metric.values.values()) {
|
|
240
|
-
const labelPairs = point.labels
|
|
241
|
-
? Object.entries(point.labels).map(([k, v]) => `${k}="${v}"`)
|
|
242
|
-
: [];
|
|
243
|
-
const labelsStr = labelPairs.length ? `{${labelPairs.join(",")}}` : "";
|
|
244
|
-
|
|
245
|
-
if (
|
|
246
|
-
metric.type === "histogram" &&
|
|
247
|
-
typeof point.value === "object" &&
|
|
248
|
-
point.value !== null
|
|
249
|
-
) {
|
|
250
|
-
// Histogram points store a {count, sum, buckets} aggregate; emitting
|
|
251
|
-
// it raw produced "[object Object]" (invalid Prometheus exposition).
|
|
252
|
-
const data = point.value as {
|
|
253
|
-
count: number;
|
|
254
|
-
sum: number;
|
|
255
|
-
buckets: Map<number, number>;
|
|
256
|
-
};
|
|
257
|
-
const bucketPrefix = labelPairs.length
|
|
258
|
-
? `${labelPairs.join(",")},`
|
|
259
|
-
: "";
|
|
260
|
-
const sortedBuckets = [...data.buckets.keys()].sort((a, b) => a - b);
|
|
261
|
-
for (const bucket of sortedBuckets) {
|
|
262
|
-
output += `${metric.name}_bucket{${bucketPrefix}le="${bucket}"} ${data.buckets.get(bucket)} ${point.timestamp}\n`;
|
|
263
|
-
}
|
|
264
|
-
output += `${metric.name}_bucket{${bucketPrefix}le="+Inf"} ${data.count} ${point.timestamp}\n`;
|
|
265
|
-
output += `${metric.name}_sum${labelsStr} ${data.sum} ${point.timestamp}\n`;
|
|
266
|
-
output += `${metric.name}_count${labelsStr} ${data.count} ${point.timestamp}\n`;
|
|
267
|
-
continue;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
output += `${metric.name}${labelsStr} ${point.value} ${point.timestamp}\n`;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return output;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
reset(): void {
|
|
277
|
-
for (const metric of this.metrics.values()) {
|
|
278
|
-
metric.values.clear();
|
|
279
|
-
}
|
|
280
|
-
this.emit("reset", {});
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
stopCollection(): void {
|
|
284
|
-
if (this.collectionInterval) {
|
|
285
|
-
clearInterval(this.collectionInterval);
|
|
286
|
-
this.collectionInterval = null;
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
export const metrics = new Metrics();
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { config } from "./config.js";
|
|
3
|
+
import { getHeapUsageSnapshot, getRssUsageSnapshot } from "./memory-usage.js";
|
|
4
|
+
|
|
5
|
+
interface MetricPoint {
|
|
6
|
+
value: number;
|
|
7
|
+
timestamp: number;
|
|
8
|
+
labels?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
type MetricType = "counter" | "gauge" | "histogram" | "summary";
|
|
12
|
+
|
|
13
|
+
interface MetricDefinition {
|
|
14
|
+
name: string;
|
|
15
|
+
type: MetricType;
|
|
16
|
+
help: string;
|
|
17
|
+
values: Map<string, MetricPoint>;
|
|
18
|
+
histogramBuckets?: number[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class Metrics extends EventEmitter {
|
|
22
|
+
private metrics: Map<string, MetricDefinition> = new Map();
|
|
23
|
+
private collectionInterval: NodeJS.Timeout | null = null;
|
|
24
|
+
|
|
25
|
+
constructor() {
|
|
26
|
+
super();
|
|
27
|
+
this.registerDefaults();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private registerDefaults(): void {
|
|
31
|
+
const defaults: Array<[string, MetricType, string]> = [
|
|
32
|
+
// Core request metrics
|
|
33
|
+
["requests.total", "counter", "Total requests processed"],
|
|
34
|
+
["requests.errors", "counter", "Total request errors"],
|
|
35
|
+
["latency.request", "histogram", "Request latency (ms)"],
|
|
36
|
+
|
|
37
|
+
// Stream metrics
|
|
38
|
+
["streams.active", "gauge", "Active SSE streams"],
|
|
39
|
+
["streams.errors", "counter", "Stream errors"],
|
|
40
|
+
|
|
41
|
+
// CAPTCHA / anti-bot metrics
|
|
42
|
+
["captcha.challenges.detected", "counter", "Detected CAPTCHA challenges"],
|
|
43
|
+
["captcha.solves.succeeded", "counter", "Successful CAPTCHA solves"],
|
|
44
|
+
["captcha.solves.failed", "counter", "Failed CAPTCHA solves"],
|
|
45
|
+
["captcha.solve.duration", "histogram", "CAPTCHA solve duration (ms)"],
|
|
46
|
+
|
|
47
|
+
// Memory metrics
|
|
48
|
+
["memory.heap.used", "gauge", "Heap memory used (bytes)"],
|
|
49
|
+
["memory.heap.total", "gauge", "Heap memory total (bytes)"],
|
|
50
|
+
[
|
|
51
|
+
"memory.heap.limit",
|
|
52
|
+
"gauge",
|
|
53
|
+
"V8 heap_size_limit used for RAM pressure (bytes)",
|
|
54
|
+
],
|
|
55
|
+
[
|
|
56
|
+
"memory.heap.usage_percent",
|
|
57
|
+
"gauge",
|
|
58
|
+
"Heap used percent vs heap_size_limit",
|
|
59
|
+
],
|
|
60
|
+
["memory.rss", "gauge", "Resident set size (bytes)"],
|
|
61
|
+
[
|
|
62
|
+
"memory.rss.usage_percent",
|
|
63
|
+
"gauge",
|
|
64
|
+
"RSS as percent of total system memory (RAM pressure signal)",
|
|
65
|
+
],
|
|
66
|
+
|
|
67
|
+
// Cache metrics
|
|
68
|
+
["cache.set", "counter", "Cache set operations"],
|
|
69
|
+
["cache.hit", "counter", "Cache hits"],
|
|
70
|
+
["cache.miss", "counter", "Cache misses"],
|
|
71
|
+
["cache.deleted", "counter", "Cache deletions"],
|
|
72
|
+
["cache.flushed", "counter", "Cache flushes"],
|
|
73
|
+
["cache.value.size", "histogram", "Cache value size (bytes)"],
|
|
74
|
+
["cache.get.latency", "histogram", "Cache get latency (ms)"],
|
|
75
|
+
["cache.hit.ratio", "gauge", "Cache hit ratio (hits / (hits + misses))"],
|
|
76
|
+
[
|
|
77
|
+
"cache.compression.ratio",
|
|
78
|
+
"histogram",
|
|
79
|
+
"Compression ratio (original / compressed)",
|
|
80
|
+
],
|
|
81
|
+
[
|
|
82
|
+
"cache.compression.bytes.saved",
|
|
83
|
+
"counter",
|
|
84
|
+
"Total bytes saved by compression",
|
|
85
|
+
],
|
|
86
|
+
[
|
|
87
|
+
"cache.topic.invalidation",
|
|
88
|
+
"counter",
|
|
89
|
+
"Cache entries invalidated by topic change",
|
|
90
|
+
],
|
|
91
|
+
[
|
|
92
|
+
"cache.memory.usage.bytes",
|
|
93
|
+
"gauge",
|
|
94
|
+
"Estimated cache memory usage (bytes)",
|
|
95
|
+
],
|
|
96
|
+
["cache.entries.count", "gauge", "Current number of cache entries"],
|
|
97
|
+
[
|
|
98
|
+
"topic.change.detected",
|
|
99
|
+
"counter",
|
|
100
|
+
"Detected conversation topic changes",
|
|
101
|
+
],
|
|
102
|
+
|
|
103
|
+
// Watchdog metrics
|
|
104
|
+
[
|
|
105
|
+
"watchdog.ram.status",
|
|
106
|
+
"gauge",
|
|
107
|
+
"Watchdog RAM status (0=ok, 1=warning, 2=critical)",
|
|
108
|
+
],
|
|
109
|
+
[
|
|
110
|
+
"watchdog.overall",
|
|
111
|
+
"gauge",
|
|
112
|
+
"Watchdog overall status (0=healthy, 1=degraded, 2=unhealthy)",
|
|
113
|
+
],
|
|
114
|
+
["watchdog.recovery.triggered", "counter", "Recovery attempts triggered"],
|
|
115
|
+
["watchdog.recovery.success", "counter", "Successful recoveries"],
|
|
116
|
+
["watchdog.recovery.failed", "counter", "Failed recoveries"],
|
|
117
|
+
];
|
|
118
|
+
|
|
119
|
+
for (const [name, type, help] of defaults) {
|
|
120
|
+
this.metrics.set(name, {
|
|
121
|
+
name,
|
|
122
|
+
type,
|
|
123
|
+
help,
|
|
124
|
+
values: new Map(),
|
|
125
|
+
histogramBuckets:
|
|
126
|
+
type === "histogram"
|
|
127
|
+
? [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000]
|
|
128
|
+
: undefined,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
increment(
|
|
134
|
+
name: string,
|
|
135
|
+
value: number = 1,
|
|
136
|
+
labels?: Record<string, string>,
|
|
137
|
+
): void {
|
|
138
|
+
const metric = this.metrics.get(name);
|
|
139
|
+
if (!metric || metric.type !== "counter") return;
|
|
140
|
+
|
|
141
|
+
const key = labels ? JSON.stringify(labels) : "default";
|
|
142
|
+
// Mutate in place to avoid reallocating a MetricPoint on every increment.
|
|
143
|
+
const point = metric.values.get(key);
|
|
144
|
+
if (point) {
|
|
145
|
+
point.value += value;
|
|
146
|
+
point.timestamp = Date.now();
|
|
147
|
+
} else {
|
|
148
|
+
metric.values.set(key, { value, timestamp: Date.now(), labels });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
gauge(name: string, value: number, labels?: Record<string, string>): void {
|
|
153
|
+
const metric = this.metrics.get(name);
|
|
154
|
+
if (!metric || metric.type !== "gauge") return;
|
|
155
|
+
|
|
156
|
+
const key = labels ? JSON.stringify(labels) : "default";
|
|
157
|
+
const point = metric.values.get(key);
|
|
158
|
+
if (point) {
|
|
159
|
+
point.value = value;
|
|
160
|
+
point.timestamp = Date.now();
|
|
161
|
+
} else {
|
|
162
|
+
metric.values.set(key, { value, timestamp: Date.now(), labels });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
histogram(
|
|
167
|
+
name: string,
|
|
168
|
+
value: number,
|
|
169
|
+
labels?: Record<string, string>,
|
|
170
|
+
): void {
|
|
171
|
+
const metric = this.metrics.get(name);
|
|
172
|
+
if (!metric || metric.type !== "histogram") return;
|
|
173
|
+
|
|
174
|
+
const key = labels ? JSON.stringify(labels) : "default";
|
|
175
|
+
const existing = metric.values.get(key);
|
|
176
|
+
// Reuse the stored aggregate object instead of re-wrapping it each call.
|
|
177
|
+
let data: { count: number; sum: number; buckets: Map<number, number> };
|
|
178
|
+
if (existing && typeof existing.value === "object" && existing.value !== null) {
|
|
179
|
+
data = existing.value as { count: number; sum: number; buckets: Map<number, number> };
|
|
180
|
+
} else {
|
|
181
|
+
data = { count: 0, sum: 0, buckets: new Map<number, number>() };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
data.count++;
|
|
185
|
+
data.sum += value;
|
|
186
|
+
const buckets = metric.histogramBuckets;
|
|
187
|
+
if (buckets) {
|
|
188
|
+
for (let i = 0; i < buckets.length; i++) {
|
|
189
|
+
const bucket = buckets[i];
|
|
190
|
+
if (value <= bucket) {
|
|
191
|
+
data.buckets.set(bucket, (data.buckets.get(bucket) || 0) + 1);
|
|
192
|
+
} else if (!data.buckets.has(bucket)) {
|
|
193
|
+
// Keep every bucket present for stable output, but skip redundant writes.
|
|
194
|
+
data.buckets.set(bucket, 0);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (existing) {
|
|
200
|
+
existing.value = data as any;
|
|
201
|
+
existing.timestamp = Date.now();
|
|
202
|
+
} else {
|
|
203
|
+
metric.values.set(key, { value: data as any, timestamp: Date.now(), labels });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
startCollection(): void {
|
|
208
|
+
if (this.collectionInterval) return;
|
|
209
|
+
|
|
210
|
+
this.collectionInterval = setInterval(() => {
|
|
211
|
+
this.collectSystemMetrics();
|
|
212
|
+
}, config.metrics.interval);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private collectSystemMetrics(): void {
|
|
216
|
+
const heap = getHeapUsageSnapshot();
|
|
217
|
+
const rss = getRssUsageSnapshot();
|
|
218
|
+
this.gauge("memory.heap.used", heap.heapUsed);
|
|
219
|
+
this.gauge("memory.heap.total", heap.heapTotal);
|
|
220
|
+
this.gauge("memory.heap.limit", heap.heapSizeLimit);
|
|
221
|
+
this.gauge("memory.heap.usage_percent", heap.usagePercent);
|
|
222
|
+
this.gauge("memory.rss", heap.rss);
|
|
223
|
+
this.gauge("memory.rss.usage_percent", rss.usagePercent);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
get(name: string, labels?: Record<string, string>): MetricPoint | null {
|
|
227
|
+
const metric = this.metrics.get(name);
|
|
228
|
+
if (!metric) return null;
|
|
229
|
+
const key = labels ? JSON.stringify(labels) : "default";
|
|
230
|
+
return metric.values.get(key) || null;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
formatPrometheus(): string {
|
|
234
|
+
let output = "";
|
|
235
|
+
for (const metric of this.metrics.values()) {
|
|
236
|
+
output += `# HELP ${metric.name} ${metric.help}\n`;
|
|
237
|
+
output += `# TYPE ${metric.name} ${metric.type}\n`;
|
|
238
|
+
|
|
239
|
+
for (const point of metric.values.values()) {
|
|
240
|
+
const labelPairs = point.labels
|
|
241
|
+
? Object.entries(point.labels).map(([k, v]) => `${k}="${v}"`)
|
|
242
|
+
: [];
|
|
243
|
+
const labelsStr = labelPairs.length ? `{${labelPairs.join(",")}}` : "";
|
|
244
|
+
|
|
245
|
+
if (
|
|
246
|
+
metric.type === "histogram" &&
|
|
247
|
+
typeof point.value === "object" &&
|
|
248
|
+
point.value !== null
|
|
249
|
+
) {
|
|
250
|
+
// Histogram points store a {count, sum, buckets} aggregate; emitting
|
|
251
|
+
// it raw produced "[object Object]" (invalid Prometheus exposition).
|
|
252
|
+
const data = point.value as {
|
|
253
|
+
count: number;
|
|
254
|
+
sum: number;
|
|
255
|
+
buckets: Map<number, number>;
|
|
256
|
+
};
|
|
257
|
+
const bucketPrefix = labelPairs.length
|
|
258
|
+
? `${labelPairs.join(",")},`
|
|
259
|
+
: "";
|
|
260
|
+
const sortedBuckets = [...data.buckets.keys()].sort((a, b) => a - b);
|
|
261
|
+
for (const bucket of sortedBuckets) {
|
|
262
|
+
output += `${metric.name}_bucket{${bucketPrefix}le="${bucket}"} ${data.buckets.get(bucket)} ${point.timestamp}\n`;
|
|
263
|
+
}
|
|
264
|
+
output += `${metric.name}_bucket{${bucketPrefix}le="+Inf"} ${data.count} ${point.timestamp}\n`;
|
|
265
|
+
output += `${metric.name}_sum${labelsStr} ${data.sum} ${point.timestamp}\n`;
|
|
266
|
+
output += `${metric.name}_count${labelsStr} ${data.count} ${point.timestamp}\n`;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
output += `${metric.name}${labelsStr} ${point.value} ${point.timestamp}\n`;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return output;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
reset(): void {
|
|
277
|
+
for (const metric of this.metrics.values()) {
|
|
278
|
+
metric.values.clear();
|
|
279
|
+
}
|
|
280
|
+
this.emit("reset", {});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
stopCollection(): void {
|
|
284
|
+
if (this.collectionInterval) {
|
|
285
|
+
clearInterval(this.collectionInterval);
|
|
286
|
+
this.collectionInterval = null;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export const metrics = new Metrics();
|