feat(admin): add live key+model fallback telemetry and RAM-buffered live request log watcher
- 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)
This commit is contained in:
parent
0e83233715
commit
299c5f4c9e
11 changed files with 2603 additions and 71 deletions
|
|
@ -2,6 +2,8 @@ import { Router, Request, Response } from 'express';
|
|||
import { configStore } from './configStore';
|
||||
import { revolverEngine } from './revolverEngine';
|
||||
import { ProviderType } from './revolverTypes';
|
||||
import { liveWatcher } from './liveWatcher';
|
||||
import { telemetryTracker } from './telemetryTracker';
|
||||
|
||||
const router = Router();
|
||||
|
||||
|
|
@ -187,4 +189,54 @@ router.get('/keys-status', (req: Request, res: Response) => {
|
|||
res.json({ providers: status, timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// GET /api/admin/live-logs/state
|
||||
router.get('/live-logs/state', (req: Request, res: Response) => {
|
||||
res.json(liveWatcher.getState());
|
||||
});
|
||||
|
||||
// POST /api/admin/live-logs/toggle
|
||||
router.post('/live-logs/toggle', (req: Request, res: Response) => {
|
||||
const { enabled } = req.body;
|
||||
const result = liveWatcher.toggleWatcher(!!enabled);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
// POST /api/admin/live-logs/flush
|
||||
router.post('/live-logs/flush', (req: Request, res: Response) => {
|
||||
liveWatcher.flush();
|
||||
res.json({ success: true, message: 'Live request logs flushed from RAM.' });
|
||||
});
|
||||
|
||||
// GET /api/admin/live-logs/entries
|
||||
router.get('/live-logs/entries', (req: Request, res: Response) => {
|
||||
const status = req.query.status as string | undefined;
|
||||
const model = req.query.model as string | undefined;
|
||||
const search = req.query.search as string | undefined;
|
||||
const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 100;
|
||||
const entries = liveWatcher.getEntries({ status, model, search, limit });
|
||||
res.json({
|
||||
state: liveWatcher.getState(),
|
||||
entries
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/admin/live-logs/stream (SSE)
|
||||
router.get('/live-logs/stream', (req: Request, res: Response) => {
|
||||
liveWatcher.subscribe(res);
|
||||
});
|
||||
|
||||
// GET /api/admin/telemetry/fallback-traces
|
||||
router.get('/telemetry/fallback-traces', (req: Request, res: Response) => {
|
||||
const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 50;
|
||||
res.json({
|
||||
journeys: telemetryTracker.getRecentJourneys(limit),
|
||||
keys: telemetryTracker.getKeyTelemetry()
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/admin/telemetry/stream (SSE)
|
||||
router.get('/telemetry/stream', (req: Request, res: Response) => {
|
||||
telemetryTracker.subscribe(res);
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
|
|
|||
1247
src/adminView.ts
1247
src/adminView.ts
File diff suppressed because it is too large
Load diff
|
|
@ -20,8 +20,8 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti
|
|||
providedKey = (req.headers['x-api-key'] as string) || (req.headers['x-admin-key'] as string);
|
||||
}
|
||||
|
||||
if (!providedKey && req.query.api_key) {
|
||||
providedKey = req.query.api_key as string;
|
||||
if (!providedKey && (req.query.api_key || req.query.token || req.query.apiKey)) {
|
||||
providedKey = (req.query.api_key || req.query.token || req.query.apiKey) as string;
|
||||
}
|
||||
|
||||
if (!providedKey) {
|
||||
|
|
|
|||
486
src/liveWatcher.ts
Normal file
486
src/liveWatcher.ts
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
import { Response } from 'express';
|
||||
import { FallbackStep, RequestFallbackJourney } from './telemetryTracker';
|
||||
|
||||
export type LiveRequestStatus = 'streaming' | 'completed' | 'fallback_completed' | 'failed' | 'cancelled';
|
||||
|
||||
export interface LiveRequestInput {
|
||||
messages: any[];
|
||||
model?: string;
|
||||
requestedModel?: string;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
topP?: number;
|
||||
rawBody?: any;
|
||||
}
|
||||
|
||||
export interface LiveRequestOutput {
|
||||
completionText?: string;
|
||||
finishReason?: string;
|
||||
tokens?: {
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
totalTokens: number;
|
||||
};
|
||||
fullResponse?: any;
|
||||
error?: any;
|
||||
}
|
||||
|
||||
export interface LiveRequestMetadata {
|
||||
headers?: Record<string, any>;
|
||||
resolvedCustomModelId?: string;
|
||||
resolvedCustomModelName?: string;
|
||||
totalCandidatesAttempted: number;
|
||||
fallbackOccurred: boolean;
|
||||
servedBy?: {
|
||||
tierIndex: number;
|
||||
tierName: string;
|
||||
providerId: string;
|
||||
providerName: string;
|
||||
providerType: string;
|
||||
model: string;
|
||||
maskedKey: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface LiveRequestDebugEvent {
|
||||
time: string;
|
||||
message: string;
|
||||
level: 'info' | 'warn' | 'error';
|
||||
details?: any;
|
||||
}
|
||||
|
||||
export interface LiveRequestDebug {
|
||||
stepTraces: FallbackStep[];
|
||||
keepAlivePingsCount: number;
|
||||
nonStreamingWhitespaceCount: number;
|
||||
events: LiveRequestDebugEvent[];
|
||||
}
|
||||
|
||||
export interface LiveRequestLogEntry {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
startTime: number;
|
||||
endTime?: number;
|
||||
method: string;
|
||||
path: string;
|
||||
clientIp?: string;
|
||||
userAgent?: string;
|
||||
status: LiveRequestStatus;
|
||||
statusCode?: number;
|
||||
durationMs: number;
|
||||
isStreaming: boolean;
|
||||
input: LiveRequestInput;
|
||||
output: LiveRequestOutput;
|
||||
metadata: LiveRequestMetadata;
|
||||
debug: LiveRequestDebug;
|
||||
}
|
||||
|
||||
export class LiveWatcher {
|
||||
private isWatcherActive: boolean = false;
|
||||
private buffer: LiveRequestLogEntry[] = [];
|
||||
private maxCapacity: number = 250;
|
||||
private sseClients: Set<Response> = new Set();
|
||||
|
||||
public isActive(): boolean {
|
||||
return this.isWatcherActive;
|
||||
}
|
||||
|
||||
public toggleWatcher(enabled: boolean): { active: boolean; bufferCount: number } {
|
||||
this.isWatcherActive = enabled;
|
||||
if (!enabled) {
|
||||
// Flush memory immediately when toggled off
|
||||
this.flush();
|
||||
}
|
||||
|
||||
this.broadcast({
|
||||
type: 'watcher_status',
|
||||
data: {
|
||||
active: this.isWatcherActive,
|
||||
bufferCount: this.buffer.length,
|
||||
maxCapacity: this.maxCapacity
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
active: this.isWatcherActive,
|
||||
bufferCount: this.buffer.length
|
||||
};
|
||||
}
|
||||
|
||||
public flush(): void {
|
||||
// Purge in-memory buffer to release RAM
|
||||
this.buffer = [];
|
||||
this.broadcast({
|
||||
type: 'watcher_flushed',
|
||||
data: {
|
||||
bufferCount: 0
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public getState(): {
|
||||
active: boolean;
|
||||
bufferCount: number;
|
||||
maxCapacity: number;
|
||||
memoryEstimateKb: number;
|
||||
} {
|
||||
// Rough estimate of buffer memory size
|
||||
let approxBytes = 0;
|
||||
try {
|
||||
approxBytes = JSON.stringify(this.buffer).length * 2;
|
||||
} catch {
|
||||
approxBytes = this.buffer.length * 1024;
|
||||
}
|
||||
|
||||
return {
|
||||
active: this.isWatcherActive,
|
||||
bufferCount: this.buffer.length,
|
||||
maxCapacity: this.maxCapacity,
|
||||
memoryEstimateKb: Math.round(approxBytes / 1024)
|
||||
};
|
||||
}
|
||||
|
||||
public getEntries(params?: {
|
||||
status?: string;
|
||||
model?: string;
|
||||
search?: string;
|
||||
limit?: number;
|
||||
}): LiveRequestLogEntry[] {
|
||||
let result = [...this.buffer];
|
||||
|
||||
if (params?.status && params.status !== 'all') {
|
||||
result = result.filter(e => e.status === params.status);
|
||||
}
|
||||
|
||||
if (params?.model && params.model !== 'all') {
|
||||
result = result.filter(e => {
|
||||
const reqModel = e.input.requestedModel || e.input.model || '';
|
||||
const resModel = e.metadata.resolvedCustomModelName || '';
|
||||
return reqModel.toLowerCase() === params.model!.toLowerCase() || resModel.toLowerCase() === params.model!.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
if (params?.search && params.search.trim() !== '') {
|
||||
const q = params.search.toLowerCase().trim();
|
||||
result = result.filter(e => {
|
||||
if (e.id.toLowerCase().includes(q)) return true;
|
||||
if ((e.input.requestedModel || '').toLowerCase().includes(q)) return true;
|
||||
if ((e.output.completionText || '').toLowerCase().includes(q)) return true;
|
||||
// Search inside messages
|
||||
if (Array.isArray(e.input.messages)) {
|
||||
for (const m of e.input.messages) {
|
||||
const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content || '');
|
||||
if (content.toLowerCase().includes(q)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
const limit = params?.limit || 250;
|
||||
return result.slice(0, limit);
|
||||
}
|
||||
|
||||
public startRequest(params: {
|
||||
requestId: string;
|
||||
method: string;
|
||||
path: string;
|
||||
clientIp?: string;
|
||||
userAgent?: string;
|
||||
isStreaming: boolean;
|
||||
body: any;
|
||||
}): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
|
||||
const entry: LiveRequestLogEntry = {
|
||||
id: params.requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
startTime: Date.now(),
|
||||
method: params.method,
|
||||
path: params.path,
|
||||
clientIp: params.clientIp,
|
||||
userAgent: params.userAgent,
|
||||
status: params.isStreaming ? 'streaming' : 'completed', // non-streaming will update on finish
|
||||
durationMs: 0,
|
||||
isStreaming: params.isStreaming,
|
||||
input: {
|
||||
messages: params.body?.messages || [],
|
||||
model: params.body?.model,
|
||||
requestedModel: params.body?.model,
|
||||
temperature: params.body?.temperature,
|
||||
maxTokens: params.body?.max_tokens,
|
||||
topP: params.body?.top_p,
|
||||
rawBody: params.body
|
||||
},
|
||||
output: {
|
||||
completionText: ''
|
||||
},
|
||||
metadata: {
|
||||
totalCandidatesAttempted: 0,
|
||||
fallbackOccurred: false
|
||||
},
|
||||
debug: {
|
||||
stepTraces: [],
|
||||
keepAlivePingsCount: 0,
|
||||
nonStreamingWhitespaceCount: 0,
|
||||
events: [
|
||||
{
|
||||
time: new Date().toISOString(),
|
||||
message: `Request received: ${params.method} ${params.path}`,
|
||||
level: 'info',
|
||||
details: { isStreaming: params.isStreaming, model: params.body?.model }
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
// Prepend to buffer (newest first)
|
||||
this.buffer.unshift(entry);
|
||||
if (this.buffer.length > this.maxCapacity) {
|
||||
this.buffer.length = this.maxCapacity;
|
||||
}
|
||||
|
||||
this.broadcast({
|
||||
type: 'request_started',
|
||||
data: entry
|
||||
});
|
||||
}
|
||||
|
||||
public recordCandidateStep(requestId: string, step: FallbackStep): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
const entry = this.buffer.find(e => e.id === requestId);
|
||||
if (!entry) return;
|
||||
|
||||
entry.debug.stepTraces.push(step);
|
||||
entry.metadata.totalCandidatesAttempted = entry.debug.stepTraces.length;
|
||||
if (entry.debug.stepTraces.length > 1) {
|
||||
entry.metadata.fallbackOccurred = true;
|
||||
}
|
||||
|
||||
entry.debug.events.push({
|
||||
time: new Date().toISOString(),
|
||||
message: `Candidate attempted: Tier ${step.tierIndex} ('${step.tierName}') Provider: ${step.providerName} (${step.providerType}) Key: ${step.maskedKey} -> ${step.status}`,
|
||||
level: step.status === 'success' ? 'info' : 'warn',
|
||||
details: {
|
||||
durationMs: step.durationMs,
|
||||
error: step.errorMessage,
|
||||
nextAction: step.nextAction
|
||||
}
|
||||
});
|
||||
|
||||
this.broadcast({
|
||||
type: 'candidate_step',
|
||||
requestId,
|
||||
data: step
|
||||
});
|
||||
}
|
||||
|
||||
public recordKeepAlive(requestId: string, type: 'sse_comment' | 'whitespace'): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
const entry = this.buffer.find(e => e.id === requestId);
|
||||
if (!entry) return;
|
||||
|
||||
if (type === 'sse_comment') {
|
||||
entry.debug.keepAlivePingsCount++;
|
||||
} else {
|
||||
entry.debug.nonStreamingWhitespaceCount++;
|
||||
}
|
||||
}
|
||||
|
||||
public appendStreamChunk(requestId: string, chunkText: string): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
const entry = this.buffer.find(e => e.id === requestId);
|
||||
if (!entry) return;
|
||||
|
||||
entry.output.completionText = (entry.output.completionText || '') + chunkText;
|
||||
entry.durationMs = Date.now() - entry.startTime;
|
||||
|
||||
this.broadcast({
|
||||
type: 'stream_chunk',
|
||||
requestId,
|
||||
chunkText,
|
||||
totalLength: entry.output.completionText.length,
|
||||
durationMs: entry.durationMs
|
||||
});
|
||||
}
|
||||
|
||||
public completeRequest(params: {
|
||||
requestId: string;
|
||||
statusCode?: number;
|
||||
journey?: RequestFallbackJourney;
|
||||
responseData?: any;
|
||||
tokens?: { promptTokens: number; completionTokens: number; totalTokens: number };
|
||||
finishReason?: string;
|
||||
}): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
const entry = this.buffer.find(e => e.id === params.requestId);
|
||||
if (!entry) return;
|
||||
|
||||
entry.endTime = Date.now();
|
||||
entry.durationMs = entry.endTime - entry.startTime;
|
||||
entry.statusCode = params.statusCode || 200;
|
||||
|
||||
const hadFallback = (params.journey?.steps?.length || 0) > 1 || entry.debug.stepTraces.length > 1;
|
||||
entry.status = hadFallback ? 'fallback_completed' : 'completed';
|
||||
|
||||
if (params.journey) {
|
||||
entry.metadata.resolvedCustomModelId = params.journey.resolvedModelId;
|
||||
entry.metadata.resolvedCustomModelName = params.journey.resolvedModelName;
|
||||
entry.metadata.fallbackOccurred = params.journey.fallbackOccurred;
|
||||
entry.metadata.totalCandidatesAttempted = params.journey.totalHops;
|
||||
if (params.journey.finalServedBy) {
|
||||
entry.metadata.servedBy = {
|
||||
tierIndex: params.journey.finalServedBy.tierIndex,
|
||||
tierName: params.journey.finalServedBy.tierName,
|
||||
providerId: '',
|
||||
providerName: params.journey.finalServedBy.providerName,
|
||||
providerType: params.journey.finalServedBy.providerType,
|
||||
model: params.journey.finalServedBy.model,
|
||||
maskedKey: params.journey.finalServedBy.maskedKey
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (params.tokens) {
|
||||
entry.output.tokens = params.tokens;
|
||||
}
|
||||
|
||||
if (params.finishReason) {
|
||||
entry.output.finishReason = params.finishReason;
|
||||
}
|
||||
|
||||
if (params.responseData) {
|
||||
entry.output.fullResponse = params.responseData;
|
||||
if (!entry.output.completionText && params.responseData.choices?.[0]?.message?.content) {
|
||||
entry.output.completionText = params.responseData.choices[0].message.content;
|
||||
}
|
||||
if (!entry.output.finishReason && params.responseData.choices?.[0]?.finish_reason) {
|
||||
entry.output.finishReason = params.responseData.choices[0].finish_reason;
|
||||
}
|
||||
if (!entry.output.tokens && params.responseData.usage) {
|
||||
entry.output.tokens = {
|
||||
promptTokens: params.responseData.usage.prompt_tokens || 0,
|
||||
completionTokens: params.responseData.usage.completion_tokens || 0,
|
||||
totalTokens: params.responseData.usage.total_tokens || 0
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
entry.debug.events.push({
|
||||
time: new Date().toISOString(),
|
||||
message: `Request completed successfully in ${entry.durationMs}ms`,
|
||||
level: 'info',
|
||||
details: {
|
||||
tokens: entry.output.tokens,
|
||||
status: entry.status,
|
||||
servedBy: entry.metadata.servedBy
|
||||
}
|
||||
});
|
||||
|
||||
this.broadcast({
|
||||
type: 'request_completed',
|
||||
data: entry
|
||||
});
|
||||
}
|
||||
|
||||
public failRequest(params: {
|
||||
requestId: string;
|
||||
statusCode?: number;
|
||||
error: any;
|
||||
journey?: RequestFallbackJourney;
|
||||
}): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
const entry = this.buffer.find(e => e.id === params.requestId);
|
||||
if (!entry) return;
|
||||
|
||||
entry.endTime = Date.now();
|
||||
entry.durationMs = entry.endTime - entry.startTime;
|
||||
entry.status = 'failed';
|
||||
entry.statusCode = params.statusCode || 500;
|
||||
entry.output.error = {
|
||||
message: params.error?.message || String(params.error),
|
||||
code: params.error?.code,
|
||||
type: params.error?.type
|
||||
};
|
||||
|
||||
if (params.journey) {
|
||||
entry.metadata.resolvedCustomModelId = params.journey.resolvedModelId;
|
||||
entry.metadata.resolvedCustomModelName = params.journey.resolvedModelName;
|
||||
entry.metadata.fallbackOccurred = params.journey.fallbackOccurred;
|
||||
entry.metadata.totalCandidatesAttempted = params.journey.totalHops;
|
||||
}
|
||||
|
||||
entry.debug.events.push({
|
||||
time: new Date().toISOString(),
|
||||
message: `Request failed after ${entry.durationMs}ms: ${params.error?.message || params.error}`,
|
||||
level: 'error',
|
||||
details: params.error
|
||||
});
|
||||
|
||||
this.broadcast({
|
||||
type: 'request_failed',
|
||||
data: entry
|
||||
});
|
||||
}
|
||||
|
||||
public cancelRequest(requestId: string): void {
|
||||
if (!this.isWatcherActive) return;
|
||||
const entry = this.buffer.find(e => e.id === requestId);
|
||||
if (!entry) return;
|
||||
|
||||
entry.endTime = Date.now();
|
||||
entry.durationMs = entry.endTime - entry.startTime;
|
||||
entry.status = 'cancelled';
|
||||
entry.statusCode = 499;
|
||||
|
||||
entry.debug.events.push({
|
||||
time: new Date().toISOString(),
|
||||
message: 'Client closed connection before completion',
|
||||
level: 'warn'
|
||||
});
|
||||
|
||||
this.broadcast({
|
||||
type: 'request_cancelled',
|
||||
data: entry
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
// Initial message
|
||||
const snapshot = {
|
||||
type: 'snapshot',
|
||||
state: this.getState(),
|
||||
entries: this.buffer.slice(0, 50),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
res.write(`data: ${JSON.stringify(snapshot)}\n\n`);
|
||||
|
||||
this.sseClients.add(res);
|
||||
|
||||
res.on('close', () => {
|
||||
this.sseClients.delete(res);
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const liveWatcher = new LiveWatcher();
|
||||
|
|
@ -11,6 +11,8 @@ import {
|
|||
ExecutionDiagnosticTrace
|
||||
} from './revolverTypes';
|
||||
import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes';
|
||||
import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker';
|
||||
import { liveWatcher } from './liveWatcher';
|
||||
|
||||
interface CandidateExecution {
|
||||
tier: FallbackTier;
|
||||
|
|
@ -239,6 +241,7 @@ export class RevolverEngine {
|
|||
if (!res.writableEnded) {
|
||||
isCancelled = true;
|
||||
if (onCancelled) onCancelled();
|
||||
liveWatcher.cancelRequest(requestId);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -257,12 +260,14 @@ export class RevolverEngine {
|
|||
// Immediately transmit an initial SSE comment ping so Cloudflare Edge receives response bytes instantly
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(': keep-alive\n\n');
|
||||
liveWatcher.recordKeepAlive(requestId, 'sse_comment');
|
||||
}
|
||||
|
||||
// Keep connection active with periodic SSE comments while waiting for model thinking / generation
|
||||
keepAliveTimer = setInterval(() => {
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(': keep-alive\n\n');
|
||||
liveWatcher.recordKeepAlive(requestId, 'sse_comment');
|
||||
}
|
||||
}, config.keepAliveIntervalMs);
|
||||
} else if (config.enableNonStreamingKeepAlive) {
|
||||
|
|
@ -282,6 +287,7 @@ export class RevolverEngine {
|
|||
}
|
||||
}
|
||||
res.write(' ');
|
||||
liveWatcher.recordKeepAlive(requestId, 'whitespace');
|
||||
}, config.nonStreamingKeepAliveDelayMs);
|
||||
}
|
||||
|
||||
|
|
@ -292,6 +298,9 @@ export class RevolverEngine {
|
|||
throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`);
|
||||
}
|
||||
|
||||
const journeyStart = Date.now();
|
||||
const fallbackSteps: FallbackStep[] = [];
|
||||
let totalHops = 0;
|
||||
let lastError: any = null;
|
||||
|
||||
// Traverse tiers: Tier 0 -> Tier 1 -> Tier 2...
|
||||
|
|
@ -311,11 +320,16 @@ export class RevolverEngine {
|
|||
return;
|
||||
}
|
||||
|
||||
const candidateStart = Date.now();
|
||||
totalHops++;
|
||||
const isLastCandidateInTier = candidate === candidates[candidates.length - 1];
|
||||
const isLastTier = tier === sortedTiers[sortedTiers.length - 1];
|
||||
|
||||
try {
|
||||
console.log(`[REVOLVER] Routing to Provider '${candidate.provider.name}' (${candidate.provider.type}) with model '${candidate.target.model}' [Key ${candidate.keyIndex + 1}/${candidate.provider.keys.length}]`);
|
||||
|
||||
if (isStreaming) {
|
||||
await this.executeStreaming({
|
||||
const streamResult = await this.executeStreaming({
|
||||
candidate,
|
||||
requestBody,
|
||||
requestedModelName,
|
||||
|
|
@ -327,7 +341,64 @@ export class RevolverEngine {
|
|||
onSuccess
|
||||
});
|
||||
cleanupTimers();
|
||||
// If stream finished successfully, return
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const successStep: FallbackStep = {
|
||||
stepIndex: totalHops,
|
||||
timestamp: new Date().toISOString(),
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerId: candidate.provider.id,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
keyIndex: candidate.keyIndex,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: 'success',
|
||||
statusCode: 200,
|
||||
nextAction: 'Served successfully'
|
||||
};
|
||||
fallbackSteps.push(successStep);
|
||||
liveWatcher.recordCandidateStep(requestId, successStep);
|
||||
|
||||
const promptTokens = streamResult?.promptTokens || Math.ceil(JSON.stringify(requestBody.messages).length / 4);
|
||||
const completionTokens = streamResult?.completionTokens || 0;
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: fallbackSteps.length > 1,
|
||||
finalServedBy: {
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key)
|
||||
},
|
||||
tokens: {
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
totalTokens: promptTokens + completionTokens
|
||||
},
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.completeRequest({
|
||||
requestId,
|
||||
statusCode: 200,
|
||||
journey,
|
||||
tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
|
||||
finishReason: streamResult?.finishReason || 'stop'
|
||||
});
|
||||
|
||||
return;
|
||||
} else {
|
||||
const responseData = await this.executeNonStreaming({
|
||||
|
|
@ -346,12 +417,69 @@ export class RevolverEngine {
|
|||
rateLimitedUntil: null
|
||||
});
|
||||
|
||||
const promptTokens = responseData.usage?.prompt_tokens || 0;
|
||||
const completionTokens = responseData.usage?.completion_tokens || 0;
|
||||
|
||||
if (onSuccess) {
|
||||
const promptTokens = responseData.usage?.prompt_tokens || 0;
|
||||
const completionTokens = responseData.usage?.completion_tokens || 0;
|
||||
onSuccess({ input: promptTokens, output: completionTokens });
|
||||
}
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const successStep: FallbackStep = {
|
||||
stepIndex: totalHops,
|
||||
timestamp: new Date().toISOString(),
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerId: candidate.provider.id,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
keyIndex: candidate.keyIndex,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: 'success',
|
||||
statusCode: 200,
|
||||
nextAction: 'Served successfully'
|
||||
};
|
||||
fallbackSteps.push(successStep);
|
||||
liveWatcher.recordCandidateStep(requestId, successStep);
|
||||
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: fallbackSteps.length > 1,
|
||||
finalServedBy: {
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key)
|
||||
},
|
||||
tokens: {
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
totalTokens: promptTokens + completionTokens
|
||||
},
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.completeRequest({
|
||||
requestId,
|
||||
statusCode: 200,
|
||||
journey,
|
||||
responseData,
|
||||
tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
|
||||
finishReason: responseData.choices?.[0]?.finish_reason || 'stop'
|
||||
});
|
||||
|
||||
if (res.headersSent) {
|
||||
// Chunked keep-alive headers were already emitted
|
||||
res.write(JSON.stringify(responseData));
|
||||
|
|
@ -365,10 +493,67 @@ export class RevolverEngine {
|
|||
lastError = err;
|
||||
console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message);
|
||||
|
||||
const stepDuration = Date.now() - candidateStart;
|
||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||
const isServerErr = this.isServerError(err);
|
||||
const cooldown = isRateLimit ? config.rateLimitDurationMs : (isServerErr ? 15000 : undefined);
|
||||
const statusType = isRateLimit ? 'rate_limited' : (isServerErr ? 'server_error' : 'failed');
|
||||
|
||||
let nextAction = '';
|
||||
if (!isLastCandidateInTier) {
|
||||
nextAction = `Rotating to next key in Tier ${tier.tierIndex}`;
|
||||
} else if (!isLastTier) {
|
||||
nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${sortedTiers[sortedTiers.indexOf(tier) + 1]?.tierIndex ?? 'next'}`;
|
||||
} else {
|
||||
nextAction = 'All tiers and candidates exhausted';
|
||||
}
|
||||
|
||||
const failedStep: FallbackStep = {
|
||||
stepIndex: totalHops,
|
||||
timestamp: new Date().toISOString(),
|
||||
tierIndex: tier.tierIndex,
|
||||
tierName: tier.name || `Tier ${tier.tierIndex}`,
|
||||
providerId: candidate.provider.id,
|
||||
providerName: candidate.provider.name,
|
||||
providerType: candidate.provider.type,
|
||||
model: candidate.target.model,
|
||||
keyIndex: candidate.keyIndex,
|
||||
maskedKey: this.store.maskKey(candidate.keyConfig.key),
|
||||
durationMs: stepDuration,
|
||||
status: statusType,
|
||||
statusCode: err.status || (isRateLimit ? 429 : 500),
|
||||
errorMessage: err.message,
|
||||
rateLimitedUntil: cooldown ? Date.now() + cooldown : null,
|
||||
cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined,
|
||||
nextAction
|
||||
};
|
||||
fallbackSteps.push(failedStep);
|
||||
liveWatcher.recordCandidateStep(requestId, failedStep);
|
||||
|
||||
// If stream has already started sending content bytes to the client, we cannot fail over cleanly
|
||||
if (streamStarted) {
|
||||
cleanupTimers();
|
||||
if (onFailure) onFailure('stream_interrupted');
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: 'all_tiers_exhausted',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: true,
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.failRequest({
|
||||
requestId,
|
||||
statusCode: 500,
|
||||
error: err,
|
||||
journey
|
||||
});
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
error: {
|
||||
|
|
@ -384,14 +569,10 @@ export class RevolverEngine {
|
|||
}
|
||||
|
||||
// Mark key rate limited or increment error
|
||||
const isRateLimit = this.isRateLimitOrQuotaError(err);
|
||||
const isServerErr = this.isServerError(err);
|
||||
|
||||
if (isRateLimit || isServerErr) {
|
||||
const cooldown = isRateLimit ? config.rateLimitDurationMs : 15000;
|
||||
console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown / 1000}s`);
|
||||
console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown! / 1000}s`);
|
||||
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
|
||||
rateLimitedUntil: Date.now() + cooldown,
|
||||
rateLimitedUntil: Date.now() + cooldown!,
|
||||
incrementError: true
|
||||
});
|
||||
} else {
|
||||
|
|
@ -399,6 +580,7 @@ export class RevolverEngine {
|
|||
incrementError: true
|
||||
});
|
||||
}
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
|
||||
// Continue loop to try next candidate in this tier
|
||||
}
|
||||
|
|
@ -412,6 +594,27 @@ export class RevolverEngine {
|
|||
if (onFailure) onFailure('all_tiers_exhausted');
|
||||
const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.';
|
||||
|
||||
const journey: RequestFallbackJourney = {
|
||||
requestId,
|
||||
timestamp: new Date().toISOString(),
|
||||
requestedModel: requestBody.model || requestedModelName,
|
||||
resolvedModelName: customModel.name,
|
||||
resolvedModelId: customModel.id,
|
||||
finalStatus: 'all_tiers_exhausted',
|
||||
totalDurationMs: Date.now() - journeyStart,
|
||||
totalHops,
|
||||
fallbackOccurred: true,
|
||||
steps: fallbackSteps
|
||||
};
|
||||
telemetryTracker.recordJourney(journey);
|
||||
telemetryTracker.broadcastKeyStatus();
|
||||
liveWatcher.failRequest({
|
||||
requestId,
|
||||
statusCode: 503,
|
||||
error: lastError || new Error(finalErrorMessage),
|
||||
journey
|
||||
});
|
||||
|
||||
if (isStreaming) {
|
||||
if (!res.destroyed && !res.writableEnded) {
|
||||
res.write(`data: ${JSON.stringify({
|
||||
|
|
@ -588,7 +791,7 @@ export class RevolverEngine {
|
|||
res: Response;
|
||||
onStreamStart: () => void;
|
||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
||||
}): Promise<void> {
|
||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
||||
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||
|
||||
if (candidate.provider.type === 'gemini') {
|
||||
|
|
@ -622,7 +825,7 @@ export class RevolverEngine {
|
|||
res: Response;
|
||||
onStreamStart: () => void;
|
||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
||||
}): Promise<void> {
|
||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
||||
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||
const genAI = this.getGeminiClient(candidate.keyConfig.key);
|
||||
|
||||
|
|
@ -669,6 +872,7 @@ export class RevolverEngine {
|
|||
if (res.destroyed) break;
|
||||
const text = chunk.text();
|
||||
fullContent += text;
|
||||
liveWatcher.appendStreamChunk(requestId, text);
|
||||
onStreamStart();
|
||||
|
||||
const chunkResponse = {
|
||||
|
|
@ -727,6 +931,12 @@ export class RevolverEngine {
|
|||
if (onSuccess) {
|
||||
onSuccess({ input: promptTokens, output: completionTokens });
|
||||
}
|
||||
|
||||
return {
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
finishReason: 'stop'
|
||||
};
|
||||
}
|
||||
|
||||
private async executeOpenAICompatibleStreaming(params: {
|
||||
|
|
@ -737,7 +947,7 @@ export class RevolverEngine {
|
|||
res: Response;
|
||||
onStreamStart: () => void;
|
||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
||||
}): Promise<void> {
|
||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
||||
const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||
|
||||
const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, '');
|
||||
|
|
@ -822,7 +1032,9 @@ export class RevolverEngine {
|
|||
parsed.model = requestedModelName;
|
||||
if (parsed.choices?.[0]?.delta?.content) {
|
||||
onStreamStart();
|
||||
totalOutputChars += parsed.choices[0].delta.content.length;
|
||||
const delta = parsed.choices[0].delta.content;
|
||||
totalOutputChars += delta.length;
|
||||
liveWatcher.appendStreamChunk(requestId, delta);
|
||||
}
|
||||
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
||||
} catch {
|
||||
|
|
@ -850,6 +1062,12 @@ export class RevolverEngine {
|
|||
if (onSuccess) {
|
||||
onSuccess({ input: estimatedInput, output: estimatedOutput });
|
||||
}
|
||||
|
||||
return {
|
||||
promptTokens: estimatedInput,
|
||||
completionTokens: estimatedOutput,
|
||||
finishReason: 'stop'
|
||||
};
|
||||
}
|
||||
|
||||
// Diagnostic Test Prompt Runner for the Admin Playground
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { revolverEngine } from './revolverEngine';
|
|||
import { authenticateApiKey } from './auth';
|
||||
import adminRoutes from './adminRoutes';
|
||||
import { renderAdminHtml } from './adminView';
|
||||
import { liveWatcher } from './liveWatcher';
|
||||
import {
|
||||
OpenAIChatRequest,
|
||||
OpenAIModelsResponse
|
||||
|
|
@ -44,9 +45,24 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
|||
body: body
|
||||
});
|
||||
|
||||
liveWatcher.startRequest({
|
||||
requestId,
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
clientIp: (req.headers['x-forwarded-for'] as string) || req.ip || req.socket.remoteAddress,
|
||||
userAgent: req.get('user-agent'),
|
||||
isStreaming: !!body?.stream,
|
||||
body
|
||||
});
|
||||
|
||||
// Validate request
|
||||
if (!body.messages || !Array.isArray(body.messages)) {
|
||||
requestTracker.recordFailure('invalid_messages');
|
||||
liveWatcher.failRequest({
|
||||
requestId,
|
||||
statusCode: 400,
|
||||
error: new Error('Invalid or missing messages array')
|
||||
});
|
||||
res.status(400).json({
|
||||
error: {
|
||||
message: 'Invalid or missing messages array',
|
||||
|
|
@ -88,6 +104,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
|||
if (!isFinished) {
|
||||
isFinished = true;
|
||||
requestTracker.recordCancelled();
|
||||
liveWatcher.cancelRequest(requestId);
|
||||
requestLogger.logError(requestId, {
|
||||
message: 'Client cancelled request',
|
||||
path: req.path
|
||||
|
|
@ -100,6 +117,11 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
|||
if (!isFinished) {
|
||||
isFinished = true;
|
||||
requestTracker.recordFailure(error.message);
|
||||
liveWatcher.failRequest({
|
||||
requestId,
|
||||
statusCode: error.status || 500,
|
||||
error
|
||||
});
|
||||
}
|
||||
|
||||
console.error('[ERROR] Error in chat completion:', {
|
||||
|
|
|
|||
175
src/telemetryTracker.ts
Normal file
175
src/telemetryTracker.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
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();
|
||||
Loading…
Add table
Add a link
Reference in a new issue