BackgroundScheduler.android.kt
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.android.kt
1package eu.friedcutlet.yokan.services.scheduling23import eu.friedcutlet.yokan.AndroidAppContext4import android.content.Context5import android.net.NetworkCapabilities6import android.net.NetworkRequest7import android.os.Build8import androidx.work.Constraints9import androidx.work.CoroutineWorker10import androidx.work.ExistingPeriodicWorkPolicy11import androidx.work.ListenableWorker12import androidx.work.NetworkType13import androidx.work.PeriodicWorkRequestBuilder14import androidx.work.WorkManager15import androidx.work.WorkerParameters16import androidx.work.workDataOf17import eu.friedcutlet.yokan.domain.ProfileId18import eu.friedcutlet.yokan.database.YokanDatabase19import java.util.concurrent.TimeUnit2021actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = AndroidBackgroundScheduler(profileId)2223/**24 * Implemented by the `Application`: a worker in a cold process bootstraps the app through it and gets25 * a profile-bound execution path, like WorkManager's `Configuration.Provider` lookup.26 */27interface BackgroundTaskHost {28 suspend fun runBackgroundTask(owner: String?, task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome): ProfileWorkResult<PeriodicTaskOutcome>29}3031private const val METADATA_REFRESH_WORK = "yokan.metadata_refresh"32private const val LIBRARY_UPDATE_WORK = "yokan.library_update"33private const val AUTO_SYNC_WORK = "yokan.auto_sync"34private const val AUTO_BACKUP_WORK = "yokan.auto_backup"3536/** Retries within one period before giving up until the next scheduled run. */37private const val MAX_WORKER_RETRIES = 33839internal fun libraryWorkConstraints(requireUnmetered: Boolean,40 config: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints): Constraints {41 val network = when (config.network) {42 eu.friedcutlet.yokan.database.DbUpdateNetwork.Legacy -> if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED43 eu.friedcutlet.yokan.database.DbUpdateNetwork.Unmetered -> NetworkType.UNMETERED44 else -> NetworkType.CONNECTED45 }46 val builder = Constraints.Builder().setRequiredNetworkType(network).setRequiresCharging(config.requireExternalPower)47 if (config.network == eu.friedcutlet.yokan.database.DbUpdateNetwork.Wifi && Build.VERSION.SDK_INT >= 28) {48 builder.setRequiredNetworkRequest(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)49 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), NetworkType.CONNECTED)50 }51 return builder.build()52}5354internal fun libraryWorkPolicy(previous: Pair<Long, Int>?, next: Pair<Long, Int>): ExistingPeriodicWorkPolicy =55 if (next.second >= 0 && previous != null && previous != next) ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE56 else ExistingPeriodicWorkPolicy.UPDATE5758internal fun periodicWorkerResult(outcome: ProfileWorkResult<PeriodicTaskOutcome>, attempt: Int): ListenableWorker.Result = when {59 !outcome.shouldRetry -> ListenableWorker.Result.success()60 outcome is ProfileWorkResult.Completed && outcome.value.status == PeriodicTaskStatus.Deferred -> ListenableWorker.Result.retry()61 attempt < MAX_WORKER_RETRIES -> ListenableWorker.Result.retry()62 else -> ListenableWorker.Result.failure()63}6465private class AndroidBackgroundScheduler(profileId: ProfileId) : BackgroundScheduler {66 private val names = ProfileWorkNamespace(profileId)67 private val owner = workDataOf(ProfileWorkNamespace.OwnerKey to profileId.value)68 /** Last (minutes, dailyAt) applied in this process; a change re-anchors instead of UPDATE-ing in place. */69 private var appliedLibrarySchedule: Pair<Long, Int>? = null7071 override fun schedule(72 metadataRefreshMinutes: Long,73 libraryUpdateMinutes: Long,74 libraryUpdateDailyAtMinutes: Int,75 autoSyncMinutes: Long,76 autoBackupHours: Long,77 requireUnmetered: Boolean,78 libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,79 ) {80 val ctx = AndroidAppContext.appContext ?: return81 val wm = WorkManager.getInstance(ctx)82 val constraints = Constraints.Builder()83 .setRequiredNetworkType(if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED)84 .build()85 if (metadataRefreshMinutes > 0) {86 wm.enqueueUniquePeriodicWork(87 names.uniqueName(METADATA_REFRESH_WORK),88 ExistingPeriodicWorkPolicy.UPDATE,89 PeriodicWorkRequestBuilder<MetadataRefreshWorker>(metadataRefreshMinutes, TimeUnit.MINUTES)90 .setInputData(owner)91 .setConstraints(constraints)92 .build(),93 )94 } else {95 wm.cancelUniqueWork(names.uniqueName(METADATA_REFRESH_WORK))96 }97 if (libraryUpdateMinutes > 0) {98 val libraryOnlyConstraints = libraryWorkConstraints(requireUnmetered, libraryConstraints)99 val daily = libraryUpdateDailyAtMinutes >= 0100 val schedule = libraryUpdateMinutes to libraryUpdateDailyAtMinutes101 // UPDATE keeps the existing period anchor, so a changed daily time must cancel and re-enqueue;102 // interval mode keeps UPDATE so every settings save does not push the next run further out.103 val policy = libraryWorkPolicy(appliedLibrarySchedule, schedule)104 appliedLibrarySchedule = schedule105 // ponytail: WorkManager re-anchors each period on the previous run's start, so a daily slot drifts106 // by however long constraints/Doze delayed the last run; switch to a self-rescheduling107 // OneTimeWorkRequest if users report drift.108 val request = PeriodicWorkRequestBuilder<LibraryUpdateWorker>(109 if (daily) 24L * 60L else libraryUpdateMinutes,110 TimeUnit.MINUTES,111 ).setConstraints(libraryOnlyConstraints).setInputData(owner)112 if (daily) request.setInitialDelay(nextDailySlotDelayMillis(libraryUpdateDailyAtMinutes), TimeUnit.MILLISECONDS)113 wm.enqueueUniquePeriodicWork(names.uniqueName(LIBRARY_UPDATE_WORK), policy, request.build())114 } else {115 appliedLibrarySchedule = null116 wm.cancelUniqueWork(names.uniqueName(LIBRARY_UPDATE_WORK))117 }118 if (autoSyncMinutes > 0) {119 wm.enqueueUniquePeriodicWork(120 names.uniqueName(AUTO_SYNC_WORK),121 ExistingPeriodicWorkPolicy.UPDATE,122 PeriodicWorkRequestBuilder<AutoSyncWorker>(autoSyncMinutes, TimeUnit.MINUTES)123 .setInputData(owner)124 .setConstraints(constraints)125 .build(),126 )127 } else {128 wm.cancelUniqueWork(names.uniqueName(AUTO_SYNC_WORK))129 }130 if (autoBackupHours > 0) {131 wm.enqueueUniquePeriodicWork(132 names.uniqueName(AUTO_BACKUP_WORK),133 ExistingPeriodicWorkPolicy.UPDATE,134 PeriodicWorkRequestBuilder<AutoBackupWorker>(autoBackupHours, TimeUnit.HOURS)135 .setInputData(owner)136 .setConstraints(Constraints.NONE)137 .build(),138 )139 } else {140 wm.cancelUniqueWork(names.uniqueName(AUTO_BACKUP_WORK))141 }142 }143144 override fun cancelAll() {145 val ctx = AndroidAppContext.appContext ?: return146 val wm = WorkManager.getInstance(ctx)147 wm.cancelUniqueWork(names.uniqueName(METADATA_REFRESH_WORK))148 wm.cancelUniqueWork(names.uniqueName(LIBRARY_UPDATE_WORK))149 wm.cancelUniqueWork(names.uniqueName(AUTO_SYNC_WORK))150 wm.cancelUniqueWork(names.uniqueName(AUTO_BACKUP_WORK))151 }152}153154/**155 * WorkManager workers delegate to the shared runner so a killed UI process156 * produces the same outcome and notification as an in-app periodic tick.157 */158class MetadataRefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {159 override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::refreshMetadata)160}161162class LibraryUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {163 override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::updateLibrary)164}165166class AutoSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {167 override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::sync)168}169170class AutoBackupWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {171 override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::backup)172}173174private suspend fun CoroutineWorker.runPeriodicTask(175 task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome,176): ListenableWorker.Result {177 // YokanApplication normally sets this; never let a worker fail on a missing context.178 if (AndroidAppContext.appContext == null) AndroidAppContext.appContext = applicationContext179 // Missing data belongs only to pre-profile Default jobs. A present but non-string ID is invalid.180 val owner = if (inputData.keyValueMap.containsKey(ProfileWorkNamespace.OwnerKey)) {181 inputData.getString(ProfileWorkNamespace.OwnerKey) ?: ""182 } else null183 val outcome = (applicationContext as BackgroundTaskHost).runBackgroundTask(owner, task)184 return periodicWorkerResult(outcome, runAttemptCount)185}186