| 1 | 'use strict'; |
| 2 | |
| 3 | const fs = require('fs'); |
| 4 | const os = require('os'); |
| 5 | const path = require('path'); |
| 6 | |
| 7 | const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs'); |
| 8 | const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024; |
| 9 | const MAX_SUBTITLE_LOG_CONTEXT_KEYS = parseContextLimit(process.env.SUBTITLE_DEBUG_LOG_CONTEXT_KEYS_MAX, 512); |
| 10 | const subtitleLogFileByContext = new Map(); |
| 11 | |
| 12 | function parseContextLimit (value, fallback) |
| 13 | { |
| 14 | const parsed = Number.parseInt(String(value || ''), 10); |
| 15 | if (Number.isInteger(parsed) && parsed >= 1) |
| 16 | { |
| 17 | return Math.min(parsed, 4096); |
| 18 | } |
| 19 | return fallback; |
| 20 | } |
| 21 | |
| 22 | function normaliseTimestampMs (timestampMs) |
| 23 | { |
| 24 | const parsed = Number(timestampMs); |
| 25 | return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : Date.now(); |
| 26 | } |
| 27 | |
| 28 | function sanitiseVideoName (videoName) |
| 29 | { |
| 30 | const raw = path.basename(String(videoName || '').trim() || 'unknown-video'); |
| 31 | const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, ''); |
| 32 | return cleaned || 'unknown-video'; |
| 33 | } |
| 34 | |
| 35 | function subtitleDebugLogFilePath (videoName, timestampMs = Date.now()) |
| 36 | { |
| 37 | const stamp = normaliseTimestampMs(timestampMs); |
| 38 | const fileName = `${stamp}-${sanitiseVideoName(videoName)}-subtitlelog.txt`; |
| 39 | return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName); |
| 40 | } |
| 41 | |
| 42 | function subtitleLogContextKey (videoName, context) |
| 43 | { |
| 44 | const source = context && context.source ? String(context.source) : 'unknown'; |
| 45 | const sessionHint = context && (context.sessionId || context.shareToken) |
| 46 | ? String(context.sessionId || context.shareToken) |
| 47 | : 'no-session'; |
| 48 | return `${sanitiseVideoName(videoName)}|${source}|${sessionHint}`; |
| 49 | } |
| 50 | |
| 51 | function resolveSubtitleLogPath (videoName, timestampMs, context) |
| 52 | { |
| 53 | const key = subtitleLogContextKey(videoName, context); |
| 54 | const existing = subtitleLogFileByContext.get(key); |
| 55 | if (existing) |
| 56 | { |
| 57 | // LRU refresh for active contexts. |
| 58 | subtitleLogFileByContext.delete(key); |
| 59 | subtitleLogFileByContext.set(key, existing); |
| 60 | return existing; |
| 61 | } |
| 62 | |
| 63 | trimSubtitleLogContextMap(); |
| 64 | |
| 65 | const targetPath = subtitleDebugLogFilePath(videoName, timestampMs); |
| 66 | subtitleLogFileByContext.set(key, targetPath); |
| 67 | trimSubtitleLogContextMap(); |
| 68 | return targetPath; |
| 69 | } |
| 70 | |
| 71 | function trimSubtitleLogContextMap () |
| 72 | { |
| 73 | if (subtitleLogFileByContext.size <= MAX_SUBTITLE_LOG_CONTEXT_KEYS) return; |
| 74 | |
| 75 | // Remove oldest references first when they no longer point at existing files. |
| 76 | for (const [key, filePath] of subtitleLogFileByContext) |
| 77 | { |
| 78 | if (subtitleLogFileByContext.size <= MAX_SUBTITLE_LOG_CONTEXT_KEYS) break; |
| 79 | if (fs.existsSync(filePath)) continue; |
| 80 | subtitleLogFileByContext.delete(key); |
| 81 | } |
| 82 | |
| 83 | // Hard cap fallback: evict oldest entries (LRU order) until under limit. |
| 84 | while (subtitleLogFileByContext.size > MAX_SUBTITLE_LOG_CONTEXT_KEYS) |
| 85 | { |
| 86 | const oldestKey = subtitleLogFileByContext.keys().next().value; |
| 87 | if (!oldestKey) break; |
| 88 | subtitleLogFileByContext.delete(oldestKey); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | function ensureSubtitleDebugLogDir () |
| 93 | { |
| 94 | fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true }); |
| 95 | } |
| 96 | |
| 97 | function serialiseLogEntry (entry) |
| 98 | { |
| 99 | const payload = entry && typeof entry === 'object' ? entry : { value: entry }; |
| 100 | const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString(); |
| 101 | return `[${timestamp}] ${JSON.stringify(payload)}\n`; |
| 102 | } |
| 103 | |
| 104 | function directoryEntriesWithStats (dirPath) |
| 105 | { |
| 106 | let entries = []; |
| 107 | try |
| 108 | { |
| 109 | entries = fs.readdirSync(dirPath, { withFileTypes: true }); |
| 110 | } catch |
| 111 | { |
| 112 | return []; |
| 113 | } |
| 114 | |
| 115 | const out = []; |
| 116 | for (const entry of entries) |
| 117 | { |
| 118 | if (!entry.isFile()) continue; |
| 119 | const fullPath = path.join(dirPath, entry.name); |
| 120 | try |
| 121 | { |
| 122 | const stat = fs.statSync(fullPath); |
| 123 | out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 }); |
| 124 | } catch |
| 125 | { |
| 126 | // Ignore files that disappear mid-scan. |
| 127 | } |
| 128 | } |
| 129 | return out; |
| 130 | } |
| 131 | |
| 132 | function getSubtitleDebugLogSnapshot () |
| 133 | { |
| 134 | const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR); |
| 135 | const latestFile = entries.slice().sort((a, b) => b.mtimeMs - a.mtimeMs)[0] || null; |
| 136 | |
| 137 | return { |
| 138 | path: SUBTITLE_DEBUG_LOG_DIR, |
| 139 | exists: fs.existsSync(SUBTITLE_DEBUG_LOG_DIR), |
| 140 | bytes: entries.reduce((sum, entry) => sum + entry.size, 0), |
| 141 | files: entries.length, |
| 142 | directories: 0, |
| 143 | latestFile, |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | function pruneSubtitleDebugLogDir () |
| 148 | { |
| 149 | ensureSubtitleDebugLogDir(); |
| 150 | const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs); |
| 151 | let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0); |
| 152 | |
| 153 | for (const entry of entries) |
| 154 | { |
| 155 | if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break; |
| 156 | try |
| 157 | { |
| 158 | fs.unlinkSync(entry.fullPath); |
| 159 | totalBytes = Math.max(0, totalBytes - entry.size); |
| 160 | } catch |
| 161 | { |
| 162 | // Ignore prune failures; logging must remain best-effort. |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | function appendSubtitleDebugEntries ({ videoName, entries, context = null }) |
| 168 | { |
| 169 | const rows = Array.isArray(entries) ? entries.filter(Boolean) : []; |
| 170 | if (!rows.length) return null; |
| 171 | |
| 172 | const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs)); |
| 173 | const targetPath = resolveSubtitleLogPath( |
| 174 | videoName, |
| 175 | firstTimestamp ? firstTimestamp.loggedAtMs : Date.now(), |
| 176 | context, |
| 177 | ); |
| 178 | |
| 179 | try |
| 180 | { |
| 181 | ensureSubtitleDebugLogDir(); |
| 182 | const text = rows.map((entry) => |
| 183 | { |
| 184 | const payload = context && typeof context === 'object' |
| 185 | ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) } |
| 186 | : entry; |
| 187 | return serialiseLogEntry(payload); |
| 188 | }).join(''); |
| 189 | fs.appendFileSync(targetPath, text, 'utf8'); |
| 190 | pruneSubtitleDebugLogDir(); |
| 191 | return targetPath; |
| 192 | } catch |
| 193 | { |
| 194 | return null; |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | function getSubtitleDebugLogContextCount () |
| 199 | { |
| 200 | return subtitleLogFileByContext.size; |
| 201 | } |
| 202 | |
| 203 | module.exports = { |
| 204 | SUBTITLE_DEBUG_LOG_DIR, |
| 205 | MAX_SUBTITLE_DEBUG_LOG_BYTES, |
| 206 | getSubtitleDebugLogSnapshot, |
| 207 | getSubtitleDebugLogContextCount, |
| 208 | subtitleDebugLogFilePath, |
| 209 | pruneSubtitleDebugLogDir, |
| 210 | appendSubtitleDebugEntries, |
| 211 | }; |