Skip to content

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

test: complete WP7 download boundary gates

David Nashash71438df3014f
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 18a79119..14470090 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -219,6 +219,7 @@ jobs:
adb shell device_config put activity_manager data_sync_fgs_timeout_duration 5000
./gradlew --console=plain :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.app.service.DownloadForegroundServiceInstrumentationTest --no-daemon
./gradlew --console=plain :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.app.service.DownloadForegroundServiceQuotaInstrumentationTest --no-daemon
+ ./gradlew --console=plain :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.app.service.DownloadForegroundServiceRecoveryInstrumentationTest --no-daemon
./gradlew --console=plain :data:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.manager.recording.PlatformReleaseSafetyInstrumentationTest --no-daemon
fi
if [ "${{ matrix.api-level }}" = "25" ] || [ "${{ matrix.api-level }}" = "36" ]; then
diff --git a/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceRecoveryInstrumentationTest.kt b/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceRecoveryInstrumentationTest.kt
new file mode 100644
index 00000000..3d25448b
--- /dev/null
+++ b/app/src/androidTest/java/com/streamvault/app/service/DownloadForegroundServiceRecoveryInstrumentationTest.kt
@@ -0,0 +1,101 @@
+package com.streamvault.app.service
+
+import android.content.Context
+import android.content.Intent
+import androidx.core.content.ContextCompat
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.DownloadDao
+import com.streamvault.data.local.entity.DownloadEntity
+import com.streamvault.domain.model.DownloadContentType
+import com.streamvault.domain.model.DownloadStatus
+import dagger.hilt.EntryPoint
+import dagger.hilt.InstallIn
+import dagger.hilt.android.EntryPointAccessors
+import dagger.hilt.components.SingletonComponent
+import java.io.File
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/** Durable restart fixture for the service's orphan-finalization path. */
+@RunWith(AndroidJUnit4::class)
+class DownloadForegroundServiceRecoveryInstrumentationTest {
+
+ @EntryPoint
+ @InstallIn(SingletonComponent::class)
+ interface DownloadRecoveryEntryPoint {
+ fun downloadDao(): DownloadDao
+ }
+
+ private lateinit var context: Context
+ private lateinit var downloadDao: DownloadDao
+ private var outputFile: File? = null
+
+ @Before
+ fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+ downloadDao = EntryPointAccessors.fromApplication(
+ context,
+ DownloadRecoveryEntryPoint::class.java
+ ).downloadDao()
+ runBlocking { downloadDao.deleteById(DOWNLOAD_ID) }
+ }
+
+ @After
+ fun tearDown() {
+ context.stopService(Intent(context, DownloadForegroundService::class.java))
+ runBlocking { downloadDao.deleteById(DOWNLOAD_ID) }
+ outputFile?.delete()
+ }
+
+ @Test
+ fun stickyRestartFinalizesFullyWrittenOrphanWithoutStartingNetworkTransfer() = runBlocking {
+ val bytes = "durable-final-bytes".toByteArray()
+ outputFile = File(context.cacheDir, "wp7-$DOWNLOAD_ID.bin").apply { writeBytes(bytes) }
+ downloadDao.insert(
+ DownloadEntity(
+ id = DOWNLOAD_ID,
+ providerId = 1L,
+ contentType = DownloadContentType.MOVIE,
+ contentId = 2L,
+ contentName = "Restart fixture",
+ streamUrl = "https://127.0.0.1:1/should-not-be-requested",
+ outputDisplayPath = outputFile!!.absolutePath,
+ status = DownloadStatus.DOWNLOADING,
+ bytesWritten = bytes.size.toLong(),
+ totalBytes = bytes.size.toLong(),
+ supportsResume = true,
+ ownerId = "dead-process",
+ ownerEpoch = 4L,
+ heartbeatAt = 1L
+ )
+ )
+
+ ContextCompat.startForegroundService(
+ context,
+ Intent(context, DownloadForegroundService::class.java)
+ )
+
+ withTimeout(10_000L) {
+ while (downloadDao.getByIdOnce(DOWNLOAD_ID)?.status != DownloadStatus.COMPLETED) {
+ delay(100L)
+ }
+ }
+
+ val recovered = downloadDao.getByIdOnce(DOWNLOAD_ID)!!
+ assertThat(recovered.status).isEqualTo(DownloadStatus.COMPLETED)
+ assertThat(recovered.bytesWritten).isEqualTo(bytes.size.toLong())
+ assertThat(recovered.ownerId).isNull()
+ assertThat(recovered.heartbeatAt).isNull()
+ }
+
+ private companion object {
+ const val DOWNLOAD_ID = "wp7-restart-finalization"
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt
index 4096043f..8659ddd0 100644
--- a/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/DownloadManagerImpl.kt
@@ -75,7 +75,6 @@ class DownloadManagerImpl @Inject constructor(
private val transferCopier = DownloadTransferCopier()
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val ownerId = UUID.randomUUID().toString()
- @Volatile private var recoveryComplete = false
@Volatile private var playbackActive = false
init {
@@ -272,8 +271,10 @@ class DownloadManagerImpl @Inject constructor(
)
private suspend fun ensureInterruptedDownloadsRecovered(): Int = recoveryMutex.withLock {
- if (recoveryComplete) return@withLock 0
- check(activeJobs.isEmpty()) { "Cannot recover downloads while this process owns active jobs" }
+ // Re-scan whenever the scheduler is idle. A process can observe an orphan after the
+ // application-start coroutine has already run, and a cached one-time result would leave
+ // that durable row unowned until a later process restart.
+ if (activeJobs.isNotEmpty()) return@withLock 0
val interrupted = downloadDao.getOrphanedDownloading(ownerId)
interrupted.forEach { entity ->
val targetLength = outputLength(entity)
@@ -330,7 +331,6 @@ class DownloadManagerImpl @Inject constructor(
}
}
}
- recoveryComplete = true
interrupted.size
}
@@ -677,10 +677,11 @@ class DownloadManagerImpl @Inject constructor(
if (!treeUri.isNullOrBlank()) {
val tree = DocumentFile.fromTreeUri(context, Uri.parse(treeUri))
- val file = tree?.createFile(mimeType, fileName)
- ?: error("Could not create download file in selected folder")
+ ?: throw FileNotFoundException("Selected download folder is unavailable")
+ val file = tree.createFile(mimeType, fileName)
+ ?: throw FileNotFoundException("Could not create download file in selected folder")
val output = context.contentResolver.openOutputStream(file.uri)
- ?: error("Could not open selected download file")
+ ?: throw FileNotFoundException("Could not open selected download file")
return@withContext OutputTarget(
uri = file.uri,
displayPath = file.name ?: fileName,
diff --git a/data/src/test/java/com/streamvault/data/manager/DownloadTransferStateMachineTest.kt b/data/src/test/java/com/streamvault/data/manager/DownloadTransferStateMachineTest.kt
index 4d336e03..5d4e2534 100644
--- a/data/src/test/java/com/streamvault/data/manager/DownloadTransferStateMachineTest.kt
+++ b/data/src/test/java/com/streamvault/data/manager/DownloadTransferStateMachineTest.kt
@@ -157,5 +157,10 @@ class DownloadTransferStateMachineTest {
fun `permission loss is permanent even when the network is unavailable`() {
assertThat(isPermanentDownloadStorageFailure(FileNotFoundException("Permission denied"))).isTrue()
assertThat(isPermanentDownloadStorageFailure(SecurityException("tree revoked"))).isTrue()
+ assertThat(
+ isPermanentDownloadStorageFailure(
+ DownloadStorageException(FileNotFoundException("selected folder revoked"))
+ )
+ ).isTrue()
}
}