- Add TelemetryTracker to record request fallback journeys, tracking step-by-step cascades across tiers, candidate error codes, cooldowns, and next actions - Add LiveWatcher for RAM-only interactive request inspection with 250-item FIFO safety cap and automatic memory flush on toggle off - Add REST and SSE streaming endpoints for real-time telemetry and live request logs - Upgrade Admin Telemetry tab with visual fallback breadcrumbs and live key health matrix - Add dedicated Live Logs tab with deep multi-tab inspector (Input, Output, Metadata, Debug), search, filters, and JSON export - Add unit and integration tests (test-live-watcher.ts, test-telemetry-fallback.ts)
175 lines
4.7 KiB
TypeScript
175 lines
4.7 KiB
TypeScript
import { Response } from 'express';
|
|
import { ProviderType } from './revolverTypes';
|
|
import { configStore } from './configStore';
|
|
|
|
export interface FallbackStep {
|
|
stepIndex: number;
|
|
timestamp: string;
|
|
tierIndex: number;
|
|
tierName: string;
|
|
providerId: string;
|
|
providerName: string;
|
|
providerType: ProviderType;
|
|
model: string;
|
|
keyIndex: number;
|
|
maskedKey: string;
|
|
durationMs: number;
|
|
status: 'success' | 'rate_limited' | 'server_error' | 'network_error' | 'timeout' | 'cancelled' | 'failed';
|
|
statusCode?: number | string;
|
|
errorMessage?: string;
|
|
rateLimitedUntil?: number | null;
|
|
cooldownSeconds?: number;
|
|
nextAction?: string;
|
|
}
|
|
|
|
export interface RequestFallbackJourney {
|
|
requestId: string;
|
|
timestamp: string;
|
|
requestedModel: string;
|
|
resolvedModelName: string;
|
|
resolvedModelId: string;
|
|
finalStatus: 'success_direct' | 'success_fallback' | 'all_tiers_exhausted' | 'cancelled';
|
|
totalDurationMs: number;
|
|
totalHops: number;
|
|
fallbackOccurred: boolean;
|
|
finalServedBy?: {
|
|
tierIndex: number;
|
|
tierName: string;
|
|
providerName: string;
|
|
providerType: ProviderType;
|
|
model: string;
|
|
maskedKey: string;
|
|
};
|
|
tokens?: {
|
|
promptTokens: number;
|
|
completionTokens: number;
|
|
totalTokens: number;
|
|
};
|
|
steps: FallbackStep[];
|
|
}
|
|
|
|
export interface KeyTelemetryItem {
|
|
providerId: string;
|
|
providerName: string;
|
|
providerType: ProviderType;
|
|
keyIndex: number;
|
|
maskedKey: string;
|
|
requestCount: number;
|
|
errorCount: number;
|
|
successCount: number;
|
|
successRatePercent: number;
|
|
isRateLimited: boolean;
|
|
cooldownRemainingSeconds: number;
|
|
lastUsed: string | null;
|
|
}
|
|
|
|
export class TelemetryTracker {
|
|
private recentJourneys: RequestFallbackJourney[] = [];
|
|
private maxJourneys: number = 100;
|
|
private sseClients: Set<Response> = new Set();
|
|
|
|
public recordJourney(journey: RequestFallbackJourney): void {
|
|
this.recentJourneys.unshift(journey);
|
|
if (this.recentJourneys.length > this.maxJourneys) {
|
|
this.recentJourneys.length = this.maxJourneys;
|
|
}
|
|
|
|
this.broadcast({
|
|
type: 'fallback_journey',
|
|
data: journey
|
|
});
|
|
}
|
|
|
|
public getRecentJourneys(limit = 50): RequestFallbackJourney[] {
|
|
return this.recentJourneys.slice(0, limit);
|
|
}
|
|
|
|
public getKeyTelemetry(): KeyTelemetryItem[] {
|
|
const providers = configStore.getProviders();
|
|
const now = Date.now();
|
|
const result: KeyTelemetryItem[] = [];
|
|
|
|
for (const p of providers) {
|
|
p.keys.forEach((k, idx) => {
|
|
const isRateLimited = !!(k.rateLimitedUntil && now < k.rateLimitedUntil);
|
|
const cooldownRemainingSeconds = isRateLimited && k.rateLimitedUntil
|
|
? Math.ceil((k.rateLimitedUntil - now) / 1000)
|
|
: 0;
|
|
const reqCount = k.requestCount || 0;
|
|
const errCount = k.errorCount || 0;
|
|
const successCount = Math.max(0, reqCount - errCount);
|
|
const successRatePercent = reqCount > 0
|
|
? Math.round((successCount / reqCount) * 100)
|
|
: 100;
|
|
|
|
result.push({
|
|
providerId: p.id,
|
|
providerName: p.name,
|
|
providerType: p.type,
|
|
keyIndex: idx,
|
|
maskedKey: configStore.maskKey(k.key),
|
|
requestCount: reqCount,
|
|
errorCount: errCount,
|
|
successCount,
|
|
successRatePercent,
|
|
isRateLimited,
|
|
cooldownRemainingSeconds,
|
|
lastUsed: k.lastUsed ? new Date(k.lastUsed).toISOString() : null
|
|
});
|
|
});
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
public subscribe(res: Response): void {
|
|
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
|
res.setHeader('Connection', 'keep-alive');
|
|
res.setHeader('X-Accel-Buffering', 'no');
|
|
if (typeof res.flushHeaders === 'function') {
|
|
res.flushHeaders();
|
|
}
|
|
|
|
// Send initial snapshot
|
|
const initialData = {
|
|
type: 'snapshot',
|
|
journeys: this.getRecentJourneys(20),
|
|
keys: this.getKeyTelemetry(),
|
|
timestamp: new Date().toISOString()
|
|
};
|
|
res.write(`data: ${JSON.stringify(initialData)}\n\n`);
|
|
|
|
this.sseClients.add(res);
|
|
|
|
res.on('close', () => {
|
|
this.sseClients.delete(res);
|
|
});
|
|
}
|
|
|
|
public broadcastKeyStatus(): void {
|
|
this.broadcast({
|
|
type: 'key_status_update',
|
|
keys: this.getKeyTelemetry(),
|
|
timestamp: new Date().toISOString()
|
|
});
|
|
}
|
|
|
|
private broadcast(payload: any): void {
|
|
if (this.sseClients.size === 0) return;
|
|
const message = `data: ${JSON.stringify(payload)}\n\n`;
|
|
for (const client of this.sseClients) {
|
|
if (!client.destroyed && !client.writableEnded) {
|
|
client.write(message);
|
|
} else {
|
|
this.sseClients.delete(client);
|
|
}
|
|
}
|
|
}
|
|
|
|
public clear(): void {
|
|
this.recentJourneys = [];
|
|
}
|
|
}
|
|
|
|
export const telemetryTracker = new TelemetryTracker();
|