YokanRuntime.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/app/YokanRuntime.kt
1package eu.friedcutlet.yokan.app23import eu.friedcutlet.yokan.app.profiles.ProfileBackgroundWork4import eu.friedcutlet.yokan.domain.ProfileId5import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult6import eu.friedcutlet.yokan.services.download.DownloadService7import eu.friedcutlet.yokan.database.DbSourceCodeLanguage8import eu.friedcutlet.yokan.services.applock.AppLockController9import eu.friedcutlet.yokan.services.applock.createPlatformAppLockController10import eu.friedcutlet.yokan.services.catchingNonCancellation11import eu.friedcutlet.yokan.services.discord.DiscordRpcService12import eu.friedcutlet.yokan.services.discord.createPlatformDiscordRpcService13import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode14import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl15import eu.friedcutlet.yokan.services.extensions.mihon.extensionServerPortFromUrl16import eu.friedcutlet.yokan.services.http.isLoopbackProxy17import eu.friedcutlet.yokan.services.logging.AppLogger18import eu.friedcutlet.yokan.services.logging.CrashReportStore19import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler20import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome21import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner22import eu.friedcutlet.yokan.services.scheduling.backupFrequencyHours23import eu.friedcutlet.yokan.services.scheduling.periodicMinutes24import eu.friedcutlet.yokan.ui.screens.reader.ReaderSystemUiController25import eu.friedcutlet.yokan.ui.screens.reader.createReaderSystemUiController26import eu.friedcutlet.yokan.util.PlatformLock27import kotlinx.coroutines.launch28import kotlin.concurrent.Volatile2930/**31 * Process-wide facade over the currently published session. Mutable dependencies capture that owner;32 * device resources and profile commands survive foreground session retirement.33 */34object YokanRuntime {35 internal val profileUi = eu.friedcutlet.yokan.app.profiles.ProfileUiLifetime()36 internal val profileCoordinator: eu.friedcutlet.yokan.app.profiles.ProfileCoordinator by lazy {37 eu.friedcutlet.yokan.app.profiles.ProfileCoordinator(38 profiles,39 eu.friedcutlet.yokan.app.profiles.createPlatformProfileSession(ProfileId.Default, profiles.syncLeases(ProfileId.Default), ::reschedulePeriodicTasks),40 openSession = { eu.friedcutlet.yokan.app.profiles.openPlatformProfileSession(it, profiles.syncLeases(it), ::reschedulePeriodicTasks) },41 prepare = { owner ->42 owner.attachLogging()43 reschedulePeriodicTasks(owner)44 if (foregroundStarted) startForeground(owner)45 },46 detach = profileUi::detach,47 deleteStorage = { id ->48 eu.friedcutlet.yokan.app.profiles.cancelProfileBackgroundWork(id)49 val exports = profiles.refresh().profiles.single { it.id == id }.exportedBackups50 eu.friedcutlet.yokan.app.profiles.deleteProfileStorage(id, exports)51 scheduleLock.withLock { lastSchedules.remove(id) }52 },53 )54 }55 internal val activeSession: eu.friedcutlet.yokan.app.profiles.ProfileSession get() = profileCoordinator.currentSession56 val database get() = activeSession.database57 val localFiles get() = activeSession.localFiles58 val notifications get() = activeSession.notifications59 val services get() = activeSession.services60 internal val together get() = activeSession.together61 val repository get() = activeSession.repository62 val periodicTasks get() = activeSession.periodicTasks63 val settings get() = activeSession.settings64 val libraryIndex get() = activeSession.libraryIndex65 val libraryUpdates get() = activeSession.libraryUpdates66 val localLibrary get() = activeSession.localLibrary67 val colorizationQueue get() = activeSession.colorizationQueue68 val migration get() = activeSession.migration69 val chapterDownloads get() = activeSession.chapterDownloads70 val sourceInstall get() = activeSession.sourceInstall71 val discordRpc: DiscordRpcService by lazy { createPlatformDiscordRpcService() }72 val readerSystemUi: ReaderSystemUiController by lazy { createReaderSystemUiController() }73 val profiles by lazy { eu.friedcutlet.yokan.app.profiles.createPlatformProfileRegistry() }74 private val backgroundWork by lazy {75 ProfileBackgroundWork(profiles, supported = { true }, sessions = profileCoordinator)76 }7778 suspend fun runBackgroundTask(79 owner: String?,80 allowLegacyDefault: Boolean = false,81 task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome,82 ): ProfileWorkResult<PeriodicTaskOutcome> = backgroundWork.run(owner, allowLegacyDefault) { session ->83 session.periodicTasks.task()84 }8586 suspend fun runBackgroundDownloads(87 owner: String?,88 allowLegacyDefault: Boolean = false,89 task: suspend DownloadService.() -> Unit,90 ): ProfileWorkResult<Unit> = backgroundWork.run(owner, allowLegacyDefault) { session ->91 session.services.downloader.task()92 }9394 val appIcons by lazy { eu.friedcutlet.yokan.services.appicons.createPlatformAppIconService() }95 val appLock: AppLockController by lazy { createPlatformAppLockController() }9697 // Serializes [bootstrap]: App.kt, desktop main, iOS BGTasks and Android workers can all call it98 // concurrently.99 private val bootstrapLock = PlatformLock()100101 @Volatile102 private var report: AppBootstrapReport? = null103 private var foregroundStarted = false104105 private val scheduleLock = PlatformLock()106 private val lastSchedules = mutableMapOf<ProfileId, PeriodicSchedule>()107108 /**109 * Runs the startup checks once per process; later calls return the same report.110 *111 * [background] callers (OS workers, BGTasks) only need services: they skip the embedded112 * extension server and the in-app [ForegroundScheduler], which start on the first foreground113 * call instead. OS task rescheduling runs in both modes because iOS BGTasks must re-submit114 * themselves after a cold background launch.115 */116 fun bootstrap(117 input: PlatformBootstrapInput = platformBootstrapInput(),118 background: Boolean = false,119 ): AppBootstrapReport = bootstrapLock.withLock {120 val current = report ?: startup(input).also { started ->121 services.scope.launch {122 catchingNonCancellation { profiles.refresh() }123 .onFailure { AppLogger.warn("Profile registry unavailable; existing Default storage remains available") }124 }125 report = started126 runCatching { reschedulePeriodicTasks() }127 .onFailure { AppLogger.warn("Could not schedule periodic tasks: ${it.message.orEmpty()}") }128 }129 if (!background && !foregroundStarted) {130 foregroundStarted = true131 startForeground(activeSession)132 }133 current134 }135136 fun bootstrapReport(): AppBootstrapReport = report ?: bootstrap()137138 /**139 * No-op until [bootstrap] has run, and when the settings-derived schedule is unchanged since140 * the last call; [BackgroundScheduler.schedule] itself is idempotent.141 */142 fun reschedulePeriodicTasks() = reschedulePeriodicTasks(activeSession)143144 private fun reschedulePeriodicTasks(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {145 if (owner.status.value != eu.friedcutlet.yokan.app.profiles.ProfileSessionStatus.Open) return146 val db = owner.database.settings()147 val syncPreference = owner.database.syncPreferences().firstOrNull()148 val syncSeconds = syncPreference149 ?.takeIf { it.syncOn && !it.authToken.isNullOrBlank() }150 ?.autoSyncFrequency151 ?: 0152 val schedule = PeriodicSchedule(153 metadataRefreshMinutes = periodicMinutes(if (db.metadataServerEnabled) db.metadataRefreshFrequencySeconds else 0),154 libraryUpdateMinutes = periodicMinutes(db.libraryUpdateFrequencySeconds),155 libraryUpdateDailyAtMinutes = db.libraryUpdateDailyAtMinutes,156 autoSyncMinutes = periodicMinutes(syncSeconds),157 autoBackupHours = backupFrequencyHours(db.backupFrequency),158 requireUnmetered = db.downloadOnlyOnWifi,159 libraryConstraints = db.features.library.deviceConstraints,160 )161 scheduleLock.withLock {162 if (schedule == lastSchedules[owner.id]) return@withLock163 owner.backgroundScheduler.schedule(164 metadataRefreshMinutes = schedule.metadataRefreshMinutes,165 libraryUpdateMinutes = schedule.libraryUpdateMinutes,166 libraryUpdateDailyAtMinutes = schedule.libraryUpdateDailyAtMinutes,167 autoSyncMinutes = schedule.autoSyncMinutes,168 autoBackupHours = schedule.autoBackupHours,169 requireUnmetered = schedule.requireUnmetered,170 libraryConstraints = schedule.libraryConstraints,171 )172 lastSchedules[owner.id] = schedule173 }174 }175176 private fun startup(input: PlatformBootstrapInput): AppBootstrapReport {177 val crashFiles = eu.friedcutlet.yokan.services.files.createPlatformLocalFileService(ProfileId.Default)178 installPlatformCrashLogger { throwable ->179 // Broken pipes are routine when a client (player, WebView resource180 // fetch, etc.) disconnects mid-write — drop them to debug so they181 // don't masquerade as crashes.182 val name = throwable::class.simpleName.orEmpty()183 val message = throwable.message.orEmpty()184 val isBrokenPipe = name == "SocketException" && message.contains("broken pipe", ignoreCase = true)185 if (isBrokenPipe) {186 AppLogger.warn("Suppressed $name: $message")187 } else {188 CrashReportStore.record(crashFiles, throwable)189 AppLogger.error("Unhandled $name: ${CrashReportStore.redact(message)}")190 }191 }192 activeSession.attachLogging()193 return runStartupChecks(input, services, discordRpc)194 }195196 private fun startForeground(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {197 scheduleExtensionServerStart(owner)198 if (owner.colorizationQueue.supported) owner.colorizationQueue.start()199 owner.foregroundScheduler.start()200 owner.syncTriggers.onTrigger(eu.friedcutlet.yokan.services.sync.SyncTriggerKind.AppStart)201 }202203 private fun scheduleExtensionServerStart(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) {204 val services = owner.services205 val database = owner.database206 if (services.extensionServer.mode == ExtensionServerRuntimeMode.IosSideloadedJvm) return207 if (database.sources().none { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }) return208 val proxy = database.settings().androidProxyServer ?: defaultMihonProxyUrl209 if (!isLoopbackProxy(proxy) || !services.extensionServer.isConfigured()) return210 services.scope.launch {211 catchingNonCancellation {212 services.extensionServer.startIfConfigured(extensionServerPortFromUrl(proxy))213 }.onSuccess { status ->214 AppLogger.info(215 "Extension runtime: local server ${status?.phase?.name?.lowercase() ?: "not configured"}",216 )217 }.onFailure { error ->218 AppLogger.warn(219 "Extension runtime: ${error.message.orEmpty().ifBlank { "local extension server failed to start" }}",220 )221 }222 }223 }224}225226/** The arguments of [BackgroundScheduler.schedule], compared to skip redundant rescheduling. */227private data class PeriodicSchedule(228 val metadataRefreshMinutes: Long,229 val libraryUpdateMinutes: Long,230 val libraryUpdateDailyAtMinutes: Int,231 val autoSyncMinutes: Long,232 val autoBackupHours: Long,233 val requireUnmetered: Boolean,234 val libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,235)236