data: atomic restores and vault-adjacent writes
- Commit
35dbac91cc85256565cb28fbbe56582454e5fc4c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 20:44 UTC (15 days ago)
- Parents
b699b73
Restore could destroy live state: SqlCipherDbCodec deleted the live DB before importing (a corrupt restore file meant total loss), and BackupHelper copied over live prefs files and deleted extra dirs before copying. Import now builds and verifies a temp DB (integrity_check ok) and swaps with .bak rollback; prefs/extras restore via sibling temp + rename swap; restore temp dirs are per-call unique. Tests prove corrupt or missing input leaves the live DB byte-identical. Also: launcher's toItemType converter no longer crashes on unknown values (APPLICATION fallback), findfamily multi-write deletes run in withWriteTransaction, everysync VaultStore uses single-edit read-modify-write, and voxels world.json / Kdbx backups write via temp+rename. Verified: library 197 + room 35 tests; compile for all touched modules.
Diff
everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.ktindex a3360dff30..030e9585ab 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/data/VaultStore.kt@@ -37,12 +37,14 @@ object VaultStore { private const val KEY = "everysync_vaults" private val json = Json { ignoreUnknownKeys = true } - fun getAll(context: Context): List<VaultMeta> {- val raw = DataStoreUtils.getInstance(context).getString(KEY)+ private fun decode(raw: String?): List<VaultMeta> { if (raw.isNullOrBlank()) return emptyList() return runCatching { json.decodeFromString<List<VaultMeta>>(raw) }.getOrDefault(emptyList()) } + fun getAll(context: Context): List<VaultMeta> =+ decode(DataStoreUtils.getInstance(context).getString(KEY))+ fun get(context: Context, vaultId: String): VaultMeta? = getAll(context).firstOrNull { it.vaultId == vaultId } @@ -54,13 +56,17 @@ object VaultStore { } else { meta }- val current = getAll(context).filterNot { it.vaultId == safe.vaultId }- DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(current + safe))+ // Atomic read-modify-write inside one DataStore edit: the old getAll()+setString+ // raced concurrent upsert/remove callers and silently dropped each other's vault.+ DataStoreUtils.getInstance(context).updateString(KEY) { raw ->+ json.encodeToString(decode(raw).filterNot { it.vaultId == safe.vaultId } + safe)+ } } suspend fun remove(context: Context, vaultId: String) {- val current = getAll(context).filterNot { it.vaultId == vaultId }- DataStoreUtils.getInstance(context).setString(KEY, json.encodeToString(current))+ DataStoreUtils.getInstance(context).updateString(KEY) { raw ->+ json.encodeToString(decode(raw).filterNot { it.vaultId == vaultId })+ } } suspend fun saveAll(context: Context, vaults: List<VaultMeta>) {
findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.ktindex 624802723f..6d1d50a8bf 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt@@ -1,6 +1,7 @@ package com.vayunmathur.findfamily.data import android.content.Context+import androidx.room3.withWriteTransaction import com.vayunmathur.library.room.RoomRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first@@ -69,11 +70,11 @@ class FindFamilyRepository internal constructor( * precise history outlived the removal (until the 7-day sweep) and * silently resurrected if the same ID was ever re-added. */- suspend fun deleteUser(user: User): Int {+ suspend fun deleteUser(user: User): Int = daoDb.withWriteTransaction { val deleted = userDao.delete(user) locationValueDao.deleteByUserid(user.id) noShowAlertDao.deleteByWatchedUserId(user.id)- return deleted+ deleted } suspend fun updateLocationMeta(@@ -125,7 +126,7 @@ class FindFamilyRepository internal constructor( * `repository.waypointStore.*`. */ internal val waypointStore: WaypointStore- get() = WaypointStore(waypointDao, userDao, noShowAlertDao)+ get() = WaypointStore(waypointDao, userDao, noShowAlertDao, daoDb) // ------------------------------------------------------------------ // LocationValue reads / writes@@ -191,6 +192,7 @@ internal class WaypointStore( private val dao: WaypointDao, private val userDao: UserDao, private val noShowAlertDao: NoShowAlertDao,+ private val database: FFDatabase, ) { suspend fun getAll(): List<Waypoint> = dao.getAll() suspend fun get(id: Long): Waypoint = dao.get(id)@@ -202,11 +204,11 @@ internal class WaypointStore( * arrivals there. Without this they pointed at a place that no longer * exists - toggles silently dead, watches firing for a deleted place. */- suspend fun delete(waypoint: Waypoint): Int {+ suspend fun delete(waypoint: Waypoint): Int = database.withWriteTransaction { val deleted = dao.delete(waypoint) userDao.clearArrivalTogglesForWaypoint(waypoint.id) userDao.clearLastWaypointForWaypoint(waypoint.id) noShowAlertDao.deleteByWaypointId(waypoint.id)- return deleted+ deleted } }
games/voxels/src/main/java/com/vayunmathur/games/voxels/data/WorldManager.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/WorldManager.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/WorldManager.ktindex ca38f79863..5ea353e71f 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/WorldManager.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/WorldManager.kt@@ -51,6 +51,28 @@ data class WorldInfo( object WorldManager { private val json = Json { ignoreUnknownKeys = true; prettyPrint = true } + /**+ * Write [meta] as `world.json` in [dir] via tmp file + rename, so a crash mid-write+ * never leaves a torn file that [listWorlds] then silently drops. Same shape as+ * `AndroidFileBlobStore.put` (library/everysync-core): temp in the same directory,+ * rename, delete+rename fallback where rename cannot replace, temp always cleaned up.+ * (No `FileFiles.writeBytes` exists in library/ — verified, it does not do this.)+ */+ private fun writeWorldMeta(dir: File, meta: WorldMeta) {+ val target = File(dir, "world.json")+ dir.mkdirs()+ val tmp = File.createTempFile("world-", ".tmp", dir)+ try {+ tmp.writeText(json.encodeToString(WorldMeta.serializer(), meta))+ if (!tmp.renameTo(target)) {+ target.delete()+ tmp.renameTo(target)+ }+ } finally {+ if (tmp.exists()) tmp.delete()+ }+ }+ private fun worldsRoot(ctx: Context): File = File(ctx.filesDir, "worlds").apply { mkdirs() } // All worlds, most-recently-played first.@@ -86,7 +108,7 @@ object WorldManager { val dir = File(root, id).apply { mkdirs() } val displayName = name.trim().ifEmpty { "New World" } val meta = WorldMeta(name = displayName, seed = seed, created = now, lastPlayed = now, mode = mode)- File(dir, "world.json").writeText(json.encodeToString(WorldMeta.serializer(), meta))+ writeWorldMeta(dir, meta) return WorldInfo(id = id, dir = dir.absolutePath, meta = meta) } @@ -109,7 +131,7 @@ object WorldManager { online = true, worldId = worldId, ownerDeviceId = ownerDeviceId, role = VoxelsRoles.OWNER, keyB64 = keyB64, )- File(dir, "world.json").writeText(json.encodeToString(WorldMeta.serializer(), meta))+ writeWorldMeta(dir, meta) return WorldInfo(id = id, dir = dir.absolutePath, meta = meta) } @@ -129,7 +151,7 @@ object WorldManager { name = name.trim().ifEmpty { "Shared World" }, seed = seed, created = now, lastPlayed = now, online = true, worldId = worldId, ownerDeviceId = ownerDeviceId, role = role, keyB64 = keyB64, )- File(dir, "world.json").writeText(json.encodeToString(WorldMeta.serializer(), meta))+ writeWorldMeta(dir, meta) return WorldInfo(id = id, dir = dir.absolutePath, meta = meta) } @@ -140,7 +162,7 @@ object WorldManager { if (!metaFile.exists()) return try { val meta = json.decodeFromString<WorldMeta>(metaFile.readText())- metaFile.writeText(json.encodeToString(WorldMeta.serializer(), meta.copy(lastPlayed = now)))+ writeWorldMeta(dir, meta.copy(lastPlayed = now)) } catch (_: Exception) {} }
launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.ktindex 887a3fa629..ef1469148a 100644--- a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt+++ b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt@@ -12,6 +12,7 @@ import com.vayunmathur.launcher.domain.LauncherItemType import com.vayunmathur.launcher.domain.PackageKey import com.vayunmathur.launcher.domain.ReconcileUseCase import com.vayunmathur.launcher.domain.containerRefOf+import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DatabaseItem /**@@ -126,5 +127,17 @@ class LauncherConverters { fun fromItemType(value: LauncherItemType): String = value.name @ColumnTypeConverter- fun toItemType(value: String): LauncherItemType = LauncherItemType.valueOf(value)+ fun toItemType(value: String): LauncherItemType =+ LauncherItemType.entries.firstOrNull { it.name == value } ?: run {+ // A newer build may have written a type this build does not know (downgrade /+ // partial upgrade). Room converters never throw: fall back to APPLICATION, the+ // safest existing value — the row stays visible and launchable from its stored+ // package/class instead of crashing every workspace read.+ Log.status(TAG, "unknown LauncherItemType '$value', defaulting to APPLICATION")+ LauncherItemType.APPLICATION+ }++ private companion object {+ const val TAG = "LauncherConverters"+ } }
library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt
diff --git a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.ktindex 2eb6ccdc74..d56d99776f 100644--- a/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt+++ b/library/room/src/main/java/com/vayunmathur/library/room/SqlCipherDbCodec.kt@@ -5,6 +5,8 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DbBackupCodec import net.zetetic.database.sqlcipher.SQLiteDatabase import java.io.File+import java.io.IOException+import java.util.UUID /** * SQLCipher-backed [DbBackupCodec]. Exports an encrypted Room database to a@@ -51,31 +53,146 @@ object SqlCipherDbCodec : DbBackupCodec { db.close() } + /**+ * Imports [inputFile] without ever putting the live database at risk+ * until the replacement is proven good:+ *+ * 1. Build the encrypted replacement in a sibling temp file.+ * 2. Verify it: reopen with [password] and require+ * `PRAGMA integrity_check` to report `ok`.+ * 3. Swap: rename live files to `*.bak-*`, rename the temp in, delete+ * the backup. On swap failure the `.bak-*` files are renamed back.+ *+ * Any failure before the swap (missing/corrupt input, wrong password,+ * failed verify) deletes only the temp file — the live DB and its+ * `-wal`/`-shm`/`-journal` sidecars stay byte-for-byte untouched.+ *+ * Callers must close the live database first (see+ * [DbBackupCodec.importDatabase]): this codec does not own Room's+ * cached instances, and an open handle would keep reading the+ * pre-swap file after the rename.+ */ override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) { loadSqlCipher() val dbFile = context.getDatabasePath(dbName)+ if (!inputFile.exists() || inputFile.length() == 0L) {+ throw IOException("importDatabase: input file missing or empty: ${inputFile.path}")+ }+ val parent = dbFile.parentFile+ ?: throw IOException("importDatabase: database has no parent directory: ${dbFile.path}")+ parent.mkdirs() - val inputPath = inputFile.canonicalPath- val outputPath = dbFile.canonicalPath-- // Delete existing database files- dbFile.delete()- File("$outputPath-wal").delete()- File("$outputPath-shm").delete()- File("$outputPath-journal").delete()+ val tempFile = File(parent, "${dbFile.name}.import-${UUID.randomUUID()}.tmp")+ try {+ buildEncryptedCopy(inputFile, tempFile, password)+ verifyEncryptedCopy(tempFile, password)+ swapIntoPlace(tempFile, dbFile)+ } finally {+ // No-op once the swap renamed the temp into place.+ deleteWithSidecars(tempFile)+ }+ } - // Create a new encrypted database from the plaintext input+ /** Creates a fresh encrypted DB at [tempFile] holding [inputFile]'s contents. */+ private fun buildEncryptedCopy(inputFile: File, tempFile: File, password: String) {+ if (tempFile.exists()) tempFile.delete()+ tempFile.createNewFile() val db = SQLiteDatabase.openDatabase(- outputPath,+ tempFile.canonicalPath, password, null, SQLiteDatabase.OPEN_READWRITE or SQLiteDatabase.CREATE_IF_NECESSARY, null )- db.rawExecSQL("PRAGMA cipher_compatibility = 4")- db.rawExecSQL("ATTACH DATABASE '$inputPath' AS plaintext KEY ''")- db.rawExecSQL("SELECT sqlcipher_export('main', 'plaintext')")- db.rawExecSQL("DETACH DATABASE plaintext")- db.close()+ try {+ db.rawExecSQL("PRAGMA cipher_compatibility = 4")+ db.rawExecSQL("ATTACH DATABASE '${inputFile.canonicalPath}' AS plaintext KEY ''")+ try {+ db.rawExecSQL("SELECT sqlcipher_export('main', 'plaintext')")+ } finally {+ db.rawExecSQL("DETACH DATABASE plaintext")+ }+ } finally {+ db.close()+ }+ }++ /**+ * Reopens [file] with [password] and requires SQLite's integrity check+ * to pass. A corrupt plaintext input produces a temp DB that fails+ * here (or fails to open at all), so the live DB is never swapped for+ * garbage. Migrations are deliberately not run here: the codec does+ * not know the app's Room schema; Room runs them on first open, the+ * same as after every restore before this change.+ */+ private fun verifyEncryptedCopy(file: File, password: String) {+ if (!file.exists() || file.length() == 0L) {+ throw IOException("importDatabase: imported database is missing or empty")+ }+ val db = SQLiteDatabase.openDatabase(+ file.canonicalPath,+ password,+ null,+ SQLiteDatabase.OPEN_READONLY,+ null+ )+ try {+ val result = db.rawQuery("PRAGMA integrity_check", null)?.use { cursor ->+ if (cursor.moveToFirst()) cursor.getString(0) else null+ }+ if (!result.equals("ok", ignoreCase = true)) {+ throw IOException("importDatabase: integrity_check failed: $result")+ }+ } finally {+ db.close()+ }+ }++ /**+ * Renames [tempFile] over [dbFile], keeping the old files as `.bak-*`+ * siblings until the new file is in place. Renames within one directory+ * are atomic on the same filesystem, so a kill mid-swap leaves either+ * the old DB or the new DB under [dbFile]'s name.+ */+ private fun swapIntoPlace(tempFile: File, dbFile: File) {+ val suffix = ".bak-${UUID.randomUUID()}"+ val liveFiles = listOf(dbFile, sidecar(dbFile, "-wal"), sidecar(dbFile, "-shm"), sidecar(dbFile, "-journal"))+ val backedUp = mutableListOf<Pair<File, File>>()+ try {+ liveFiles.forEach { live ->+ if (!live.exists()) return@forEach+ val bak = File("${live.path}$suffix")+ if (!live.renameTo(bak)) {+ throw IOException("importDatabase: failed to move ${live.path} aside")+ }+ backedUp += live to bak+ }+ if (!tempFile.renameTo(dbFile)) {+ throw IOException("importDatabase: failed to move imported database into place")+ }+ // Carry any temp sidecars (e.g. a WAL not yet checkpointed at+ // close) in under the live name so they stay paired with it.+ listOf("-wal", "-shm", "-journal").forEach { ext ->+ val tmpSide = File("${tempFile.path}$ext")+ if (tmpSide.exists()) tmpSide.renameTo(sidecar(dbFile, ext))+ }+ } catch (e: Exception) {+ // Roll back: remove any partially swapped new file, restore old.+ if (dbFile.exists() && backedUp.any { it.first == dbFile }) dbFile.delete()+ backedUp.asReversed().forEach { (live, bak) ->+ if (bak.exists()) bak.renameTo(live)+ }+ throw e+ }+ backedUp.forEach { (_, bak) -> bak.delete() }+ }++ private fun sidecar(dbFile: File, ext: String): File = File("${dbFile.path}$ext")++ private fun deleteWithSidecars(file: File, includeSelf: Boolean = true) {+ if (includeSelf) file.delete()+ File("${file.path}-wal").delete()+ File("${file.path}-shm").delete()+ File("${file.path}-journal").delete() } }
library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt
diff --git a/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.ktindex de3058c8f6..72bfbce48f 100644--- a/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt+++ b/library/room/src/test/java/com/vayunmathur/library/room/SqlCipherDbCodecTest.kt@@ -39,7 +39,11 @@ class SqlCipherDbCodecTest { } @Test- fun `import deletes the old database files before the native open`() {+ fun `failed import leaves the old database files untouched`() {+ // Temp-verify-swap: the replacement is built beside the live DB and+ // only swapped in after verification. On this host the native layer+ // cannot load (and a corrupt input would fail verification on a+ // device), so the import must fail with the live set intact. val dbFile = context.getDatabasePath("import-target-db") dbFile.parentFile?.mkdirs() dbFile.writeBytes(byteArrayOf(1))@@ -52,18 +56,60 @@ class SqlCipherDbCodecTest { runCatching { SqlCipherDbCodec.importDatabase(context, "import-target-db", "pw", input) }- // Whatever the native layer then does on this host, the old file- // set is gone first: a half-finished import must not leave a WAL- // from the previous database behind.- kotlin.test.assertFalse(wal.exists())- kotlin.test.assertFalse(shm.exists())- kotlin.test.assertFalse(journal.exists())+ kotlin.test.assertTrue(dbFile.exists())+ kotlin.test.assertTrue(byteArrayOf(1).contentEquals(dbFile.readBytes()))+ kotlin.test.assertTrue(byteArrayOf(2).contentEquals(wal.readBytes()))+ kotlin.test.assertTrue(byteArrayOf(3).contentEquals(shm.readBytes()))+ kotlin.test.assertTrue(byteArrayOf(4).contentEquals(journal.readBytes()))+ // No temp import file is left behind in the databases directory.+ val leftovers = dbFile.parentFile?.listFiles()+ ?.filter { it.name.contains(".import-") || it.name.contains(".bak-") }+ .orEmpty()+ kotlin.test.assertTrue(leftovers.isEmpty(), "leftover swap files: $leftovers")+ } finally {+ dbFile.delete(); wal.delete(); shm.delete(); journal.delete()+ input.delete()+ }+ }++ @Test+ fun `corrupt input leaves the live database untouched`() {+ val dbFile = context.getDatabasePath("corrupt-target-db")+ dbFile.parentFile?.mkdirs()+ val liveBytes = ByteArray(64) { 7 }+ dbFile.writeBytes(liveBytes)+ val input = File(context.cacheDir, "corrupt-plaintext.db")+ input.writeBytes(ByteArray(64) { 0x55 }) // not a SQLite file at all+ try {+ runCatching {+ SqlCipherDbCodec.importDatabase(context, "corrupt-target-db", "pw", input)+ }+ kotlin.test.assertTrue(dbFile.exists())+ kotlin.test.assertTrue(liveBytes.contentEquals(dbFile.readBytes())) } finally { dbFile.delete() input.delete() } } + @Test+ fun `missing input leaves the live database untouched`() {+ val dbFile = context.getDatabasePath("missing-input-db")+ dbFile.parentFile?.mkdirs()+ dbFile.writeBytes(byteArrayOf(8, 8, 8))+ val input = File(context.cacheDir, "does-not-exist-plaintext.db")+ if (input.exists()) input.delete()+ try {+ runCatching {+ SqlCipherDbCodec.importDatabase(context, "missing-input-db", "pw", input)+ }+ kotlin.test.assertTrue(dbFile.exists())+ kotlin.test.assertTrue(byteArrayOf(8, 8, 8).contentEquals(dbFile.readBytes()))+ } finally {+ dbFile.delete()+ }+ }+ @Test fun `exporting a database that does not exist writes nothing`() { val output = File(context.cacheDir, "export-should-not-exist.db")
library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt b/library/src/main/java/com/vayunmathur/library/util/BackupHelper.ktindex fd1dbda9b3..29e8321e85 100644--- a/library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt+++ b/library/src/main/java/com/vayunmathur/library/util/BackupHelper.kt@@ -5,8 +5,10 @@ import com.vayunmathur.library.log.Log import java.io.BufferedInputStream import java.io.BufferedOutputStream import java.io.File+import java.io.IOException import java.io.InputStream import java.io.OutputStream+import java.util.UUID import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream@@ -20,13 +22,23 @@ import java.util.zip.ZipOutputStream */ interface DbBackupCodec { fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File)++ /**+ * Imports [inputFile] as the live database [dbName].+ *+ * Contract: implementations must build and verify the replacement away+ * from the live files first, and only swap it in once it is known good —+ * a corrupt or unreadable [inputFile] must leave the live database+ * untouched. Callers must close any open handle to the live database+ * before calling this: the codec does not own Room's cached instances,+ * and an open handle keeps the pre-swap file alive on Linux.+ */ fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) } /** ZIP packing, restore and database file handling shared by the backup formats. */ object BackupHelper { private const val TAG = "BackupHelper"- private const val RESTORE_TEMP_NAME = "restore_temp" private const val DATASTORE_DEFAULT_NAME = "datastore_default" fun zipFiles(files: List<File>, baseDir: File, outputStream: OutputStream) {@@ -69,20 +81,23 @@ object BackupHelper { dbCodec: DbBackupCodec? = null, ) { val tempDir = createTimestampedTempDir(context)- val filesToZip = mutableListOf<File>()+ try {+ val filesToZip = mutableListOf<File>() - warnOnMissingCodec(dbConfigs, dbCodec, ::warnBackupSkipped)- exportDatabases(context, dbConfigs, dbCodec, tempDir, filesToZip)- stageDatastoreFiles(context, datastoreNames, tempDir, filesToZip)- stagePrefFiles(context, prefNames, tempDir, filesToZip)- stageExtraFiles(extraFiles, tempDir, filesToZip)+ warnOnMissingCodec(dbConfigs, dbCodec, ::warnBackupSkipped)+ exportDatabases(context, dbConfigs, dbCodec, tempDir, filesToZip)+ stageDatastoreFiles(context, datastoreNames, tempDir, filesToZip)+ stagePrefFiles(context, prefNames, tempDir, filesToZip)+ stageExtraFiles(extraFiles, tempDir, filesToZip) - if (filesToZip.isEmpty()) {- Log.error(TAG, "performFullBackup: NO FILES TO BACKUP!")- }+ if (filesToZip.isEmpty()) {+ Log.error(TAG, "performFullBackup: NO FILES TO BACKUP!")+ } - zipFiles(filesToZip, tempDir, outputStream)- tempDir.deleteRecursively()+ zipFiles(filesToZip, tempDir, outputStream)+ } finally {+ tempDir.deleteRecursively()+ } } fun performFullRestore(@@ -94,30 +109,91 @@ object BackupHelper { inputStream: InputStream, dbCodec: DbBackupCodec? = null, ) {- val tempDir = createTempDir(context, RESTORE_TEMP_NAME)- unzipFiles(inputStream, tempDir)-- warnOnMissingCodec(dbConfigs, dbCodec, ::warnRestoreSkipped)- importDatabases(context, dbConfigs, dbCodec, tempDir)- restoreDatastoreFiles(context, datastoreNames, tempDir)- restorePrefFiles(context, prefNames, tempDir)- restoreExtraFiles(extraFilesMapping, tempDir)+ // Unique per restore: a fixed dir would collide between concurrent+ // restores and could be wiped from under an in-flight one.+ val tempDir = createUniqueTempDir(context, "restore_temp")+ try {+ unzipFiles(inputStream, tempDir) - tempDir.deleteRecursively()+ warnOnMissingCodec(dbConfigs, dbCodec, ::warnRestoreSkipped)+ importDatabases(context, dbConfigs, dbCodec, tempDir)+ restoreDatastoreFiles(context, datastoreNames, tempDir)+ restorePrefFiles(context, prefNames, tempDir)+ restoreExtraFiles(extraFilesMapping, tempDir)+ } finally {+ tempDir.deleteRecursively()+ } } - private fun createTimestampedTempDir(context: Context): File {- val tempDir = File(context.cacheDir, "backup_temp_${System.currentTimeMillis()}")- if (tempDir.exists()) tempDir.deleteRecursively()+ private fun createTimestampedTempDir(context: Context): File =+ createUniqueTempDir(context, "backup_temp")++ private fun createUniqueTempDir(context: Context, prefix: String): File {+ val tempDir = File(+ context.cacheDir,+ "${prefix}_${System.currentTimeMillis()}_${UUID.randomUUID()}",+ ) tempDir.mkdirs() return tempDir } - private fun createTempDir(context: Context, name: String): File {- val tempDir = File(context.cacheDir, name)- if (tempDir.exists()) tempDir.deleteRecursively()- tempDir.mkdirs()- return tempDir+ /**+ * Replaces [target] with [source]'s bytes atomically: copy to a sibling+ * temp file on the same filesystem, then rename over the target. A kill+ * mid-copy tears only the temp file; the live file is either fully old+ * or fully new, never partial.+ */+ private fun atomicReplaceFile(source: File, target: File) {+ val parent = target.parentFile+ ?: throw IOException("Target has no parent directory: ${target.path}")+ parent.mkdirs()+ val tmp = File(parent, "${target.name}.tmp-${UUID.randomUUID()}")+ try {+ source.copyTo(tmp, overwrite = true)+ if (!tmp.renameTo(target)) {+ throw IOException("Failed to rename ${tmp.path} over ${target.path}")+ }+ } finally {+ if (tmp.exists()) tmp.delete()+ }+ }++ /**+ * Swaps [target] (file or directory) for [source]: stage [source] as a+ * sibling of [target], rename the old target aside, rename the staged+ * copy in, then delete the old one. A kill mid-swap leaves either the+ * old tree or the new tree in place (plus at most a `.restore-bak-*`+ * sibling the next restore's aside-rename does not collide with,+ * because the suffix is unique per call).+ */+ private fun swapIntoPlace(source: File, target: File) {+ // Used for both files and directories: a plain rename-over cannot+ // replace a directory with a file (or vice versa), so extras always+ // go through the aside-swap, unlike datastore/prefs (always files).+ val parent = target.parentFile+ ?: throw IOException("Target has no parent directory: ${target.path}")+ parent.mkdirs()+ val staging = File(parent, "${target.name}.restore-tmp-${UUID.randomUUID()}")+ val aside = File(parent, "${target.name}.restore-bak-${UUID.randomUUID()}")+ try {+ if (source.isDirectory) {+ source.copyRecursively(staging, overwrite = false)+ } else {+ source.copyTo(staging, overwrite = false)+ }+ val movedAside = target.exists() && target.renameTo(aside)+ if (target.exists() && !movedAside) {+ throw IOException("Failed to move ${target.path} aside for restore")+ }+ if (!staging.renameTo(target)) {+ // Put the old tree back before giving up.+ if (movedAside) aside.renameTo(target)+ throw IOException("Failed to rename ${staging.path} over ${target.path}")+ }+ if (movedAside) aside.deleteRecursively()+ } finally {+ if (staging.exists()) staging.deleteRecursively()+ } } private fun warnOnMissingCodec(@@ -242,8 +318,7 @@ object BackupHelper { val extracted = File(tempDir, "$dsName.preferences_pb") if (!extracted.exists()) return@forEach val targetFile = datastoreTarget(context, dsName)- targetFile.parentFile?.mkdirs()- extracted.copyTo(targetFile, true)+ atomicReplaceFile(extracted, targetFile) } } @@ -260,8 +335,7 @@ object BackupHelper { val extracted = File(tempDir, "$prefName.xml") if (!extracted.exists()) return@forEach val targetFile = File(context.dataDir, "shared_prefs/$prefName.xml")- targetFile.parentFile?.mkdirs()- extracted.copyTo(targetFile, true)+ atomicReplaceFile(extracted, targetFile) } } @@ -269,13 +343,7 @@ object BackupHelper { extraFilesMapping.forEach { (zipName, targetFile) -> val extractedFile = File(tempDir, zipName) if (!extractedFile.exists()) return@forEach- if (targetFile.exists()) targetFile.deleteRecursively()- if (extractedFile.isDirectory) {- extractedFile.copyRecursively(targetFile, true)- } else {- targetFile.parentFile?.mkdirs()- extractedFile.copyTo(targetFile, true)- }+ swapIntoPlace(extractedFile, targetFile) } } }
library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.ktindex e419d5a054..ef2525f91c 100644--- a/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt+++ b/library/src/test/java/com/vayunmathur/library/util/LibraryBackupTest.kt@@ -99,6 +99,71 @@ class LibraryBackupTest { assertEquals(listOf("notes:pw1:db-bytes"), codec.imported) } + @Test fun restoreLeavesNoTempOrBackupFilesBehind() {+ val extra = File(ctx.cacheDir, "swap-note.txt").apply { writeText("new-body") }+ val dsDir = File(ctx.filesDir, "datastore").apply { mkdirs() }+ val dsFile = File(dsDir, "swapstore.preferences_pb").apply { writeBytes(byteArrayOf(4, 5)) }+ val prefDir = File(ctx.dataDir, "shared_prefs").apply { mkdirs() }+ val prefFile = File(prefDir, "swapprefs.xml").apply { writeText("<map>new</map>") }+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(+ ctx, emptyList(), listOf("swapstore"), listOf("swapprefs"), listOf(extra), out,+ )+ // Live files now hold stale bytes that restore must replace wholesale.+ extra.writeText("old-body"); dsFile.writeBytes(byteArrayOf(0)); prefFile.writeText("<map>old</map>")+ BackupHelper.performFullRestore(+ ctx, emptyList(), listOf("swapstore"), listOf("swapprefs"),+ mapOf("swap-note.txt" to extra), ByteArrayInputStream(out.toByteArray()),+ )+ assertEquals("new-body", extra.readText())+ assertTrue(byteArrayOf(4, 5).contentEquals(dsFile.readBytes()))+ assertEquals("<map>new</map>", prefFile.readText())+ // Atomic rename consumes the sibling temps: nothing torn left behind.+ listOf(ctx.cacheDir, dsDir, prefDir).forEach { dir ->+ val junk = dir.listFiles()?.filter {+ it.name.contains(".tmp-") || it.name.contains(".restore-")+ }.orEmpty()+ assertTrue(junk.isEmpty(), "leftover restore temps in $dir: $junk")+ }+ }++ @Test fun restoreDoesNotUseOrWipeFixedRestoreTempDir() {+ // A pre-existing fixed restore_temp dir belongs to no restore in+ // flight: a unique per-restore dir must leave it completely alone.+ val fixed = File(ctx.cacheDir, "restore_temp").apply { mkdirs() }+ val sentinel = File(fixed, "keep.txt").apply { writeText("keep") }+ val extra = File(ctx.cacheDir, "uniq-note.txt").apply { writeText("uniq-body") }+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), emptyList(), emptyList(), listOf(extra), out)+ extra.delete()+ BackupHelper.performFullRestore(+ ctx, emptyList(), emptyList(), emptyList(),+ mapOf("uniq-note.txt" to extra), ByteArrayInputStream(out.toByteArray()),+ )+ assertEquals("uniq-body", extra.readText())+ assertEquals("keep", sentinel.readText())+ }++ @Test fun restoreExtraDirectorySwapsWholeTreeAndDropsStaleFiles() {+ val dir = File(ctx.cacheDir, "swapdir-src").apply { mkdirs() }+ File(dir, "fresh.txt").writeText("fresh")+ val out = ByteArrayOutputStream()+ BackupHelper.performFullBackup(ctx, emptyList(), emptyList(), emptyList(), listOf(dir), out)+ val target = File(ctx.cacheDir, "swapdir-target").apply { mkdirs() }+ File(target, "stale.txt").writeText("stale")+ File(target, "fresh.txt").writeText("old")+ BackupHelper.performFullRestore(+ ctx, emptyList(), emptyList(), emptyList(),+ mapOf("swapdir-src" to target), ByteArrayInputStream(out.toByteArray()),+ )+ assertEquals("fresh", File(target, "fresh.txt").readText())+ assertFalse(File(target, "stale.txt").exists(), "swap replaces the whole tree")+ val junk = ctx.cacheDir.listFiles()?.filter {+ it.name.contains(".restore-") || it.name.contains(".tmp-")+ }.orEmpty()+ assertTrue(junk.isEmpty(), "leftover swap dirs: $junk")+ }+ @Test fun backupWithoutCodecSkipsDatabasesButStillZipsExtras() { val extra = File(ctx.cacheDir, "only.txt").apply { writeText("x") } val out = ByteArrayOutputStream()