diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakData.kt b/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakData.kt index d88160ad03..e84101057a 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakData.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/FlatpakData.kt @@ -21,6 +21,7 @@ object FlatpakData { private const val KEPT = ".ld.so" private const val RESERVE = 64L shl 20 private val ID = Regex("(?!\\.+$)[A-Za-z0-9_.-]+") + private const val SEP = ">" private val lock = Any() fun enabled(context: Context): Set = SessionPrefs.flatpakCardData(context) @@ -43,7 +44,12 @@ object FlatpakData { val card = cardDir(context, id) ?: return@flatMap emptyList() val guest = internalDir(context, id) val kept = File(guest, KEPT) - if (id in SessionPrefs.flatpakDataMoving(context)) discardLeftovers(context, id, guest) + try { + purge(guest) + purge(card) + } catch (e: Exception) { + Log.w(TAG, "$id: the old copy of a moved folder could not be removed", e) + } if (!card.isDirectory && !card.mkdirs() || !kept.isDirectory && !kept.mkdirs() || !File(card, KEPT).isDirectory && !File(card, KEPT).mkdirs()) { Log.w(TAG, "$id: data folder could not be prepared; internal this session") return@flatMap emptyList() @@ -64,16 +70,22 @@ object FlatpakData { val to = if (toCard) card else internal onProgress(context.getString(R.string.store_data_moving), -1) val staging = File(to.parentFile, ".${to.name}.moving") + val marker = marker(id, to) val placed = ArrayList() try { - if (toCard && hasSymlink(from)) return@synchronized context.getString(R.string.store_data_symlinks) + if (hasSymlink(from)) return@synchronized context.getString(R.string.store_data_symlinks) if (!to.isDirectory && !to.mkdirs()) throw IOException("could not create ${to.path}") - if (id in SessionPrefs.flatpakDataMoving(context)) clear(to) - else if (entries(to).isNotEmpty()) return@synchronized context.getString(R.string.store_data_failed) + purge(from) + purge(to) + if (entries(to).isNotEmpty()) { + if (marker !in SessionPrefs.flatpakDataMoving(context)) return@synchronized context.getString(R.string.store_data_failed) + clear(to) + } val bytes = size(from) val free = freeBytes(to) if (free < bytes + RESERVE) return@synchronized context.getString(R.string.store_data_space, com.droiddeck.launcher.core.FileUtils.sizeToString(free)) - if (!SessionPrefs.setFlatpakDataMoving(context, id, true)) throw IOException("could not record the move") + SessionPrefs.flatpakDataMoving(context).filter { it.startsWith("$id$SEP") && it != marker }.forEach { SessionPrefs.setFlatpakDataMoving(context, it, false) } + if (!SessionPrefs.setFlatpakDataMoving(context, marker, true)) throw IOException("could not record the move") if (staging.exists() && !staging.deleteRecursively()) throw IOException("could not clear ${staging.path}") staging.mkdirs() entries(from).forEach { it.copyRecursively(File(staging, it.name), overwrite = true) } @@ -90,14 +102,14 @@ object FlatpakData { } } catch (e: Exception) { Log.w(TAG, "$id: move to ${if (toCard) "game storage" else "internal"} failed", e) - placed.forEach { it.deleteRecursively() } - staging.deleteRecursively() + val cleaned = placed.map { it.deleteRecursively() }.all { it } && (!staging.exists() || staging.deleteRecursively()) + if (cleaned) SessionPrefs.setFlatpakDataMoving(context, marker, false) return@synchronized context.getString(R.string.store_data_failed) } try { - clear(from) + retire(from) if (!toCard && !from.deleteRecursively()) throw IOException("could not remove ${from.path}") - SessionPrefs.setFlatpakDataMoving(context, id, false) + SessionPrefs.setFlatpakDataMoving(context, marker, false) null } catch (e: Exception) { Log.w(TAG, "$id: the data moved but the old copy could not be removed", e) @@ -105,13 +117,23 @@ object FlatpakData { } } - private fun discardLeftovers(context: Context, id: String, dir: File) { - try { - clear(dir) - SessionPrefs.setFlatpakDataMoving(context, id, false) - } catch (e: Exception) { - Log.w(TAG, "$id: leftover data from an interrupted move could not be removed", e) - } + internal fun marker(id: String, to: File) = "$id$SEP${to.path}" + + private fun trash(dir: File) = File(dir.parentFile, ".${dir.name}.old") + + private fun purge(dir: File) { + val old = trash(dir) + if (old.exists() && !old.deleteRecursively()) throw IOException("could not remove ${old.path}") + } + + private fun retire(dir: File) { + purge(dir) + val old = trash(dir) + val entries = entries(dir) + if (entries.isEmpty()) return + if (!old.mkdirs()) throw IOException("could not create ${old.path}") + entries.forEach { if (!it.renameTo(File(old, it.name))) throw IOException("could not retire ${it.path}") } + purge(dir) } private fun clear(dir: File) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 03f7c066a8..482b3837ec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1917,7 +1917,7 @@ object SessionPrefs { fun flatpakDataMoving(context: Context): Set = idSet(context, "flatpakDataMoving") - fun setFlatpakDataMoving(context: Context, id: String, on: Boolean): Boolean = commitId(context, "flatpakDataMoving", id, on) + fun setFlatpakDataMoving(context: Context, marker: String, on: Boolean): Boolean = commitId(context, "flatpakDataMoving", marker, on) private fun idSet(context: Context, key: String): Set = prefs(context).getStringSet(key, null)?.toSet().orEmpty() diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/FlatpakDataTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/FlatpakDataTest.kt index 657d01cacc..beb413ff9f 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/FlatpakDataTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/FlatpakDataTest.kt @@ -157,19 +157,22 @@ class FlatpakDataTest { val release = java.util.concurrent.CountDownLatch(1) var result: String? = "pending" val mover = Thread { - result = FlatpakData.move(app, id, true, { _, _ -> }, { inMove.countDown(); release.await(); free }) + result = FlatpakData.move(app, id, true, { _, _ -> }, { inMove.countDown(); release.await(10, java.util.concurrent.TimeUnit.SECONDS); free }) } mover.start() assertTrue(inMove.await(10, java.util.concurrent.TimeUnit.SECONDS)) SessionState.running = true var binds: List? = null val session = Thread { binds = FlatpakData.binds(app) } - session.start() - session.join(300) - assertTrue(session.isAlive) - release.countDown() - mover.join(10_000) - session.join(10_000) + try { + session.start() + session.join(300) + assertTrue(session.isAlive) + } finally { + release.countDown() + mover.join(10_000) + session.join(10_000) + } assertNull(result) assertEquals(2, binds!!.size) assertTrue(binds!!.first().startsWith(File(card, "flatpak-data/$id").path)) @@ -193,41 +196,76 @@ class FlatpakDataTest { assertNull(move(id, true)) } + private fun cardFolder() = File(card, "flatpak-data/$id") + @Test fun aMoveInterruptedMidPlacementCanBeRetried() { seed() - assertTrue(SessionPrefs.setFlatpakDataMoving(app, id, true)) - File(card, "flatpak-data/$id/.srb2kart").mkdirs() - File(card, "flatpak-data/$id/partial.bin").writeText("half") + assertTrue(SessionPrefs.setFlatpakDataMoving(app, FlatpakData.marker(id, cardFolder()), true)) + File(cardFolder(), ".srb2kart").mkdirs() + File(cardFolder(), "partial.bin").writeText("half") assertNull(move(id, true)) - val onCard = File(card, "flatpak-data/$id") - assertFalse(File(onCard, "partial.bin").exists()) - assertEquals(1000, File(onCard, ".srb2kart/addons/map.pk3").length()) + assertFalse(File(cardFolder(), "partial.bin").exists()) + assertEquals(1000, File(cardFolder(), ".srb2kart/addons/map.pk3").length()) assertTrue(SessionPrefs.flatpakDataMoving(app).isEmpty()) assertTrue(FlatpakData.entries(FlatpakData.internalDir(app, id)).isEmpty()) } - @Test fun staleDataLeftAtTheSourceIsDroppedAtSessionStart() { + @Test fun aJournalForAnotherDestinationNeverAuthorisesClearingThisOne() { seed() - assertNull(move(id, true)) - assertTrue(SessionPrefs.setFlatpakDataMoving(app, id, true)) - File(FlatpakData.internalDir(app, id), "stale.bin").writeText("old") - assertEquals(2, FlatpakData.binds(app).size) - assertEquals(listOf(".ld.so"), FlatpakData.internalDir(app, id).list()!!.toList()) - assertEquals(1000, File(card, "flatpak-data/$id/.srb2kart/addons/map.pk3").length()) - assertTrue(SessionPrefs.flatpakDataMoving(app).isEmpty()) + val other = File(tmp.newFolder("other"), "flatpak-data/$id") + assertTrue(SessionPrefs.setFlatpakDataMoving(app, FlatpakData.marker(id, other), true)) + File(cardFolder(), "keep.txt").apply { parentFile!!.mkdirs() }.writeText("old") + assertEquals(app.getString(R.string.store_data_failed), move(id, true)) + assertEquals("old", File(cardFolder(), "keep.txt").readText()) + assertTrue(File(FlatpakData.internalDir(app, id), ".srb2kart/addons/map.pk3").isFile) } - @Test fun staleDataAtTheDestinationIsDroppedBeforeMovingBack() { + @Test fun anInterruptedMoveBackCanBeRetried() { seed() assertNull(move(id, true)) - assertTrue(SessionPrefs.setFlatpakDataMoving(app, id, true)) - File(FlatpakData.internalDir(app, id), "stale.bin").writeText("old") - assertNull(move(id, false)) val internal = FlatpakData.internalDir(app, id) - assertFalse(File(internal, "stale.bin").exists()) + assertTrue(SessionPrefs.setFlatpakDataMoving(app, FlatpakData.marker(id, internal), true)) + File(internal, "partial.bin").writeText("half") + assertNull(move(id, false)) + assertFalse(File(internal, "partial.bin").exists()) assertEquals(1000, File(internal, ".srb2kart/addons/map.pk3").length()) } + @Test fun oldDataLeftAtTheSourceIsDroppedAtSessionStart() { + seed() + assertNull(move(id, true)) + val internal = FlatpakData.internalDir(app, id) + File(internal.parentFile, ".${internal.name}.old").apply { mkdirs() }.let { File(it, "stale.bin").writeText("old") } + assertEquals(2, FlatpakData.binds(app).size) + assertFalse(File(internal.parentFile, ".${internal.name}.old").exists()) + assertEquals(1000, File(cardFolder(), ".srb2kart/addons/map.pk3").length()) + } + + @Test fun dataWrittenWhileTheCardWasDetachedSurvivesItsReturn() { + seed() + assertNull(move(id, true)) + SessionPrefs.setGameStorage(app, "/storage/0000-0000/Android/data/x/files/steam", "gone") + assertTrue(FlatpakData.binds(app).isEmpty()) + val save = File(FlatpakData.internalDir(app, id), "save.dat").apply { writeText("new") } + SessionPrefs.setGameStorage(app, card.path, "SD") + assertEquals(2, FlatpakData.binds(app).size) + assertEquals("new", save.readText()) + assertEquals(app.getString(R.string.store_data_failed), move(id, false)) + assertEquals("new", save.readText()) + assertEquals(1000, File(cardFolder(), ".srb2kart/addons/map.pk3").length()) + assertEquals(setOf(id), FlatpakData.enabled(app)) + } + + @Test fun aSymlinkOnTheCardRefusesTheMoveBack() { + seed() + assertNull(move(id, true)) + Files.createSymbolicLink(File(cardFolder(), "link").toPath(), File("config").toPath()) + assertEquals(app.getString(R.string.store_data_symlinks), move(id, false)) + assertEquals(setOf(id), FlatpakData.enabled(app)) + assertEquals(1000, File(cardFolder(), ".srb2kart/addons/map.pk3").length()) + assertTrue(FlatpakData.entries(FlatpakData.internalDir(app, id)).isEmpty()) + } + @Test fun anUnreadableSourceIsNotTreatedAsEmpty() { FlatpakData.internalDir(app, id).apply { parentFile!!.mkdirs() }.writeText("not a folder") assertEquals(app.getString(R.string.store_data_failed), move(id, true)) diff --git a/docs/development/flatpak.md b/docs/development/flatpak.md index ecd1f2e040..9a26360563 100644 --- a/docs/development/flatpak.md +++ b/docs/development/flatpak.md @@ -82,15 +82,17 @@ the folder to `flatpak-data/` beside the library, checks the copy's size, an internal one. `FlatpakData.binds` then binds the card folder over `/root/.var/app/` in every session, and `BwrapSpawner` translates the sandbox's binds through it like any other session bind. -- The move is per app and refused from session start until its teardown finishes, when the data holds symlinks (exFAT and FAT +- The move is per app and refused from session start until its teardown finishes, when the data holds symlinks in either location (exFAT and FAT cannot store them), or when the card lacks the size plus 64 MB. - `.ld.so` is not moved. Flatpak fills it with a symlink to the runtime's linker cache, so it stays internal and is bound over the card folder. -- The destination is journaled before anything is written (`flatpakDataMoving`). A move that is - interrupted, or whose old copy cannot be removed, leaves data only in the location the app does not - use; the next move into it, or the next session start for the card case, clears it first. A folder - that cannot be listed fails the move instead of counting as empty. -- With the card detached, the app uses its internal folder for that session; the choice is kept. +- The destination and its path are journaled (`flatpakDataMoving`) before anything is written. A later + move clears a non-empty destination only when the journal names that same folder; otherwise it is + refused. The old copy is renamed to `..old` beside it and then deleted, so leftovers are always + recognisable and the next move or session start removes them. Live data is never deleted to tidy up. A + folder that cannot be listed fails the move instead of counting as empty. +- With the card detached, the app uses its internal folder for that session; the choice is kept. Those + files stay untouched when the card returns, and a move back is refused while they are there. - "Move data to internal storage" reverses it. ## The store