Colota - Android GPS Location tracker
fix(export): stop treating a failed page read as the end of the data (#631)
Max Dietrich4453299dde90
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.mdindex f9d63332..383f4db6 100644--- a/apps/docs/docs/guides/data-export.md+++ b/apps/docs/docs/guides/data-export.md@@ -98,7 +98,7 @@ If several devices export into the same folder and none of the templates include- Writes to a temporary file first, then copies to the export directory - if something goes wrong mid-export, you never get a partial or corrupted file- After copying, verifies the destination file exists and has the correct size before deleting the temp file- If the export loop is cancelled (e.g. by disabling auto-export), it cleans up gracefully without leaving partial files-- Permanent errors (invalid config, directory access issues) fail immediately; transient errors (I/O failures) retry up to 3 times+- Permanent errors (invalid config, directory access issues) fail immediately; transient errors (I/O failures, a failed database read) retry up to 3 times- If the selected directory becomes inaccessible (permissions revoked), auto-export disables itself and a notification prompts you to re-select the directory- A notification is shown after each export with the file name and location count- Old export files beyond the retention limit are cleaned up after each successful export. Cleanup only considers files matching Colota's own export naming pattern, so unrelated files and subfolders in the directory are never toucheddiff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex 3e78c999..088aacaf 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -596,22 +596,18 @@ class DatabaseHelper private constructor(context: Context) :/*** Returns all locations ordered chronologically (ASC) with pagination.* Used for export operations where chronological order is required.+ * Throws on a read failure so an export never ends as complete with rows missing.*/- fun getLocationsChronological(limit: Int, offset: Int): List<Map<String, Any?>> {- return try {- readableDatabase.query(- TABLE_LOCATIONS, null, null, null, null, null,- "timestamp ASC, id ASC", "$limit OFFSET $offset"- ).use { it.toMapList() }- } catch (e: Exception) {- AppLogger.e(TAG, "Error reading locations chronologically", e)- emptyList()- }- }+ fun getLocationsChronological(limit: Int, offset: Int): List<Map<String, Any?>> =+ readableDatabase.query(+ TABLE_LOCATIONS, null, null, null, null, null,+ "timestamp ASC, id ASC", "$limit OFFSET $offset"+ ).use { it.toMapList() }/*** Retrieves locations within a date range, ordered chronologically.- * Used for rendering track polylines on the map view.+ * Used for the map polyline, the trip export and the incremental auto-export.+ * Throws on a read failure; the map's JS wrapper falls back to an empty list.** @param startTimestamp Start of range (Unix seconds, inclusive)* @param endTimestamp End of range (Unix seconds, inclusive)@@ -622,21 +618,15 @@ class DatabaseHelper private constructor(context: Context) :endTimestamp: Long,limit: Int = 0,offset: Int = 0- ): List<Map<String, Any?>> {- return try {- readableDatabase.query(- TABLE_LOCATIONS, null,- "timestamp >= ? AND timestamp <= ?",- arrayOf(startTimestamp.toString(), endTimestamp.toString()),- null, null,- "timestamp ASC, id ASC",- if (limit > 0) "$limit OFFSET $offset" else null- ).use { it.toMapList() }- } catch (e: Exception) {- AppLogger.e(TAG, "Error reading locations by date range", e)- emptyList()- }- }+ ): List<Map<String, Any?>> =+ readableDatabase.query(+ TABLE_LOCATIONS, null,+ "timestamp >= ? AND timestamp <= ?",+ arrayOf(startTimestamp.toString(), endTimestamp.toString()),+ null, null,+ "timestamp ASC, id ASC",+ if (limit > 0) "$limit OFFSET $offset" else null+ ).use { it.toMapList() }/**diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.ktindex 9b77a838..33ed07b3 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt@@ -11,6 +11,7 @@ import android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.content.pm.ServiceInfo+import android.database.SQLExceptionimport android.net.Uriimport android.os.Buildimport android.provider.DocumentsContract@@ -37,6 +38,9 @@ class AutoExportWorker(params: WorkerParameters) : CoroutineWorker(appContext, params) {+ // Only the SAF copy raises this, so a directory verdict can never be reached from a database read+ private class DirectoryAccessException(message: String) : Exception(message)+companion object {private const val TAG = "AutoExportWorker"private const val CHANNEL_ID = "auto_export"@@ -214,7 +218,7 @@ class AutoExportWorker(userMessage = "Invalid export configuration: ${e.message}",retry = false)- } catch (e: IllegalStateException) {+ } catch (e: DirectoryAccessException) {handleExportFailure(tempFile, config, db, e,error = "Directory access failed: ${e.message}",@@ -222,6 +226,14 @@ class AutoExportWorker(userMessage = "Could not access export directory: ${e.message}",retry = false)+ } catch (e: SQLException) {+ handleExportFailure(+ tempFile, config, db, e,+ error = "Read failed: ${e.message}",+ logMessage = "Auto-export failed - database read, will retry",+ userMessage = "Could not read locations. Will retry.",+ retry = true+ )} catch (e: IOException) {handleExportFailure(tempFile, config, db, e,@@ -270,13 +282,13 @@ class AutoExportWorker(val docFile = DocumentFile.fromTreeUri(appContext, dirUri)?.createFile(mimeType, fileName)- ?: throw IllegalStateException("Failed to create file in selected directory")+ ?: throw DirectoryAccessException("Failed to create file in selected directory")resolver.openOutputStream(docFile.uri)?.use { outStream ->sourceFile.inputStream().use { inStream ->inStream.copyTo(outStream)}- } ?: throw IllegalStateException("Failed to open output stream")+ } ?: throw DirectoryAccessException("Failed to open output stream")return docFile}diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.ktindex a3b4a6f0..653c5a24 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt@@ -514,7 +514,8 @@ object ExportConverters {/*** Streams a paginated export to file. On cancellation mid-write the footer* is skipped and the partial row count is returned; file cleanup is the- * caller's job.+ * caller's job. A page read that throws deletes the file and propagates, so+ * a failed export never looks complete.*/fun exportToFile(format: String,@@ -529,21 +530,26 @@ object ExportConverters {var offset = 0var cancelled = false- sink.use {- OutputStreamWriter(outputFile.outputStream(), Charsets.UTF_8).use { w ->- writer.writeHeader(w)-- while (true) {- if (shouldCancel()) { cancelled = true; break }- val page = fetchPage(pageSize, offset)- if (page.isEmpty()) break- writer.writeRows(w, page.map(ExportRow::from), offset, sink)- totalRows += page.size- offset += pageSize+ try {+ sink.use {+ OutputStreamWriter(outputFile.outputStream(), Charsets.UTF_8).use { w ->+ writer.writeHeader(w)++ while (true) {+ if (shouldCancel()) { cancelled = true; break }+ val page = fetchPage(pageSize, offset)+ if (page.isEmpty()) break+ writer.writeRows(w, page.map(ExportRow::from), offset, sink)+ totalRows += page.size+ offset += pageSize+ }++ if (!cancelled) writer.writeFooter(w, sink)}-- if (!cancelled) writer.writeFooter(w, sink)}+ } catch (e: Exception) {+ outputFile.delete()+ throw e}return totalRows}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.ktindex cfb6def9..e836b87e 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/data/DatabaseHelperSQLiteTest.kt@@ -742,6 +742,24 @@ class DatabaseHelperSQLiteTest {assertTrue(result.isEmpty())}+ // ========================================================================+ // Export readers throw, so a failed page never ends an export as complete+ // ========================================================================++ @Test+ fun `getLocationsByDateRange throws when the read fails`() {+ db.writableDatabase.execSQL("DROP TABLE locations")++ assertThrows(SQLiteException::class.java) { db.getLocationsByDateRange(0L, 9999L, 100, 0) }+ }++ @Test+ fun `getLocationsChronological throws when the read fails`() {+ db.writableDatabase.execSQL("DROP TABLE locations")++ assertThrows(SQLiteException::class.java) { db.getLocationsChronological(100, 0) }+ }+// ========================================================================// Stats and cleanup// ========================================================================diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerReadFailureTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerReadFailureTest.ktnew file mode 100644index 00000000..f7da6bfd--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerReadFailureTest.kt@@ -0,0 +1,105 @@+package com.Colota.export++import android.database.sqlite.SQLiteException+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import com.Colota.data.DatabaseHelper+import com.Colota.util.AppLogger+import io.mockk.*+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** A read that fails mid-export must retry and must not advance the incremental watermark. */+@RunWith(RobolectricTestRunner::class)+class AutoExportWorkerReadFailureTest {++ private lateinit var db: DatabaseHelper+ private lateinit var spy: DatabaseHelper++ @Before+ fun setUp() {+ resetSingleton()+ db = DatabaseHelper.getInstance(ApplicationProvider.getApplicationContext())++ mockkObject(AppLogger)+ every { AppLogger.d(any(), any()) } just Runs+ every { AppLogger.i(any(), any()) } just Runs+ every { AppLogger.w(any(), any()) } just Runs+ every { AppLogger.e(any(), any()) } just Runs+ every { AppLogger.e(any(), any(), any()) } just Runs++ db.saveSetting("autoExportEnabled", "true")+ db.saveSetting("autoExportUri", "content://com.android.externalstorage.documents/tree/primary%3AColota")+ db.saveSetting("autoExportMode", "incremental")+ db.saveSetting("lastAutoExportTimestamp", "1700000000")+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1700000500L)++ spy = spyk(db)+ mockkObject(DatabaseHelper.Companion)+ every { DatabaseHelper.getInstance(any()) } returns spy+ }++ @After+ fun tearDown() {+ unmockkObject(DatabaseHelper.Companion)+ unmockkObject(AppLogger)+ db.close()+ resetSingleton()+ }++ private fun resetSingleton() {+ val field = DatabaseHelper::class.java.getDeclaredField("INSTANCE")+ field.isAccessible = true+ field.set(null, null)+ }++ private fun runWorker(): ListenableWorker.Result {+ val worker = TestListenableWorkerBuilder<AutoExportWorker>(ApplicationProvider.getApplicationContext())+ .setTags(listOf(AutoExportScheduler.IMMEDIATE_WORK_TAG))+ .build()+ return runBlocking { worker.doWork() }+ }++ @Test+ fun `a page read that fails after rows were written retries and leaves the watermark alone`() {+ every { spy.getLocationsByDateRange(any(), any(), any(), any()) } answers {+ if (arg<Int>(3) == 0) listOf(mapOf("latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000500L))+ else throw SQLiteException("disk I/O error")+ }++ val result = runWorker()++ assertTrue("expected retry, got $result", result is ListenableWorker.Result.Retry)+ val config = AutoExportConfig.from(db)+ assertEquals(1700000000L, config.lastExportTimestamp)+ assertTrue("expected the read arm, got ${config.lastError}", config.lastError!!.startsWith("Read failed:"))+ }++ @Test+ fun `a CursorWindow IllegalStateException retries instead of blaming the directory`() {+ every { spy.getLocationsByDateRange(any(), any(), any(), any()) } throws IllegalStateException("Couldn't read row 0, col 0 from CursorWindow")++ val result = runWorker()++ assertTrue("expected retry, got $result", result is ListenableWorker.Result.Retry)+ val config = AutoExportConfig.from(db)+ assertEquals(1700000000L, config.lastExportTimestamp)+ assertTrue("expected the generic arm, got ${config.lastError}", config.lastError!!.startsWith("Export failed:"))+ }++ @Test+ fun `an unusable export directory fails without retry`() {+ val result = runWorker()++ assertTrue("expected failure, got $result", result is ListenableWorker.Result.Failure)+ val config = AutoExportConfig.from(db)+ assertEquals(1700000000L, config.lastExportTimestamp)+ assertTrue("expected the directory arm, got ${config.lastError}", config.lastError!!.startsWith("Directory access failed:"))+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.ktindex 5ed0c201..31d4036e 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt@@ -18,6 +18,20 @@ class ExportConvertersTest {mapOf("latitude" to 48.8566, "longitude" to 2.3522, "accuracy" to 15.0, "altitude" to 40.0, "speed" to 0.5, "bearing" to 90.0, "battery" to 72L, "battery_status" to 1L, "timestamp" to 1700003600L))+ // --- exportToFile ---++ @Test+ fun `exportToFile rethrows a later page read failure and removes the partial file`() {+ val outputFile = tempFolder.newFile("export.geojson")++ assertThrows(IllegalStateException::class.java) {+ ExportConverters.exportToFile("geojson", outputFile, pageSize = 1) { _, offset ->+ if (offset == 0) sampleRows.take(1) else throw IllegalStateException("disk I/O error")+ }+ }+ assertFalse(outputFile.exists())+ }+// --- extensionFor ---@Testdiff --git a/fastlane/metadata/android/en-US/changelogs/48.txt b/fastlane/metadata/android/en-US/changelogs/48.txtindex e9e95973..99f7ebe4 100644--- a/fastlane/metadata/android/en-US/changelogs/48.txt+++ b/fastlane/metadata/android/en-US/changelogs/48.txt@@ -1,2 +1,3 @@- Settings are no longer replaced with defaults when the app fails to read them- Log exports no longer contain webhook ids or session tokens from the endpoint address+- Exports stop with an error instead of silently leaving out locations when a database read fails