feat: add Zstandard (.json.zst) compression for saved logs and full completion text persistence
This commit is contained in:
parent
9d44c92b01
commit
792f8a1160
10 changed files with 886 additions and 43 deletions
38
README.md
38
README.md
|
|
@ -242,15 +242,39 @@ List available models
|
||||||
#### `GET /health`
|
#### `GET /health`
|
||||||
Health check endpoint with key rotation statistics
|
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:
|
Each log entry contains:
|
||||||
- timestamp
|
- `timestamp`
|
||||||
- request ID
|
- `requestId`
|
||||||
- type (request/response/error)
|
- `type` (`request` / `response` / `error`)
|
||||||
- full request/response data
|
- `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
|
## 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) |
|
| `GEMINI_API_KEYS` | Comma-separated list of Gemini API keys | (required) |
|
||||||
| `PORT` | Server port | 3000 |
|
| `PORT` | Server port | 3000 |
|
||||||
| `LOG_DIR` | Directory for log files | ./logs |
|
| `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_TUNNEL_TOKEN` | Cloudflare tunnel token (Docker only) | (required for Docker) |
|
||||||
| `CLOUDFLARE_DOMAIN` | Domain for Cloudflare tunnel (Docker only) | (required for Docker) |
|
| `CLOUDFLARE_DOMAIN` | Domain for Cloudflare tunnel (Docker only) | (required for Docker) |
|
||||||
|
|
||||||
|
|
|
||||||
21
package.json
21
package.json
|
|
@ -8,22 +8,29 @@
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/index.js",
|
||||||
"dev": "ts-node src/index.ts",
|
"dev": "ts-node src/index.ts",
|
||||||
"watch": "tsc --watch",
|
"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": "",
|
"author": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@bokuweb/zstd-wasm": "^0.0.27",
|
||||||
"@google/generative-ai": "^0.21.0",
|
"@google/generative-ai": "^0.21.0",
|
||||||
"express": "^4.18.2",
|
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.3.1"
|
"dotenv": "^16.3.1",
|
||||||
|
"express": "^4.18.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/express": "^4.17.21",
|
|
||||||
"@types/cors": "^2.8.17",
|
"@types/cors": "^2.8.17",
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
"@types/node": "^20.10.0",
|
"@types/node": "^20.10.0",
|
||||||
"typescript": "^5.3.3",
|
"ts-node": "^10.9.2",
|
||||||
"ts-node": "^10.9.2"
|
"typescript": "^5.3.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,10 @@ export const config = {
|
||||||
maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10),
|
maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10),
|
||||||
maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10),
|
maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10),
|
||||||
// Gemini Content Moderation
|
// 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) {
|
if (!config.apiPassword) {
|
||||||
|
|
|
||||||
151
src/inspectLogs.ts
Normal file
151
src/inspectLogs.ts
Normal file
|
|
@ -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 -- <YYYY-MM-DD|filename> Print log entries for a specific date or file
|
||||||
|
npm run logs -- <target> --pretty Pretty-print JSON entries
|
||||||
|
npm run logs -- <target> --search <q> Filter log entries matching search query
|
||||||
|
npm run logs -- --compress Compress all previous days' .json logs to .json.zst
|
||||||
|
npm run logs -- --decompress <target> 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();
|
||||||
|
}
|
||||||
212
src/logCompression.ts
Normal file
212
src/logCompression.ts
Normal file
|
|
@ -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<string, any>,
|
||||||
|
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<string>();
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
@ -1,22 +1,30 @@
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { config } from './config';
|
import { config } from './config';
|
||||||
|
import {
|
||||||
|
compressLogFileSync,
|
||||||
|
CompressionResult,
|
||||||
|
readLogFileContentSync
|
||||||
|
} from './logCompression';
|
||||||
|
|
||||||
interface LogEntry {
|
export interface LogEntry {
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
requestId: string;
|
requestId: string;
|
||||||
type: 'request' | 'response' | 'error';
|
type: 'request' | 'response' | 'error';
|
||||||
data: any;
|
data: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
class RequestLogger {
|
export class RequestLogger {
|
||||||
private logDir: string;
|
private logDir: string;
|
||||||
private currentLogFile: string;
|
private currentLogFile: string;
|
||||||
|
private getDateString: () => string;
|
||||||
|
|
||||||
constructor() {
|
constructor(logDir?: string, dateProvider?: () => string) {
|
||||||
this.logDir = config.logDir;
|
this.logDir = logDir || config.logDir;
|
||||||
|
this.getDateString = dateProvider || (() => new Date().toISOString().split('T')[0]);
|
||||||
this.ensureLogDirectory();
|
this.ensureLogDirectory();
|
||||||
this.currentLogFile = this.getLogFileName();
|
this.currentLogFile = this.getLogFileName();
|
||||||
|
this.compressOldLogs();
|
||||||
}
|
}
|
||||||
|
|
||||||
private ensureLogDirectory(): void {
|
private ensureLogDirectory(): void {
|
||||||
|
|
@ -26,7 +34,7 @@ class RequestLogger {
|
||||||
}
|
}
|
||||||
|
|
||||||
private getLogFileName(): string {
|
private getLogFileName(): string {
|
||||||
const date = new Date().toISOString().split('T')[0];
|
const date = this.getDateString();
|
||||||
return path.join(this.logDir, `api-logs-${date}.json`);
|
return path.join(this.logDir, `api-logs-${date}.json`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -34,10 +42,78 @@ class RequestLogger {
|
||||||
const newLogFile = this.getLogFileName();
|
const newLogFile = this.getLogFileName();
|
||||||
if (newLogFile !== this.currentLogFile) {
|
if (newLogFile !== this.currentLogFile) {
|
||||||
this.currentLogFile = newLogFile;
|
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 {
|
private writeLog(entry: LogEntry): void {
|
||||||
|
this.ensureLogDirectory();
|
||||||
this.updateLogFileIfNeeded();
|
this.updateLogFileIfNeeded();
|
||||||
|
|
||||||
const logLine = JSON.stringify(entry) + '\n';
|
const logLine = JSON.stringify(entry) + '\n';
|
||||||
|
|
|
||||||
|
|
@ -311,7 +311,10 @@ export class RevolverEngine {
|
||||||
requestId: string;
|
requestId: string;
|
||||||
res: Response;
|
res: Response;
|
||||||
isStreaming: boolean;
|
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;
|
onFailure?: (reason?: string) => void;
|
||||||
onCancelled?: () => void;
|
onCancelled?: () => void;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
|
|
@ -551,9 +554,14 @@ export class RevolverEngine {
|
||||||
|
|
||||||
const promptTokens = responseData.usage?.prompt_tokens || 0;
|
const promptTokens = responseData.usage?.prompt_tokens || 0;
|
||||||
const completionTokens = responseData.usage?.completion_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) {
|
if (onSuccess) {
|
||||||
onSuccess({ input: promptTokens, output: completionTokens });
|
onSuccess(
|
||||||
|
{ input: promptTokens, output: completionTokens },
|
||||||
|
{ completionText, finishReason, responseData }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const stepDuration = Date.now() - candidateStart;
|
const stepDuration = Date.now() - candidateStart;
|
||||||
|
|
@ -1079,8 +1087,11 @@ export class RevolverEngine {
|
||||||
requestId: string;
|
requestId: string;
|
||||||
res: Response;
|
res: Response;
|
||||||
onStreamStart: () => void;
|
onStreamStart: () => void;
|
||||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
onSuccess?: (
|
||||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
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 { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||||
|
|
||||||
if (candidate.provider.type === 'gemini') {
|
if (candidate.provider.type === 'gemini') {
|
||||||
|
|
@ -1113,8 +1124,11 @@ export class RevolverEngine {
|
||||||
requestId: string;
|
requestId: string;
|
||||||
res: Response;
|
res: Response;
|
||||||
onStreamStart: () => void;
|
onStreamStart: () => void;
|
||||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
onSuccess?: (
|
||||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
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 { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||||
const genAI = this.getGeminiClient(candidate.keyConfig.key);
|
const genAI = this.getGeminiClient(candidate.keyConfig.key);
|
||||||
|
|
||||||
|
|
@ -1292,13 +1306,17 @@ export class RevolverEngine {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (onSuccess) {
|
if (onSuccess) {
|
||||||
onSuccess({ input: promptTokens, output: completionTokens });
|
onSuccess(
|
||||||
|
{ input: promptTokens, output: completionTokens },
|
||||||
|
{ completionText: fullContent, finishReason: 'stop' }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
promptTokens,
|
promptTokens,
|
||||||
completionTokens,
|
completionTokens,
|
||||||
finishReason: 'stop'
|
finishReason: 'stop',
|
||||||
|
completionText: fullContent
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1309,8 +1327,11 @@ export class RevolverEngine {
|
||||||
requestId: string;
|
requestId: string;
|
||||||
res: Response;
|
res: Response;
|
||||||
onStreamStart: () => void;
|
onStreamStart: () => void;
|
||||||
onSuccess?: (tokens: { input: number; output: number }) => void;
|
onSuccess?: (
|
||||||
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
|
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 { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params;
|
||||||
|
|
||||||
const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, '');
|
const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, '');
|
||||||
|
|
@ -1369,6 +1390,8 @@ export class RevolverEngine {
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
let buffer = '';
|
let buffer = '';
|
||||||
let totalOutputChars = 0;
|
let totalOutputChars = 0;
|
||||||
|
let fullContent = '';
|
||||||
|
let finishReason = 'stop';
|
||||||
let streamHasStarted = false;
|
let streamHasStarted = false;
|
||||||
|
|
||||||
const processText = (textChunk: string) => {
|
const processText = (textChunk: string) => {
|
||||||
|
|
@ -1393,11 +1416,15 @@ export class RevolverEngine {
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(dataStr);
|
const parsed = JSON.parse(dataStr);
|
||||||
parsed.model = requestedModelName;
|
parsed.model = requestedModelName;
|
||||||
|
if (parsed.choices?.[0]?.finish_reason) {
|
||||||
|
finishReason = parsed.choices[0].finish_reason;
|
||||||
|
}
|
||||||
if (parsed.choices?.[0]?.delta?.content) {
|
if (parsed.choices?.[0]?.delta?.content) {
|
||||||
onStreamStart();
|
onStreamStart();
|
||||||
streamHasStarted = true;
|
streamHasStarted = true;
|
||||||
const delta = parsed.choices[0].delta.content;
|
const delta = parsed.choices[0].delta.content;
|
||||||
totalOutputChars += delta.length;
|
totalOutputChars += delta.length;
|
||||||
|
fullContent += delta;
|
||||||
liveWatcher.appendStreamChunk(requestId, delta);
|
liveWatcher.appendStreamChunk(requestId, delta);
|
||||||
}
|
}
|
||||||
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
res.write(`data: ${JSON.stringify(parsed)}\n\n`);
|
||||||
|
|
@ -1461,13 +1488,17 @@ export class RevolverEngine {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (onSuccess) {
|
if (onSuccess) {
|
||||||
onSuccess({ input: estimatedInput, output: estimatedOutput });
|
onSuccess(
|
||||||
|
{ input: estimatedInput, output: estimatedOutput },
|
||||||
|
{ completionText: fullContent, finishReason }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
promptTokens: estimatedInput,
|
promptTokens: estimatedInput,
|
||||||
completionTokens: estimatedOutput,
|
completionTokens: estimatedOutput,
|
||||||
finishReason: 'stop'
|
finishReason,
|
||||||
|
completionText: fullContent
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -113,13 +113,16 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
requestId,
|
requestId,
|
||||||
res,
|
res,
|
||||||
isStreaming: !!body.stream,
|
isStreaming: !!body.stream,
|
||||||
onSuccess: (tokens) => {
|
onSuccess: (tokens, details) => {
|
||||||
isFinished = true;
|
isFinished = true;
|
||||||
requestTracker.recordSuccess(tokens);
|
requestTracker.recordSuccess(tokens);
|
||||||
requestLogger.logResponse(requestId, {
|
requestLogger.logResponse(requestId, {
|
||||||
statusCode: 200,
|
statusCode: 200,
|
||||||
response: {
|
response: {
|
||||||
streaming: !!body.stream,
|
streaming: !!body.stream,
|
||||||
|
content: details?.completionText ?? '',
|
||||||
|
finishReason: details?.finishReason ?? 'stop',
|
||||||
|
...(details?.responseData ? { fullResponse: details.responseData } : {}),
|
||||||
usage: {
|
usage: {
|
||||||
prompt_tokens: tokens.input,
|
prompt_tokens: tokens.input,
|
||||||
completion_tokens: tokens.output,
|
completion_tokens: tokens.output,
|
||||||
|
|
|
||||||
29
src/stats.ts
29
src/stats.ts
|
|
@ -2,6 +2,7 @@ import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { config } from './config';
|
import { config } from './config';
|
||||||
import { configStore } from './configStore';
|
import { configStore } from './configStore';
|
||||||
|
import { listLogFilesSync, readLogFileContentSync } from './logCompression';
|
||||||
|
|
||||||
export interface StatsData {
|
export interface StatsData {
|
||||||
totalRequests: number;
|
totalRequests: number;
|
||||||
|
|
@ -74,11 +75,13 @@ export class StatsTracker {
|
||||||
|
|
||||||
private activeRequests: number = 0;
|
private activeRequests: number = 0;
|
||||||
private serverStartedAt: Date = new Date();
|
private serverStartedAt: Date = new Date();
|
||||||
|
private logDir: string;
|
||||||
private statsFilePath: string;
|
private statsFilePath: string;
|
||||||
private saveTimeout: NodeJS.Timeout | null = null;
|
private saveTimeout: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
constructor() {
|
constructor(logDir?: string) {
|
||||||
this.statsFilePath = path.join(config.logDir, 'stats.json');
|
this.logDir = logDir || config.logDir;
|
||||||
|
this.statsFilePath = path.join(this.logDir, 'stats.json');
|
||||||
this.ensureLogDir();
|
this.ensureLogDir();
|
||||||
this.loadStats();
|
this.loadStats();
|
||||||
|
|
||||||
|
|
@ -88,9 +91,9 @@ export class StatsTracker {
|
||||||
}
|
}
|
||||||
|
|
||||||
private ensureLogDir(): void {
|
private ensureLogDir(): void {
|
||||||
if (!fs.existsSync(config.logDir)) {
|
if (!fs.existsSync(this.logDir)) {
|
||||||
try {
|
try {
|
||||||
fs.mkdirSync(config.logDir, { recursive: true });
|
fs.mkdirSync(this.logDir, { recursive: true });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[STATS] Failed to create log directory:', err);
|
console.error('[STATS] Failed to create log directory:', err);
|
||||||
}
|
}
|
||||||
|
|
@ -136,20 +139,24 @@ export class StatsTracker {
|
||||||
|
|
||||||
private rebuildFromExistingLogs(): void {
|
private rebuildFromExistingLogs(): void {
|
||||||
try {
|
try {
|
||||||
if (!fs.existsSync(config.logDir)) return;
|
if (!fs.existsSync(this.logDir)) return;
|
||||||
const files = fs.readdirSync(config.logDir).filter(f => f.startsWith('api-logs-') && f.endsWith('.json'));
|
const files = listLogFilesSync(this.logDir);
|
||||||
if (files.length === 0) return;
|
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<string>();
|
||||||
|
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const filePath = path.join(config.logDir, file);
|
const filePath = path.join(this.logDir, file);
|
||||||
const content = fs.readFileSync(filePath, 'utf8');
|
const content = readLogFileContentSync(filePath);
|
||||||
const lines = content.split('\n');
|
const lines = content.split('\n');
|
||||||
|
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
if (!line.trim()) continue;
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed || seenLines.has(trimmed)) continue;
|
||||||
|
seenLines.add(trimmed);
|
||||||
try {
|
try {
|
||||||
const entry = JSON.parse(line);
|
const entry = JSON.parse(trimmed);
|
||||||
if (entry.type === 'response') {
|
if (entry.type === 'response') {
|
||||||
const status = entry.data?.statusCode || 200;
|
const status = entry.data?.statusCode || 200;
|
||||||
if (status >= 200 && status < 400) {
|
if (status >= 200 && status < 400) {
|
||||||
|
|
|
||||||
327
test-log-compression.ts
Normal file
327
test-log-compression.ts
Normal file
|
|
@ -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<void>(resolve => upstreamServer.listen(0, resolve));
|
||||||
|
const upstreamPort = (upstreamServer.address() as any).port;
|
||||||
|
|
||||||
|
const appServer = http.createServer(app);
|
||||||
|
await new Promise<void>(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);
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue