Yokan / rebuild
Course 1 8624561

AppBootstrap.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/AppBootstrap.kt

implementation130 lines
1package eu.friedcutlet.yokan.app23import eu.friedcutlet.yokan.database.DbSettings4import eu.friedcutlet.yokan.database.DbSourceCodeLanguage5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.services.discord.DiscordRpcService7import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl8import eu.friedcutlet.yokan.services.http.isLoopbackProxy9import eu.friedcutlet.yokan.services.logging.AppLogger10import eu.friedcutlet.yokan.services.runBlockingCompat1112enum class StartupStatus {13    Ok,14    Warning,15    Error,16}1718data class StartupCheck(19    val name: String,20    val status: StartupStatus,21    val notes: String,22)2324data class PlatformBootstrapInput(25    val platformName: String,26    val initialDeepLink: String? = null,27    val appDataPath: String? = null,28)2930data class AppBootstrapReport(31    val platform: PlatformBootstrapInput,32    val checks: List<StartupCheck>,33) {34    val initialDeepLink: String? get() = platform.initialDeepLink35    val hasErrors: Boolean get() = checks.any { it.status == StartupStatus.Error }36    val summary: String get() = "${checks.count { it.status == StartupStatus.Ok }} ok, ${checks.count { it.status == StartupStatus.Warning }} warnings, ${checks.count { it.status == StartupStatus.Error }} errors"37}3839/** Runs the startup checks listed in Settings → About and logs each one. */40internal fun runStartupChecks(41    input: PlatformBootstrapInput,42    services: YokanServices,43    discordRpc: DiscordRpcService,44): AppBootstrapReport {45    val checks = buildList {46        add(startupOk("Platform", "${input.platformName}${input.appDataPath?.let { " data=$it" }.orEmpty()}"))47        add(checkPersistence(services.database))48        add(checkDownloadWorkers(services))49        add(checkExtensionRuntime(services))50        add(checkDeepLinks(input))51        add(checkLogging())52        add(checkDiscordRpc(input, services.database.settings(), discordRpc))53    }54    checks.forEach { check ->55        when (check.status) {56            StartupStatus.Ok -> AppLogger.info("${check.name}: ${check.notes}")57            StartupStatus.Warning -> AppLogger.warn("${check.name}: ${check.notes}")58            StartupStatus.Error -> AppLogger.error("${check.name}: ${check.notes}")59        }60    }61    return AppBootstrapReport(input, checks)62}6364expect fun platformBootstrapInput(): PlatformBootstrapInput6566expect fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit)6768private fun checkPersistence(database: YokanDatabase): StartupCheck {69    val snapshot = database.snapshot()70    return startupOk(71        "Persistence",72        "loaded ${snapshot.mangas.size} titles, ${snapshot.chapters.size} chapters, ${snapshot.sources.size} sources",73    )74}7576private fun checkDownloadWorkers(services: YokanServices): StartupCheck = runCatching {77    runBlockingCompat { services.downloader.initialize(services.database.settings().concurrentDownloads) }78    startupOk("Download workers", "initialized pool size ${services.database.settings().concurrentDownloads}; recovered ${services.downloader.activeDownloads().size} active tasks")79}.getOrElse { error ->80    startupError("Download workers", error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() })81}8283private fun checkExtensionRuntime(services: YokanServices): StartupCheck {84    val sources = services.database.sources()85    val jsCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.JavaScript }86    val mihonCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }87    val lnReaderCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.LnReader }88    val proxy = services.database.settings().androidProxyServer ?: defaultMihonProxyUrl89    val usesLocalProxy = isLoopbackProxy(proxy)90    var serverNote = if (mihonCount > 0 && !usesLocalProxy) "; remote extension server configured" else ""91    var serverWarning: String? = null92    if (mihonCount > 0 && usesLocalProxy) {93        if (!services.extensionServer.isConfigured()) {94            serverWarning = "local extension server is not installed or bundled"95        } else {96            serverNote = "; local server startup scheduled"97        }98    }99    val runtimeFailures = sources.mapNotNull { source ->100        runCatching { services.extensionRuntimeFactory.create(source).dispose() }101            .exceptionOrNull()102            ?.let { error -> "${source.name}: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" }103    }104    val notes = "QuickJS=$jsCount, Mihon=$mihonCount via $proxy, LNReader=$lnReaderCount"105    val fullNotes = notes + serverNote106    return when {107        runtimeFailures.isNotEmpty() -> startupError("Extension runtime", runtimeFailures.joinToString())108        serverWarning != null -> startupWarning("Extension runtime", "$fullNotes; $serverWarning")109        else -> startupOk("Extension runtime", fullNotes)110    }111}112113private fun checkDeepLinks(input: PlatformBootstrapInput): StartupCheck =114    startupOk("Deep links", input.initialDeepLink?.let { "captured initial link $it" } ?: "initialized; no initial link")115116private fun checkLogging(): StartupCheck = startupOk("Logging", "in-memory startup and crash log buffer ready")117118private fun checkDiscordRpc(input: PlatformBootstrapInput, settings: DbSettings, service: DiscordRpcService): StartupCheck = when {119    !settings.enableDiscordRpc -> startupOk("Discord RPC", "disabled in settings")120    else -> {121        val status = service.initialize(settings)122        if (status.connected) startupOk("Discord RPC", status.message) else startupWarning("Discord RPC", status.message)123    }124}125126private fun startupOk(name: String, notes: String) = StartupCheck(name, StartupStatus.Ok, notes)127128private fun startupWarning(name: String, notes: String) = StartupCheck(name, StartupStatus.Warning, notes)129130private fun startupError(name: String, notes: String) = StartupCheck(name, StartupStatus.Error, notes)131

Search chapters, reference and source filenames.