Yokan / rebuild
Course 1 8624561

BackgroundScheduler.ios.kt

composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.ios.kt

implementation139 lines
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)23package eu.friedcutlet.yokan.services.scheduling45import eu.friedcutlet.yokan.services.logging.AppLogger6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.domain.ProfileId8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.SupervisorJob11import kotlinx.coroutines.cancel12import platform.BackgroundTasks.BGAppRefreshTaskRequest13import platform.BackgroundTasks.BGProcessingTaskRequest14import platform.BackgroundTasks.BGTask15import platform.BackgroundTasks.BGTaskScheduler16import platform.Foundation.NSDate1718private const val METADATA_REFRESH_TASK = "eu.friedcutlet.yokan.metadata-refresh"19private const val LIBRARY_UPDATE_TASK = "eu.friedcutlet.yokan.library-update"20private const val AUTO_SYNC_TASK = "eu.friedcutlet.yokan.auto-sync"21private const val REGISTRY_RETRY_DELAY_SECONDS = 15.0 * 60.02223/**24 * Registers BGTask handlers before launch returns. [tasks] validates and opens the recorded owner,25 * since a background launch has no UI to do it.26 */27internal fun registerIosBackgroundTasks(28    tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult<PeriodicTaskOutcome>,29) = IosBackgroundScheduler.register(tasks)3031actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler {32    // These fixed identifiers are permitted in Info.plist and permanently belong to Default.33    return if (profileId == ProfileId.Default) IosBackgroundScheduler else NoProfileBackgroundScheduler34}3536/**37 * Metadata refresh and sync are `BGAppRefreshTask`s (~30 s budget). The library update is a38 * `BGProcessingTask`: minutes of runtime, network required, run when iOS deems the device idle.39 * A daily time is only an `earliestBeginDate`; iOS picks the actual moment.40 */41private object IosBackgroundScheduler : BackgroundScheduler {42    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)43    private var registered = false44    private var metadataRefreshMinutes = 0L45    private var libraryUpdateMinutes = 0L46    private var libraryUpdateDailyAtMinutes = -147    private var autoSyncMinutes = 0L48    private var requireLibraryPower = false4950    fun register(tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult<PeriodicTaskOutcome>) {51        if (registered) return52        registered = true53        register(METADATA_REFRESH_TASK, { metadataRefreshMinutes * 60.0 }) { tasks(ProfileId.Default, PeriodicTaskRunner::refreshMetadata) }54        register(LIBRARY_UPDATE_TASK, ::libraryUpdateDelaySeconds) { tasks(ProfileId.Default, PeriodicTaskRunner::updateLibrary) }55        register(AUTO_SYNC_TASK, { autoSyncMinutes * 60.0 }) { tasks(ProfileId.Default, PeriodicTaskRunner::sync) }56    }5758    override fun schedule(59        metadataRefreshMinutes: Long,60        libraryUpdateMinutes: Long,61        libraryUpdateDailyAtMinutes: Int,62        autoSyncMinutes: Long,63        autoBackupHours: Long,64        requireUnmetered: Boolean,65        libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,66    ) {67        this.metadataRefreshMinutes = metadataRefreshMinutes68        this.libraryUpdateMinutes = libraryUpdateMinutes69        this.libraryUpdateDailyAtMinutes = libraryUpdateDailyAtMinutes70        this.autoSyncMinutes = autoSyncMinutes71        this.requireLibraryPower = libraryConstraints.requireExternalPower72        submit(METADATA_REFRESH_TASK, metadataRefreshMinutes * 60.0)73        submit(LIBRARY_UPDATE_TASK, libraryUpdateDelaySeconds())74        submit(AUTO_SYNC_TASK, autoSyncMinutes * 60.0)75    }7677    private fun libraryUpdateDelaySeconds(): Double = when {78        libraryUpdateMinutes <= 0 -> 0.079        libraryUpdateDailyAtMinutes >= 0 -> nextDailySlotDelayMillis(libraryUpdateDailyAtMinutes) / 1000.080        else -> libraryUpdateMinutes * 60.081    }8283    override fun cancelAll() {84        BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(METADATA_REFRESH_TASK)85        BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(LIBRARY_UPDATE_TASK)86        BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(AUTO_SYNC_TASK)87    }8889    private fun register(90        identifier: String,91        delaySeconds: () -> Double,92        run: suspend () -> ProfileWorkResult<PeriodicTaskOutcome>,93    ) {94        BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifier(identifier, usingQueue = null) { task ->95            val bgTask = task ?: return@registerForTaskWithIdentifier96            submit(identifier, delaySeconds())97            val job = launchCompletingBackgroundTask(scope, {98                val outcome = run()99                // A cold launch has no in-memory schedule until admission opens the session.100                // Preserve retry eligibility without opening a database when metadata is unavailable.101                if (outcome == ProfileWorkResult.Retry) {102                    submit(identifier, maxOf(delaySeconds(), REGISTRY_RETRY_DELAY_SECONDS))103                }104                if (outcome is ProfileWorkResult.Completed && outcome.value.status == PeriodicTaskStatus.Deferred) {105                    submit(identifier, REGISTRY_RETRY_DELAY_SECONDS)106                }107                outcome108            }) { success ->109                bgTask.setTaskCompletedWithSuccess(success)110            }111            bgTask.expirationHandler = { job.cancel() }112        }113    }114115    private fun submit(identifier: String, delaySeconds: Double) {116        BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(identifier)117        if (delaySeconds <= 0.0) return118        val request = if (identifier == LIBRARY_UPDATE_TASK) {119            BGProcessingTaskRequest(identifier).apply {120                requiresNetworkConnectivity = true121                requiresExternalPower = requireLibraryPower122            }123        } else {124            BGAppRefreshTaskRequest(identifier)125        }126        request.earliestBeginDate = NSDate(127            timeIntervalSinceReferenceDate = NSDate().timeIntervalSinceReferenceDate + delaySeconds,128        )129        runCatching { BGTaskScheduler.sharedScheduler.submitTaskRequest(request, error = null) }130            .onFailure { AppLogger.warn("Could not schedule $identifier: ${it.message.orEmpty()}") }131    }132}133134private object NoProfileBackgroundScheduler : BackgroundScheduler {135    override fun schedule(metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int,136        autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean,137        libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints) = Unit138    override fun cancelAll() = Unit139}140

Search chapters, reference and source filenames.