@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.ProfileId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import platform.BackgroundTasks.BGAppRefreshTaskRequest import platform.BackgroundTasks.BGProcessingTaskRequest import platform.BackgroundTasks.BGTask import platform.BackgroundTasks.BGTaskScheduler import platform.Foundation.NSDate private const val METADATA_REFRESH_TASK = "eu.friedcutlet.yokan.metadata-refresh" private const val LIBRARY_UPDATE_TASK = "eu.friedcutlet.yokan.library-update" private const val AUTO_SYNC_TASK = "eu.friedcutlet.yokan.auto-sync" private const val REGISTRY_RETRY_DELAY_SECONDS = 15.0 * 60.0 /** * Registers BGTask handlers before launch returns. [tasks] validates and opens the recorded owner, * since a background launch has no UI to do it. */ internal fun registerIosBackgroundTasks( tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult, ) = IosBackgroundScheduler.register(tasks) actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler { // These fixed identifiers are permitted in Info.plist and permanently belong to Default. return if (profileId == ProfileId.Default) IosBackgroundScheduler else NoProfileBackgroundScheduler } /** * Metadata refresh and sync are `BGAppRefreshTask`s (~30 s budget). The library update is a * `BGProcessingTask`: minutes of runtime, network required, run when iOS deems the device idle. * A daily time is only an `earliestBeginDate`; iOS picks the actual moment. */ private object IosBackgroundScheduler : BackgroundScheduler { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private var registered = false private var metadataRefreshMinutes = 0L private var libraryUpdateMinutes = 0L private var libraryUpdateDailyAtMinutes = -1 private var autoSyncMinutes = 0L private var requireLibraryPower = false fun register(tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult) { if (registered) return registered = true register(METADATA_REFRESH_TASK, { metadataRefreshMinutes * 60.0 }) { tasks(ProfileId.Default, PeriodicTaskRunner::refreshMetadata) } register(LIBRARY_UPDATE_TASK, ::libraryUpdateDelaySeconds) { tasks(ProfileId.Default, PeriodicTaskRunner::updateLibrary) } register(AUTO_SYNC_TASK, { autoSyncMinutes * 60.0 }) { tasks(ProfileId.Default, PeriodicTaskRunner::sync) } } override fun schedule( metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int, autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean, libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints, ) { this.metadataRefreshMinutes = metadataRefreshMinutes this.libraryUpdateMinutes = libraryUpdateMinutes this.libraryUpdateDailyAtMinutes = libraryUpdateDailyAtMinutes this.autoSyncMinutes = autoSyncMinutes this.requireLibraryPower = libraryConstraints.requireExternalPower submit(METADATA_REFRESH_TASK, metadataRefreshMinutes * 60.0) submit(LIBRARY_UPDATE_TASK, libraryUpdateDelaySeconds()) submit(AUTO_SYNC_TASK, autoSyncMinutes * 60.0) } private fun libraryUpdateDelaySeconds(): Double = when { libraryUpdateMinutes <= 0 -> 0.0 libraryUpdateDailyAtMinutes >= 0 -> nextDailySlotDelayMillis(libraryUpdateDailyAtMinutes) / 1000.0 else -> libraryUpdateMinutes * 60.0 } override fun cancelAll() { BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(METADATA_REFRESH_TASK) BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(LIBRARY_UPDATE_TASK) BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(AUTO_SYNC_TASK) } private fun register( identifier: String, delaySeconds: () -> Double, run: suspend () -> ProfileWorkResult, ) { BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifier(identifier, usingQueue = null) { task -> val bgTask = task ?: return@registerForTaskWithIdentifier submit(identifier, delaySeconds()) val job = launchCompletingBackgroundTask(scope, { val outcome = run() // A cold launch has no in-memory schedule until admission opens the session. // Preserve retry eligibility without opening a database when metadata is unavailable. if (outcome == ProfileWorkResult.Retry) { submit(identifier, maxOf(delaySeconds(), REGISTRY_RETRY_DELAY_SECONDS)) } if (outcome is ProfileWorkResult.Completed && outcome.value.status == PeriodicTaskStatus.Deferred) { submit(identifier, REGISTRY_RETRY_DELAY_SECONDS) } outcome }) { success -> bgTask.setTaskCompletedWithSuccess(success) } bgTask.expirationHandler = { job.cancel() } } } private fun submit(identifier: String, delaySeconds: Double) { BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(identifier) if (delaySeconds <= 0.0) return val request = if (identifier == LIBRARY_UPDATE_TASK) { BGProcessingTaskRequest(identifier).apply { requiresNetworkConnectivity = true requiresExternalPower = requireLibraryPower } } else { BGAppRefreshTaskRequest(identifier) } request.earliestBeginDate = NSDate( timeIntervalSinceReferenceDate = NSDate().timeIntervalSinceReferenceDate + delaySeconds, ) runCatching { BGTaskScheduler.sharedScheduler.submitTaskRequest(request, error = null) } .onFailure { AppLogger.warn("Could not schedule $identifier: ${it.message.orEmpty()}") } } } private object NoProfileBackgroundScheduler : BackgroundScheduler { override fun schedule(metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int, autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean, libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints) = Unit override fun cancelAll() = Unit }