downloadservice: create parent dirs and run downloads in a worker
- Commit
9c9b1304f5928422d8f806456ee25f3cb0e5ff9b- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 04:50 UTC (3 months ago)
- Parents
a6b4006
Diff
library/downloadservice/build.gradle.kts
diff --git a/library/downloadservice/build.gradle.kts b/library/downloadservice/build.gradle.ktsindex b300abd4fc..a6c6ec6b22 100644--- a/library/downloadservice/build.gradle.kts+++ b/library/downloadservice/build.gradle.kts@@ -4,4 +4,6 @@ plugins { dependencies { implementation(project(":library"))+ // WorkManager: the download runs in ModelDownloadWorker so it outlives the gating screen.+ implementation(project(":library:work")) }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.ktindex 2ba12229f4..a6fdccaa41 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt@@ -2,6 +2,7 @@ package com.vayunmathur.library.downloadservice import android.app.DownloadManager import android.content.Context+import android.util.Log import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn@@ -17,6 +18,8 @@ import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp+import androidx.work.WorkInfo+import androidx.work.WorkManager import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.round import kotlinx.coroutines.CancellationException@@ -37,8 +40,11 @@ import kotlin.coroutines.coroutineContext * an optional [sha256] verified after the download completes. Both the plain * `Triple(url, fileName, description)` API and the [ModelDownloadItem] API funnel * into this so the download loop only deals with one shape.+ *+ * [fileName] may contain a subdirectory (`small100/encoder.ncnn.bin`), which the+ * download loop creates on demand. */-private data class DownloadSpec(+internal data class DownloadSpec( val fileName: String, val description: String, val url: String,@@ -108,12 +114,19 @@ private fun InitialDownloadScreen( ) { val context = LocalContext.current - // Stream each required file directly into the app's external files dir (no- // DownloadManager), writing the same DataStore keys the UI below observes.- // When every requested file is present on disk, advance to the main page.- LaunchedEffect(Unit) {- runDownloadsCore(context, ds, specs)- if (allFilesPresent(context, specs)) {+ // The download runs in a WorkManager job, not in this composition: it used to live in a+ // LaunchedEffect, so leaving the screen (or a configuration change) cancelled a multi-hundred-MB+ // transfer. The screen only enqueues and observes now; `.part` files let a stopped run resume.+ val workName = remember(specs) { ModelDownloadWorker.uniqueName(specs) }+ LaunchedEffect(specs) { ModelDownloadWorker.enqueue(context, specs) }++ val workInfo by remember(workName) {+ WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow(workName)+ }.collectAsState(emptyList())+ val state = workInfo.firstOrNull()?.state++ LaunchedEffect(state) {+ if (state == WorkInfo.State.SUCCEEDED && allFilesPresent(context, specs)) { onAllDownloaded() } }@@ -138,6 +151,20 @@ private fun InitialDownloadScreen( Spacer(Modifier.height(32.dp)) + // A silently-stuck screen was the old failure mode: every attempt threw, the loop gave+ // up, and nothing said so. Offer an explicit retry instead.+ if (state == WorkInfo.State.FAILED) {+ Text(+ text = stringResource(R.string.download_failed),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.error+ )+ Button(onClick = { ModelDownloadWorker.retry(context, specs) }) {+ Text(stringResource(R.string.retry))+ }+ Spacer(Modifier.height(24.dp))+ }+ LazyColumn( verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.fillMaxWidth()@@ -175,12 +202,17 @@ private const val DOWNLOAD_BUFFER_SIZE = 1 shl 16 private const val CONNECT_TIMEOUT_MS = 30_000 private const val READ_TIMEOUT_MS = 30_000 +private const val TAG = "ModelDownload"+ /** * Mirror-only on-demand download: fetches each [ModelDownloadItem] from the * self-hosted mirror (no third-party fallback), with optional SHA-256 * verification (supply-chain mitigation #1). Publishes the same `progress_*` / * `speed_*` DataStore keys as the initial screen and skips files already present- * on disk.+ * on disk. Returns whether every file ended up on disk and verified.+ *+ * This runs in the caller's scope, so it is for downloads the caller is already+ * waiting on; first-launch gating goes through [ModelDownloadWorker] instead. */ suspend fun downloadModels( context: Context,@@ -198,13 +230,18 @@ suspend fun downloadModels( * Files are processed sequentially; each publishes `progress_*` / `speed_*` for * the UI. On checksum mismatch the download is retried; on final failure any * `.part` file is left in place so the next run resumes it.+ *+ * Returns true only when every spec ended up on disk and verified, so the caller+ * ([ModelDownloadWorker]) can ask WorkManager to retry rather than reporting a+ * success that leaves the app gated forever. */-private suspend fun runDownloadsCore(+internal suspend fun runDownloadsCore( context: Context, ds: DataStoreUtils, specs: List<DownloadSpec>,-) = withContext(Dispatchers.IO) {+): Boolean = withContext(Dispatchers.IO) { val dir = context.getExternalFilesDir(null)+ var allDownloaded = true for (spec in specs) { // Sever any legacy DownloadManager claim on an already-present file before // we treat it as a plain app file (one-time, guarded — see fn docs).@@ -223,8 +260,9 @@ private suspend fun runDownloadsCore( ds.setDouble("progress_${spec.fileName}", 0.0) } }- downloadSpec(ds, dir, spec)+ if (!downloadSpec(ds, dir, spec)) allDownloaded = false }+ allDownloaded } /**@@ -232,13 +270,13 @@ private suspend fun runDownloadsCore( * atomically renames it to the final name. Retries transient failures up to * [MAX_ATTEMPTS]; on a checksum mismatch the partial is discarded and the file * is re-fetched from scratch. On final failure any `.part` is left for the next- * run to resume (the download screen stays, as before).+ * run to resume, and false is returned so the caller can surface it. */ private suspend fun downloadSpec( ds: DataStoreUtils, dir: File?, spec: DownloadSpec,-) {+): Boolean { val finalFile = File(dir, spec.fileName) val partFile = File(dir, "${spec.fileName}.part") @@ -247,19 +285,23 @@ private suspend fun downloadSpec( streamToPart(ds, spec, partFile) if (checksumOk(partFile, spec.sha256)) { finalizeDownload(ds, spec, partFile, finalFile)- return+ return true } // Corrupt/tampered copy — drop the partial and re-fetch from scratch.+ Log.w(TAG, "checksum mismatch for ${spec.fileName}; refetching") partFile.delete() } catch (e: CancellationException) {- // Cooperative cancellation (screen left / process paused): keep the- // `.part` so the next run resumes via the Range header.+ // Cooperative cancellation (worker stopped): keep the `.part` so the+ // next run resumes via the Range header. throw e- } catch (_: Exception) {+ } catch (e: Exception) { // Transient network error — keep the `.part` for resume and back off.+ Log.w(TAG, "attempt ${attempt + 1}/$MAX_ATTEMPTS failed for ${spec.fileName}", e) if (attempt < MAX_ATTEMPTS - 1) delay(RETRY_DELAY_MS) } }+ Log.e(TAG, "giving up on ${spec.fileName} after $MAX_ATTEMPTS attempts")+ return false } /**@@ -272,6 +314,10 @@ private suspend fun streamToPart( spec: DownloadSpec, partFile: File, ) {+ // fileName can name a subdirectory ("small100/encoder.ncnn.bin"). FileOutputStream does not+ // create missing parents, so without this every attempt died with ENOENT before a single byte+ // was written — which is exactly how the SMaLL-100 download hung at 0% with no error.+ partFile.parentFile?.mkdirs() var startOffset = if (partFile.exists()) partFile.length() else 0L val conn = (URL(spec.url).openConnection() as HttpURLConnection).apply { connectTimeout = CONNECT_TIMEOUT_MS
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.ktnew file mode 100644index 0000000000..51fb30725a--- /dev/null+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt@@ -0,0 +1,123 @@+package com.vayunmathur.library.downloadservice++import android.content.Context+import androidx.work.BackoffPolicy+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.Data+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.library.util.DataStoreUtils+import java.util.concurrent.TimeUnit++/**+ * Runs the model download outside any composition.+ *+ * The download used to run in a `LaunchedEffect` on the gating screen, so it was cancelled by a+ * rotation, a back press or the app being backgrounded, and a partial transfer of a multi-hundred-MB+ * model only resumed if the user happened to reopen that exact screen. Here it survives all of+ * those, and a failed run is retried by WorkManager with exponential backoff instead of being+ * swallowed.+ *+ * This is a plain background worker, so the platform stops it after roughly ten minutes of+ * execution. That is fine because the work is resumable: partial bytes live in `<fileName>.part`+ * and the next run continues with a `Range` request, so a large bundle completes across several+ * runs. Promote it to a foreground worker (`setForeground`) if it needs to finish in one pass.+ */+class ModelDownloadWorker(context: Context, params: WorkerParameters) :+ CoroutineWorker(context, params) {++ override suspend fun doWork(): Result {+ val specs = readSpecs(inputData)+ if (specs.isEmpty()) return Result.failure()++ val ds = DataStoreUtils.getInstance(applicationContext)+ return when {+ runDownloadsCore(applicationContext, ds, specs) -> Result.success()+ // Keep retrying transient problems (flaky network, mirror hiccup) but eventually stop so+ // the screen can offer a retry rather than backing off forever.+ runAttemptCount + 1 >= MAX_RUN_ATTEMPTS -> Result.failure()+ else -> Result.retry()+ }+ }++ companion object {+ private const val KEY_URLS = "urls"+ private const val KEY_FILE_NAMES = "fileNames"+ private const val KEY_DESCRIPTIONS = "descriptions"+ private const val KEY_HASHES = "hashes"++ /** Absent SHA-256, encoded as an empty string because [Data] holds no nulls. */+ private const val NO_HASH = ""++ private const val MAX_RUN_ATTEMPTS = 6+ private const val BACKOFF_SECONDS = 30L++ /**+ * Stable unique-work name for [specs], so re-entering the screen observes the run already in+ * flight instead of starting a second one.+ */+ internal fun uniqueName(specs: List<DownloadSpec>): String {+ val key = specs.joinToString("\u0000") { it.fileName }.hashCode()+ return "model_download_${key.toUInt().toString(16)}"+ }++ /** Enqueues the download, keeping any run already in progress for the same [specs]. */+ internal fun enqueue(context: Context, specs: List<DownloadSpec>) =+ enqueue(context, specs, ExistingWorkPolicy.KEEP)++ /** Restarts the download after a failure, replacing the failed run. */+ internal fun retry(context: Context, specs: List<DownloadSpec>) =+ enqueue(context, specs, ExistingWorkPolicy.REPLACE)++ private fun enqueue(+ context: Context,+ specs: List<DownloadSpec>,+ policy: ExistingWorkPolicy,+ ) {+ val data = Data.Builder()+ .putStringArray(KEY_URLS, specs.map { it.url }.toTypedArray())+ .putStringArray(KEY_FILE_NAMES, specs.map { it.fileName }.toTypedArray())+ .putStringArray(KEY_DESCRIPTIONS, specs.map { it.description }.toTypedArray())+ .putStringArray(KEY_HASHES, specs.map { it.sha256 ?: NO_HASH }.toTypedArray())+ .build()++ val request = OneTimeWorkRequestBuilder<ModelDownloadWorker>()+ .setInputData(data)+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .build()+ )+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_SECONDS, TimeUnit.SECONDS)+ .build()++ WorkManager.getInstance(context)+ .enqueueUniqueWork(uniqueName(specs), policy, request)+ }++ private fun readSpecs(data: Data): List<DownloadSpec> {+ val urls = data.getStringArray(KEY_URLS) ?: return emptyList()+ val fileNames = data.getStringArray(KEY_FILE_NAMES) ?: return emptyList()+ val descriptions = data.getStringArray(KEY_DESCRIPTIONS) ?: return emptyList()+ val hashes = data.getStringArray(KEY_HASHES) ?: return emptyList()+ if (fileNames.size != urls.size ||+ descriptions.size != urls.size ||+ hashes.size != urls.size+ ) {+ return emptyList()+ }+ return urls.indices.map { i ->+ DownloadSpec(+ fileName = fileNames[i],+ description = descriptions[i],+ url = urls[i],+ sha256 = hashes[i].takeIf { it != NO_HASH },+ )+ }+ }+ }+}
library/downloadservice/src/main/res/values/strings.xml
diff --git a/library/downloadservice/src/main/res/values/strings.xml b/library/downloadservice/src/main/res/values/strings.xmlindex b7b6886ed6..40a796bd2a 100644--- a/library/downloadservice/src/main/res/values/strings.xml+++ b/library/downloadservice/src/main/res/values/strings.xml@@ -9,6 +9,10 @@ <string name="downloading_required_components_for_this">Downloading required components for this app.</string> <!-- Shared library: downloadservice – InitialDownloader: Status label left of percent in progress row when file download is finished --> <string name="completed">Completed</string>- <!-- Shared library: downloadservice – InitialDownloader: Status label left of percent when download is in progress, includes ellipsis -->- <string name="downloading">Downloading…</string>+ <!-- Shared library: downloadservice - InitialDownloader: Status label left of percent when download is in progress, includes ellipsis -->+ <string name="downloading">Downloading.</string>+ <!-- Shared library: downloadservice - InitialDownloader: Error shown on the first-launch blocker screen when the component download gave up. Error color, above a Retry button -->+ <string name="download_failed">Download failed. Check your connection and try again.</string>+ <!-- Shared library: downloadservice - InitialDownloader: Button that restarts a failed component download -->+ <string name="retry">Retry</string> </resources>