Address third review of automatic backup (#77)

Rotation never removes the backup just written, unreachable folders are retried, the running state covers scheduled runs, and a folder switch mid-run no longer records a failure.
This commit is contained in:
makiolaj committed 2026-11-17 11:26:12 +01:00
1 parent 47a79413b1
commit 7642c49ef6
9 files changed
+54 -51

No files matched your search

@@ -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() }
}
}
@@ -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<String>, keep: Int, now: Instant): List<String> =
names.mapNotNull { name -> timestampOf(name)?.takeIf { !it.isAfter(now) }?.let { name to it } }
fun staleBackups(names: Collection<String>, keep: Int, current: String): List<String> =
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<String>): List<String> =
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)
}
@@ -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
}
}
@@ -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<Boolean> =
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<Boolean> = 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
@@ -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()
}
}
@@ -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
}
@@ -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<AutoBackupUiState> =
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())
@@ -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)
@@ -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<String>, 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)
}