diff --git a/README.md b/README.md index 1db4ca5..57de6db 100644 --- a/README.md +++ b/README.md @@ -242,15 +242,39 @@ List available models #### `GET /health` Health check endpoint with key rotation statistics -## Logging +## Logging & Automatic Zstandard Compression -All requests and responses are logged to JSON files in the configured `LOG_DIR`. Log files are named by date: `api-logs-YYYY-MM-DD.json` +All requests and responses (including full prompts and assistant completion text) are logged to newline-delimited JSON files in the configured `LOG_DIR`. + +- **Active Today's Log:** Kept uncompressed at `api-logs-YYYY-MM-DD.json` for fast real-time appends. +- **Historical Logs (`.json.zst`):** On server startup and upon daily UTC date rollover, any previous days' `api-logs-YYYY-MM-DD.json` files are automatically compressed using **Zstandard** (default level `19`) into `api-logs-YYYY-MM-DD.json.zst` and the uncompressed `.json` file is removed. If a `.json.zst` archive already exists for that date, new entries are losslessly merged and deduplicated before re-compressing. +- **Stats Rebuild Compatibility:** `StatsTracker` transparently reads both `.json` and `.json.zst` files when reconstructing historical statistics. Each log entry contains: -- timestamp -- request ID -- type (request/response/error) -- full request/response data +- `timestamp` +- `requestId` +- `type` (`request` / `response` / `error`) +- `data` (full request payload, assistant completion text, finish reason, and token usage) + +### Inspecting & Decompressing Saved Logs + +Use the built-in CLI inspector (`npm run logs`) to view or extract compressed logs: + +```bash +# List all saved log files (.json and .json.zst) with sizes, compression ratios, and entry counts +npm run logs + +# Print all entries for a specific date or filename (automatically decompresses .zst in memory) +npm run logs -- 2026-11-04 +npm run logs -- 2026-11-04 --pretty +npm run logs -- 2026-11-04 --search "model-name" + +# Extract a .json.zst archive back to a .json file on disk +npm run logs -- --decompress 2026-11-04 + +# Manually trigger compression of previous days' logs +npm run logs -- --compress +``` ## Key Rotation Strategy @@ -269,6 +293,8 @@ The system uses a round-robin rotation strategy with rate limit awareness: | `GEMINI_API_KEYS` | Comma-separated list of Gemini API keys | (required) | | `PORT` | Server port | 3000 | | `LOG_DIR` | Directory for log files | ./logs | +| `ENABLE_LOG_COMPRESSION` | Automatically compress past days' logs to `.json.zst` | `true` | +| `LOG_COMPRESSION_LEVEL` | Zstandard compression level (`1`โ€“`22`) | `19` | | `CLOUDFLARE_TUNNEL_TOKEN` | Cloudflare tunnel token (Docker only) | (required for Docker) | | `CLOUDFLARE_DOMAIN` | Domain for Cloudflare tunnel (Docker only) | (required for Docker) | diff --git a/package.json b/package.json index cd16ef0..f49e4ef 100644 --- a/package.json +++ b/package.json @@ -8,22 +8,29 @@ "start": "node dist/index.js", "dev": "ts-node src/index.ts", "watch": "tsc --watch", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-content-length-resilience.ts && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts && API_PASSWORD=test_password ts-node test-moderation-and-cooldown-recovery.ts" + "logs": "ts-node src/inspectLogs.ts", + "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-content-length-resilience.ts && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts && API_PASSWORD=test_password ts-node test-moderation-and-cooldown-recovery.ts && API_PASSWORD=test_password ts-node test-log-compression.ts" }, - "keywords": ["openai", "gemini", "api", "rotation"], + "keywords": [ + "openai", + "gemini", + "api", + "rotation" + ], "author": "", "license": "MIT", "dependencies": { + "@bokuweb/zstd-wasm": "^0.0.27", "@google/generative-ai": "^0.21.0", - "express": "^4.18.2", "cors": "^2.8.5", - "dotenv": "^16.3.1" + "dotenv": "^16.3.1", + "express": "^4.18.2" }, "devDependencies": { - "@types/express": "^4.17.21", "@types/cors": "^2.8.17", + "@types/express": "^4.17.21", "@types/node": "^20.10.0", - "typescript": "^5.3.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "typescript": "^5.3.3" } } diff --git a/src/config.ts b/src/config.ts index 1fd22d5..e876b77 100644 --- a/src/config.ts +++ b/src/config.ts @@ -22,7 +22,10 @@ export const config = { maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10), maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10), // Gemini Content Moderation - disableGeminiModeration: process.env.DISABLE_GEMINI_MODERATION !== 'false' + disableGeminiModeration: process.env.DISABLE_GEMINI_MODERATION !== 'false', + // Persistent Log Compression (Zstandard) + enableLogCompression: process.env.ENABLE_LOG_COMPRESSION !== 'false', + logCompressionLevel: Math.min(22, Math.max(1, parseInt(process.env.LOG_COMPRESSION_LEVEL || '19', 10))) }; if (!config.apiPassword) { diff --git a/src/inspectLogs.ts b/src/inspectLogs.ts new file mode 100644 index 0000000..1af7348 --- /dev/null +++ b/src/inspectLogs.ts @@ -0,0 +1,151 @@ +import fs from 'fs'; +import path from 'path'; + +// Allow running the CLI log utility without requiring API_PASSWORD in environment +if (!process.env.API_PASSWORD) { + process.env.API_PASSWORD = 'cli_inspector'; +} + +import { config } from './config'; +import { listLogFilesSync, readLogFileContentSync } from './logCompression'; +import { requestLogger } from './logger'; + +function resolveTargetFile(logDir: string, target: string): string | null { + const candidates = [ + path.join(logDir, target), + path.join(logDir, `api-logs-${target}.json.zst`), + path.join(logDir, `api-logs-${target}.json`), + path.join(logDir, `${target}.zst`) + ]; + + for (const c of candidates) { + if (fs.existsSync(c) && fs.statSync(c).isFile()) { + return c; + } + } + return null; +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(2)} MB`; +} + +export function runCli(args: string[] = process.argv.slice(2), logDir: string = config.logDir): void { + if (args.includes('--help') || args.includes('-h')) { + console.log(` +GeminiRevolver Persistent Log Inspector (Zstandard .json.zst) + +Usage: + npm run logs List all saved log files (.json and .json.zst) + npm run logs -- --list List all saved log files with sizes and entry counts + npm run logs -- Print log entries for a specific date or file + npm run logs -- --pretty Pretty-print JSON entries + npm run logs -- --search Filter log entries matching search query + npm run logs -- --compress Compress all previous days' .json logs to .json.zst + npm run logs -- --decompress Extract a .json.zst archive back to .json on disk +`); + return; + } + + if (args.includes('--compress')) { + const results = requestLogger.compressOldLogs(); + if (results.length === 0) { + console.log('No uncompressed historical log files needed compression.'); + } else { + console.log(`Compressed ${results.length} historical log file(s).`); + } + return; + } + + const decompressIdx = args.indexOf('--decompress'); + if (decompressIdx !== -1) { + const target = args[decompressIdx + 1]; + if (!target) { + console.error('Error: Please provide a date (YYYY-MM-DD) or filename after --decompress.'); + process.exit(1); + } + const resolved = resolveTargetFile(logDir, target); + if (!resolved || !resolved.endsWith('.zst')) { + console.error(`Error: Could not find compressed .zst log file for '${target}' in ${logDir}`); + process.exit(1); + } + const content = readLogFileContentSync(resolved); + const outPath = resolved.slice(0, -4); // strip .zst + fs.writeFileSync(outPath, content, 'utf8'); + console.log(`Decompressed ${path.basename(resolved)} -> ${outPath} (${formatBytes(Buffer.byteLength(content, 'utf8'))})`); + return; + } + + const pretty = args.includes('--pretty'); + const searchIdx = args.indexOf('--search'); + const searchQuery = searchIdx !== -1 ? (args[searchIdx + 1] || '').toLowerCase() : ''; + + const positional = args.filter((arg, idx) => { + if (arg.startsWith('--')) return false; + if (searchIdx !== -1 && idx === searchIdx + 1) return false; + return true; + }); + + if (positional.length === 0 || args.includes('--list')) { + const files = listLogFilesSync(logDir); + if (files.length === 0) { + console.log(`No saved log files found in ${logDir}`); + return; + } + + console.log(`\nSaved Log Files in ${logDir}:\n`); + console.log( + `${'Filename'.padEnd(34)} | ${'Disk Size'.padStart(10)} | ${'Raw Size'.padStart(10)} | ${'Ratio'.padStart(8)} | ${'Entries'.padStart(7)}` + ); + console.log('-'.repeat(81)); + + for (const file of files) { + const fullPath = path.join(logDir, file); + const stat = fs.statSync(fullPath); + const content = readLogFileContentSync(fullPath); + const rawBytes = Buffer.byteLength(content, 'utf8'); + const linesCount = content.split('\n').filter(l => l.trim().length > 0).length; + const ratio = file.endsWith('.zst') && rawBytes > 0 + ? `-${((1 - stat.size / rawBytes) * 100).toFixed(1)}%` + : 'active'; + + console.log( + `${file.padEnd(34)} | ${formatBytes(stat.size).padStart(10)} | ${formatBytes(rawBytes).padStart(10)} | ${ratio.padStart(8)} | ${String(linesCount).padStart(7)}` + ); + } + console.log(''); + return; + } + + for (const target of positional) { + const resolved = resolveTargetFile(logDir, target); + if (!resolved) { + console.error(`Error: Log file not found for '${target}' in ${logDir}`); + process.exit(1); + } + + const content = readLogFileContentSync(resolved); + const lines = content.split('\n').filter(l => l.trim().length > 0); + + for (const line of lines) { + if (searchQuery && !line.toLowerCase().includes(searchQuery)) { + continue; + } + if (pretty) { + try { + console.log(JSON.stringify(JSON.parse(line), null, 2)); + } catch { + console.log(line); + } + } else { + console.log(line); + } + } + } +} + +if (require.main === module) { + runCli(); +} diff --git a/src/logCompression.ts b/src/logCompression.ts new file mode 100644 index 0000000..3c39164 --- /dev/null +++ b/src/logCompression.ts @@ -0,0 +1,212 @@ +import fs from 'fs'; +import path from 'path'; +import zlib from 'zlib'; +import { config } from './config'; + +// Load @bokuweb/zstd-wasm and initialize synchronously via WebAssembly.Instance +const zstdEntryPath = require.resolve('@bokuweb/zstd-wasm'); +const zstdCommonDir = path.dirname(zstdEntryPath); +const { Module } = require(path.join(zstdCommonDir, 'module.js')); +const zstdWasm = require('@bokuweb/zstd-wasm'); + +let wasmInitialized = false; + +function ensureZstdInitialized(): void { + if (wasmInitialized) return; + + // If Node 22.15+ native zstd is available, we don't even need WASM, + // but initializing WASM as fallback is fast and deterministic. + if (typeof (zlib as any).zstdCompressSync === 'function') { + wasmInitialized = true; + return; + } + + const wasmPath = path.join(zstdCommonDir, 'zstd.wasm'); + const wasmBytes = fs.readFileSync(wasmPath); + + Module.instantiateWasm = ( + info: Record, + receiveInstance: (instance: any, mod?: any) => void + ) => { + const Wasm = (globalThis as any).WebAssembly; + const wasmModule = new Wasm.Module(wasmBytes); + const instance = new Wasm.Instance(wasmModule, info); + receiveInstance(instance, wasmModule); + return instance.exports; + }; + + Module.init(); + wasmInitialized = true; +} + +export interface CompressionResult { + archivePath: string; + originalBytes: number; + compressedBytes: number; + mergedWithExisting: boolean; +} + +/** + * Compress a Buffer or UTF-8 string using Zstandard at the specified level (1-22). + */ +export function compressZstdSync( + input: Buffer | string, + level: number = config.logCompressionLevel +): Buffer { + ensureZstdInitialized(); + const clampedLevel = Math.min(22, Math.max(1, Math.floor(level || 19))); + const buf = typeof input === 'string' ? Buffer.from(input, 'utf8') : input; + + if (typeof (zlib as any).zstdCompressSync === 'function') { + const zstdParams = (zlib as any).constants?.ZSTD_c_compressionLevel; + const options = zstdParams !== undefined ? { params: { [zstdParams]: clampedLevel } } : undefined; + return (zlib as any).zstdCompressSync(buf, options); + } + + const compressedUint8: Uint8Array = zstdWasm.compress(buf, clampedLevel); + return Buffer.from(compressedUint8.buffer, compressedUint8.byteOffset, compressedUint8.byteLength); +} + +/** + * Decompress a Zstandard-compressed Buffer back to an uncompressed Buffer. + */ +export function decompressZstdSync(input: Buffer): Buffer { + if (!input || input.byteLength === 0) { + return Buffer.alloc(0); + } + + ensureZstdInitialized(); + + if (typeof (zlib as any).zstdDecompressSync === 'function') { + return (zlib as any).zstdDecompressSync(input); + } + + // Provide a generous fallback heap size in case a frame header omits content size + const fallbackHeapSize = Math.max(10 * 1024 * 1024, input.byteLength * 25); + const decompressedUint8: Uint8Array = zstdWasm.decompress(input, { + defaultHeapSize: fallbackHeapSize + }); + return Buffer.from(decompressedUint8.buffer, decompressedUint8.byteOffset, decompressedUint8.byteLength); +} + +/** + * Merge two newline-delimited JSON strings while preserving line order and avoiding + * duplicate identical entries (e.g. if a previous compression run was interrupted before unlink). + */ +export function mergeJsonlContents(existingContent: string, newContent: string): string { + const seen = new Set(); + const mergedLines: string[] = []; + + for (const rawLine of existingContent.split('\n')) { + const trimmed = rawLine.trim(); + if (!trimmed) continue; + if (!seen.has(trimmed)) { + seen.add(trimmed); + mergedLines.push(trimmed); + } + } + + for (const rawLine of newContent.split('\n')) { + const trimmed = rawLine.trim(); + if (!trimmed) continue; + if (!seen.has(trimmed)) { + seen.add(trimmed); + mergedLines.push(trimmed); + } + } + + return mergedLines.length > 0 ? mergedLines.join('\n') + '\n' : ''; +} + +/** + * Read a log file (.json or .json.zst) and return its UTF-8 text content. + */ +export function readLogFileContentSync(filePath: string): string { + if (!fs.existsSync(filePath)) { + return ''; + } + + if (filePath.endsWith('.zst')) { + const compressed = fs.readFileSync(filePath); + if (compressed.byteLength === 0) return ''; + return decompressZstdSync(compressed).toString('utf8'); + } + + return fs.readFileSync(filePath, 'utf8'); +} + +/** + * Atomically compress an uncompressed daily log file (`api-logs-YYYY-MM-DD.json`) + * into `api-logs-YYYY-MM-DD.json.zst` and delete the original `.json` file. + * If a `.json.zst` file already exists for that date, merges the lines before re-compressing. + */ +export function compressLogFileSync( + jsonFilePath: string, + level: number = config.logCompressionLevel +): CompressionResult | null { + if (!fs.existsSync(jsonFilePath)) { + return null; + } + + const archivePath = jsonFilePath.endsWith('.zst') ? jsonFilePath : `${jsonFilePath}.zst`; + const newRawText = fs.readFileSync(jsonFilePath, 'utf8'); + + // If the uncompressed file is completely empty and no archive exists, just remove the empty file + if (!newRawText.trim() && !fs.existsSync(archivePath)) { + fs.unlinkSync(jsonFilePath); + return null; + } + + let finalContent = newRawText; + let mergedWithExisting = false; + + if (fs.existsSync(archivePath)) { + try { + const existingContent = readLogFileContentSync(archivePath); + if (existingContent.trim()) { + finalContent = mergeJsonlContents(existingContent, newRawText); + mergedWithExisting = true; + } + } catch (err) { + console.error(`[LOG_COMPRESSION] Warning: failed to read existing archive ${archivePath}, overwriting with merged content:`, err); + } + } + + const uncompressedBuffer = Buffer.from(finalContent, 'utf8'); + const compressedBuffer = compressZstdSync(uncompressedBuffer, level); + + // Verify decompression integrity before committing to disk + const verifiedBuffer = decompressZstdSync(compressedBuffer); + if (verifiedBuffer.byteLength !== uncompressedBuffer.byteLength) { + throw new Error( + `Zstandard verification size mismatch for ${jsonFilePath}: expected ${uncompressedBuffer.byteLength}, got ${verifiedBuffer.byteLength}` + ); + } + + const tmpPath = `${archivePath}.tmp.${process.pid}.${Date.now()}`; + fs.writeFileSync(tmpPath, compressedBuffer); + fs.renameSync(tmpPath, archivePath); + + // Remove original uncompressed .json file now that .json.zst is safely written + if (fs.existsSync(jsonFilePath)) { + fs.unlinkSync(jsonFilePath); + } + + return { + archivePath, + originalBytes: uncompressedBuffer.byteLength, + compressedBytes: compressedBuffer.byteLength, + mergedWithExisting + }; +} + +/** + * List all daily API log files (.json and .json.zst) in the given directory, sorted chronologically. + */ +export function listLogFilesSync(logDir: string): string[] { + if (!fs.existsSync(logDir)) return []; + return fs + .readdirSync(logDir) + .filter(f => f.startsWith('api-logs-') && (f.endsWith('.json') || f.endsWith('.json.zst'))) + .sort(); +} diff --git a/src/logger.ts b/src/logger.ts index a7314e7..e89fb75 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,22 +1,30 @@ import fs from 'fs'; import path from 'path'; import { config } from './config'; +import { + compressLogFileSync, + CompressionResult, + readLogFileContentSync +} from './logCompression'; -interface LogEntry { +export interface LogEntry { timestamp: string; requestId: string; type: 'request' | 'response' | 'error'; data: any; } -class RequestLogger { +export class RequestLogger { private logDir: string; private currentLogFile: string; + private getDateString: () => string; - constructor() { - this.logDir = config.logDir; + constructor(logDir?: string, dateProvider?: () => string) { + this.logDir = logDir || config.logDir; + this.getDateString = dateProvider || (() => new Date().toISOString().split('T')[0]); this.ensureLogDirectory(); this.currentLogFile = this.getLogFileName(); + this.compressOldLogs(); } private ensureLogDirectory(): void { @@ -26,7 +34,7 @@ class RequestLogger { } private getLogFileName(): string { - const date = new Date().toISOString().split('T')[0]; + const date = this.getDateString(); return path.join(this.logDir, `api-logs-${date}.json`); } @@ -34,10 +42,78 @@ class RequestLogger { const newLogFile = this.getLogFileName(); if (newLogFile !== this.currentLogFile) { this.currentLogFile = newLogFile; + this.compressOldLogs(); } } + /** + * Compress all previous days' uncompressed `api-logs-YYYY-MM-DD.json` files into `.json.zst` + * while leaving today's active log file uncompressed for fast appends. + */ + public compressOldLogs(): CompressionResult[] { + if (!config.enableLogCompression) return []; + this.ensureLogDirectory(); + + const activeFileName = path.basename(this.getLogFileName()); + const results: CompressionResult[] = []; + + try { + const files = fs + .readdirSync(this.logDir) + .filter(f => f.startsWith('api-logs-') && f.endsWith('.json') && f !== activeFileName) + .sort(); + + for (const file of files) { + const fullPath = path.join(this.logDir, file); + try { + const res = compressLogFileSync(fullPath, config.logCompressionLevel); + if (res) { + results.push(res); + const ratio = res.originalBytes > 0 + ? ((1 - res.compressedBytes / res.originalBytes) * 100).toFixed(1) + : '0.0'; + console.log( + `[LOGGER] Compressed historical log ${file} -> ${path.basename(res.archivePath)} (${res.originalBytes}B -> ${res.compressedBytes}B, ${ratio}% reduction)` + ); + } + } catch (err) { + console.error(`[LOGGER] Failed to compress historical log file ${file}:`, err); + } + } + } catch (err) { + console.error('[LOGGER] Error scanning log directory for compression:', err); + } + + return results; + } + + /** + * Read and parse log entries from either an uncompressed `.json` or compressed `.json.zst` file. + */ + public readLogEntries(filePath: string): LogEntry[] { + const content = readLogFileContentSync(filePath); + if (!content.trim()) return []; + + const entries: LogEntry[] = []; + for (const line of content.split('\n')) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + entries.push(JSON.parse(trimmed)); + } catch { + // Ignore malformed lines + } + } + return entries; + } + + public getCurrentLogFile(): string { + this.updateLogFileIfNeeded(); + return this.currentLogFile; + } + private writeLog(entry: LogEntry): void { + this.ensureLogDirectory(); this.updateLogFileIfNeeded(); const logLine = JSON.stringify(entry) + '\n'; diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index 3883712..d8ea6e9 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -311,7 +311,10 @@ export class RevolverEngine { requestId: string; res: Response; isStreaming: boolean; - onSuccess?: (tokens: { input: number; output: number }) => void; + onSuccess?: ( + tokens: { input: number; output: number }, + details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } + ) => void; onFailure?: (reason?: string) => void; onCancelled?: () => void; }): Promise { @@ -551,9 +554,14 @@ export class RevolverEngine { const promptTokens = responseData.usage?.prompt_tokens || 0; const completionTokens = responseData.usage?.completion_tokens || 0; + const completionText = responseData.choices?.[0]?.message?.content || ''; + const finishReason = responseData.choices?.[0]?.finish_reason || 'stop'; if (onSuccess) { - onSuccess({ input: promptTokens, output: completionTokens }); + onSuccess( + { input: promptTokens, output: completionTokens }, + { completionText, finishReason, responseData } + ); } const stepDuration = Date.now() - candidateStart; @@ -1079,8 +1087,11 @@ export class RevolverEngine { requestId: string; res: Response; onStreamStart: () => void; - onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> { + onSuccess?: ( + tokens: { input: number; output: number }, + details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } + ) => void; + }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string; completionText: string }> { const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; if (candidate.provider.type === 'gemini') { @@ -1113,8 +1124,11 @@ export class RevolverEngine { requestId: string; res: Response; onStreamStart: () => void; - onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> { + onSuccess?: ( + tokens: { input: number; output: number }, + details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } + ) => void; + }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string; completionText: string }> { const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; const genAI = this.getGeminiClient(candidate.keyConfig.key); @@ -1292,13 +1306,17 @@ export class RevolverEngine { }); if (onSuccess) { - onSuccess({ input: promptTokens, output: completionTokens }); + onSuccess( + { input: promptTokens, output: completionTokens }, + { completionText: fullContent, finishReason: 'stop' } + ); } return { promptTokens, completionTokens, - finishReason: 'stop' + finishReason: 'stop', + completionText: fullContent }; } @@ -1309,8 +1327,11 @@ export class RevolverEngine { requestId: string; res: Response; onStreamStart: () => void; - onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> { + onSuccess?: ( + tokens: { input: number; output: number }, + details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } + ) => void; + }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string; completionText: string }> { const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, ''); @@ -1369,6 +1390,8 @@ export class RevolverEngine { const decoder = new TextDecoder(); let buffer = ''; let totalOutputChars = 0; + let fullContent = ''; + let finishReason = 'stop'; let streamHasStarted = false; const processText = (textChunk: string) => { @@ -1393,11 +1416,15 @@ export class RevolverEngine { try { const parsed = JSON.parse(dataStr); parsed.model = requestedModelName; + if (parsed.choices?.[0]?.finish_reason) { + finishReason = parsed.choices[0].finish_reason; + } if (parsed.choices?.[0]?.delta?.content) { onStreamStart(); streamHasStarted = true; const delta = parsed.choices[0].delta.content; totalOutputChars += delta.length; + fullContent += delta; liveWatcher.appendStreamChunk(requestId, delta); } res.write(`data: ${JSON.stringify(parsed)}\n\n`); @@ -1461,13 +1488,17 @@ export class RevolverEngine { }); if (onSuccess) { - onSuccess({ input: estimatedInput, output: estimatedOutput }); + onSuccess( + { input: estimatedInput, output: estimatedOutput }, + { completionText: fullContent, finishReason } + ); } return { promptTokens: estimatedInput, completionTokens: estimatedOutput, - finishReason: 'stop' + finishReason, + completionText: fullContent }; } diff --git a/src/routes.ts b/src/routes.ts index f25c763..206a581 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -113,13 +113,16 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { requestId, res, isStreaming: !!body.stream, - onSuccess: (tokens) => { + onSuccess: (tokens, details) => { isFinished = true; requestTracker.recordSuccess(tokens); requestLogger.logResponse(requestId, { statusCode: 200, response: { streaming: !!body.stream, + content: details?.completionText ?? '', + finishReason: details?.finishReason ?? 'stop', + ...(details?.responseData ? { fullResponse: details.responseData } : {}), usage: { prompt_tokens: tokens.input, completion_tokens: tokens.output, diff --git a/src/stats.ts b/src/stats.ts index 2850bf0..9d35808 100644 --- a/src/stats.ts +++ b/src/stats.ts @@ -2,6 +2,7 @@ import fs from 'fs'; import path from 'path'; import { config } from './config'; import { configStore } from './configStore'; +import { listLogFilesSync, readLogFileContentSync } from './logCompression'; export interface StatsData { totalRequests: number; @@ -74,11 +75,13 @@ export class StatsTracker { private activeRequests: number = 0; private serverStartedAt: Date = new Date(); + private logDir: string; private statsFilePath: string; private saveTimeout: NodeJS.Timeout | null = null; - constructor() { - this.statsFilePath = path.join(config.logDir, 'stats.json'); + constructor(logDir?: string) { + this.logDir = logDir || config.logDir; + this.statsFilePath = path.join(this.logDir, 'stats.json'); this.ensureLogDir(); this.loadStats(); @@ -88,9 +91,9 @@ export class StatsTracker { } private ensureLogDir(): void { - if (!fs.existsSync(config.logDir)) { + if (!fs.existsSync(this.logDir)) { try { - fs.mkdirSync(config.logDir, { recursive: true }); + fs.mkdirSync(this.logDir, { recursive: true }); } catch (err) { console.error('[STATS] Failed to create log directory:', err); } @@ -136,20 +139,24 @@ export class StatsTracker { 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 (!fs.existsSync(this.logDir)) return; + const files = listLogFilesSync(this.logDir); if (files.length === 0) return; - console.log(`[STATS] Scanning ${files.length} existing log file(s) to aggregate initial stats...`); + console.log(`[STATS] Scanning ${files.length} existing log file(s) (.json & .json.zst) to aggregate initial stats...`); + const seenLines = new Set(); + for (const file of files) { - const filePath = path.join(config.logDir, file); - const content = fs.readFileSync(filePath, 'utf8'); + const filePath = path.join(this.logDir, file); + const content = readLogFileContentSync(filePath); const lines = content.split('\n'); for (const line of lines) { - if (!line.trim()) continue; + const trimmed = line.trim(); + if (!trimmed || seenLines.has(trimmed)) continue; + seenLines.add(trimmed); try { - const entry = JSON.parse(line); + const entry = JSON.parse(trimmed); if (entry.type === 'response') { const status = entry.data?.statusCode || 200; if (status >= 200 && status < 400) { diff --git a/test-log-compression.ts b/test-log-compression.ts new file mode 100644 index 0000000..92c5afb --- /dev/null +++ b/test-log-compression.ts @@ -0,0 +1,327 @@ +import fs from 'fs'; +import path from 'path'; +import http from 'http'; +import assert from 'assert'; +import app from './src/index'; +import { config } from './src/config'; +import { configStore } from './src/configStore'; +import { RequestLogger } from './src/logger'; +import { StatsTracker } from './src/stats'; +import { + compressZstdSync, + decompressZstdSync, + readLogFileContentSync, + listLogFilesSync +} from './src/logCompression'; +import { runCli } from './src/inspectLogs'; + +async function runLogCompressionTests() { + console.log('๐Ÿงช Starting Persistent Log Compression (Zstandard) & History Tests...\n'); + + const tmpLogDir = path.join(__dirname, 'logs', `test-zstd-${Date.now()}`); + fs.mkdirSync(tmpLogDir, { recursive: true }); + + try { + // 1. Test Zstandard round-trip compression & high compression ratio on JSONL + console.log('1. Testing Zstandard (level 19) round-trip compression & ratio...'); + const sampleLines: string[] = []; + for (let i = 0; i < 50; i++) { + sampleLines.push( + JSON.stringify({ + timestamp: `2026-10-20T12:00:${String(i).padStart(2, '0')}.000Z`, + requestId: `req_sample_${i}`, + type: 'request', + data: { + path: '/v1/chat/completions', + method: 'POST', + body: { + model: 'gemini-flash-lite-latest', + messages: [{ role: 'user', content: `Sample repeated prompt text number ${i} for compression testing.` }] + } + } + }) + ); + } + const rawPayload = sampleLines.join('\n') + '\n'; + const compressed = compressZstdSync(rawPayload, 19); + const decompressed = decompressZstdSync(compressed).toString('utf8'); + + assert.strictEqual(decompressed, rawPayload, 'Decompressed Zstd content must match original byte-for-byte'); + assert.ok( + compressed.byteLength < Buffer.byteLength(rawPayload, 'utf8') * 0.25, + `Expected >75% compression on JSONL logs (raw=${Buffer.byteLength(rawPayload)}B, compressed=${compressed.byteLength}B)` + ); + console.log( + ` โœ“ Zstandard round-trip verified (${Buffer.byteLength(rawPayload)}B -> ${compressed.byteLength}B, ${((1 - compressed.byteLength / Buffer.byteLength(rawPayload)) * 100).toFixed(1)}% reduction).` + ); + + // 2. Test startup compression of historical logs & daily rollover compression + console.log('\n2. Testing startup compression and automatic daily date rollover...'); + const day1File = path.join(tmpLogDir, 'api-logs-2026-10-20.json'); + const day2File = path.join(tmpLogDir, 'api-logs-2026-10-21.json'); + + const day1Entry1 = JSON.stringify({ + timestamp: '2026-10-20T10:00:00.000Z', + requestId: 'req_day1_1', + type: 'response', + data: { + statusCode: 200, + response: { + streaming: false, + content: 'Day 1 response', + usage: { prompt_tokens: 10, completion_tokens: 20, total_tokens: 30 } + } + } + }); + const day2Entry1 = JSON.stringify({ + timestamp: '2026-10-21T11:00:00.000Z', + requestId: 'req_day2_1', + type: 'error', + data: { message: 'Simulated error on day 2' } + }); + + fs.writeFileSync(day1File, day1Entry1 + '\n', 'utf8'); + fs.writeFileSync(day2File, day2Entry1 + '\n', 'utf8'); + + let currentDay = '2026-10-22'; + const logger = new RequestLogger(tmpLogDir, () => currentDay); + + // Day 1 and Day 2 should now be .json.zst, and original .json removed + assert.strictEqual(fs.existsSync(day1File), false, 'Day 1 uncompressed .json should be deleted'); + assert.strictEqual(fs.existsSync(`${day1File}.zst`), true, 'Day 1 .json.zst should exist'); + assert.strictEqual(fs.existsSync(day2File), false, 'Day 2 uncompressed .json should be deleted'); + assert.strictEqual(fs.existsSync(`${day2File}.zst`), true, 'Day 2 .json.zst should exist'); + + // Write to Day 3 (active day: 2026-10-22) + logger.logRequest('req_day3_1', { path: '/v1/chat/completions', method: 'POST' }); + logger.logResponse('req_day3_1', { + statusCode: 200, + response: { + streaming: false, + content: 'Day 3 active response', + usage: { prompt_tokens: 15, completion_tokens: 25, total_tokens: 40 } + } + }); + + const day3File = path.join(tmpLogDir, 'api-logs-2026-10-22.json'); + assert.strictEqual(fs.existsSync(day3File), true, 'Active day .json must remain uncompressed'); + assert.strictEqual(fs.existsSync(`${day3File}.zst`), false, 'Active day must not be compressed yet'); + + // Roll over to Day 4 (2026-10-23) + currentDay = '2026-10-23'; + logger.logRequest('req_day4_1', { path: '/v1/models', method: 'GET' }); + + const day4File = path.join(tmpLogDir, 'api-logs-2026-10-23.json'); + assert.strictEqual(fs.existsSync(day3File), false, 'Rolled-over Day 3 .json must be deleted after compression'); + assert.strictEqual(fs.existsSync(`${day3File}.zst`), true, 'Rolled-over Day 3 .json.zst must be created'); + assert.strictEqual(fs.existsSync(day4File), true, 'New active Day 4 .json must exist uncompressed'); + console.log(' โœ“ Startup compression and automatic rollover compression verified.'); + + // 3. Test safe merge when both .json and .json.zst exist for a past date + console.log('\n3. Testing lossless merge when late .json entries exist alongside .json.zst...'); + const day1LateEntry = JSON.stringify({ + timestamp: '2026-10-20T23:59:59.000Z', + requestId: 'req_day1_late', + type: 'response', + data: { + statusCode: 200, + response: { + streaming: true, + content: 'Late day 1 response', + usage: { prompt_tokens: 5, completion_tokens: 5, total_tokens: 10 } + } + } + }); + // Write both duplicate entry1 and new lateEntry into uncompressed day1File + fs.writeFileSync(day1File, day1Entry1 + '\n' + day1LateEntry + '\n', 'utf8'); + logger.compressOldLogs(); + + assert.strictEqual(fs.existsSync(day1File), false, 'Merged .json file should be deleted'); + const mergedDay1Entries = logger.readLogEntries(`${day1File}.zst`); + assert.strictEqual(mergedDay1Entries.length, 2, 'Merged .json.zst must contain exactly 2 deduplicated entries'); + assert.strictEqual(mergedDay1Entries[0].requestId, 'req_day1_1'); + assert.strictEqual(mergedDay1Entries[1].requestId, 'req_day1_late'); + console.log(' โœ“ Lossless merge & deduplication into existing .json.zst archive verified.'); + + // 4. Test StatsTracker rebuildFromExistingLogs across .json.zst and .json + console.log('\n4. Testing StatsTracker.rebuildFromExistingLogs() with compressed .json.zst archives...'); + const customStats = new StatsTracker(tmpLogDir); + const summary = customStats.getStatsSummary(); + // Expected: + // - Day 1 (.zst): 2 successful responses (10+20=30 tok, 5+5=10 tok) -> 2 wentThrough, 40 tok + // - Day 2 (.zst): 1 error -> 1 failed + // - Day 3 (.zst): 1 successful response (15+25=40 tok) -> 1 wentThrough, 40 tok + // - Day 4 (.json): 1 request only (no response yet) + assert.strictEqual(summary.requests.wentThrough, 3, 'Should count 3 successful responses across .zst archives'); + assert.strictEqual(summary.requests.failed, 1, 'Should count 1 failed request from .zst archive'); + assert.strictEqual(summary.requests.total, 4, 'Total completed/failed requests should be 4'); + assert.strictEqual(summary.tokens.input, 30, 'Input tokens should be 10 + 5 + 15 = 30'); + assert.strictEqual(summary.tokens.output, 50, 'Output tokens should be 20 + 5 + 25 = 50'); + assert.strictEqual(summary.tokens.total, 80, 'Total tokens should be 80'); + console.log(' โœ“ StatsTracker transparently rebuilt stats from compressed .json.zst archives.'); + + // 5. Test CLI Inspector (--list and --decompress) + console.log('\n5. Testing CLI log inspector utility...'); + runCli(['--list'], tmpLogDir); + runCli(['--decompress', '2026-10-21'], tmpLogDir); + assert.strictEqual(fs.existsSync(day2File), true, '--decompress should restore .json file from .json.zst'); + const restoredContent = readLogFileContentSync(day2File); + assert.ok(restoredContent.includes('req_day2_1'), 'Restored .json file should contain original entry'); + console.log(' โœ“ CLI log inspector (--list and --decompress) verified.'); + + // 6. Test full completion text persistence on POST /v1/chat/completions (non-streaming and streaming) + console.log('\n6. Testing full completion text persistence in saved response logs...'); + const upstreamServer = http.createServer((req, res) => { + let bodyStr = ''; + req.on('data', chunk => (bodyStr += chunk)); + req.on('end', () => { + const parsed = JSON.parse(bodyStr || '{}'); + if (parsed.stream) { + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + res.write( + `data: ${JSON.stringify({ + id: 'chatcmpl-stream-log', + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: parsed.model, + choices: [{ index: 0, delta: { content: 'Persistent ' }, finish_reason: null }] + })}\n\n` + ); + res.write( + `data: ${JSON.stringify({ + id: 'chatcmpl-stream-log', + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: parsed.model, + choices: [{ index: 0, delta: { content: 'stream history!' }, finish_reason: 'stop' }] + })}\n\n` + ); + res.write('data: [DONE]\n\n'); + res.end(); + } else { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + id: 'chatcmpl-nonstream-log', + object: 'chat.completion', + created: Math.floor(Date.now() / 1000), + model: parsed.model, + choices: [ + { + index: 0, + message: { role: 'assistant', content: 'Persistent non-stream history!' }, + finish_reason: 'stop' + } + ], + usage: { prompt_tokens: 8, completion_tokens: 6, total_tokens: 14 } + }) + ); + } + }); + }); + + await new Promise(resolve => upstreamServer.listen(0, resolve)); + const upstreamPort = (upstreamServer.address() as any).port; + + const appServer = http.createServer(app); + await new Promise(resolve => appServer.listen(0, resolve)); + const appPort = (appServer.address() as any).port; + + const testProvider = configStore.saveProvider({ + name: 'Log History Test Provider', + type: 'custom', + baseUrl: `http://localhost:${upstreamPort}/v1`, + keys: ['sk-log-history-test'] + }); + const testModelName = `log-history-model-${Date.now()}`; + const testModel = configStore.saveCustomModel({ + name: testModelName, + isDefault: false, + tiers: [{ tierIndex: 0, name: 'Main', targets: [{ providerId: testProvider.id, model: 'mock-model' }] }] + }); + + try { + // Non-streaming request + const nonStreamRes = await fetch(`http://localhost:${appPort}/v1/chat/completions`, { + method: 'POST', + headers: { + Authorization: `Bearer ${config.apiPassword}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: testModelName, + stream: false, + messages: [{ role: 'user', content: 'Record my non-stream response' }] + }) + }); + assert.strictEqual(nonStreamRes.status, 200); + await nonStreamRes.json(); + + // Streaming request + const streamRes = await fetch(`http://localhost:${appPort}/v1/chat/completions`, { + method: 'POST', + headers: { + Authorization: `Bearer ${config.apiPassword}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: testModelName, + stream: true, + messages: [{ role: 'user', content: 'Record my stream response' }] + }) + }); + assert.strictEqual(streamRes.status, 200); + await streamRes.text(); + + const activeLogPath = path.join(config.logDir, `api-logs-${new Date().toISOString().split('T')[0]}.json`); + const activeEntries = logger.readLogEntries(activeLogPath); + const recentResponses = activeEntries.filter(e => e.type === 'response').slice(-2); + + assert.strictEqual(recentResponses.length, 2, 'Should have logged 2 recent responses'); + assert.strictEqual( + recentResponses[0].data.response.content, + 'Persistent non-stream history!', + 'Non-streaming response log must include full completion content' + ); + assert.ok( + recentResponses[0].data.response.fullResponse, + 'Non-streaming response log must include fullResponse payload' + ); + assert.strictEqual( + recentResponses[1].data.response.content, + 'Persistent stream history!', + 'Streaming response log must include full assembled completion content' + ); + + // Also verify that historical logs in ./logs prior to today were automatically compressed to .json.zst + const prodLogFiles = listLogFilesSync(config.logDir); + const todayFileName = `api-logs-${new Date().toISOString().split('T')[0]}.json`; + for (const file of prodLogFiles) { + if (file !== todayFileName) { + assert.ok( + file.endsWith('.json.zst'), + `Historical log file ${file} in ${config.logDir} should be compressed as .json.zst` + ); + } + } + + console.log(' โœ“ Full completion text persistence (streaming & non-streaming) and ./logs archive state verified.'); + } finally { + configStore.deleteCustomModel(testModel.id); + configStore.deleteProvider(testProvider.id); + appServer.close(); + upstreamServer.close(); + } + + console.log('\n๐ŸŽ‰ ALL PERSISTENT LOG COMPRESSION TESTS PASSED!'); + } finally { + if (fs.existsSync(tmpLogDir)) { + fs.rmSync(tmpLogDir, { recursive: true, force: true }); + } + } +} + +runLogCompressionTests().catch(err => { + console.error('โŒ Log compression test failed:', err); + process.exit(1); +});