Skip to content

Colota - Android GPS Location tracker

fix(sync): close the upload reply and stream a day's locations (#953)

Max Dietrich5b22545d2d3e
diff --git a/apps/docs/docs/api-reference.md b/apps/docs/docs/api-reference.md
index ff478464..38aa0d67 100644
--- a/apps/docs/docs/api-reference.md
+++ b/apps/docs/docs/api-reference.md
@@ -19,6 +19,7 @@ Configure the HTTP method in **Settings → Connection → Request format → HT
```
Content-Type: application/json; charset=UTF-8
Accept: application/json
+Connection: close
```
Additional headers may be included based on your [authentication](/docs/configuration/authentication) configuration.
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 526b90c6..6b770fb1 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -212,6 +212,8 @@ Orchestrates batch location uploads with:
HTTP client. Injects auth headers, caches connectivity checks, and detects unmetered connections and VPN status for sync condition filtering. SSID detection needs a location-flagged network callback, which is attributed as location access, so it is registered only while the sync `wifi_ssid` condition is active; profile conditions read the name through a one-shot probe when the network changes. Connected Wi-Fi is tracked separately with a plain (unflagged) Wi-Fi-transport callback, so the profile conditions also see the network under a VPN. Endpoint policy (HTTPS-for-public, private host detection) is delegated to `UrlSafety`.
+Every request uses its own connection: it sends `Connection: close` and closes the response before disconnecting, so Android releases the connection at once instead of keeping it in its pool.
+
For mTLS-protected endpoints, builds the `HttpsURLConnection` with a custom `SSLSocketFactory` supplied by `ClientCertSslContextProvider` (per-instance, never `setDefaultSSLSocketFactory()` - the override is scoped to outbound location sync, not the whole process).
### UrlSafety
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index dabbe642..0bfcc40d 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -382,9 +382,18 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun getLocationsByDateRange(startTimestamp: Double, endTimestamp: Double, promise: Promise) =
executeAsync(promise) {
- val rawData = dbHelper.getLocationsByDateRange(startTimestamp.toLong(), endTimestamp.toLong())
Arguments.createArray().apply {
- rawData.forEach { row -> pushMap(Arguments.makeNativeMap(row)) }
+ dbHelper.forEachLocationInRange(startTimestamp.toLong(), endTimestamp.toLong()) { row ->
+ pushMap(Arguments.createMap().apply {
+ for ((key, value) in row) {
+ when (value) {
+ is Number -> putDouble(key, value.toDouble())
+ is String -> putString(key, value)
+ else -> putNull(key)
+ }
+ }
+ })
+ }
}
}
diff --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.kt
index cf4afbcd..50900ccd 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
@@ -557,10 +557,10 @@ class DatabaseHelper private constructor(context: Context) :
private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES, TABLE_PROFILES)
- private fun Cursor.toMapList(): List<Map<String, Any?>> = buildList {
+ private inline fun Cursor.forEachRow(onRow: (Map<String, Any?>) -> Unit) {
val columns = columnNames
while (moveToNext()) {
- add(buildMap {
+ onRow(buildMap {
for (col in columns) {
val idx = getColumnIndex(col)
if (idx != -1) {
@@ -576,6 +576,8 @@ class DatabaseHelper private constructor(context: Context) :
}
}
+ private fun Cursor.toMapList(): List<Map<String, Any?>> = buildList { forEachRow(::add) }
+
fun getTableData(tableName: String, limit: Int, offset: Int): List<Map<String, Any?>> {
require(tableName in ALLOWED_TABLES) { "Invalid table name: $tableName" }
@@ -610,12 +612,11 @@ class DatabaseHelper private constructor(context: Context) :
/**
* Retrieves locations within a date range, ordered chronologically.
- * 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.
+ * Used for the trip export and the incremental auto-export. Throws on a read failure.
*
* @param startTimestamp Start of range (Unix seconds, inclusive)
* @param endTimestamp End of range (Unix seconds, inclusive)
- * @return Locations ordered by timestamp ASC for polyline drawing
+ * @return Locations ordered by timestamp ASC
*/
fun getLocationsByDateRange(
startTimestamp: Long,
@@ -632,6 +633,21 @@ class DatabaseHelper private constructor(context: Context) :
if (limit > 0) "$limit OFFSET $offset" else null
).use { it.toMapList() }
+ private val SCREEN_LOCATION_COLUMNS = arrayOf(
+ "id", "latitude", "longitude", "accuracy", "altitude", "speed", "bearing",
+ "battery", "battery_status", "timestamp", "sent", "note"
+ )
+
+ /** One row at a time: a dense day held as a list is tens of MB on the Java heap. */
+ fun forEachLocationInRange(startTimestamp: Long, endTimestamp: Long, onRow: (Map<String, Any?>) -> Unit) =
+ readableDatabase.query(
+ TABLE_LOCATIONS, SCREEN_LOCATION_COLUMNS,
+ "timestamp >= ? AND timestamp <= ?",
+ arrayOf(startTimestamp.toString(), endTimestamp.toString()),
+ null, null,
+ "timestamp ASC, id ASC"
+ ).use { it.forEachRow(onRow) }
+
/**
* Adds location to transmission queue.
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
index eadc6e2e..ca4ca3ff 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
@@ -304,6 +304,7 @@ class NetworkManager(private val context: Context) {
doOutput = true
}
extraHeaders.forEach { (key, value) -> setRequestProperty(key, value) }
+ setRequestProperty("Connection", "close")
connectTimeout = CONNECTION_TIMEOUT
readTimeout = READ_TIMEOUT
useCaches = false
@@ -459,18 +460,7 @@ class NetworkManager(private val context: Context) {
connection = buildConnection(targetUrl, isGet, extraHeaders)
logRequest(connection, isGet, resolvedEndpoint, targetUrl, transformedPayload)
if (!isGet) writeBody(connection, transformedPayload)
- val responseCode = connection.responseCode
- if (responseCode in 200..299) {
- TestEndpointResult(true, httpStatus = responseCode)
- } else {
- val errorBody = readErrorBody(connection)
- TestEndpointResult(
- false,
- httpStatus = responseCode,
- errorMessage = "Server returned $responseCode: $errorBody",
- retryAfterSeconds = if (responseCode == 429) retryAfterOf(connection) else null
- )
- }
+ readResponse(connection)
} catch (e: SSLHandshakeException) {
TestEndpointResult(false, errorMessage = mtlsErrorMessage(e))
} catch (e: UnrecoverableKeyException) {
@@ -514,9 +504,33 @@ class NetworkManager(private val context: Context) {
}
}
+ private fun readResponse(connection: HttpURLConnection): TestEndpointResult {
+ val responseCode = connection.responseCode
+ try {
+ if (responseCode in 200..299) return TestEndpointResult(true, httpStatus = responseCode)
+ val errorBody = readErrorBody(connection)
+ return TestEndpointResult(
+ false,
+ httpStatus = responseCode,
+ errorMessage = "Server returned $responseCode: $errorBody",
+ retryAfterSeconds = if (responseCode == 429) retryAfterOf(connection) else null
+ )
+ } finally {
+ discardBody(connection)
+ }
+ }
+
private fun readBatchResponse(connection: HttpURLConnection, batchSize: Int): BatchResult {
val responseCode = connection.responseCode
- return when (responseCode) {
+ try {
+ return batchVerdict(connection, responseCode, batchSize)
+ } finally {
+ discardBody(connection)
+ }
+ }
+
+ private fun batchVerdict(connection: HttpURLConnection, responseCode: Int, batchSize: Int): BatchResult =
+ when (responseCode) {
in 200..299 -> {
AppLogger.d(TAG, "Batch of $batchSize sent successfully")
BatchResult.Success
@@ -541,6 +555,13 @@ class NetworkManager(private val context: Context) {
BatchResult.ServerError(responseCode)
}
}
+
+ // disconnect() alone leaves a connection whose reply was never closed in the platform's pool for minutes.
+ private fun discardBody(connection: HttpURLConnection) {
+ try {
+ (connection.errorStream ?: connection.inputStream)?.close()
+ } catch (_: Exception) {
+ }
}
private fun retryAfterOf(connection: HttpURLConnection): Long? =
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
index 1fadcc76..bbcc485a 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
@@ -845,6 +845,35 @@ class LocationServiceModuleTest {
assertNoVacuum(db)
}
+ // A dense day held as one list is tens of MB on the Java heap.
+ @Test
+ fun `a day of locations reaches JS row by row, never as a list of the whole day`() {
+ val db = stubDatabase()
+ every { Arguments.createArray() } answers { JavaOnlyArray() }
+ every { db.forEachLocationInRange(1000L, 2000L, any()) } answers {
+ val onRow = thirdArg<(Map<String, Any?>) -> Unit>()
+ onRow(mapOf("id" to 1L, "timestamp" to 1000L, "note" to null))
+ onRow(mapOf("id" to 2L, "timestamp" to 2000L, "note" to "Coffee stop"))
+ }
+ lateinit var settled: Promise
+
+ awaitPromise { promise ->
+ settled = promise
+ LocationServiceModule(mockContext).getLocationsByDateRange(1000.0, 2000.0, promise)
+ }
+
+ verify {
+ settled.resolve(match {
+ val rows = it as JavaOnlyArray
+ rows.size() == 2 &&
+ rows.getMap(0)?.isNull("note") == true &&
+ rows.getMap(1)?.getDouble("timestamp") == 2000.0 &&
+ rows.getMap(1)?.getString("note") == "Coffee stop"
+ })
+ }
+ verify(exactly = 0) { db.getLocationsByDateRange(any(), any(), any(), any()) }
+ }
+
@Test
fun `a bulk delete on Data management still rewrites the database`() {
val db = stubDatabase()
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.kt
index 2bc911ec..412cdd05 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
@@ -809,6 +809,47 @@ class DatabaseHelperSQLiteTest {
assertTrue(result.isEmpty())
}
+ // ========================================================================
+ // forEachLocationInRange
+ // ========================================================================
+
+ private fun screenRows(start: Long, end: Long) =
+ buildList { db.forEachLocationInRange(start, end) { add(it) } }
+
+ @Test
+ fun `forEachLocationInRange hands over the range in ascending order, boundaries included`() {
+ db.saveLocation(latitude = 55.0, longitude = 16.0, timestamp = 3000L)
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 500L)
+ db.saveLocation(latitude = 54.0, longitude = 15.0, timestamp = 2000L)
+ db.saveLocation(latitude = 53.0, longitude = 14.0, timestamp = 1000L)
+
+ assertEquals(listOf(1000L, 2000L), screenRows(1000L, 2000L).map { it["timestamp"] })
+ }
+
+ // The server URL is stored on every row and no screen reads it.
+ @Test
+ fun `forEachLocationInRange carries what a screen shows and leaves the endpoint behind`() {
+ db.saveLocation(latitude = 52.0, longitude = 13.0, timestamp = 1000L, endpoint = "https://example.com/api")
+
+ val row = screenRows(0L, 9999L).single()
+
+ assertEquals(
+ setOf(
+ "id", "latitude", "longitude", "accuracy", "altitude", "speed", "bearing",
+ "battery", "battery_status", "timestamp", "sent", "note"
+ ),
+ row.keys
+ )
+ assertEquals(52.0, row["latitude"])
+ }
+
+ @Test
+ fun `forEachLocationInRange throws when the read fails`() {
+ db.writableDatabase.execSQL("DROP TABLE locations")
+
+ assertThrows(SQLiteException::class.java) { db.forEachLocationInRange(0L, 9999L) {} }
+ }
+
// ========================================================================
// Export readers throw, so a failed page never ends an export as complete
// ========================================================================
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
index d03d9626..5d983770 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/NetworkManagerTest.kt
@@ -421,6 +421,144 @@ class NetworkManagerTest {
assertEquals(BatchResult.RateLimited(30), method.invoke(createNetworkManagerViaReflection(), connection, 50))
}
+ // --- releasing the connection ---
+
+ private fun readBatchResponse(connection: java.net.HttpURLConnection): Any? {
+ val method = NetworkManager::class.java.getDeclaredMethod(
+ "readBatchResponse", java.net.HttpURLConnection::class.java, Int::class.javaPrimitiveType
+ )
+ method.isAccessible = true
+ return method.invoke(createNetworkManagerViaReflection(), connection, 50)
+ }
+
+ // Android keeps a connection whose reply was never closed pooled for minutes, TLS buffers included.
+ @Test
+ fun `an accepted batch closes the reply it does not read`() {
+ val reply = mockk<java.io.InputStream>(relaxed = true)
+ val connection = mockk<java.net.HttpURLConnection>(relaxed = true)
+ every { connection.responseCode } returns 200
+ every { connection.errorStream } returns null
+ every { connection.inputStream } returns reply
+
+ assertEquals(BatchResult.Success, readBatchResponse(connection))
+
+ verify(exactly = 1) { reply.close() }
+ }
+
+ @Test
+ fun `a rate-limited batch closes the error page it does not read`() {
+ val page = mockk<java.io.InputStream>(relaxed = true)
+ val connection = mockk<java.net.HttpURLConnection>(relaxed = true)
+ every { connection.responseCode } returns 429
+ every { connection.errorStream } returns page
+
+ readBatchResponse(connection)
+
+ verify(exactly = 1) { page.close() }
+ }
+
+ @Test
+ fun `a reply that fails to open does not turn an accepted batch into a failure`() {
+ val connection = mockk<java.net.HttpURLConnection>(relaxed = true)
+ every { connection.responseCode } returns 204
+ every { connection.errorStream } returns null
+ every { connection.inputStream } throws java.io.IOException("stream closed")
+
+ assertEquals(BatchResult.Success, readBatchResponse(connection))
+ }
+
+ private fun readResponse(connection: java.net.HttpURLConnection): TestEndpointResult {
+ val method = NetworkManager::class.java.getDeclaredMethod("readResponse", java.net.HttpURLConnection::class.java)
+ method.isAccessible = true
+ return method.invoke(createNetworkManagerViaReflection(), connection) as TestEndpointResult
+ }
+
+ @Test
+ fun `an accepted upload closes the reply it does not read`() {
+ val reply = mockk<java.io.InputStream>(relaxed = true)
+ val connection = mockk<java.net.HttpURLConnection>(relaxed = true)
+ every { connection.responseCode } returns 200
+ every { connection.errorStream } returns null
+ every { connection.inputStream } returns reply
+
+ assertTrue(readResponse(connection).ok)
+
+ verify(exactly = 1) { reply.close() }
+ }
+
+ // Android offers no error stream below 400, so a redirect it does not follow has only the plain one.
+ @Test
+ fun `a redirect that is not followed is a failure whose reply is still closed`() {
+ val reply = mockk<java.io.InputStream>(relaxed = true)
+ val connection = mockk<java.net.HttpURLConnection>(relaxed = true)
+ every { connection.responseCode } returns 307
+ every { connection.errorStream } returns null
+ every { connection.inputStream } returns reply
+
+ val result = readResponse(connection)
+
+ assertFalse(result.ok)
+ assertEquals(307, result.httpStatus)
+ verify(exactly = 1) { reply.close() }
+ }
+
+ @Test
+ fun `a custom Connection header cannot switch connection reuse back on`() {
+ val method = NetworkManager::class.java.getDeclaredMethod(
+ "buildConnection", java.net.URL::class.java, Boolean::class.javaPrimitiveType, Map::class.java
+ )
+ method.isAccessible = true
+
+ for (isGet in listOf(false, true)) {
+ val connection = method.invoke(
+ createNetworkManagerViaReflection(), java.net.URL("http://127.0.0.1:9/"), isGet, mapOf("Connection" to "keep-alive")
+ ) as java.net.HttpURLConnection
+
+ assertEquals("close", connection.getRequestProperty("Connection"))
+ }
+ }
+
+ // Without the header a closed reply is pooled for reuse, and a stale pooled connection fails a streamed POST.
+ @Test
+ fun `an upload asks the server to close the connection and still counts as sent`() {
+ val server = java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))
+ val headers = java.util.concurrent.CompletableFuture<List<String>>()
+ val serving = Thread {
+ try {
+ server.accept().use { socket ->
+ val input = socket.getInputStream().bufferedReader(Charsets.ISO_8859_1)
+ val lines = generateSequence { input.readLine() }.takeWhile { it.isNotEmpty() }.toList()
+ val length = lines.first { it.startsWith("Content-Length", ignoreCase = true) }.substringAfter(":").trim().toInt()
+ repeat(length) { input.read() }
+ headers.complete(lines)
+ val body = """{"ok":true}"""
+ socket.getOutputStream().write(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.length}\r\n\r\n$body".toByteArray()
+ )
+ }
+ } catch (e: Exception) {
+ headers.completeExceptionally(e)
+ }
+ }.apply { start() }
+ try {
+ val caps = mockk<NetworkCapabilities>(relaxed = true)
+ every { caps.hasCapability(any()) } returns true
+ val cm = mockk<ConnectivityManager>(relaxed = true)
+ every { cm.getNetworkCapabilities(any()) } returns caps
+
+ val result = kotlinx.coroutines.runBlocking {
+ newManagerWith(cm).sendToEndpoint(JSONObject().put("lat", 1.0), "http://127.0.0.1:${server.localPort}/")
+ }
+
+ assertEquals(BatchResult.Success, result)
+ val sent = headers.get(5, java.util.concurrent.TimeUnit.SECONDS)
+ assertTrue("request headers were $sent", sent.any { it.equals("Connection: close", ignoreCase = true) })
+ } finally {
+ serving.join(5000)
+ server.close()
+ }
+ }
+
private fun invokeReadErrorBody(body: String?): String {
val connection = io.mockk.mockk<java.net.HttpURLConnection>(relaxed = true)
io.mockk.every { connection.errorStream } returns body?.byteInputStream()
diff --git a/fastlane/metadata/android/en-US/changelogs/53.txt b/fastlane/metadata/android/en-US/changelogs/53.txt
new file mode 100644
index 00000000..8eb1447c
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/53.txt
@@ -0,0 +1 @@
+- Less memory used when opening a day with many points and when sending a large upload backlog