import fs from 'fs'; import path from 'path'; import { config } from './config'; import { configStore } from './configStore'; export interface StatsData { totalRequests: number; wentThrough: number; failed: number; cancelled: number; inputTokens: number; outputTokens: number; totalTokens: number; firstRequestAt: string | null; lastRequestAt: string | null; } export interface StatsSummary { requests: { total: number; wentThrough: number; failed: number; cancelled: number; successRate: number; }; tokens: { total: number; input: number; output: number; }; activeRequests: number; uptimeSeconds: number; uptimeFormatted: string; startedAt: string; lastRequestAt: string | null; server: { model: string; configuredKeysCount: number; }; } export interface RequestTracker { recordSuccess: (tokens: { input: number; output: number }) => void; recordFailure: (reason?: string) => void; recordCancelled: (tokens?: { input: number; output: number }) => void; } export function estimateTokens(text: string): number { if (!text) return 0; // Approximation: ~4 characters per token for typical text/code return Math.max(1, Math.ceil(text.length / 4)); } export function estimateMessagesTokens(messages: any[]): number { if (!Array.isArray(messages) || messages.length === 0) return 0; const fullText = messages .map(m => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content || ''))) .join('\n'); return estimateTokens(fullText); } export class StatsTracker { private stats: StatsData = { totalRequests: 0, wentThrough: 0, failed: 0, cancelled: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0, firstRequestAt: null, lastRequestAt: null }; private activeRequests: number = 0; private serverStartedAt: Date = new Date(); private statsFilePath: string; private saveTimeout: NodeJS.Timeout | null = null; constructor() { this.statsFilePath = path.join(config.logDir, 'stats.json'); this.ensureLogDir(); this.loadStats(); // Ensure save on process termination process.on('SIGINT', () => this.saveSync()); process.on('SIGTERM', () => this.saveSync()); } private ensureLogDir(): void { if (!fs.existsSync(config.logDir)) { try { fs.mkdirSync(config.logDir, { recursive: true }); } catch (err) { console.error('[STATS] Failed to create log directory:', err); } } } private loadStats(): void { try { if (fs.existsSync(this.statsFilePath)) { const raw = fs.readFileSync(this.statsFilePath, 'utf8'); const parsed = JSON.parse(raw); this.stats = { totalRequests: Number(parsed.totalRequests) || 0, wentThrough: Number(parsed.wentThrough) || 0, failed: Number(parsed.failed) || 0, cancelled: Number(parsed.cancelled) || 0, inputTokens: Number(parsed.inputTokens) || 0, outputTokens: Number(parsed.outputTokens) || 0, totalTokens: Number(parsed.totalTokens) || 0, firstRequestAt: parsed.firstRequestAt || null, lastRequestAt: parsed.lastRequestAt || null }; // Sanity check total calculation if (this.stats.totalRequests < (this.stats.wentThrough + this.stats.failed + this.stats.cancelled)) { this.stats.totalRequests = this.stats.wentThrough + this.stats.failed + this.stats.cancelled; } if (this.stats.totalTokens < (this.stats.inputTokens + this.stats.outputTokens)) { this.stats.totalTokens = this.stats.inputTokens + this.stats.outputTokens; } console.log('[STATS] Loaded existing stats from disk:', { requests: this.stats.totalRequests, tokens: this.stats.totalTokens }); return; } // If stats.json does not exist, check if there are historical log files this.rebuildFromExistingLogs(); } catch (err) { console.error('[STATS] Error loading stats file, initializing fresh stats:', err); } } private rebuildFromExistingLogs(): void { try { if (!fs.existsSync(config.logDir)) return; const files = fs.readdirSync(config.logDir).filter(f => f.startsWith('api-logs-') && f.endsWith('.json')); if (files.length === 0) return; console.log(`[STATS] Scanning ${files.length} existing log file(s) to aggregate initial stats...`); for (const file of files) { const filePath = path.join(config.logDir, file); const content = fs.readFileSync(filePath, 'utf8'); const lines = content.split('\n'); for (const line of lines) { if (!line.trim()) continue; try { const entry = JSON.parse(line); if (entry.type === 'response') { const status = entry.data?.statusCode || 200; if (status >= 200 && status < 400) { this.stats.wentThrough++; const usage = entry.data?.response?.usage; if (usage) { this.stats.inputTokens += Number(usage.prompt_tokens) || 0; this.stats.outputTokens += Number(usage.completion_tokens) || 0; } } else { this.stats.failed++; } if (!this.stats.firstRequestAt || entry.timestamp < this.stats.firstRequestAt) { this.stats.firstRequestAt = entry.timestamp; } if (!this.stats.lastRequestAt || entry.timestamp > this.stats.lastRequestAt) { this.stats.lastRequestAt = entry.timestamp; } } else if (entry.type === 'error') { this.stats.failed++; if (!this.stats.lastRequestAt || entry.timestamp > this.stats.lastRequestAt) { this.stats.lastRequestAt = entry.timestamp; } } } catch { // ignore malformed line } } } this.stats.totalRequests = this.stats.wentThrough + this.stats.failed + this.stats.cancelled; this.stats.totalTokens = this.stats.inputTokens + this.stats.outputTokens; this.saveSync(); console.log('[STATS] Rebuilt historical stats successfully:', { requests: this.stats.totalRequests, tokens: this.stats.totalTokens }); } catch (err) { console.error('[STATS] Error scanning historical logs:', err); } } private scheduleSave(): void { if (this.saveTimeout) return; this.saveTimeout = setTimeout(() => { this.saveTimeout = null; this.saveSync(); }, 1000); } public saveSync(): void { try { this.ensureLogDir(); const tmpPath = `${this.statsFilePath}.tmp`; fs.writeFileSync(tmpPath, JSON.stringify(this.stats, null, 2), 'utf8'); fs.renameSync(tmpPath, this.statsFilePath); } catch (err) { console.error('[STATS] Error saving stats to file:', err); } } private updateTimestamps(): void { const now = new Date().toISOString(); if (!this.stats.firstRequestAt) { this.stats.firstRequestAt = now; } this.stats.lastRequestAt = now; } public startRequest(endpoint?: string): RequestTracker { this.activeRequests++; let resolved = false; return { recordSuccess: (tokens: { input: number; output: number }) => { if (resolved) return; resolved = true; this.activeRequests = Math.max(0, this.activeRequests - 1); this.stats.totalRequests++; this.stats.wentThrough++; const safeInput = Math.max(0, Math.round(tokens.input || 0)); const safeOutput = Math.max(0, Math.round(tokens.output || 0)); this.stats.inputTokens += safeInput; this.stats.outputTokens += safeOutput; this.stats.totalTokens += safeInput + safeOutput; this.updateTimestamps(); this.scheduleSave(); }, recordFailure: (_reason?: string) => { if (resolved) return; resolved = true; this.activeRequests = Math.max(0, this.activeRequests - 1); this.stats.totalRequests++; this.stats.failed++; this.updateTimestamps(); this.scheduleSave(); }, recordCancelled: (tokens?: { input: number; output: number }) => { if (resolved) return; resolved = true; this.activeRequests = Math.max(0, this.activeRequests - 1); this.stats.totalRequests++; this.stats.cancelled++; if (tokens) { const safeInput = Math.max(0, Math.round(tokens.input || 0)); const safeOutput = Math.max(0, Math.round(tokens.output || 0)); this.stats.inputTokens += safeInput; this.stats.outputTokens += safeOutput; this.stats.totalTokens += safeInput + safeOutput; } this.updateTimestamps(); this.scheduleSave(); } }; } public recordDirectSuccess(tokens: { input: number; output: number }, _endpoint?: string): void { this.stats.totalRequests++; this.stats.wentThrough++; const safeInput = Math.max(0, Math.round(tokens.input || 0)); const safeOutput = Math.max(0, Math.round(tokens.output || 0)); this.stats.inputTokens += safeInput; this.stats.outputTokens += safeOutput; this.stats.totalTokens += safeInput + safeOutput; this.updateTimestamps(); this.scheduleSave(); } public recordDirectFailure(_reason?: string, _endpoint?: string): void { this.stats.totalRequests++; this.stats.failed++; this.updateTimestamps(); this.scheduleSave(); } public recordDirectCancelled(tokens?: { input: number; output: number }, _endpoint?: string): void { this.stats.totalRequests++; this.stats.cancelled++; if (tokens) { const safeInput = Math.max(0, Math.round(tokens.input || 0)); const safeOutput = Math.max(0, Math.round(tokens.output || 0)); this.stats.inputTokens += safeInput; this.stats.outputTokens += safeOutput; this.stats.totalTokens += safeInput + safeOutput; } this.updateTimestamps(); this.scheduleSave(); } public getStatsSummary(): StatsSummary { const total = this.stats.totalRequests; const wentThrough = this.stats.wentThrough; const failed = this.stats.failed; const cancelled = this.stats.cancelled; const successRate = total > 0 ? Number(((wentThrough / total) * 100).toFixed(1)) : 100.0; const uptimeSeconds = Math.floor((Date.now() - this.serverStartedAt.getTime()) / 1000); const uptimeFormatted = this.formatUptime(uptimeSeconds); const providers = configStore.getProviders(); const totalKeys = providers.reduce((sum, p) => sum + p.keys.length, 0); const keysCount = totalKeys > 0 ? totalKeys : config.geminiApiKeys.length; const activeModel = configStore.getDefaultModel()?.name || config.model; return { requests: { total, wentThrough, failed, cancelled, successRate }, tokens: { total: this.stats.totalTokens, input: this.stats.inputTokens, output: this.stats.outputTokens }, activeRequests: this.activeRequests, uptimeSeconds, uptimeFormatted, startedAt: this.serverStartedAt.toISOString(), lastRequestAt: this.stats.lastRequestAt, server: { model: activeModel, configuredKeysCount: keysCount } }; } private formatUptime(seconds: number): string { const d = Math.floor(seconds / 86400); const h = Math.floor((seconds % 86400) / 3600); const m = Math.floor((seconds % 3600) / 60); const s = seconds % 60; if (d > 0) return `${d}d ${h}h ${m}m`; if (h > 0) return `${h}h ${m}m ${s}s`; if (m > 0) return `${m}m ${s}s`; return `${s}s`; } public renderStatsHtml(summary: StatsSummary): string { const { requests, tokens, activeRequests, uptimeFormatted, lastRequestAt, server } = summary; const wentThroughPct = requests.total > 0 ? ((requests.wentThrough / requests.total) * 100).toFixed(1) : '100.0'; const failedPct = requests.total > 0 ? ((requests.failed / requests.total) * 100).toFixed(1) : '0.0'; const cancelledPct = requests.total > 0 ? ((requests.cancelled / requests.total) * 100).toFixed(1) : '0.0'; const inputTokensPct = tokens.total > 0 ? ((tokens.input / tokens.total) * 100).toFixed(1) : '50.0'; const outputTokensPct = tokens.total > 0 ? ((tokens.output / tokens.total) * 100).toFixed(1) : '50.0'; return ` GeminiRevolver — API Telemetry & Statistics

GeminiRevolver

OpenAI v1 Compatible Gemini Key Rotation Gateway

Model: ${server.model}
Key Pool: ${server.configuredKeysCount} Keys Rotating
Uptime: ${uptimeFormatted}
Total Requests
${requests.total.toLocaleString()}
${requests.wentThrough.toLocaleString()} ok • ${requests.failed.toLocaleString()} err • ${requests.cancelled.toLocaleString()} drop
Success Rate
${requests.successRate}%
Completed vs total incoming calls
Total Tokens
${tokens.total.toLocaleString()}
In: ${tokens.input.toLocaleString()} • Out: ${tokens.output.toLocaleString()}
Active In-Flight
${activeRequests}
${activeRequests === 0 ? 'Idle • Ready for requests' : 'Processing active completions'}
Request Breakdown
${requests.total.toLocaleString()} total
Went Through (Completed)
${requests.wentThrough.toLocaleString()} ${wentThroughPct}%
Failed (Error / Rate Limit)
${requests.failed.toLocaleString()} ${failedPct}%
Cancelled (Client Disconnected)
${requests.cancelled.toLocaleString()} ${cancelledPct}%
Token Distribution
${tokens.total.toLocaleString()} tokens
Input Tokens (Prompt)
${tokens.input.toLocaleString()} ${inputTokensPct}%
Output Tokens (Completion)
${tokens.output.toLocaleString()} ${outputTokensPct}%
Total Combined Tokens
${tokens.total.toLocaleString()} 100.0%
Active Model Engine ${server.model}
Key Rotation Pool ${server.configuredKeysCount} keys rotating
Gateway Uptime ${uptimeFormatted}
Last Request ${lastRequestAt ? new Date(lastRequestAt).toLocaleTimeString() : 'None yet'}
Zero-Knowledge Privacy: This public dashboard provides aggregate telemetry counts only. No prompt messages, completion texts, client IPs, user tokens, or Gemini API keys are ever stored or exposed.
`; } } export const statsTracker = new StatsTracker();