GeminiRevolver/src/logCompression.ts

212 lines
6.9 KiB
TypeScript

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();
}