Yokan / rebuild
Course 1 8624561

PeriodicTaskRunner.kt

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

implementation175 lines
1package eu.friedcutlet.yokan.services.scheduling23import eu.friedcutlet.yokan.data.YokanRepository4import eu.friedcutlet.yokan.data.toDb5import eu.friedcutlet.yokan.database.DbItemType6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.domain.ItemType8import eu.friedcutlet.yokan.services.backup.BackupOptions9import eu.friedcutlet.yokan.services.backup.BackupService10import eu.friedcutlet.yokan.services.catchingNonCancellation11import eu.friedcutlet.yokan.services.logging.AppLogger12import eu.friedcutlet.yokan.services.library.LibraryUpdaterService13import eu.friedcutlet.yokan.services.metadata.MetadataService14import eu.friedcutlet.yokan.services.notifications.NotificationChannel15import eu.friedcutlet.yokan.services.notifications.NotificationPayload16import eu.friedcutlet.yokan.services.notifications.NotificationService17import eu.friedcutlet.yokan.services.sync.SyncService1819enum class PeriodicTaskStatus { Completed, Failed, Skipped, Deferred }2021data class PeriodicTaskOutcome(22    val status: PeriodicTaskStatus,23    val message: String,24) {25    val shouldRetry: Boolean get() = status == PeriodicTaskStatus.Failed || status == PeriodicTaskStatus.Deferred26    val attempted: Boolean get() = status != PeriodicTaskStatus.Skipped && status != PeriodicTaskStatus.Deferred27}2829/** Shared execution path for foreground timers and OS background workers. */30class PeriodicTaskRunner(31    private val database: YokanDatabase,32    private val repository: YokanRepository,33    private val metadata: MetadataService,34    private val libraryUpdater: LibraryUpdaterService,35    private val sync: SyncService,36    private val notifications: NotificationService,37    private val backup: BackupService? = null,38    private val updateGate: AutomaticUpdateGate = AutomaticUpdateGate(),39) {40    suspend fun refreshMetadata(): PeriodicTaskOutcome = execute(PeriodicTask.Metadata) {41        val settings = database.settings()42        if (!settings.metadataServerEnabled) {43            return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Metadata refresh is disabled.")44        }45        val baseUrl = settings.metadataServerUrl.trim()46        if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {47            return@execute PeriodicTaskOutcome(48                PeriodicTaskStatus.Failed,49                "Metadata server URL must start with http:// or https://.",50            )51        }52        val titles = ItemType.entries.flatMap(repository::library)53        var updated = 054        var unmatched = 055        var failed = 056        titles.forEach { title ->57            catchingNonCancellation { metadata.bestMatch(baseUrl, title.name, title.itemType.toDb()) }58                .onSuccess { match ->59                    if (match == null) {60                        unmatched++61                    } else if (repository.applyMetadata(title.id, match) != null) {62                        updated++63                    } else {64                        failed++65                    }66                }67                .onFailure { failed++ }68        }69        PeriodicTaskOutcome(70            PeriodicTaskStatus.Completed,71            "Updated metadata for $updated of ${titles.size} titles; $unmatched unmatched, $failed failed.",72        )73    }7475    suspend fun updateLibrary(): PeriodicTaskOutcome = execute(PeriodicTask.Library) {76        if (!updateGate.check(database.settings()).allowed) {77            return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Deferred, "Automatic library update is waiting for device/network conditions.")78        }79        var checked = 080        var updated = 081        var failed = 082        var crashedTypes = 083        for (type in DbItemType.entries) {84            var deferred = false85            catchingNonCancellation { libraryUpdater.updateLibrary(type,86                mayStartTitle = { updateGate.check(database.settings()).allowed }) }87                .onSuccess { result ->88                    checked += result.checked89                    updated += result.updated90                    failed += result.failed91                    deferred = result.deferred92                }93                .onFailure { crashedTypes++ }94            if (deferred) return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Deferred,95                "Automatic library update paused after $checked titles; $updated updated, $failed failed. Waiting for device/network conditions.")96        }97        val message = "Checked $checked titles; $updated updated, $failed failed" +98            if (crashedTypes > 0) ", $crashedTypes libraries could not run." else "."99        PeriodicTaskOutcome(100            if (crashedTypes == DbItemType.entries.size) PeriodicTaskStatus.Failed else PeriodicTaskStatus.Completed,101            message,102        )103    }104105    suspend fun sync(): PeriodicTaskOutcome = execute(PeriodicTask.Sync) {106        val preference = database.syncPreferences().firstOrNull()107        if (preference?.syncOn != true || preference.authToken.isNullOrBlank()) {108            return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Automatic sync is not configured.")109        }110        val result = sync.sync(preference.syncId ?: 1L, database.settings())111        val details = buildList {112            add("${result.uploadedChanges} uploaded")113            add("${result.downloadedChanges} downloaded")114            if (result.settingsSynced) add("settings synced")115        }.joinToString(", ")116        PeriodicTaskOutcome(117            if (result.errors.isEmpty()) PeriodicTaskStatus.Completed else PeriodicTaskStatus.Failed,118            if (result.errors.isEmpty()) {119                "Sync complete: $details."120            } else {121                "Sync finished with ${result.errors.size} errors: $details."122            },123        )124    }125126    suspend fun backup(): PeriodicTaskOutcome = execute(PeriodicTask.Backup) {127        val settings = database.settings()128        if (backup == null || backupFrequencyHours(settings.backupFrequency) <= 0) {129            return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Automatic backup is disabled.")130        }131        val result = backup.createBackup(BackupOptions(compressionLevel = settings.backupCompressionLevel ?: 6))132        PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Saved ${result.itemCount} items to ${result.fileName}.")133    }134135    private suspend fun execute(136        task: PeriodicTask,137        block: suspend () -> PeriodicTaskOutcome,138    ): PeriodicTaskOutcome {139        val outcome = catchingNonCancellation { block() }.getOrElse { error ->140            PeriodicTaskOutcome(141                PeriodicTaskStatus.Failed,142                error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty().ifBlank { "Unknown error" } },143            )144        }145        if (outcome.status == PeriodicTaskStatus.Skipped || outcome.status == PeriodicTaskStatus.Deferred) return outcome146        val title = "${task.label} ${if (outcome.status == PeriodicTaskStatus.Completed) "complete" else "failed"}"147        if (outcome.status == PeriodicTaskStatus.Failed || task.notifiesSuccess) {148            notifications.notify(149                NotificationPayload(150                    channel = task.channel,151                    title = title,152                    message = outcome.message.take(240),153                    tag = task.tag,154                ),155            )156        }157        val log = "$title: ${outcome.message}"158        if (outcome.status == PeriodicTaskStatus.Completed) AppLogger.info(log) else AppLogger.warn(log)159        return outcome160    }161162    private enum class PeriodicTask(163        val label: String,164        val channel: NotificationChannel,165        val tag: String,166        val notifiesSuccess: Boolean = true,167    ) {168        Metadata("Metadata refresh", NotificationChannel.LibraryUpdates, "periodic.metadata"),169        Library("Library update", NotificationChannel.LibraryUpdates, "periodic.library"),170        Sync("Automatic sync", NotificationChannel.Sync, "periodic.sync"),171172        // BackupService already posts "Backup created" for every successful backup.173        Backup("Automatic backup", NotificationChannel.Backup, "periodic.backup", notifiesSuccess = false),174    }175}176

Search chapters, reference and source filenames.