feat(#147, #411): stable undated latest copy per backup series

This commit is contained in:
makiolaj committed 2026-11-13 21:56:54 +01:00
1 parent d86a09b744
commit 88c64d5786
5 files changed
+143 -25

No files matched your search

@@ -29,6 +29,7 @@ import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.calendula.domain.backup.backupTargets
import de.jeanlucmakiola.calendula.domain.backup.planBackupFiles
import de.jeanlucmakiola.calendula.domain.backup.updatedBackupLedger
import de.jeanlucmakiola.calendula.domain.backup.updatedLatestLedger
import de.jeanlucmakiola.calendula.domain.ics.IcsWriter
import de.jeanlucmakiola.floret.android.hasPermission
import kotlinx.coroutines.NonCancellable
@@ -181,6 +182,13 @@ class BackupWorker(
val name = exporter.writeToFolder(folder, listing, plan.fileName, content)
ledger = updatedBackupLedger(ledger, plan, name, undeleted = plan.prune, liveKeys)
prefs.setAutoBackupLedger(ledger)
plan.latestName?.let { latest ->
val latestName = exporter.writeToFolder(folder, listing, latest, content)
ledger = updatedLatestLedger(ledger, plan, latestName, plan.staleLatest, liveKeys)
prefs.setAutoBackupLedger(ledger)
val staleLeft = exporter.deleteFromFolder(listing, plan.staleLatest)
ledger = updatedLatestLedger(ledger, plan, latestName, staleLeft, liveKeys)
}
val undeleted = exporter.deleteFromFolder(listing, plan.prune)
ledger = updatedBackupLedger(ledger, plan, name, undeleted, liveKeys)
prefs.setAutoBackupLedger(ledger)
@@ -68,13 +68,22 @@ data class BackupFilePlan(
val keep: List<String>,
/** Earlier files of this series beyond the retention count, oldest first. */
val prune: List<String>,
/**
* The stable, undated copy overwritten every run (`<base>.ics`), for tools
* that follow one path. Null when a file of that name is in the folder but
* isn't one this backup wrote: the user's own file is never overwritten.
*/
val latestName: String?,
/** This series' earlier stable copies under a name it no longer uses (a rename), to delete. */
val staleLatest: List<String> = emptyList(),
)
/**
* The files the automatic backup has written, per series key, oldest first.
* Pruning only ever deletes names recorded here, so a series is its files, not
* whatever currently matches a calendar's name: renames, same-named calendars
* and the user's own files in the folder can't pull in the wrong ones.
* and the user's own files in the folder can't pull in the wrong ones. A
* series' stable copy is recorded apart, under [latestLedgerKey].
*/
typealias BackupLedger = Map<String, List<String>>
@@ -83,9 +92,17 @@ const val COMBINED_SERIES = "combined"
/** The combined file's series name; also the fixed name used before #411. */
const val COMBINED_BACKUP_BASE = "calendula-backup"
/** The single file every automatic backup overwrote before #411. */
/**
* The single file every automatic backup overwrote before #411: the combined
* series' stable copy now, so an old setup keeps its path.
*/
const val LEGACY_BACKUP_FILE = "$COMBINED_BACKUP_BASE.ics"
private const val LATEST_PREFIX = "latest-"
/** Where the ledger records the stable copy of the series [key]. */
fun latestLedgerKey(key: String): String = "$LATEST_PREFIX$key"
/** The retention choices the settings offer, newest kept first. */
val BACKUP_KEEP_OPTIONS: List<Int> = listOf(1, 2, 3, 5, 7, 10)
@@ -136,10 +153,12 @@ fun backupFileName(baseName: String, at: LocalDateTime): String =
"${baseName}_${at.format(STAMP_FORMAT)}$ICS_EXTENSION"
/**
* Plan one run: a new file per target, and which of the series' recorded files
* ([ledger]) fall out of the newest [keep], the new one included. Recorded files
* no longer in the folder ([existing]) are forgotten. The pre-#411
* [LEGACY_BACKUP_FILE] joins the combined series as its oldest file.
* Plan one run: a new dated file per target, and which of the series' recorded
* files ([ledger]) fall out of the newest [keep], the new one included. Recorded
* files no longer in the folder ([existing]) are forgotten. Each target also
* gets its stable copy, which retention never touches; a renamed series drops
* its old one. The pre-#411 [LEGACY_BACKUP_FILE] is the combined series'
* stable copy, so it is overwritten rather than left to go stale.
*/
fun planBackupFiles(
targets: List<BackupTarget>,
@@ -149,21 +168,21 @@ fun planBackupFiles(
keep: Int,
): List<BackupFilePlan> {
val retain = keep.coerceAtLeast(1)
val ownLatest = ledger.filterKeys { it.startsWith(LATEST_PREFIX) }.values.flatten().toSet() + LEGACY_BACKUP_FILE
val currentLatest = targets.map { latestFileName(it.baseName) }.toSet()
return targets.map { target ->
val fileName = backupFileName(target.baseName, at)
val recorded = ledger[target.key].orEmpty()
val legacy = if (target.key == COMBINED_SERIES && LEGACY_BACKUP_FILE !in recorded) {
listOf(LEGACY_BACKUP_FILE)
} else {
emptyList()
}
val earlier = (legacy + recorded).filter { it in existing && it != fileName }.distinct()
val earlier = ledger[target.key].orEmpty().filter { it in existing && it != fileName }.distinct()
val kept = earlier.takeLast(retain - 1)
val latest = latestFileName(target.baseName)
BackupFilePlan(
target = target,
fileName = fileName,
keep = kept,
prune = earlier.dropLast(kept.size),
latestName = latest.takeIf { it !in existing || it in ownLatest },
staleLatest = ledger[latestLedgerKey(target.key)].orEmpty()
.filter { it in existing && it != latest && it !in currentLatest },
)
}
}
@@ -181,11 +200,37 @@ fun updatedBackupLedger(
undeleted: Collection<String>,
liveKeys: Set<String>,
): BackupLedger {
val next = previous.filterKeys { it in liveKeys || it == COMBINED_SERIES }.toMutableMap()
val next = previous.livePart(liveKeys)
next[plan.target.key] = (plan.prune.filter { it in undeleted } + plan.keep + writtenName).distinct()
return next.filterValues { it.isNotEmpty() }
}
/**
* The ledger once [plan]'s stable copy landed as [writtenName]: recorded with
* any stale copy that wouldn't delete ([undeleted]), so a later run retries it.
*/
fun updatedLatestLedger(
previous: BackupLedger,
plan: BackupFilePlan,
writtenName: String,
undeleted: Collection<String>,
liveKeys: Set<String>,
): BackupLedger {
val next = previous.livePart(liveKeys)
next[latestLedgerKey(plan.target.key)] = (plan.staleLatest.filter { it in undeleted } + writtenName).distinct()
return next.filterValues { it.isNotEmpty() }
}
/** Entries of calendars that still exist; a deleted calendar's files stay, unrecorded. */
private fun BackupLedger.livePart(liveKeys: Set<String>): MutableMap<String, List<String>> =
filterKeys { key ->
val series = key.removePrefix(LATEST_PREFIX)
series in liveKeys || series == COMBINED_SERIES
}.toMutableMap()
/** `Work.ics`: the series' stable copy. */
fun latestFileName(baseName: String): String = "$baseName$ICS_EXTENSION"
private const val LEDGER_ENTRY_SEP = "|"
private const val LEDGER_KEY_SEP = "/"
+1 -1
View File
@@ -912,7 +912,7 @@
<item quantity="one">Only the latest</item>
<item quantity="other">The latest %d</item>
</plurals>
<string name="calendars_auto_backup_keep_hint">Counted per file: with one file per calendar, each calendar keeps this many. Older backups Calendula wrote are deleted after each run; a calendar you stop backing up keeps its last files, and nothing else in the folder is touched.</string>
<string name="calendars_auto_backup_keep_hint">Counted per file: with one file per calendar, each calendar keeps this many dated copies, plus one undated copy that always holds the latest backup. Older backups Calendula wrote are deleted after each run; a calendar you stop backing up keeps its last files, and nothing else in the folder is touched.</string>
<string name="calendars_auto_backup_status_never">No automatic backup yet</string>
<string name="calendars_auto_backup_status_ok">Last backup: %1$s</string>
<string name="calendars_auto_backup_status_failed">Last backup failed: %1$s</string>
@@ -128,21 +128,81 @@ class BackupPlanTest {
assertThat(plan.prune).isEmpty()
}
private val combined = BackupTarget(COMBINED_SERIES, setOf(1L, 2L), COMBINED_BACKUP_BASE, null)
@Test
fun `the pre-411 backup file is the combined series' oldest member`() {
val target = BackupTarget(COMBINED_SERIES, setOf(1L, 2L), COMBINED_BACKUP_BASE, null)
val newer = "calendula-backup_2026-11-12_09-00-00.ics"
val ledger = mapOf(COMBINED_SERIES to listOf(newer))
val existing = setOf(LEGACY_BACKUP_FILE, newer)
assertThat(planBackupFiles(listOf(target), ledger, existing, at, keep = 3).single().prune).isEmpty()
assertThat(planBackupFiles(listOf(target), ledger, existing, at, keep = 2).single().prune)
.containsExactly(LEGACY_BACKUP_FILE)
fun `the pre-411 backup file becomes the combined series' stable copy`() {
val plan = planBackupFiles(listOf(combined), emptyMap(), setOf(LEGACY_BACKUP_FILE), at, keep = 1).single()
assertThat(plan.latestName).isEqualTo(LEGACY_BACKUP_FILE)
assertThat(plan.prune).isEmpty()
}
@Test
fun `per-calendar series leave the legacy combined file alone`() {
val plan = planBackupFiles(listOf(work), emptyMap(), setOf(LEGACY_BACKUP_FILE), at, keep = 1).single()
assertThat(plan.prune).isEmpty()
assertThat(plan.staleLatest).isEmpty()
assertThat(plan.latestName).isEqualTo("Work.ics")
}
@Test
fun `the stable copy is never pruned and never overwrites the user's own file`() {
val ours = planBackupFiles(
listOf(work),
mapOf("1" to listOf("Work_a.ics"), latestLedgerKey("1") to listOf("Work.ics")),
setOf("Work_a.ics", "Work.ics"),
at,
keep = 1,
).single()
assertThat(ours.latestName).isEqualTo("Work.ics")
assertThat(ours.prune).containsExactly("Work_a.ics")
val foreign = planBackupFiles(listOf(work), emptyMap(), setOf("Work.ics"), at, keep = 1).single()
assertThat(foreign.latestName).isNull()
}
@Test
fun `a renamed calendar replaces its old stable copy`() {
val job = BackupTarget("1", setOf(1L), "Job", "Job")
val plan = planBackupFiles(
listOf(job),
mapOf(latestLedgerKey("1") to listOf("Work.ics")),
setOf("Work.ics"),
at,
keep = 3,
).single()
assertThat(plan.latestName).isEqualTo("Job.ics")
assertThat(plan.staleLatest).containsExactly("Work.ics")
assertThat(updatedLatestLedger(emptyMap(), plan, "Job.ics", emptySet(), setOf("1")))
.containsExactly(latestLedgerKey("1"), listOf("Job.ics"))
}
@Test
fun `a stable copy another calendar took over is not deleted, but rewritten by it`() {
// Calendar 1 was "Work", is now "Job"; calendar 2 is now called "Work".
val ledger = mapOf(latestLedgerKey("1") to listOf("Work.ics"))
val plans = planBackupFiles(
listOf(BackupTarget("1", setOf(1L), "Job", "Job"), BackupTarget("2", setOf(2L), "Work", "Work")),
ledger,
setOf("Work.ics"),
at,
keep = 1,
)
assertThat(plans[0].staleLatest).isEmpty()
assertThat(plans[1].latestName).isEqualTo("Work.ics")
}
@Test
fun `a deleted calendar's ledger entries are dropped, its files left`() {
val plan = planBackupFiles(listOf(work), emptyMap(), emptySet(), at, keep = 1).single()
val next = updatedLatestLedger(
previous = mapOf(latestLedgerKey("7") to listOf("Gone.ics"), latestLedgerKey(COMBINED_SERIES) to listOf(LEGACY_BACKUP_FILE)),
plan = plan,
writtenName = "Work.ics",
undeleted = emptySet(),
liveKeys = setOf("1"),
)
assertThat(next.keys).containsExactly(latestLedgerKey("1"), latestLedgerKey(COMBINED_SERIES))
}
@Test
+7 -2
View File
@@ -474,8 +474,13 @@ each series to the retention count after its new file has landed. Pruning only
deletes names recorded in a per-series ledger of files the backup wrote
(`auto_backup_files`, keyed by calendar id), never whatever happens to match a
name, so renames, same-named calendars and the user's own files are safe; the
pre-#411 fixed `calendula-backup.ics` counts as the combined series' oldest file,
and an install that already had a folder stays on the combined layout.
Each series also keeps a stable undated copy (`<calendar name>.ics`, or
`calendula-backup.ics` combined) overwritten every run, so sync tools and
subscriptions can follow one path; retention never touches it, it never
overwrites a file the backup didn't write, and a renamed calendar's old copy is
deleted while a deselected one's is kept. The pre-#411 fixed
`calendula-backup.ics` simply is the combined series' stable copy, and an
install that already had a folder stays on the combined layout.
**A backup carries the series' deleted occurrences.** `EXDATE` lives on the
master row, so the export query's `ORIGINAL_ID IS NULL` filter — which does drop