From 9339f9f0fbbf963975f84469795bcfd8586315e7 Mon Sep 17 00:00:00 2001 From: Torsten Grote Date: Thu, 10 Oct 2024 10:33:32 -0300 Subject: [PATCH] when cached snapshot is corrupted fall back to loading from backend --- .../seedvault/repo/SnapshotManager.kt | 7 ++++++- .../seedvault/repo/SnapshotManagerTest.kt | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/stevesoltys/seedvault/repo/SnapshotManager.kt b/app/src/main/java/com/stevesoltys/seedvault/repo/SnapshotManager.kt index e85f2b05..3d8969f7 100644 --- a/app/src/main/java/com/stevesoltys/seedvault/repo/SnapshotManager.kt +++ b/app/src/main/java/com/stevesoltys/seedvault/repo/SnapshotManager.kt @@ -133,7 +133,12 @@ internal class SnapshotManager( val file = File(snapshotFolder, snapshotHandle.name) snapshotFolder.mkdirs() val inputStream = if (file.isFile) { - loader.loadFile(file, snapshotHandle.hash) + try { + loader.loadFile(file, snapshotHandle.hash) + } catch (e: Exception) { + log.error(e) { "Error loading $snapshotHandle from local cache. Trying backend..." } + loader.loadFile(snapshotHandle, file) + } } else { loader.loadFile(snapshotHandle, file) } diff --git a/app/src/test/java/com/stevesoltys/seedvault/repo/SnapshotManagerTest.kt b/app/src/test/java/com/stevesoltys/seedvault/repo/SnapshotManagerTest.kt index 5104f5a6..6142cf91 100644 --- a/app/src/test/java/com/stevesoltys/seedvault/repo/SnapshotManagerTest.kt +++ b/app/src/test/java/com/stevesoltys/seedvault/repo/SnapshotManagerTest.kt @@ -34,6 +34,7 @@ import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.file.Path +import java.security.GeneralSecurityException import java.security.MessageDigest import kotlin.random.Random @@ -132,6 +133,26 @@ internal class SnapshotManagerTest : TransportTest() { assertEquals(listOf(snapshot), snapshotManager.loadCachedSnapshots()) } + @Test + fun `snapshot corrupted on cache falls back to backend`(@TempDir tmpDir: Path) = runBlocking { + val snapshotManager = getSnapshotManager(File(tmpDir.toString())) + val snapshot = snapshot { token = 1337 } + val snapshotData = snapshot.toByteArray() + val inputStream = ByteArrayInputStream(snapshotData) + val snapshotHandle = AppBackupFileType.Snapshot(repoId, chunkId1) + val file = getSnapshotFolder(tmpDir, snapshotHandle.name) + + every { crypto.repoId } returns repoId + coEvery { loader.loadFile(file, snapshotHandle.hash) } throws GeneralSecurityException() + coEvery { loader.loadFile(snapshotHandle, file) } returns inputStream + + assertEquals(listOf(snapshot), snapshotManager.onSnapshotsLoaded(listOf(snapshotHandle))) + + coVerify { // did load from backend + loader.loadFile(snapshotHandle, file) + } + } + @Test fun `failing to load a snapshot isn't fatal`(@TempDir tmpDir: Path) = runBlocking { val snapshotManager = getSnapshotManager(File(tmpDir.toString()))