|
| 1 | +import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs' |
| 2 | +import { join } from 'node:path' |
| 3 | + |
| 4 | +import type { RequestLogEntry } from '../store/types.ts' |
| 5 | +import type { |
| 6 | + RequestLogConfig, |
| 7 | + RequestLogFilter, |
| 8 | + RequestLogStats, |
| 9 | + RequestLogTrendPoint, |
| 10 | +} from './types.ts' |
| 11 | +import { normalizeRequestLogConfig } from './types.ts' |
| 12 | +import { |
| 13 | + sanitizeRequestLogEntry, |
| 14 | + sanitizeRequestLogUpdates, |
| 15 | + trimRequestLogsToMaxEntries, |
| 16 | +} from './sanitizer.ts' |
| 17 | + |
| 18 | +interface RequestLogManagerOptions { |
| 19 | + storageDir: string |
| 20 | + config?: Partial<RequestLogConfig> |
| 21 | +} |
| 22 | + |
| 23 | +export class RequestLogManager { |
| 24 | + private readonly logFile: string |
| 25 | + private readonly storageDir: string |
| 26 | + private requestLogs: RequestLogEntry[] = [] |
| 27 | + private config: RequestLogConfig |
| 28 | + private initialized = false |
| 29 | + |
| 30 | + constructor(options: RequestLogManagerOptions) { |
| 31 | + this.storageDir = options.storageDir |
| 32 | + this.logFile = join(options.storageDir, 'request-logs.ndjson') |
| 33 | + this.config = normalizeRequestLogConfig(options.config) |
| 34 | + } |
| 35 | + |
| 36 | + async initialize(): Promise<void> { |
| 37 | + if (this.initialized) return |
| 38 | + |
| 39 | + mkdirSync(this.storageDir, { recursive: true }) |
| 40 | + this.requestLogs = this.loadRequestLogs() |
| 41 | + this.initialized = true |
| 42 | + } |
| 43 | + |
| 44 | + setConfig(config: Partial<RequestLogConfig>): void { |
| 45 | + this.config = normalizeRequestLogConfig(config) |
| 46 | + this.requestLogs = trimRequestLogsToMaxEntries(this.requestLogs, this.config) |
| 47 | + this.persist() |
| 48 | + } |
| 49 | + |
| 50 | + async migrateLegacyLogs(legacyLogs: RequestLogEntry[]): Promise<boolean> { |
| 51 | + this.ensureInitialized() |
| 52 | + |
| 53 | + if (legacyLogs.length === 0 || this.requestLogs.length > 0) { |
| 54 | + return false |
| 55 | + } |
| 56 | + |
| 57 | + this.requestLogs = trimRequestLogsToMaxEntries( |
| 58 | + legacyLogs |
| 59 | + .sort((a, b) => a.timestamp - b.timestamp) |
| 60 | + .map((entry) => ({ |
| 61 | + ...sanitizeRequestLogEntry(stripId(entry), this.config), |
| 62 | + id: entry.id, |
| 63 | + })), |
| 64 | + this.config, |
| 65 | + ) |
| 66 | + this.persist() |
| 67 | + |
| 68 | + return true |
| 69 | + } |
| 70 | + |
| 71 | + addRequestLog(entry: Omit<RequestLogEntry, 'id'>): RequestLogEntry { |
| 72 | + this.ensureInitialized() |
| 73 | + |
| 74 | + const logEntry: RequestLogEntry = { |
| 75 | + ...sanitizeRequestLogEntry(entry, this.config), |
| 76 | + id: generateId(), |
| 77 | + } |
| 78 | + |
| 79 | + if (!this.config.enabled) { |
| 80 | + return logEntry |
| 81 | + } |
| 82 | + |
| 83 | + this.requestLogs.push(logEntry) |
| 84 | + this.requestLogs = trimRequestLogsToMaxEntries(this.requestLogs, this.config) |
| 85 | + this.persist() |
| 86 | + |
| 87 | + return logEntry |
| 88 | + } |
| 89 | + |
| 90 | + updateRequestLog(id: string, updates: Partial<RequestLogEntry>): boolean { |
| 91 | + this.ensureInitialized() |
| 92 | + if (!this.config.enabled || this.config.maxEntries <= 0) { |
| 93 | + return false |
| 94 | + } |
| 95 | + |
| 96 | + const index = this.requestLogs.findIndex((entry) => entry.id === id) |
| 97 | + if (index === -1) { |
| 98 | + return false |
| 99 | + } |
| 100 | + |
| 101 | + this.requestLogs[index] = { |
| 102 | + ...this.requestLogs[index], |
| 103 | + ...sanitizeRequestLogUpdates(updates, this.config), |
| 104 | + } |
| 105 | + this.persist() |
| 106 | + return true |
| 107 | + } |
| 108 | + |
| 109 | + getRequestLogs(limit?: number, filter?: RequestLogFilter): RequestLogEntry[] { |
| 110 | + this.ensureInitialized() |
| 111 | + let result = [...this.requestLogs] |
| 112 | + |
| 113 | + if (filter?.status) { |
| 114 | + result = result.filter((entry) => entry.status === filter.status) |
| 115 | + } |
| 116 | + |
| 117 | + if (filter?.providerId) { |
| 118 | + result = result.filter((entry) => entry.providerId === filter.providerId) |
| 119 | + } |
| 120 | + |
| 121 | + result.sort((a, b) => b.timestamp - a.timestamp) |
| 122 | + |
| 123 | + if (limit && result.length > limit) { |
| 124 | + return result.slice(0, limit) |
| 125 | + } |
| 126 | + |
| 127 | + return result |
| 128 | + } |
| 129 | + |
| 130 | + getRequestLogById(id: string): RequestLogEntry | undefined { |
| 131 | + this.ensureInitialized() |
| 132 | + return this.requestLogs.find((entry) => entry.id === id) |
| 133 | + } |
| 134 | + |
| 135 | + clearRequestLogs(): void { |
| 136 | + this.ensureInitialized() |
| 137 | + this.requestLogs = [] |
| 138 | + this.persist() |
| 139 | + } |
| 140 | + |
| 141 | + getRequestLogStats(): RequestLogStats { |
| 142 | + this.ensureInitialized() |
| 143 | + const today = new Date().toISOString().split('T')[0] |
| 144 | + const todayStart = new Date(today).getTime() |
| 145 | + const todayEnd = todayStart + 24 * 60 * 60 * 1000 |
| 146 | + const todayLogs = this.requestLogs.filter((entry) => entry.timestamp >= todayStart && entry.timestamp < todayEnd) |
| 147 | + |
| 148 | + return { |
| 149 | + total: this.requestLogs.length, |
| 150 | + success: this.requestLogs.filter((entry) => entry.status === 'success').length, |
| 151 | + error: this.requestLogs.filter((entry) => entry.status === 'error').length, |
| 152 | + todayTotal: todayLogs.length, |
| 153 | + todaySuccess: todayLogs.filter((entry) => entry.status === 'success').length, |
| 154 | + todayError: todayLogs.filter((entry) => entry.status === 'error').length, |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + getRequestLogTrend(days: number = 7): RequestLogTrendPoint[] { |
| 159 | + this.ensureInitialized() |
| 160 | + const dayMs = 24 * 60 * 60 * 1000 |
| 161 | + const today = new Date().toISOString().split('T')[0] |
| 162 | + const todayStart = new Date(today).getTime() |
| 163 | + const trends: RequestLogTrendPoint[] = [] |
| 164 | + |
| 165 | + for (let i = days - 1; i >= 0; i--) { |
| 166 | + const dayStart = todayStart - i * dayMs |
| 167 | + const dayEnd = dayStart + dayMs |
| 168 | + const date = new Date(dayStart).toISOString().split('T')[0] |
| 169 | + const dayLogs = this.requestLogs.filter((entry) => entry.timestamp >= dayStart && entry.timestamp < dayEnd) |
| 170 | + const successLogs = dayLogs.filter((entry) => entry.status === 'success') |
| 171 | + const errorLogs = dayLogs.filter((entry) => entry.status === 'error') |
| 172 | + const totalLatency = successLogs.reduce((sum, entry) => sum + entry.latency, 0) |
| 173 | + |
| 174 | + trends.push({ |
| 175 | + date, |
| 176 | + total: dayLogs.length, |
| 177 | + success: successLogs.length, |
| 178 | + error: errorLogs.length, |
| 179 | + avgLatency: successLogs.length > 0 ? Math.round(totalLatency / successLogs.length) : 0, |
| 180 | + }) |
| 181 | + } |
| 182 | + |
| 183 | + return trends |
| 184 | + } |
| 185 | + |
| 186 | + exportRequestLogs(): RequestLogEntry[] { |
| 187 | + this.ensureInitialized() |
| 188 | + return [...this.requestLogs] |
| 189 | + } |
| 190 | + |
| 191 | + private ensureInitialized(): void { |
| 192 | + if (!this.initialized) { |
| 193 | + throw new Error('RequestLogManager is not initialized') |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + private loadRequestLogs(): RequestLogEntry[] { |
| 198 | + if (!existsSync(this.logFile)) { |
| 199 | + return [] |
| 200 | + } |
| 201 | + |
| 202 | + const content = readFileSync(this.logFile, 'utf-8').trim() |
| 203 | + if (!content) { |
| 204 | + return [] |
| 205 | + } |
| 206 | + |
| 207 | + return content |
| 208 | + .split('\n') |
| 209 | + .filter(Boolean) |
| 210 | + .map((line) => { |
| 211 | + try { |
| 212 | + return JSON.parse(line) as RequestLogEntry |
| 213 | + } catch { |
| 214 | + return null |
| 215 | + } |
| 216 | + }) |
| 217 | + .filter((entry): entry is RequestLogEntry => entry !== null) |
| 218 | + } |
| 219 | + |
| 220 | + private persist(): void { |
| 221 | + const content = this.requestLogs.map((entry) => JSON.stringify(entry)).join('\n') |
| 222 | + writeFileSync(this.logFile, content, 'utf-8') |
| 223 | + } |
| 224 | +} |
| 225 | + |
| 226 | +function generateId(): string { |
| 227 | + return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}` |
| 228 | +} |
| 229 | + |
| 230 | +function stripId(entry: RequestLogEntry): Omit<RequestLogEntry, 'id'> { |
| 231 | + const { id: _id, ...rest } = entry |
| 232 | + return rest |
| 233 | +} |
0 commit comments