fix(#516): review round 3 - restore missing stable copies on change runs, blocked series reported once, kept copies of deselected calendars suffix the name

This commit is contained in:
makiolaj committed 2026-11-25 15:20:11 +01:00
1 parent 732548a989
commit 4a14ebde2d
7 files changed
+85 -20

No files matched your search

@@ -278,7 +278,8 @@ class BackupWorker(
* change run (#516) leaves the dated files and their retention to the
* schedule and rewrites only the stable copies whose calendars changed.
* With the interval off, no run writes dated files, so a series whose
* stable name a file of the user's holds counts as failed.
* stable name a file of the user's holds counts as failed (a change run
* only when its content changed), and run-now skips current copies too.
*/
private suspend fun runBackup(
deps: Deps,
@@ -324,7 +325,11 @@ class BackupWorker(
} else {
emptyMap()
}
if (changeRun && targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } }) {
// Unless a stable copy went missing: with the interval off, nothing else would restore it.
if (changeRun &&
targets.all { preHashes[it.key].let { hash -> hash != null && hash == fingerprints[it.key] } } &&
(!listing.complete || targets.all { latestFileName(it.baseName) in listing.files })
) {
return RunOutcome.NothingToDo
}
val plans = planBackupFiles(
@@ -410,13 +415,17 @@ class BackupWorker(
} else {
null
}
// Its hash still goes on record, so a later change run can stop early.
if (hash != null) rememberBlocked(plan, hash)
if (!plan.backedUp(intervalOn)) {
// Its hash still goes on record, so a later change run can stop early.
val blockedHash = hash ?: if (trackHashes) export(target)?.let { fingerprintOf(target, it) } else null
blockedHash?.let { rememberBlocked(plan, it) }
// Reported once per content: a change run doesn't fail again on one that didn't change.
if (changeRun && hash == fingerprints[target.key]) continue
failed++
blocked++
continue
}
if (hash != null) rememberBlocked(plan, hash)
if (hash != null && !plan.needsRefresh(hash, fingerprints, listing.files.keys, listing.complete)) {
if (plan.latestName in listing.files) landedLatest += target.key
continue
@@ -428,6 +437,14 @@ class BackupWorker(
}
val fingerprint = fingerprintOf(target, text)
if (!changeRun) rememberBlocked(plan, fingerprint)
// Without the interval, run-now leaves a stable copy that is already current alone.
if (!changeRun && latestOnly && trackHashes && plan.latestName in listing.files &&
fingerprints[target.key] == fingerprint
) {
landedLatest += target.key
written++
continue
}
val bytes = text.toByteArray(Charsets.UTF_8)
// Not cancellable once a file exists: it must reach the ledger.
withContext(NonCancellable) {
@@ -131,7 +131,7 @@ class SettingsBackupEngine @Inject constructor(
step("reminders") { reminderScanner.scan() }
step("auto backup") {
BackupScheduler.reconcile(context, settingsPrefs)
// As in the settings screen, switching the interval (#516) backs up right away.
// Like the settings screen, an import that switches the interval (#516) backs up right away.
val active = after[SettingsKeys.autoBackupEnabled] && after[SettingsKeys.autoBackupFolderUri] != null
if (active && before.autoBackupScheduled != after.autoBackupScheduled) BackupScheduler.runNow(context)
}
@@ -1141,10 +1141,14 @@ val Preferences.autoBackupSelection: BackupSelection
val Preferences.autoBackupScheduled: Boolean
get() = backupIntervalOn(this[SettingsKeys.autoBackupScheduledStored], this[SettingsKeys.autoBackupOnChange])
/** Turning it off brings the interval back for good, not only while it stays off. */
/**
* Turning it off brings the interval back for good, and turning it on starts
* with the interval on, so an interval-off stored without it (a settings
* import) never takes effect.
*/
internal fun applyAutoBackupOnChange(prefs: MutablePreferences, enabled: Boolean) {
if (!enabled || !prefs[SettingsKeys.autoBackupOnChange]) prefs[SettingsKeys.autoBackupScheduledStored] = true
prefs[SettingsKeys.autoBackupOnChange] = enabled
if (!enabled) prefs[SettingsKeys.autoBackupScheduledStored] = true
}
/**
@@ -131,8 +131,10 @@ private val STAMP_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern(STAMP_
* it, then one holding dated files under it; series that already write under
* their id suffix keep that; with no claim at all the lowest id keeps the
* name. The others take their id as a suffix until every name in the run is
* distinct. Ledger names gone from the folder ([existing], when known) claim
* nothing. A calendar named like the combined file is always suffixed.
* distinct. A stable copy a series outside the run still holds (a calendar
* taken out of the backup) is kept, so a calendar now named like it is
* suffixed too. Ledger names gone from the folder ([existing], when known)
* claim nothing. A calendar named like the combined file is always suffixed.
*/
fun backupTargets(
calendars: List<CalendarSource>,
@@ -150,14 +152,22 @@ fun backupTargets(
val bases = calendars.associateTo(LinkedHashMap()) {
it.id to safeFileName(it.displayName, MAX_BASE_BYTES, fallback = "calendar")
}
val runKeys = calendars.map { latestLedgerKey(it.id.toString()) }.toSet()
val heldOutside = present.filterKeys { it.startsWith(LATEST_PREFIX) && it !in runKeys }
.values.flatten().map { it.lowercase() }.toSet()
while (true) {
val clashing = bases.entries.groupBy({ it.value.lowercase() }, { it.key })
.filter { (lower, ids) -> ids.size > 1 || lower == COMBINED_BACKUP_BASE.lowercase() }
if (clashing.isEmpty()) break
clashing.forEach { (lower, ids) ->
val keeper = if (lower == COMBINED_BACKUP_BASE.lowercase()) null else present.keeperOf(ids, bases)
ids.filter { it != keeper }.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" }
if (clashing.isNotEmpty()) {
clashing.forEach { (lower, ids) ->
val keeper = if (lower == COMBINED_BACKUP_BASE.lowercase()) null else present.keeperOf(ids, bases)
ids.filter { it != keeper }.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" }
}
continue
}
val taken = bases.filterValues { latestFileName(it).lowercase() in heldOutside }.keys
if (taken.isEmpty()) break
taken.forEach { id -> bases[id] = "${bases.getValue(id)}-$id" }
}
return calendars.map { calendar ->
BackupTarget(
@@ -317,7 +327,10 @@ fun backupIntervalOn(stored: Boolean, onChange: Boolean): Boolean = stored || !o
/** Without the interval there are no dated files, so every run only refreshes the stable copies. */
fun backupRunLatestOnly(changeRun: Boolean, intervalOn: Boolean): Boolean = changeRun || !intervalOn
/** Whether a run can back this series up at all: without dated files, only through its stable copy. */
/**
* Whether a run can back this series up at all: without dated files, only
* through its stable copy, which a file of the user's can block.
*/
fun BackupFilePlan.backedUp(intervalOn: Boolean): Boolean = intervalOn || latestName != null
/** Closest offered retention count to [stored], so a stray value still shows a row. */
@@ -5,6 +5,7 @@ import de.jeanlucmakiola.calendula.testSettings
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import androidx.compose.ui.unit.dp
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.domain.CalendarSource
@@ -982,6 +983,21 @@ class SettingsPrefsTest {
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `an interval-off stored without after-change backups doesn't stick once they go on`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
val prefs = SettingsPrefs(store)
store.updateData { p ->
val m = p.toMutablePreferences()
m[booleanPreferencesKey("auto_backup_scheduled")] = false
m
}
assertThat(prefs.autoBackupScheduled.first()).isTrue()
assertThat(prefs.setAutoBackupOnChange(true)).isFalse()
assertThat(prefs.autoBackupScheduled.first()).isTrue()
}
@Test
fun `a pre-411 install adopts its old file when the layout is pinned in place`(@TempDir tempDir: Path) = runTest {
val store = testDataStore(tempDir, "test_settings")
@@ -107,6 +107,18 @@ class BackupPlanTest {
.containsExactly("Fitness", "Fitness-20").inOrder()
}
@Test
fun `a stable copy kept for a calendar out of the backup isn't taken over or left blocking`() {
val ledger = mapOf(latestLedgerKey("9") to listOf("Fitness.ics"))
val target = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, setOf("Fitness.ics")).single()
assertThat(target.baseName).isEqualTo("Fitness-20")
val plan = planBackupFiles(listOf(target), ledger, setOf("Fitness.ics"), at, keep = 3).single()
assertThat(plan.backedUp(intervalOn = false)).isTrue()
val gone = backupTargets(listOf(cal(20L, "Fitness")), combined = false, ledger, existing = emptySet()).single()
assertThat(gone.baseName).isEqualTo("Fitness")
}
@Test
fun `a calendar named like the combined file doesn't share its series`() {
val target = backupTargets(listOf(cal(4L, COMBINED_BACKUP_BASE)), combined = false).single()
+9 -6
View File
@@ -645,12 +645,15 @@ the app, is left to the next scheduled run.
While the option is on, the interval itself can be switched off
(`auto_backup_scheduled`, read through `backupIntervalOn`, so it never counts as
off without the option): the periodic work is cancelled and no run writes or
prunes dated files. Run-now then rewrites every stable copy, change runs only
the changed ones, and a series whose stable name a file of the user's holds
counts as failed (not retried), since nothing else backs it up. Turning the
option off sets the interval back on, at the interval it had; any switch of the
interval backs up right away. What the text above leaves to the next scheduled
run then waits for the next run-now.
prunes dated files. Every run then rewrites only the stable copies that changed
or are missing from a complete listing (a change run checks for missing ones
even when no hash moved, since no scheduled run would restore them), and a
series whose stable name a file of the user's holds counts as failed (not
retried), since nothing else backs it up; a change run reports it again only
once its content changed. Turning the option on or off sets the interval back
on, at the interval it had; any switch of the interval backs up right away.
What the text above leaves to the next scheduled run then waits for the next
run-now.
**A backup carries the series' deleted and moved occurrences.** `EXDATE` lives on
the master row and is part of `EventExportProjection`; `IcsWriter` marks an