package eu.friedcutlet.yokan.services.logging import eu.friedcutlet.yokan.util.nowMillis import eu.friedcutlet.yokan.util.PlatformLock import eu.friedcutlet.yokan.services.files.LocalFileService import kotlin.concurrent.Volatile import kotlin.time.ExperimentalTime import kotlin.time.Instant import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime /** [seq] is unique and increasing for the process, so UIs can key rows by it. */ internal data class LogEntry(val seq: Long, val timeMillis: Long, val level: String, val message: String) { fun format(): String = "${formatLogTimestamp(timeMillis)} $level: $message" } /** * Single sink for every log line produced by [AppLogger], `ExtensionLogger`, * and the HTTP-request logger. Secrets matching [CrashReportStore.redact] are masked first. * * Behavior: * - Always println to stdout, so logs are visible in the platform console * (terminal on desktop, `adb logcat -s System.out` on Android, Xcode * console on iOS). * - Keeps the last [MaxRecentEntries] lines, plus the last [MaxProblemEntries] warnings and * errors, in memory for the Developer settings screen. * - Once [attach]ed and while the file-logging setting is on (off by default), * also appends to `LocalFileService.cacheRoot/logs/yokan.log`. When that file passes * [MaxLogFileBytes] it becomes `yokan.log.1` (replacing the previous one), so logs on disk * never exceed about twice that size. */ internal object LogSink { private const val LOG_RELATIVE_PATH = "logs/yokan.log" const val MaxLogFileBytes = 1024L * 1024 const val MaxRecentEntries = 500 const val MaxProblemEntries = 200 private const val MaxLogMessageChars = 16 * 1024 private const val TruncatedMessageMarker = "…[truncated]" private val fileLock = PlatformLock() private val memoryLock = PlatformLock() private val recent = ArrayDeque(MaxRecentEntries) private val problems = ArrayDeque(MaxProblemEntries) private var nextSeq = 0L private class FileTarget(val files: LocalFileService, val path: String, val enabled: () -> Boolean) { /** Unknown until the first append in this process; then tracked without touching the disk. */ var sizeBytes = -1L } // Set once by the composition root; until then lines only reach stdout and memory. @Volatile private var target: FileTarget? = null /** [fileLoggingEnabled] runs for every line, so it must be cheap and must not take locks. */ fun attach(files: LocalFileService, fileLoggingEnabled: () -> Boolean): Any? { val path = runCatching { "${files.cacheRoot.trimEnd('/')}/$LOG_RELATIVE_PATH" }.getOrNull() ?: return null return fileLock.withLock { FileTarget(files, path, fileLoggingEnabled).also { target = it } } } /** Retiring an old owner cannot detach a later session's file target. */ fun detach(token: Any?) = fileLock.withLock { if (target === token) target = null } fun write(level: String, message: String) { val redacted = CrashReportStore.redact(message) val boundedMessage = if (redacted.length > MaxLogMessageChars) { redacted.take(MaxLogMessageChars - TruncatedMessageMarker.length) + TruncatedMessageMarker } else { redacted } val entry = memoryLock.withLock { LogEntry(nextSeq++, nowMillis(), level.take(32), boundedMessage).also { recent.addBounded(it, MaxRecentEntries) if (level != "INFO") problems.addBounded(it, MaxProblemEntries) } } val line = entry.format() println("[yokan] $line") val sink = target ?: return if (runCatching(sink.enabled).getOrDefault(false)) { fileLock.withLock { if (target !== sink) return@withLock runCatching { sink.sizeBytes = appendRotatingLog(sink.files, sink.path, sink.sizeBytes, (line + "\n").encodeToByteArray()) } } } } fun recentEntries(): List = memoryLock.withLock { recent.toList() } fun problemEntries(): List = memoryLock.withLock { problems.toList() } fun clearMemory() { memoryLock.withLock { recent.clear() problems.clear() } } /** Returns the path of the on-disk log file, regardless of whether logging is on. */ fun logFilePath(): String? = target?.path /** Bytes currently on disk for the log and its rotated predecessor. */ fun logFileBytes(): Long { val sink = target ?: return 0L return fileLock.withLock { runCatching { sink.files.directorySize(sink.path) + sink.files.directorySize(rotatedLogPath(sink.path)) }.getOrDefault(0L) } } private fun ArrayDeque.addBounded(value: T, max: Int) { if (size == max) removeFirst() addLast(value) } } @OptIn(ExperimentalTime::class) internal fun formatLogTimestamp(timeMillis: Long): String { val local = Instant.fromEpochMilliseconds(timeMillis).toLocalDateTime(TimeZone.currentSystemDefault()) return buildString { append(local.year.toString().padStart(4, '0')) append('-') append((local.month.ordinal + 1).toString().padStart(2, '0')) append('-') append(local.day.toString().padStart(2, '0')) append(' ') append(local.hour.toString().padStart(2, '0')) append(':') append(local.minute.toString().padStart(2, '0')) append(':') append(local.second.toString().padStart(2, '0')) } } internal fun rotatedLogPath(path: String) = "$path.1" /** * Appends [bytes] to [path] (streaming; the history is never read), first moving the file to * [rotatedLogPath] when the append would pass [maxBytes]. [knownSize] < 0 means "stat the file"; * returns the size after the append so callers can track it without touching the disk. */ internal fun appendRotatingLog(files: LocalFileService, path: String, knownSize: Long, bytes: ByteArray, maxBytes: Long = LogSink.MaxLogFileBytes): Long { val size = if (knownSize < 0) files.directorySize(path) else knownSize if (bytes.size.toLong() > maxBytes) return size val exceedsCap = size > 0 && size > maxBytes - bytes.size if (exceedsCap && !files.promote(path, rotatedLogPath(path))) return size val base = if (exceedsCap) 0L else size files.appendBytes(path, bytes) return base + bytes.size }