Colota - Android GPS Location tracker
fix(backup): resume tracking after a failed restore (#634)
Max Dietrichcb8de4d5a3ff
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex b05990f2..232a3438 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -82,7 +82,7 @@ Second React Native bridge module (exposed as `"BackupServiceModule"`). Owns the- `pickBackupDestination` / `pickBackupSource` - launches the Storage Access Framework picker (`ACTION_CREATE_DOCUMENT` / `ACTION_OPEN_DOCUMENT`); a single in-flight picker is enforced via a 5-minute timeout.- `createBackup(uri, password)` - validates password strength, claims an operation mutex, runs `BackupBuilder` against a cacheDir-staged file, then atomically copies into the SAF destination. Stops promotion to a foreground service when finished.-- `restoreBackup(uri, password)` - cancels the location service and any auto-export work, polls until both stop, runs `BackupRestorer`, then forces `tracking_enabled=false` so the destination device doesn't auto-resume. Its `finally` re-arms the auto-export alarm from whichever DB is live, because `pauseAllDbWriters` cancelled it whether or not the restore went through.+- `restoreBackup(uri, password)` - cancels the location service and any auto-export work, polls until both stop, runs `BackupRestorer`, then forces `tracking_enabled=false` so the destination device doesn't auto-resume. Its `finally` re-arms the auto-export alarm from whichever DB is live, because `pauseAllDbWriters` cancelled it whether or not the restore went through, and starts tracking again through `TrackingControl.start` when the restore failed before it replaced the database. A failure raised after the swap (`SECRETS_PARTIAL`) leaves tracking off like a success does, because the live DB is then the backup's.- `applyRestore` - JS calls this after the success dialog is dismissed; it triggers `reactHost.reload()` so all modules re-read state from the restored DB.Both `createBackup` and `restoreBackup` await `BackupOrphanCleanup.awaitComplete()` before claiming the operation mutex, ensuring the launch-time orphan sweeper can't race active operations.diff --git a/apps/docs/docs/guides/backup-restore.md b/apps/docs/docs/guides/backup-restore.mdindex a17ef6b8..525fc3cf 100644--- a/apps/docs/docs/guides/backup-restore.md+++ b/apps/docs/docs/guides/backup-restore.md@@ -63,7 +63,7 @@ Replaces all current data Restoring overwrites every location, setting, geofence### What Gets Paused-To swap the database safely, the restore stops the location tracking service and any in-flight auto-export. If a writer can't be stopped within ~5 seconds the restore aborts before touching your data. The auto-export schedule is armed again when the restore finishes, whether or not it succeeded.+To swap the database safely, the restore stops the location tracking service and any in-flight auto-export. If a writer can't be stopped within ~5 seconds the restore aborts before touching your data. The auto-export schedule is armed again when the restore finishes, whether or not it succeeded, and a restore that aborts before replacing your data starts tracking again.After restore, tracking is left **off** so the new device doesn't silently start uploading on the old credentials. Re-enable it when you've checked the data is correct.diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.ktindex f85d610b..a80a161a 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt@@ -10,6 +10,7 @@ import android.net.Uriimport android.os.StatFsimport android.provider.DocumentsContractimport com.Colota.backup.BackupBuilder+import com.Colota.backup.BackupErrorimport com.Colota.backup.BackupExceptionimport com.Colota.backup.BackupForegroundServiceimport com.Colota.backup.BackupOrphanCleanup@@ -20,6 +21,7 @@ import com.Colota.data.SettingsKeysimport com.Colota.export.AutoExportSchedulerimport com.Colota.export.AutoExportWorkerimport com.Colota.service.LocationForegroundService+import com.Colota.triggers.TrackingControlimport com.Colota.util.AppLoggerimport com.Colota.util.SafPickerCoordinatorimport com.facebook.react.ReactApplication@@ -198,17 +200,23 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :promise.reject("E_BUSY", "Another backup or restore is in progress")return@launch}+ var dbReplaced = false+ var trackingWasEnabled = falsetry {val uri = Uri.parse(uriString)ensureFreeSpaceForRestore(uri)startForegroundOnMain("Restoring backup...")+ // Read before pauseAllDbWriters clears it, and outside it so a straggler timeout still resumes.+ trackingWasEnabled = DatabaseHelper.getInstance(reactApplicationContext)+ .getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"pauseAllDbWriters()val input = reactApplicationContext.contentResolver.openInputStream(uri)?: throw IllegalStateException("Could not open input stream for $uriString")input.use { BackupRestorer(reactApplicationContext).restore(it, passwordChars) }+ dbReplaced = true// Swap is done; clear the writer block so the post-restore saveSetting can land on the new DB.DatabaseHelper.setRestoreInProgress(false)@@ -219,6 +227,8 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :promise.resolve(true)} catch (e: Exception) {+ // The swap happens inside restore(); SECRETS_PARTIAL is the only failure raised after it.+ if (e is BackupException && e.error == BackupError.SECRETS_PARTIAL) dbReplaced = trueAppLogger.e(TAG, "restoreBackup failed", e)promise.reject(errorCode(e), e.message ?: "Restore failed", e)} finally {@@ -231,6 +241,20 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :} catch (e: Exception) {AppLogger.w(TAG, "scheduleNext failed after restore: ${e.message}")}+ // Once the database is the backup's, the destination-device rule applies and tracking stays off.+ // Not in the catch: every saveSetting here is gated until the finally clears restoreInProgress.+ if (!dbReplaced && trackingWasEnabled) {+ try {+ // A denied startForeground returns before the service writes the flag, and the+ // watchdog it arms disarms itself while the flag still reads false.+ DatabaseHelper.getInstance(reactApplicationContext)+ .saveSetting(SettingsKeys.TRACKING_ENABLED, "true")+ TrackingControl.start(reactApplicationContext, "Resumed after a failed restore")+ AppLogger.i(TAG, "Resumed tracking after a failed restore")+ } catch (e: Exception) {+ AppLogger.w(TAG, "Could not resume tracking after a failed restore: ${e.message}")+ }+ }operationMutex.unlock()}}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/BackupServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/BackupServiceModuleTest.ktindex 592a1e01..51dd7fce 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/BackupServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/BackupServiceModuleTest.kt@@ -12,9 +12,15 @@ import androidx.test.core.app.ApplicationProviderimport androidx.work.Configurationimport androidx.work.testing.WorkManagerTestInitHelperimport com.Colota.backup.BackupBuilder+import com.Colota.backup.BackupError+import com.Colota.backup.BackupExceptionimport com.Colota.backup.BackupOrphanCleanup+import com.Colota.backup.BackupRestorerimport com.Colota.data.DatabaseHelper+import com.Colota.data.SettingsKeysimport com.Colota.export.AutoExportScheduler+import com.Colota.service.LocationForegroundService+import com.Colota.triggers.TrackingControlimport com.Colota.util.AppLoggerimport com.Colota.util.SecureStorageHelperimport com.facebook.react.bridge.JavaOnlyArray@@ -22,6 +28,7 @@ import com.facebook.react.bridge.Promiseimport com.facebook.react.bridge.BridgeReactContextimport io.mockk.*import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.test.UnconfinedTestDispatcherimport kotlinx.coroutines.test.resetMain@@ -85,6 +92,10 @@ class BackupServiceModuleTest {every { SecureStorageHelper.getInstance(any()) } returns secureStoragemockkObject(AutoExportScheduler)+ mockkConstructor(BackupRestorer::class)+ every { anyConstructed<BackupRestorer>().restore(any(), any()) } answers { callOriginal() }+ mockkObject(TrackingControl)+ every { TrackingControl.start(any(), any()) } just Runs// restoreBackup awaits the orphan sweep, which only MainApplication.onCreate startsBackupOrphanCleanup.start(context)@@ -104,6 +115,8 @@ class BackupServiceModuleTest {@Afterfun tearDown() {unmockkObject(AutoExportScheduler)+ unmockkConstructor(BackupRestorer::class)+ unmockkObject(TrackingControl)unmockkObject(SecureStorageHelper.Companion)unmockkObject(AppLogger)DatabaseHelper.getInstance(context).close()@@ -151,6 +164,106 @@ class BackupServiceModuleTest {assertTrue("the alarm follows the restored DB, not the one replaced", shadowOf(alarmManager).scheduledAlarms.isEmpty())}+ @Test+ fun `a failed restore restarts the tracking it stopped`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")++ val outcome = restore(backup, "wrong".toCharArray())++ assertEquals("E_BACKUP_WRONG_PASSWORD", outcome.rejectCode)+ verify(exactly = 1) { TrackingControl.start(any(), "Resumed after a failed restore") }+ }++ @Test+ fun `a failed restore leaves tracking off when it was already off`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")++ val outcome = restore(backup, "wrong".toCharArray())++ assertEquals("E_BACKUP_WRONG_PASSWORD", outcome.rejectCode)+ verify(exactly = 0) { TrackingControl.start(any(), any()) }+ }++ @Test+ fun `a successful restore leaves tracking stopped on purpose`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")++ val outcome = restore(backup, password)++ assertTrue("restore should resolve", outcome.resolved)+ verify(exactly = 0) { TrackingControl.start(any(), any()) }+ assertEquals("false", db.getSetting(SettingsKeys.TRACKING_ENABLED, "true"))+ }++ @Test+ fun `a restore that replaced the database keeps tracking off even when it then fails`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")+ // Secrets fail after the swap, so the live DB is the backup's and the destination-device rule applies+ every { anyConstructed<BackupRestorer>().restore(any(), any()) } throws+ BackupException(BackupError.SECRETS_PARTIAL, "credentials could not be applied")++ val outcome = restore(backup, password)++ assertEquals("E_BACKUP_SECRETS_PARTIAL", outcome.rejectCode)+ verify(exactly = 0) { TrackingControl.start(any(), any()) }+ }++ @Test+ fun `a restore aborted by a writer that would not stop resumes tracking`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")+ // pauseAllDbWriters throws instead of returning, which is why the flag is read before it runs+ mockkObject(LocationForegroundService.Companion)+ try {+ every { LocationForegroundService.isRunning } returns true++ val outcome = restore(backup, password)++ assertEquals("E_BACKUP_PRECONDITION", outcome.rejectCode)+ verify(exactly = 1) { TrackingControl.start(any(), "Resumed after a failed restore") }+ } finally {+ unmockkObject(LocationForegroundService.Companion)+ }+ }++ @Test+ fun `the resume writes the tracking flag itself so a denied start still recovers`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")+ // Left false, the watchdog the denied start arms disarms itself on its first tick+ every { TrackingControl.start(any(), any()) } just Runs++ restore(backup, "wrong".toCharArray())++ assertEquals("true", db.getSetting(SettingsKeys.TRACKING_ENABLED, "false"))+ }++ @Test+ fun `a denied resume leaves the module usable`() {+ enableAutoExport()+ val backup = backupBytes()+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")+ every { TrackingControl.start(any(), any()) } throws IllegalStateException("FGS start denied")++ val denied = restore(backup, "wrong".toCharArray())+ assertEquals("E_BACKUP_WRONG_PASSWORD", denied.rejectCode)++ // An escaping resume would strand operationMutex and lock out every later backup and restore+ every { TrackingControl.start(any(), any()) } just Runs+ val next = restore(backup, "wrong".toCharArray())+ assertEquals("E_BACKUP_WRONG_PASSWORD", next.rejectCode)+ }+// promise.resolve fires before the finally re-arms, so the re-arm needs its own latchprivate fun restore(backup: ByteArray, pw: CharArray): Outcome {val outcome = Outcome()@@ -173,9 +286,21 @@ class BackupServiceModuleTest {assertTrue("restore did not settle", outcome.settled.await(30, TimeUnit.SECONDS))assertTrue("restore finished without re-arming", outcome.rearmed.await(10, TimeUnit.SECONDS))+ awaitIdle()return outcome}+ // The resume runs after both latches; the mutex is released by the finally's last statement,+ // which makes "the whole finally is done" observable instead of a guessed delay.+ private fun awaitIdle() {+ val field = BackupServiceModule::class.java.getDeclaredField("operationMutex")+ field.isAccessible = true+ val mutex = field.get(module) as Mutex+ val deadline = System.currentTimeMillis() + 10_000+ while (mutex.isLocked && System.currentTimeMillis() < deadline) Thread.sleep(10)+ assertFalse("restore never released the operation mutex", mutex.isLocked)+ }+private fun enableAutoExport() {db.saveSetting("autoExportEnabled", "true")db.saveSetting("autoExportInterval", "daily")diff --git a/fastlane/metadata/android/en-US/changelogs/48.txt b/fastlane/metadata/android/en-US/changelogs/48.txtindex 45212cd4..c60e0ea5 100644--- a/fastlane/metadata/android/en-US/changelogs/48.txt+++ b/fastlane/metadata/android/en-US/changelogs/48.txt@@ -4,3 +4,4 @@- Auto-export no longer fails when the folder app has not registered the new file yet- Switching auto-export off stops a running export- Auto-export keeps its schedule after a backup restore+- An aborted backup restore starts tracking again instead of leaving it off