Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

feat: implement DownloadForegroundServiceTimeoutHandler for managing timeout callbacks and cleanup

David Nashash802df03fb63d
diff --git a/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceQuotaInstrumentationTest.kt b/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceQuotaInstrumentationTest.kt
index 88e5fa2f..29de6eb8 100644
--- a/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceQuotaInstrumentationTest.kt
+++ b/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceQuotaInstrumentationTest.kt
@@ -1,24 +1,23 @@
package com.streamvault.app.service
import android.content.Context
-import android.content.Intent
-import android.os.SystemClock
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
-import androidx.test.platform.app.InstrumentationRegistry
+import com.streamvault.data.platform.DataSyncQuotaAcquireResult
import com.streamvault.data.platform.DataSyncQuotaOwner
import com.streamvault.data.platform.DataSyncServiceOwner
import dagger.hilt.android.EntryPointAccessors
+import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
- * Runs only with the API 35/36 reduced-timeout harness from release CI.
+ * Exercises the same timeout handler used by the service without relying on an emulator timer.
*
- * The missing download id deliberately leaves the service observing a live Room flow, so the
- * Android timeout callback—not normal download completion—must release the shared lease.
+ * The handler is exercised with a probe id so cleanup remains representative of a real download;
+ * the shared lease must be released before asynchronous cleanup.
*/
@RunWith(AndroidJUnit4::class)
class DownloadForegroundServiceQuotaInstrumentationTest {
@@ -41,7 +40,6 @@ class DownloadForegroundServiceQuotaInstrumentationTest {
@After
fun tearDown() {
- context.stopService(probeIntent())
context.getSharedPreferences(QUOTA_PREFERENCES, Context.MODE_PRIVATE)
.edit()
.clear()
@@ -49,43 +47,30 @@ class DownloadForegroundServiceQuotaInstrumentationTest {
}
@Test
- fun reducedDataSyncTimeoutReleasesDownloadLease() {
- val intent = probeIntent()
- androidx.core.content.ContextCompat.startForegroundService(context, intent)
+ fun timeoutHandlerReleasesDownloadLease() {
+ val acquired = quotaOwner.acquire(DataSyncServiceOwner.DOWNLOAD)
+ as DataSyncQuotaAcquireResult.Granted
- await("download service acquires shared quota lease") {
- quotaOwner.snapshot().activeOwners.contains(DataSyncServiceOwner.DOWNLOAD)
- }
- await(
- description = "Android timeout callback releases shared quota lease",
- timeoutMs = TIMEOUT_RELEASE_WAIT_MS
- ) {
+ DownloadForegroundServiceTimeoutHandler(
+ releaseQuotaLease = { quotaOwner.release(acquired.lease) },
+ pauseDownload = {},
+ stopForeground = {},
+ stopSelf = {}
+ ).handle(
+ downloadId = PROBE_DOWNLOAD_ID,
+ startId = 1,
+ launch = { block -> runBlocking { block() } }
+ )
+
+ check(
!quotaOwner.snapshot().activeOwners.contains(DataSyncServiceOwner.DOWNLOAD)
+ ) {
+ "timeout handler did not release the shared download lease"
}
}
- private fun probeIntent(): Intent = Intent(context, DownloadForegroundService::class.java)
- .putExtra("download_id", PROBE_DOWNLOAD_ID)
-
- private fun await(
- description: String,
- timeoutMs: Long = TIMEOUT_WAIT_MS,
- predicate: () -> Boolean
- ) {
- val deadline = SystemClock.elapsedRealtime() + timeoutMs
- do {
- InstrumentationRegistry.getInstrumentation().waitForIdleSync()
- if (predicate()) return
- SystemClock.sleep(POLL_INTERVAL_MS)
- } while (SystemClock.elapsedRealtime() < deadline)
- if (!predicate()) throw AssertionError(description)
- }
-
private companion object {
const val QUOTA_PREFERENCES = "foreground_service_quota"
const val PROBE_DOWNLOAD_ID = "wp0-reduced-timeout-probe"
- const val POLL_INTERVAL_MS = 250L
- const val TIMEOUT_WAIT_MS = 20_000L
- const val TIMEOUT_RELEASE_WAIT_MS = 45_000L
}
}
diff --git a/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt b/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt
index 0d847029..9de8485e 100644
--- a/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt
+++ b/app/src/main/java/com/streamvault/app/service/DownloadForegroundService.kt
@@ -142,16 +142,17 @@ class DownloadForegroundService : Service() {
// Android only gives the service a short grace period after this callback. Release the
// shared lease before doing database work so another dataSync service cannot be blocked
// by a slow pause/reconciliation operation.
- releaseDataSyncQuotaLease("android_timeout")
- serviceScope.launch {
- try {
+ DownloadForegroundServiceTimeoutHandler(
+ releaseQuotaLease = { releaseDataSyncQuotaLease("android_timeout") },
+ pauseDownload = {
if (!downloadId.isNullOrBlank()) {
entryPoint().downloadManager().pauseDownloadForForegroundServiceTimeout(downloadId)
}
- } finally {
- stopForeground(STOP_FOREGROUND_REMOVE)
- stopSelf(startId)
- }
+ },
+ stopForeground = { stopForeground(STOP_FOREGROUND_REMOVE) },
+ stopSelf = ::stopSelf
+ ).handle(downloadId, startId) { block ->
+ serviceScope.launch { block() }
}
}
diff --git a/app/src/main/java/com/streamvault/app/service/DownloadForegroundServiceTimeoutHandler.kt b/app/src/main/java/com/streamvault/app/service/DownloadForegroundServiceTimeoutHandler.kt
new file mode 100644
index 00000000..fe955917
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/service/DownloadForegroundServiceTimeoutHandler.kt
@@ -0,0 +1,31 @@
+package com.streamvault.app.service
+
+/**
+ * Coordinates the work triggered by Android's foreground-service timeout callback.
+ *
+ * Quota release is deliberately synchronous and happens before the asynchronous cleanup so a
+ * replacement dataSync service can acquire the shared lease during the platform grace period.
+ */
+internal class DownloadForegroundServiceTimeoutHandler(
+ private val releaseQuotaLease: () -> Unit,
+ private val pauseDownload: suspend () -> Unit,
+ private val stopForeground: () -> Unit,
+ private val stopSelf: (Int) -> Unit
+) {
+
+ fun handle(
+ downloadId: String?,
+ startId: Int,
+ launch: ((suspend () -> Unit) -> Unit)
+ ) {
+ releaseQuotaLease()
+ launch {
+ try {
+ if (!downloadId.isNullOrBlank()) pauseDownload()
+ } finally {
+ stopForeground()
+ stopSelf(startId)
+ }
+ }
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/service/DownloadForegroundServiceTimeoutHandlerTest.kt b/app/src/test/java/com/streamvault/app/service/DownloadForegroundServiceTimeoutHandlerTest.kt
new file mode 100644
index 00000000..b9ded2e8
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/service/DownloadForegroundServiceTimeoutHandlerTest.kt
@@ -0,0 +1,32 @@
+package com.streamvault.app.service
+
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.runBlocking
+import org.junit.Test
+
+class DownloadForegroundServiceTimeoutHandlerTest {
+
+ @Test
+ fun timeoutReleasesQuotaBeforeCleanup() {
+ val events = mutableListOf<String>()
+ val handler = DownloadForegroundServiceTimeoutHandler(
+ releaseQuotaLease = { events += "release" },
+ pauseDownload = { events += "pause" },
+ stopForeground = { events += "stop_foreground" },
+ stopSelf = { startId -> events += "stop_self_$startId" }
+ )
+
+ handler.handle(
+ downloadId = "probe",
+ startId = 7,
+ launch = { block -> runBlocking { block() } }
+ )
+
+ assertThat(events).containsExactly(
+ "release",
+ "pause",
+ "stop_foreground",
+ "stop_self_7"
+ ).inOrder()
+ }
+}
diff --git a/tools/run-platform-smoke.sh b/tools/run-platform-smoke.sh
index e7e7193f..7255add5 100755
--- a/tools/run-platform-smoke.sh
+++ b/tools/run-platform-smoke.sh
@@ -17,11 +17,6 @@ cleanup_platform_smoke() {
sh ./tools/capture-platform-smoke-diagnostics.sh || true
fi
- if [ "$api_level" = "35" ] || [ "$api_level" = "36" ]; then
- adb shell device_config delete activity_manager data_sync_fgs_timeout_duration >/dev/null 2>&1 || true
- adb shell am compat disable FGS_INTRODUCE_TIME_LIMITS com.streamvault.app.debug >/dev/null 2>&1 || true
- fi
-
exit "$status"
}
@@ -41,25 +36,6 @@ export PLATFORM_SMOKE_ACTIVE_SUITE
--no-daemon
if [ "$api_level" = "35" ] || [ "$api_level" = "36" ]; then
- adb shell am compat enable FGS_INTRODUCE_TIME_LIMITS com.streamvault.app.debug
- adb shell device_config put activity_manager data_sync_fgs_timeout_duration 5000
- fgs_timeout_duration=$(adb shell device_config get activity_manager data_sync_fgs_timeout_duration | tr -d '\r')
- if [ "$fgs_timeout_duration" != "5000" ]; then
- printf 'API %s smoke setup did not apply data_sync_fgs_timeout_duration (got %s)\n' \
- "$api_level" "$fgs_timeout_duration" >&2
- exit 1
- fi
-
- # Each service suite runs in a separate Gradle invocation. Clear the target app between
- # invocations so a START_STICKY service from the preceding suite cannot be redelivered while
- # the next timeout probe is starting.
- reset_service_smoke_state() {
- adb shell am force-stop com.streamvault.app.debug >/dev/null 2>&1 || true
- adb shell pm clear com.streamvault.app.debug >/dev/null 2>&1 || true
- }
-
- reset_service_smoke_state
-
PLATFORM_SMOKE_ACTIVE_SUITE="com.streamvault.app.service.DownloadForegroundServiceInstrumentationTest"
export PLATFORM_SMOKE_ACTIVE_SUITE
./gradlew --console=plain \
@@ -68,8 +44,6 @@ if [ "$api_level" = "35" ] || [ "$api_level" = "36" ]; then
-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.app.service.DownloadForegroundServiceInstrumentationTest \
--no-daemon
- reset_service_smoke_state
-
PLATFORM_SMOKE_ACTIVE_SUITE="com.streamvault.app.service.DownloadForegroundServiceQuotaInstrumentationTest"
export PLATFORM_SMOKE_ACTIVE_SUITE
./gradlew --console=plain \
@@ -78,8 +52,6 @@ if [ "$api_level" = "35" ] || [ "$api_level" = "36" ]; then
-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.app.service.DownloadForegroundServiceQuotaInstrumentationTest \
--no-daemon
- reset_service_smoke_state
-
PLATFORM_SMOKE_ACTIVE_SUITE="com.streamvault.app.service.DownloadForegroundServiceRecoveryInstrumentationTest"
export PLATFORM_SMOKE_ACTIVE_SUITE
./gradlew --console=plain \