Write an automatic backup under a free name instead of skipping a taken one (#77)

This commit is contained in:
makiolaj committed 2026-11-20 13:01:25 +01:00
1 parent 6352ae3f30
commit 69edcb2b71
4 files changed
+87 -32

No files matched your search

@@ -32,31 +32,48 @@ object AutoBackupPolicy {
private const val EXTENSION = ".zip"
private const val PARTIAL_SUFFIX = ".partial"
private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss'Z'", Locale.ROOT)
private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6}Z)\.zip""")
private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6}Z)(?:-([1-9]\d{0,5}))?\.zip""")
/** `agendula-backup-2026-11-17-143005Z.zip`: sortable, and readable in a file manager. */
fun fileName(at: Instant): String = PREFIX + STAMP.format(at.atOffset(ZoneOffset.UTC)) + EXTENSION
/**
* `agendula-backup-2026-11-17-143005Z.zip`: sortable, and readable in a
* file manager. The [n]th backup taken in one second gets `-n`.
*/
fun fileName(at: Instant, n: Int = 0): String =
PREFIX + STAMP.format(at.atOffset(ZoneOffset.UTC)) + (if (n > 0) "-$n" else "") + EXTENSION
/** The first name for a backup taken [at] that neither it nor its [partialName] has in [taken]. */
fun freeName(at: Instant, taken: Set<String>): String =
generateSequence(0) { it + 1 }.map { fileName(at, it) }.first { it !in taken && partialName(it) !in taken }
/** The name a backup is written under until it is complete. */
fun partialName(fileName: String): String = fileName + PARTIAL_SUFFIX
/** When the backup named [name] was taken, or null when it is not one of ours. */
fun timestampOf(name: String): Instant? =
fun timestampOf(name: String): Instant? = rankOf(name)?.first
private fun rankOf(name: String): Pair<Instant, Int>? =
NAME.matchEntire(name)?.let { match ->
runCatching { LocalDateTime.parse(match.groupValues[1], STAMP).toInstant(ZoneOffset.UTC) }.getOrNull()
val at = runCatching { LocalDateTime.parse(match.groupValues[1], STAMP).toInstant(ZoneOffset.UTC) }.getOrNull()
at?.let { it to (match.groupValues[2].toIntOrNull() ?: 0) }
}
/**
* 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.
* skewed clock can never rotate it away. Any other of the same second goes:
* it may be one a run never finished, and must not take a good one's place.
*/
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 }
fun staleBackups(names: Collection<String>, keep: Int, current: String): List<String> {
val at = timestampOf(current)
val (sameSecond, others) = names.filter { it != current }
.mapNotNull { name -> rankOf(name)?.let { name to it } }
.partition { it.second.first == at }
val older = others
.sortedWith(compareByDescending<Pair<String, Pair<Instant, Int>>> { it.second.first }.thenByDescending { it.second.second })
.map { it.first }
.drop(clampKeep(keep) - 1)
return sameSecond.map { it.first } + older
}
/** Backups a run never finished, e.g. because the process was killed mid-write. */
fun abandonedPartials(names: Collection<String>): List<String> =
@@ -50,9 +50,13 @@ class AutoBackupWorker @AssistedInject constructor(
val documents = readLists()
val tree = folder.toUri()
val stamp = Instant.ofEpochMilli(now)
val fileName = AutoBackupPolicy.fileName(stamp)
writer.writeZipToTree(tree, fileName, AutoBackupPolicy.partialName(fileName), documents) { names ->
AutoBackupPolicy.staleBackups(names, config.keepCount, fileName) + AutoBackupPolicy.abandonedPartials(names)
writer.writeZipToTree(
tree,
documents,
name = { taken -> AutoBackupPolicy.freeName(stamp, taken) },
partialName = AutoBackupPolicy::partialName,
) { names, written ->
AutoBackupPolicy.staleBackups(names, config.keepCount, written) + AutoBackupPolicy.abandonedPartials(names)
}
prefs.recordSuccess(now)
notifier.cancelFailure()
@@ -99,52 +99,56 @@ class ExportWriter @Inject constructor(
}
/**
* Writes every document into a new zip named [fileName] inside [treeUri],
* then deletes the files [prune] picks from the folder's names (best effort:
* a file that will not go is left, and the write still counts).
* Writes every document into a new zip inside [treeUri], under the [name]
* it picks given the folder's names, then deletes the files [prune] picks
* from those names and the one written (best effort: a file that will not
* go is left, and the write still counts). Only a file the folder held
* before the write can be pruned.
*
* Where the provider can rename, the zip is written under [partialName] and
* renamed once complete, so a run that fails — or a process killed mid-write
* — never leaves a truncated file under a finished name. Elsewhere it is
* written under [fileName] directly. An existing [fileName] is left as it is.
* Where the provider can rename, the zip is written under its [partialName]
* and renamed once complete, so a run that fails — or a process killed
* mid-write — never leaves a truncated file under a finished name.
* Elsewhere it is written under its name directly.
*/
suspend fun writeZipToTree(
treeUri: Uri,
fileName: String,
partialName: String,
documents: List<ExportDocument>,
prune: (Set<String>) -> Collection<String> = { emptyList() },
name: (taken: Set<String>) -> String,
partialName: (String) -> String,
prune: (names: Set<String>, written: String) -> Collection<String> = { _, _ -> emptyList() },
): ExportResult = withContext(io) {
val tree = openTree(treeUri)
val children = runCatching {
val (children, written) = runCatching {
val children = childDocuments(treeUri)
if (fileName !in children) writeViaPartial(tree, fileName, partialName, documents)
children - partialName
val fileName = name(children.keys)
check(fileName !in children) { "The name picked is taken" }
children to writeViaPartial(tree, fileName, partialName(fileName), documents)
}.getOrElse { throw failureIn(tree, it) }
prune(children.keys + fileName).forEach { name ->
val uri = children[name] ?: return@forEach
prune(children.keys + written, written).forEach { pruned ->
val uri = children[pruned] ?: return@forEach
runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }
}
ExportResult(documents.size, documents.map { it.fileName })
}
/** Writes the zip as [writeZipToTree] describes and returns the name the provider gave it. */
private fun writeViaPartial(
tree: DocumentFile,
fileName: String,
partialName: String,
documents: List<ExportDocument>,
) {
): String {
val partial = tree.createFile(MIME_PARTIAL, partialName)
if (partial == null || !partial.supportsRename()) {
partial?.let { runCatching { it.delete() } }
createAndZip(tree, MIME_ZIP, fileName, documents)
return
return createAndZip(tree, MIME_ZIP, fileName, documents).name ?: fileName
}
zipOrDelete(partial, documents)
if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) {
runCatching { partial.delete() }
createAndZip(tree, MIME_ZIP, fileName, documents)
return createAndZip(tree, MIME_ZIP, fileName, documents).name ?: fileName
}
return partial.name ?: fileName
}
private fun DocumentFile.supportsRename(): Boolean = runCatching {
@@ -72,6 +72,36 @@ class AutoBackupPolicyTest {
assertThat(AutoBackupPolicy.abandonedPartials(listOf(partial, name(1), "notes.partial"))).containsExactly(partial)
}
@Test
fun `a backup taken in a second that has one already gets a name of its own`() {
val base = name(17)
assertThat(AutoBackupPolicy.freeName(at(17), setOf("notes.txt"))).isEqualTo(base)
val second = AutoBackupPolicy.freeName(at(17), setOf(base))
assertThat(second).isEqualTo("agendula-backup-2026-11-17-030005Z-1.zip")
assertThat(AutoBackupPolicy.freeName(at(17), setOf(base, second)))
.isEqualTo("agendula-backup-2026-11-17-030005Z-2.zip")
assertThat(AutoBackupPolicy.freeName(at(17), setOf(AutoBackupPolicy.partialName(base)))).isEqualTo(second)
assertThat(AutoBackupPolicy.timestampOf(second)).isEqualTo(at(17))
assertThat(AutoBackupPolicy.timestampOf("agendula-backup-2026-11-17-030005Z-0.zip")).isNull()
}
@Test
fun `a backup of the same second never keeps its place over an older good one`() {
val clash = name(5)
val written = AutoBackupPolicy.freeName(at(5), setOf(clash))
val names = listOf(clash, written, name(4), name(3))
assertThat(stale(names, keep = 3, current = written)).containsExactly(clash)
assertThat(stale(names, keep = 2, current = written)).containsExactly(clash, name(3))
}
@Test
fun `numbered backups of one second sort after the bare one`() {
val later = AutoBackupPolicy.fileName(at(4), 2)
val names = listOf(AutoBackupPolicy.fileName(at(4), 1), later, name(4), name(5))
assertThat(stale(names, keep = 2, current = name(5)))
.containsExactly(AutoBackupPolicy.fileName(at(4), 1), name(4)).inOrder()
}
@Test
fun `clamps the user's choices`() {
assertThat(AutoBackupPolicy.clampInterval(15)).isEqualTo(AutoBackupPolicy.MIN_INTERVAL_MINUTES)