Yokan / rebuild
Course 1 8624561

ForegroundScheduler.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/ForegroundScheduler.kt

implementation109 lines
1package eu.friedcutlet.yokan.services.scheduling23import eu.friedcutlet.yokan.database.DbSettings4import eu.friedcutlet.yokan.database.YokanDatabase5import eu.friedcutlet.yokan.services.catchingNonCancellation6import eu.friedcutlet.yokan.services.logging.AppLogger7import eu.friedcutlet.yokan.services.system.isOnUnmeteredNetwork8import eu.friedcutlet.yokan.util.nowMillis9import kotlinx.coroutines.CoroutineScope10import kotlinx.coroutines.Job11import kotlinx.coroutines.delay12import kotlinx.coroutines.launch1314/**15 * Process-local fallback for desktop/web and an immediate in-app companion to16 * OS background schedulers. Every completed task uses [PeriodicTaskRunner], so17 * foreground and background executions produce the same result notification.18 *19 * The ticker runs in the owner's [scope]; cancelling it stops the scheduler.20 */21class ForegroundScheduler(22    private val database: YokanDatabase,23    private val periodicTasks: PeriodicTaskRunner,24    private val scope: CoroutineScope,25) {26    private var job: Job? = null2728    fun start() {29        if (job?.isActive == true) return30        job = scope.launch {31            val lastRun = LastRun(startedAt = nowMillis())32            while (true) {33                catchingNonCancellation { tick(lastRun) }34                    .onFailure { AppLogger.warn("ForegroundScheduler tick failed: ${it.message.orEmpty()}") }35                delay(60_000)36            }37        }38    }3940    fun stop() {41        job?.cancel()42        job = null43    }4445    private suspend fun tick(lastRun: LastRun) {46        val settings = database.settings()47        val networkAllowed = !settings.downloadOnlyOnWifi || isOnUnmeteredNetwork()48        if (49            networkAllowed &&50            settings.metadataServerEnabled &&51            shouldRun(settings.metadataRefreshFrequencySeconds, lastRun.metadataRefresh)52        ) {53            if (attempt("Metadata refresh") { periodicTasks.refreshMetadata() }) lastRun.metadataRefresh = nowMillis()54        }55        // Library-specific admission belongs to the shared runner, including explicit overrides.56        if (shouldRunLibraryUpdate(settings, lastRun.libraryUpdate, lastRun.startedAt)) {57            if (attempt("Library update") { periodicTasks.updateLibrary() }) lastRun.libraryUpdate = nowMillis()58        }59        if (shouldRunBackup(settings, lastRun.backup)) {60            if (attempt("Automatic backup") { periodicTasks.backup() }) lastRun.backup = nowMillis()61        }62        val syncPreference = database.syncPreferences().firstOrNull()63        if (64            networkAllowed &&65            syncPreference?.syncOn == true &&66            !syncPreference.authToken.isNullOrBlank() &&67            shouldRun(syncPreference.autoSyncFrequency, lastRun.sync)68        ) {69            if (attempt("Automatic sync") { periodicTasks.sync() }) lastRun.sync = nowMillis()70        }71        if (!networkAllowed) {72            AppLogger.info("ForegroundScheduler skipped network work: metered connection while downloadOnlyOnWifi is on.")73        }74    }7576    /**77     * Runs one task in isolation so its failure neither skips the others nor resets their78     * timestamps. A task that throws still counts as attempted and waits for its next slot79     * instead of re-running every tick.80     */81    private suspend fun attempt(label: String, task: suspend () -> PeriodicTaskOutcome): Boolean =82        catchingNonCancellation { task().attempted }.getOrElse { error ->83            AppLogger.warn("$label failed: ${error.message.orEmpty()}")84            true85        }8687    private fun shouldRun(seconds: Int, last: Long): Boolean =88        seconds > 0 && nowMillis() - last >= seconds.toLong() * 1000L8990    /** Daily mode fires once per slot, and only for slots after this scheduler started. */91    private fun shouldRunLibraryUpdate(settings: DbSettings, last: Long, startedAt: Long): Boolean {92        if (settings.libraryUpdateFrequencySeconds <= 0) return false93        if (settings.libraryUpdateDailyAtMinutes < 0) return shouldRun(settings.libraryUpdateFrequencySeconds, last)94        return latestDailySlotMillis(settings.libraryUpdateDailyAtMinutes) > maxOf(last, startedAt)95    }9697    private fun shouldRunBackup(settings: DbSettings, last: Long): Boolean {98        val frequencyHours = backupFrequencyHours(settings.backupFrequency)99        return frequencyHours > 0 && nowMillis() - last >= frequencyHours * 60L * 60L * 1000L100    }101102    /** Last-run timestamps, confined to the ticker coroutine. */103    private class LastRun(val startedAt: Long) {104        var metadataRefresh = 0L105        var libraryUpdate = 0L106        var backup = 0L107        var sync = 0L108    }109}110

Search chapters, reference and source filenames.