dsh-nvidia-models-panel 1.3.22 → 1.3.24
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 +21 -21
- package/README.md +104 -104
- package/package.json +51 -51
- package/src/client.js +1261 -1222
- package/src/group.js +652 -652
- package/src/index.js +1253 -1253
- package/src/usage.js +285 -285
package/src/usage.js
CHANGED
|
@@ -1,285 +1,285 @@
|
|
|
1
|
-
// usage.js — process-level daily usage registry for the NVIDIA 模型组.
|
|
2
|
-
// Pure logic, zero dependencies, unit-testable. Records one entry per model
|
|
3
|
-
// attempt made by the failover engine so the panel can show, per day:
|
|
4
|
-
// • overall calls / success / failure / auto-failover count / tokens
|
|
5
|
-
// • per-model usage (calls, ok, fail, avg first-byte, tokens)
|
|
6
|
-
// • a rolling log of the most recent attempts (with failover provenance)
|
|
7
|
-
|
|
8
|
-
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
9
|
-
|
|
10
|
-
/** Format a timestamp as a local-day key `YYYY-MM-DD`. */
|
|
11
|
-
export function dayKeyOf(ts = Date.now()) {
|
|
12
|
-
const d = new Date(ts);
|
|
13
|
-
const y = d.getFullYear();
|
|
14
|
-
const m = String(d.getMonth() + 1).padStart(2, '0');
|
|
15
|
-
const day = String(d.getDate()).padStart(2, '0');
|
|
16
|
-
return `${y}-${m}-${day}`;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function emptyDay() {
|
|
20
|
-
return {
|
|
21
|
-
total: { calls: 0, ok: 0, fail: 0, failovers: 0, inputTokens: 0, outputTokens: 0 },
|
|
22
|
-
members: new Map(),
|
|
23
|
-
log: [],
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function emptyMember() {
|
|
28
|
-
return {
|
|
29
|
-
calls: 0,
|
|
30
|
-
ok: 0,
|
|
31
|
-
fail: 0,
|
|
32
|
-
failovers: 0,
|
|
33
|
-
inputTokens: 0,
|
|
34
|
-
outputTokens: 0,
|
|
35
|
-
lastAt: 0,
|
|
36
|
-
lastError: '',
|
|
37
|
-
sumFirstByteMs: 0,
|
|
38
|
-
firstByteSamples: 0,
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function num(value) {
|
|
43
|
-
const n = Number(value);
|
|
44
|
-
return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* @param {object} [opts]
|
|
49
|
-
* @param {() => number} [opts.now] clock (defaults to Date.now)
|
|
50
|
-
* @param {number} [opts.retentionDays] how many day buckets to keep (default 7)
|
|
51
|
-
* @param {number} [opts.maxLogPerDay] rolling log cap per day (default 200)
|
|
52
|
-
* @param {{load:()=>Promise<any>, save:(data:any)=>Promise<void>}} [opts.storage]
|
|
53
|
-
* optional persistence adapter. Without it the registry stays in-memory only.
|
|
54
|
-
*/
|
|
55
|
-
export function createUsageRegistry(opts = {}) {
|
|
56
|
-
const clock = typeof opts.now === 'function' ? opts.now : () => Date.now();
|
|
57
|
-
const retentionDays = Number.isFinite(opts.retentionDays) && opts.retentionDays > 0 ? opts.retentionDays : 7;
|
|
58
|
-
const maxLogPerDay =
|
|
59
|
-
Number.isFinite(opts.maxLogPerDay) && opts.maxLogPerDay > 0 ? Math.floor(opts.maxLogPerDay) : 200;
|
|
60
|
-
const storage = opts.storage && typeof opts.storage.load === 'function' && typeof opts.storage.save === 'function'
|
|
61
|
-
? opts.storage
|
|
62
|
-
: null;
|
|
63
|
-
|
|
64
|
-
/** @type {Map<string, ReturnType<typeof emptyDay>>} */
|
|
65
|
-
const days = new Map();
|
|
66
|
-
|
|
67
|
-
function dayFor(at) {
|
|
68
|
-
const key = dayKeyOf(at);
|
|
69
|
-
let day = days.get(key);
|
|
70
|
-
if (!day) {
|
|
71
|
-
day = emptyDay();
|
|
72
|
-
days.set(key, day);
|
|
73
|
-
}
|
|
74
|
-
return day;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// ---- persistence -------------------------------------------------------
|
|
78
|
-
// Serialise the whole registry (Map -> plain object) and write a full
|
|
79
|
-
// snapshot on every change. A serial write chain prevents overlapping
|
|
80
|
-
// writes from clobbering each other; failures are swallowed so persistence
|
|
81
|
-
// never breaks the hot failover path.
|
|
82
|
-
let writeChain = Promise.resolve();
|
|
83
|
-
|
|
84
|
-
function serialize() {
|
|
85
|
-
const out = {};
|
|
86
|
-
for (const [key, day] of days) {
|
|
87
|
-
out[key] = {
|
|
88
|
-
total: { ...day.total },
|
|
89
|
-
members: Object.fromEntries(day.members),
|
|
90
|
-
log: day.log.slice(),
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
return { version: 1, days: out };
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function deserialize(data) {
|
|
97
|
-
if (!data || typeof data !== 'object' || !data.days || typeof data.days !== 'object') return;
|
|
98
|
-
for (const [key, raw] of Object.entries(data.days)) {
|
|
99
|
-
if (typeof key !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(key) || !raw || typeof raw !== 'object') continue;
|
|
100
|
-
const day = emptyDay();
|
|
101
|
-
if (raw.total && typeof raw.total === 'object') {
|
|
102
|
-
const t = day.total;
|
|
103
|
-
for (const k of Object.keys(t)) t[k] = num(raw.total[k]);
|
|
104
|
-
}
|
|
105
|
-
if (raw.members && typeof raw.members === 'object') {
|
|
106
|
-
for (const [id, m] of Object.entries(raw.members)) {
|
|
107
|
-
if (!m || typeof m !== 'object') continue;
|
|
108
|
-
const clean = emptyMember();
|
|
109
|
-
for (const k of Object.keys(clean)) clean[k] = k === 'lastError' ? String(m[k] || '') : num(m[k]);
|
|
110
|
-
day.members.set(id, clean);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
if (Array.isArray(raw.log)) {
|
|
114
|
-
day.log = raw.log.slice(-maxLogPerDay).map((e) => ({
|
|
115
|
-
at: num(e && e.at),
|
|
116
|
-
memberId: String((e && e.memberId) || 'unknown'),
|
|
117
|
-
ok: !!(e && e.ok),
|
|
118
|
-
failover: !!(e && e.failover),
|
|
119
|
-
failoverFrom: String((e && e.failoverFrom) || ''),
|
|
120
|
-
firstByteMs: num(e && e.firstByteMs),
|
|
121
|
-
elapsedMs: num(e && e.elapsedMs),
|
|
122
|
-
inputTokens: num(e && e.inputTokens),
|
|
123
|
-
outputTokens: num(e && e.outputTokens),
|
|
124
|
-
error: String((e && e.error) || ''),
|
|
125
|
-
}));
|
|
126
|
-
}
|
|
127
|
-
days.set(key, day);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
function persist() {
|
|
132
|
-
if (!storage) return;
|
|
133
|
-
writeChain = writeChain.then(async () => {
|
|
134
|
-
try {
|
|
135
|
-
prune();
|
|
136
|
-
await storage.save(serialize());
|
|
137
|
-
} catch {
|
|
138
|
-
// Persistence is best-effort; in-memory stats remain authoritative.
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
/** Load a previously persisted snapshot into memory (best-effort). */
|
|
144
|
-
async function hydrate() {
|
|
145
|
-
if (!storage) return;
|
|
146
|
-
try {
|
|
147
|
-
const data = await storage.load();
|
|
148
|
-
if (data != null) deserialize(data);
|
|
149
|
-
prune();
|
|
150
|
-
} catch {
|
|
151
|
-
// Corrupt / missing storage: start fresh, never throw into apply().
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
function prune() {
|
|
156
|
-
const cutoff = clock() - retentionDays * DAY_MS;
|
|
157
|
-
for (const key of [...days.keys()]) {
|
|
158
|
-
// Parse the local-day key back to a timestamp; drop buckets older than retention.
|
|
159
|
-
const [y, m, d] = key.split('-').map((x) => Number(x));
|
|
160
|
-
const t = new Date(y, m - 1, d).getTime();
|
|
161
|
-
if (Number.isFinite(t) && t < cutoff) days.delete(key);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* Record one attempt (one member tried). Returns the stored log entry.
|
|
167
|
-
* @param {object} entry
|
|
168
|
-
* @param {number} [entry.at] timestamp (defaults to clock())
|
|
169
|
-
* @param {string} [entry.sessionId]
|
|
170
|
-
* @param {string} entry.memberId
|
|
171
|
-
* @param {boolean} entry.ok
|
|
172
|
-
* @param {boolean} [entry.failover] this attempt was reached via failover
|
|
173
|
-
* @param {string|number} [entry.failoverFrom] member we failed over from
|
|
174
|
-
* @param {number} [entry.firstByteMs]
|
|
175
|
-
* @param {number} [entry.elapsedMs]
|
|
176
|
-
* @param {number} [entry.inputTokens]
|
|
177
|
-
* @param {number} [entry.outputTokens]
|
|
178
|
-
* @param {string} [entry.error]
|
|
179
|
-
*/
|
|
180
|
-
function record(entry = {}) {
|
|
181
|
-
const at = Number.isFinite(entry.at) ? entry.at : clock();
|
|
182
|
-
const day = dayFor(at);
|
|
183
|
-
const memberId = String(entry.memberId || 'unknown');
|
|
184
|
-
const ok = !!entry.ok;
|
|
185
|
-
|
|
186
|
-
let m = day.members.get(memberId);
|
|
187
|
-
if (!m) {
|
|
188
|
-
m = emptyMember();
|
|
189
|
-
day.members.set(memberId, m);
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const inputTokens = num(entry.inputTokens);
|
|
193
|
-
const outputTokens = num(entry.outputTokens);
|
|
194
|
-
const firstByteMs = num(entry.firstByteMs);
|
|
195
|
-
|
|
196
|
-
day.total.calls += 1;
|
|
197
|
-
day.total.inputTokens += inputTokens;
|
|
198
|
-
day.total.outputTokens += outputTokens;
|
|
199
|
-
m.calls += 1;
|
|
200
|
-
m.inputTokens += inputTokens;
|
|
201
|
-
m.outputTokens += outputTokens;
|
|
202
|
-
m.lastAt = at;
|
|
203
|
-
if (ok) {
|
|
204
|
-
day.total.ok += 1;
|
|
205
|
-
m.ok += 1;
|
|
206
|
-
if (firstByteMs > 0) {
|
|
207
|
-
m.sumFirstByteMs += firstByteMs;
|
|
208
|
-
m.firstByteSamples += 1;
|
|
209
|
-
}
|
|
210
|
-
} else {
|
|
211
|
-
day.total.fail += 1;
|
|
212
|
-
m.fail += 1;
|
|
213
|
-
m.lastError = String(entry.error || '');
|
|
214
|
-
}
|
|
215
|
-
if (entry.failover) {
|
|
216
|
-
day.total.failovers += 1;
|
|
217
|
-
m.failovers += 1;
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const logEntry = {
|
|
221
|
-
at,
|
|
222
|
-
memberId,
|
|
223
|
-
ok,
|
|
224
|
-
failover: !!entry.failover,
|
|
225
|
-
failoverFrom: entry.failoverFrom != null ? String(entry.failoverFrom) : '',
|
|
226
|
-
firstByteMs,
|
|
227
|
-
elapsedMs: num(entry.elapsedMs),
|
|
228
|
-
inputTokens,
|
|
229
|
-
outputTokens,
|
|
230
|
-
error: String(entry.error || ''),
|
|
231
|
-
};
|
|
232
|
-
day.log.push(logEntry);
|
|
233
|
-
if (day.log.length > maxLogPerDay) {
|
|
234
|
-
day.log.splice(0, day.log.length - maxLogPerDay);
|
|
235
|
-
}
|
|
236
|
-
persist();
|
|
237
|
-
return logEntry;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** Return a plain, serialisable summary of one day (default today). */
|
|
241
|
-
function snapshot(dayKey) {
|
|
242
|
-
const key = dayKey || dayKeyOf(clock());
|
|
243
|
-
const day = days.get(key) || emptyDay();
|
|
244
|
-
const members = [];
|
|
245
|
-
for (const [id, m] of day.members) {
|
|
246
|
-
members.push({
|
|
247
|
-
id,
|
|
248
|
-
calls: m.calls,
|
|
249
|
-
ok: m.ok,
|
|
250
|
-
fail: m.fail,
|
|
251
|
-
failovers: m.failovers,
|
|
252
|
-
avgFirstByteMs: m.firstByteSamples > 0 ? Math.round(m.sumFirstByteMs / m.firstByteSamples) : 0,
|
|
253
|
-
inputTokens: m.inputTokens,
|
|
254
|
-
outputTokens: m.outputTokens,
|
|
255
|
-
lastAt: m.lastAt,
|
|
256
|
-
lastError: m.lastError,
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
members.sort((a, b) => b.calls - a.calls);
|
|
260
|
-
const log = day.log.slice().reverse();
|
|
261
|
-
return {
|
|
262
|
-
day: key,
|
|
263
|
-
total: { ...day.total },
|
|
264
|
-
members,
|
|
265
|
-
log,
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/** Wipe one day's stats, or everything when no dayKey is given. */
|
|
270
|
-
function reset(dayKey) {
|
|
271
|
-
if (dayKey) {
|
|
272
|
-
days.delete(dayKey);
|
|
273
|
-
} else {
|
|
274
|
-
days.clear();
|
|
275
|
-
}
|
|
276
|
-
persist();
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** List the day keys currently retained (newest last). */
|
|
280
|
-
function days_() {
|
|
281
|
-
return [...days.keys()].sort();
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
return { record, snapshot, reset, prune, days: days_, hydrate, serialize, deserialize };
|
|
285
|
-
}
|
|
1
|
+
// usage.js — process-level daily usage registry for the NVIDIA 模型组.
|
|
2
|
+
// Pure logic, zero dependencies, unit-testable. Records one entry per model
|
|
3
|
+
// attempt made by the failover engine so the panel can show, per day:
|
|
4
|
+
// • overall calls / success / failure / auto-failover count / tokens
|
|
5
|
+
// • per-model usage (calls, ok, fail, avg first-byte, tokens)
|
|
6
|
+
// • a rolling log of the most recent attempts (with failover provenance)
|
|
7
|
+
|
|
8
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
/** Format a timestamp as a local-day key `YYYY-MM-DD`. */
|
|
11
|
+
export function dayKeyOf(ts = Date.now()) {
|
|
12
|
+
const d = new Date(ts);
|
|
13
|
+
const y = d.getFullYear();
|
|
14
|
+
const m = String(d.getMonth() + 1).padStart(2, '0');
|
|
15
|
+
const day = String(d.getDate()).padStart(2, '0');
|
|
16
|
+
return `${y}-${m}-${day}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function emptyDay() {
|
|
20
|
+
return {
|
|
21
|
+
total: { calls: 0, ok: 0, fail: 0, failovers: 0, inputTokens: 0, outputTokens: 0 },
|
|
22
|
+
members: new Map(),
|
|
23
|
+
log: [],
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function emptyMember() {
|
|
28
|
+
return {
|
|
29
|
+
calls: 0,
|
|
30
|
+
ok: 0,
|
|
31
|
+
fail: 0,
|
|
32
|
+
failovers: 0,
|
|
33
|
+
inputTokens: 0,
|
|
34
|
+
outputTokens: 0,
|
|
35
|
+
lastAt: 0,
|
|
36
|
+
lastError: '',
|
|
37
|
+
sumFirstByteMs: 0,
|
|
38
|
+
firstByteSamples: 0,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function num(value) {
|
|
43
|
+
const n = Number(value);
|
|
44
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {object} [opts]
|
|
49
|
+
* @param {() => number} [opts.now] clock (defaults to Date.now)
|
|
50
|
+
* @param {number} [opts.retentionDays] how many day buckets to keep (default 7)
|
|
51
|
+
* @param {number} [opts.maxLogPerDay] rolling log cap per day (default 200)
|
|
52
|
+
* @param {{load:()=>Promise<any>, save:(data:any)=>Promise<void>}} [opts.storage]
|
|
53
|
+
* optional persistence adapter. Without it the registry stays in-memory only.
|
|
54
|
+
*/
|
|
55
|
+
export function createUsageRegistry(opts = {}) {
|
|
56
|
+
const clock = typeof opts.now === 'function' ? opts.now : () => Date.now();
|
|
57
|
+
const retentionDays = Number.isFinite(opts.retentionDays) && opts.retentionDays > 0 ? opts.retentionDays : 7;
|
|
58
|
+
const maxLogPerDay =
|
|
59
|
+
Number.isFinite(opts.maxLogPerDay) && opts.maxLogPerDay > 0 ? Math.floor(opts.maxLogPerDay) : 200;
|
|
60
|
+
const storage = opts.storage && typeof opts.storage.load === 'function' && typeof opts.storage.save === 'function'
|
|
61
|
+
? opts.storage
|
|
62
|
+
: null;
|
|
63
|
+
|
|
64
|
+
/** @type {Map<string, ReturnType<typeof emptyDay>>} */
|
|
65
|
+
const days = new Map();
|
|
66
|
+
|
|
67
|
+
function dayFor(at) {
|
|
68
|
+
const key = dayKeyOf(at);
|
|
69
|
+
let day = days.get(key);
|
|
70
|
+
if (!day) {
|
|
71
|
+
day = emptyDay();
|
|
72
|
+
days.set(key, day);
|
|
73
|
+
}
|
|
74
|
+
return day;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---- persistence -------------------------------------------------------
|
|
78
|
+
// Serialise the whole registry (Map -> plain object) and write a full
|
|
79
|
+
// snapshot on every change. A serial write chain prevents overlapping
|
|
80
|
+
// writes from clobbering each other; failures are swallowed so persistence
|
|
81
|
+
// never breaks the hot failover path.
|
|
82
|
+
let writeChain = Promise.resolve();
|
|
83
|
+
|
|
84
|
+
function serialize() {
|
|
85
|
+
const out = {};
|
|
86
|
+
for (const [key, day] of days) {
|
|
87
|
+
out[key] = {
|
|
88
|
+
total: { ...day.total },
|
|
89
|
+
members: Object.fromEntries(day.members),
|
|
90
|
+
log: day.log.slice(),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
return { version: 1, days: out };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function deserialize(data) {
|
|
97
|
+
if (!data || typeof data !== 'object' || !data.days || typeof data.days !== 'object') return;
|
|
98
|
+
for (const [key, raw] of Object.entries(data.days)) {
|
|
99
|
+
if (typeof key !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(key) || !raw || typeof raw !== 'object') continue;
|
|
100
|
+
const day = emptyDay();
|
|
101
|
+
if (raw.total && typeof raw.total === 'object') {
|
|
102
|
+
const t = day.total;
|
|
103
|
+
for (const k of Object.keys(t)) t[k] = num(raw.total[k]);
|
|
104
|
+
}
|
|
105
|
+
if (raw.members && typeof raw.members === 'object') {
|
|
106
|
+
for (const [id, m] of Object.entries(raw.members)) {
|
|
107
|
+
if (!m || typeof m !== 'object') continue;
|
|
108
|
+
const clean = emptyMember();
|
|
109
|
+
for (const k of Object.keys(clean)) clean[k] = k === 'lastError' ? String(m[k] || '') : num(m[k]);
|
|
110
|
+
day.members.set(id, clean);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (Array.isArray(raw.log)) {
|
|
114
|
+
day.log = raw.log.slice(-maxLogPerDay).map((e) => ({
|
|
115
|
+
at: num(e && e.at),
|
|
116
|
+
memberId: String((e && e.memberId) || 'unknown'),
|
|
117
|
+
ok: !!(e && e.ok),
|
|
118
|
+
failover: !!(e && e.failover),
|
|
119
|
+
failoverFrom: String((e && e.failoverFrom) || ''),
|
|
120
|
+
firstByteMs: num(e && e.firstByteMs),
|
|
121
|
+
elapsedMs: num(e && e.elapsedMs),
|
|
122
|
+
inputTokens: num(e && e.inputTokens),
|
|
123
|
+
outputTokens: num(e && e.outputTokens),
|
|
124
|
+
error: String((e && e.error) || ''),
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
days.set(key, day);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function persist() {
|
|
132
|
+
if (!storage) return;
|
|
133
|
+
writeChain = writeChain.then(async () => {
|
|
134
|
+
try {
|
|
135
|
+
prune();
|
|
136
|
+
await storage.save(serialize());
|
|
137
|
+
} catch {
|
|
138
|
+
// Persistence is best-effort; in-memory stats remain authoritative.
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Load a previously persisted snapshot into memory (best-effort). */
|
|
144
|
+
async function hydrate() {
|
|
145
|
+
if (!storage) return;
|
|
146
|
+
try {
|
|
147
|
+
const data = await storage.load();
|
|
148
|
+
if (data != null) deserialize(data);
|
|
149
|
+
prune();
|
|
150
|
+
} catch {
|
|
151
|
+
// Corrupt / missing storage: start fresh, never throw into apply().
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function prune() {
|
|
156
|
+
const cutoff = clock() - retentionDays * DAY_MS;
|
|
157
|
+
for (const key of [...days.keys()]) {
|
|
158
|
+
// Parse the local-day key back to a timestamp; drop buckets older than retention.
|
|
159
|
+
const [y, m, d] = key.split('-').map((x) => Number(x));
|
|
160
|
+
const t = new Date(y, m - 1, d).getTime();
|
|
161
|
+
if (Number.isFinite(t) && t < cutoff) days.delete(key);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Record one attempt (one member tried). Returns the stored log entry.
|
|
167
|
+
* @param {object} entry
|
|
168
|
+
* @param {number} [entry.at] timestamp (defaults to clock())
|
|
169
|
+
* @param {string} [entry.sessionId]
|
|
170
|
+
* @param {string} entry.memberId
|
|
171
|
+
* @param {boolean} entry.ok
|
|
172
|
+
* @param {boolean} [entry.failover] this attempt was reached via failover
|
|
173
|
+
* @param {string|number} [entry.failoverFrom] member we failed over from
|
|
174
|
+
* @param {number} [entry.firstByteMs]
|
|
175
|
+
* @param {number} [entry.elapsedMs]
|
|
176
|
+
* @param {number} [entry.inputTokens]
|
|
177
|
+
* @param {number} [entry.outputTokens]
|
|
178
|
+
* @param {string} [entry.error]
|
|
179
|
+
*/
|
|
180
|
+
function record(entry = {}) {
|
|
181
|
+
const at = Number.isFinite(entry.at) ? entry.at : clock();
|
|
182
|
+
const day = dayFor(at);
|
|
183
|
+
const memberId = String(entry.memberId || 'unknown');
|
|
184
|
+
const ok = !!entry.ok;
|
|
185
|
+
|
|
186
|
+
let m = day.members.get(memberId);
|
|
187
|
+
if (!m) {
|
|
188
|
+
m = emptyMember();
|
|
189
|
+
day.members.set(memberId, m);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const inputTokens = num(entry.inputTokens);
|
|
193
|
+
const outputTokens = num(entry.outputTokens);
|
|
194
|
+
const firstByteMs = num(entry.firstByteMs);
|
|
195
|
+
|
|
196
|
+
day.total.calls += 1;
|
|
197
|
+
day.total.inputTokens += inputTokens;
|
|
198
|
+
day.total.outputTokens += outputTokens;
|
|
199
|
+
m.calls += 1;
|
|
200
|
+
m.inputTokens += inputTokens;
|
|
201
|
+
m.outputTokens += outputTokens;
|
|
202
|
+
m.lastAt = at;
|
|
203
|
+
if (ok) {
|
|
204
|
+
day.total.ok += 1;
|
|
205
|
+
m.ok += 1;
|
|
206
|
+
if (firstByteMs > 0) {
|
|
207
|
+
m.sumFirstByteMs += firstByteMs;
|
|
208
|
+
m.firstByteSamples += 1;
|
|
209
|
+
}
|
|
210
|
+
} else {
|
|
211
|
+
day.total.fail += 1;
|
|
212
|
+
m.fail += 1;
|
|
213
|
+
m.lastError = String(entry.error || '');
|
|
214
|
+
}
|
|
215
|
+
if (entry.failover) {
|
|
216
|
+
day.total.failovers += 1;
|
|
217
|
+
m.failovers += 1;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const logEntry = {
|
|
221
|
+
at,
|
|
222
|
+
memberId,
|
|
223
|
+
ok,
|
|
224
|
+
failover: !!entry.failover,
|
|
225
|
+
failoverFrom: entry.failoverFrom != null ? String(entry.failoverFrom) : '',
|
|
226
|
+
firstByteMs,
|
|
227
|
+
elapsedMs: num(entry.elapsedMs),
|
|
228
|
+
inputTokens,
|
|
229
|
+
outputTokens,
|
|
230
|
+
error: String(entry.error || ''),
|
|
231
|
+
};
|
|
232
|
+
day.log.push(logEntry);
|
|
233
|
+
if (day.log.length > maxLogPerDay) {
|
|
234
|
+
day.log.splice(0, day.log.length - maxLogPerDay);
|
|
235
|
+
}
|
|
236
|
+
persist();
|
|
237
|
+
return logEntry;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Return a plain, serialisable summary of one day (default today). */
|
|
241
|
+
function snapshot(dayKey) {
|
|
242
|
+
const key = dayKey || dayKeyOf(clock());
|
|
243
|
+
const day = days.get(key) || emptyDay();
|
|
244
|
+
const members = [];
|
|
245
|
+
for (const [id, m] of day.members) {
|
|
246
|
+
members.push({
|
|
247
|
+
id,
|
|
248
|
+
calls: m.calls,
|
|
249
|
+
ok: m.ok,
|
|
250
|
+
fail: m.fail,
|
|
251
|
+
failovers: m.failovers,
|
|
252
|
+
avgFirstByteMs: m.firstByteSamples > 0 ? Math.round(m.sumFirstByteMs / m.firstByteSamples) : 0,
|
|
253
|
+
inputTokens: m.inputTokens,
|
|
254
|
+
outputTokens: m.outputTokens,
|
|
255
|
+
lastAt: m.lastAt,
|
|
256
|
+
lastError: m.lastError,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
members.sort((a, b) => b.calls - a.calls);
|
|
260
|
+
const log = day.log.slice().reverse();
|
|
261
|
+
return {
|
|
262
|
+
day: key,
|
|
263
|
+
total: { ...day.total },
|
|
264
|
+
members,
|
|
265
|
+
log,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Wipe one day's stats, or everything when no dayKey is given. */
|
|
270
|
+
function reset(dayKey) {
|
|
271
|
+
if (dayKey) {
|
|
272
|
+
days.delete(dayKey);
|
|
273
|
+
} else {
|
|
274
|
+
days.clear();
|
|
275
|
+
}
|
|
276
|
+
persist();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** List the day keys currently retained (newest last). */
|
|
280
|
+
function days_() {
|
|
281
|
+
return [...days.keys()].sort();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return { record, snapshot, reset, prune, days: days_, hydrate, serialize, deserialize };
|
|
285
|
+
}
|