diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt b/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt index 94fe777..4d686f1 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/AgendulaApp.kt @@ -75,6 +75,7 @@ class AgendulaApp : Application(), Configuration.Provider { if (started.get()) runCatching { entryPoint.taskNotifier().refreshChannel() } } startupGate.start() + entryPoint.autoBackupScheduler().start() refreshNotificationChannels() ProcessLifecycleOwner.get().lifecycle.addObserver(entryPoint.databaseCheckpoint()) scope.launch { @@ -90,7 +91,6 @@ class AgendulaApp : Application(), Configuration.Provider { runCatching { entryPoint.reminderRefresher().start() } runCatching { entryPoint.providerSnapshotSource().start() } runCatching { ReminderMaintenanceWorker.schedule(this@AgendulaApp) } - runCatching { entryPoint.autoBackupScheduler().start() } } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt index 82221a9..bb2e116 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicy.kt @@ -47,21 +47,23 @@ object AutoBackupPolicy { } /** - * The backups in [names] beyond the newest [keep], newest first. A name dated - * after [now] (a skewed clock, another device) is left out of the ranking - * altogether: counted, it would outrank and rotate away the backup just written. + * The backups in [names] beyond the newest [keep], newest first. [current], + * the backup just written, always ranks first, so one dated ahead by a + * skewed clock can never rotate it away. */ - fun staleBackups(names: Collection, keep: Int, now: Instant): List = - names.mapNotNull { name -> timestampOf(name)?.takeIf { !it.isAfter(now) }?.let { name to it } } + fun staleBackups(names: Collection, keep: Int, current: String): List = + names.filter { it != current } + .mapNotNull { name -> timestampOf(name)?.let { name to it } } .sortedByDescending { it.second } - .drop(clampKeep(keep)) .map { it.first } + .drop(clampKeep(keep) - 1) /** Backups a run never finished, e.g. because the process was killed mid-write. */ fun abandonedPartials(names: Collection): List = names.filter { it.endsWith(PARTIAL_SUFFIX) && timestampOf(it.removeSuffix(PARTIAL_SUFFIX)) != null } - fun clampInterval(minutes: Int): Int = minutes.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) + /** Whole hours, within bounds. */ + fun clampInterval(minutes: Int): Int = (minutes / 60 * 60).coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt index 745f349..de399b4 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPrefs.kt @@ -40,13 +40,7 @@ enum class BackupFailure(val export: ExportFailure?, val transient: Boolean) { ; companion object { - fun of(failure: ExportFailure): BackupFailure = when (failure) { - ExportFailure.FOLDER_UNAVAILABLE -> FOLDER_UNAVAILABLE - ExportFailure.FOLDER_NOT_WRITABLE -> FOLDER_NOT_WRITABLE - ExportFailure.CANNOT_CREATE_FILE -> CANNOT_CREATE_FILE - ExportFailure.LOST_ACCESS -> LOST_ACCESS - ExportFailure.WRITE_FAILED -> WRITE_FAILED - } + fun of(failure: ExportFailure): BackupFailure = entries.firstOrNull { it.export == failure } ?: WRITE_FAILED } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt index 739d1ad..77c4700 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupScheduler.kt @@ -12,6 +12,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.agendula.data.di.ApplicationScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map @@ -38,7 +39,7 @@ class AutoBackupScheduler @Inject constructor( private data class Plan(val folderUri: String, val intervalMinutes: Int) - /** Call once, from `Application.onCreate`. */ + /** Call once, first thing in `Application.onCreate`, so no settings change predates the collector. */ fun start() { scope.launch { runCatching { forgetUngrantedFolder() } @@ -69,16 +70,19 @@ class AutoBackupScheduler @Inject constructor( ) } - /** Whether a [runNow] backup is about to run or running; waiting out a retry does not count. */ - val runningNow: Flow = - WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW) - .map { infos -> - infos.any { - it.state == WorkInfo.State.RUNNING || - (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) - } - } - .distinctUntilChanged() + /** + * Whether a backup is running, or a [runNow] one is about to; a periodic one + * waiting for its time, or any run waiting out a retry, does not count. + */ + val running: Flow = WorkManager.getInstance(context).let { workManager -> + combine( + workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW), + workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME), + ) { now, periodic -> + now.any { it.state == WorkInfo.State.RUNNING || (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) } || + periodic.any { it.state == WorkInfo.State.RUNNING } + }.distinctUntilChanged() + } /** * Settings restored onto another device (Android's own backup) bring the diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt index 0081693..231c1d2 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupWorker.kt @@ -9,7 +9,6 @@ import androidx.work.WorkerParameters import dagger.assisted.Assisted import dagger.assisted.AssistedInject import de.jeanlucmakiola.agendula.data.export.ExportFailedException -import de.jeanlucmakiola.agendula.data.export.ExportFailure import de.jeanlucmakiola.agendula.data.export.ExportWriter import de.jeanlucmakiola.agendula.data.export.TaskExporter import de.jeanlucmakiola.agendula.data.tasks.StartupGate @@ -39,13 +38,11 @@ class AutoBackupWorker @AssistedInject constructor( private val notifier: BackupNotifier, ) : CoroutineWorker(context, params) { - // The periodic run and "Back up now" are separate work chains; one at a time, - // or one run's rotation could delete what the other is still writing. + // One at a time across the periodic and "now" chains. override suspend fun doWork(): Result = runLock.withLock { backUp() } private suspend fun backUp(): Result { val config = prefs.config.first() - // Turned off since this was queued: nothing to do, and nothing to retry. val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success() val now = System.currentTimeMillis() return try { @@ -55,7 +52,7 @@ class AutoBackupWorker @AssistedInject constructor( val stamp = Instant.ofEpochMilli(now) val fileName = AutoBackupPolicy.fileName(stamp) writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) { names -> - AutoBackupPolicy.staleBackups(names, config.keepCount, stamp) + AutoBackupPolicy.abandonedPartials(names) + AutoBackupPolicy.staleBackups(names, config.keepCount, fileName) + AutoBackupPolicy.abandonedPartials(names) } prefs.recordSuccess(now) notifier.cancelFailure() @@ -64,13 +61,16 @@ class AutoBackupWorker @AssistedInject constructor( throw cancelled } catch (error: Exception) { Log.w(TAG, "Automatic backup failed", error) + // The user moved the backup elsewhere mid-run; the old folder's failure is not theirs. + if (prefs.config.first().folderUri != folder) return Result.success() val reason = when (error) { is BackupFailedException -> error.failure is ExportFailedException -> BackupFailure.of(error.failure) - else -> BackupFailure.of(ExportFailure.WRITE_FAILED) + else -> BackupFailure.WRITE_FAILED } val retry = reason.transient && runAttemptCount < MAX_RETRIES - if (prefs.recordFailure(now, reason, final = !retry) >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() + val failures = prefs.recordFailure(now, reason, final = !retry) + if (!retry && failures >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure() if (retry) Result.retry() else Result.failure() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt index ec71c71..515430b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/export/ExportWriter.kt @@ -198,6 +198,8 @@ class ExportWriter @Inject constructor( private fun openWritableTree(treeUri: Uri): DocumentFile { val tree = DocumentFile.fromTreeUri(context, treeUri) ?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) + // An unmounted volume or a dead provider answers neither query. + if (!tree.exists()) throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE) if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE) return tree } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt index c5c2450..255b709 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/AutoBackupViewModel.kt @@ -49,15 +49,13 @@ class AutoBackupViewModel @Inject constructor( private val folderRejected = MutableStateFlow(false) - // A provider query, so off the main thread: the folder may be on an SD card - // or a cloud provider that is slow to answer. Starts unknown so the rest of - // the screen does not wait for it. + // A provider query: off the main thread, and not holding up the rest of the state. private val folderName = prefs.config.map { it.folderUri }.distinctUntilChanged().map { uri -> uri?.let { withContext(io) { runCatching { DocumentFile.fromTreeUri(context, it.toUri())?.name }.getOrNull() } } }.onStart { emit(null) } val state: StateFlow = - combine(prefs.config, prefs.status, scheduler.runningNow, folderName, folderRejected) { + combine(prefs.config, prefs.status, scheduler.running, folderName, folderRejected) { config, status, running, name, rejected -> AutoBackupUiState(config, status, running, name, rejected) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AutoBackupUiState()) diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt index 9e938a4..08cfdd3 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/settings/BackupScreen.kt @@ -85,8 +85,7 @@ internal fun BackupScreen( summary = stringResource(R.string.backup_auto_hint), checked = config.active, onCheckedChange = { on -> - // On without a folder has nowhere to write: ask for one, and the - // pick turns it on. + // No folder yet: the pick turns it on. if (on && config.folderUri == null) launchFolderPicker() else viewModel.setEnabled(on) }, position = if (config.active) Position.Top else Position.Alone, @@ -249,13 +248,14 @@ private fun backupKeepLabel(count: Int): String = pluralStringResource(R.plurals @Composable private fun backupStatusText(state: AutoBackupUiState): String { val status = state.status - // "5 minutes ago" has to move on while the screen stays open. - val now by produceState(System.currentTimeMillis()) { + // Ticks so "5 minutes ago" moves on; never behind a run that just finished. + val tick by produceState(System.currentTimeMillis()) { while (true) { delay(STATUS_TICK_MILLIS) value = System.currentTimeMillis() } } + val now = maxOf(tick, status.lastRunMillis, status.lastSuccessMillis) val failure = status.failure return when { state.running -> stringResource(R.string.backup_auto_status_running) diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt index a071d37..b3bca3e 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/backup/AutoBackupPolicyTest.kt @@ -11,9 +11,8 @@ class AutoBackupPolicyTest { private fun name(day: Int, hour: Int = 3) = AutoBackupPolicy.fileName(at(day, hour)) - private companion object { - val NOW: Instant = Instant.parse("2026-11-30T00:00:00Z") - } + private fun stale(names: List, keep: Int, current: String = names.max()) = + AutoBackupPolicy.staleBackups(names, keep, current) @Test fun `names a backup by its UTC time`() { @@ -33,35 +32,38 @@ class AutoBackupPolicyTest { @Test fun `rotation drops everything beyond the newest kept`() { val names = listOf(name(3), name(1), name(5), name(4), name(2)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 3, now = NOW)).containsExactly(name(2), name(1)).inOrder() + assertThat(stale(names, keep = 3)).containsExactly(name(2), name(1)).inOrder() } @Test fun `rotation orders by time within a day`() { val names = listOf(name(1, hour = 23), name(1, hour = 9), name(1, hour = 10)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(1, hour = 10), name(1, hour = 9)) + assertThat(stale(names, keep = 1)).containsExactly(name(1, hour = 10), name(1, hour = 9)) } @Test fun `rotation leaves files that are not backups alone`() { val names = listOf("notes.txt", "agendula-tasks.zip", AutoBackupPolicy.partialName(name(3)), name(1), name(2)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(1)) + assertThat(stale(names, keep = 1, current = name(2))).containsExactly(name(1)) } @Test fun `rotation keeps at least the newest backup`() { - assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 0, now = NOW)).containsExactly(name(1)) + assertThat(stale(listOf(name(1), name(2)), keep = 0)).containsExactly(name(1)) } @Test fun `nothing is stale while under the limit`() { - assertThat(AutoBackupPolicy.staleBackups(listOf(name(1), name(2)), keep = 7, now = NOW)).isEmpty() + assertThat(stale(listOf(name(1), name(2)), keep = 7)).isEmpty() } @Test fun `a backup dated in the future never outranks the one just written`() { - val names = listOf("agendula-backup-2027-06-01-000000Z.zip", name(5), name(4)) - assertThat(AutoBackupPolicy.staleBackups(names, keep = 1, now = NOW)).containsExactly(name(4)) + val future = "agendula-backup-2027-06-01-000000Z.zip" + assertThat(stale(listOf(future, name(5), name(4)), keep = 1, current = name(5))) + .containsExactly(future, name(4)) + assertThat(stale(listOf(future, name(5), name(4)), keep = 2, current = name(5))) + .containsExactly(name(4)) } @Test @@ -74,6 +76,7 @@ class AutoBackupPolicyTest { fun `clamps the user's choices`() { assertThat(AutoBackupPolicy.clampInterval(15)).isEqualTo(AutoBackupPolicy.MIN_INTERVAL_MINUTES) assertThat(AutoBackupPolicy.clampInterval(1_440)).isEqualTo(1_440) + assertThat(AutoBackupPolicy.clampInterval(90)).isEqualTo(60) assertThat(AutoBackupPolicy.clampKeep(0)).isEqualTo(1) assertThat(AutoBackupPolicy.clampKeep(5_000)).isEqualTo(AutoBackupPolicy.MAX_KEEP) }