appstore: delete staged APKs after install, sweep stale cache (#871)
- Commit
dfb2dad8b7bcf26ca1b55f980f3a054cfdeecd1d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-10-31 19:38 UTC (1 month ago)
- Parents
77ec79e
Symptom: the App Store's cacheDir grew to multi-GB sizes (1.8 GB reported on 2.6.11), with no way to reclaim the space short of clearing app data. Root cause: every install path stages APK bytes in cacheDir before committing them to a PackageInstaller session, but SessionInstaller only deleted those files on verification rejection. A committed install left its APKs behind, a failed or cancelled attempt left them behind, and every Play update left a whole versioned directory behind (the resume cache keys per version, so old versions were never reused). Crash-orphaned files had no cleanup path at all. Fix: centralize staging paths and deletion in a new DownloadCache helper. InstallCoordinator deletes staged APKs in a finally after every direct and Play install attempt (success, failure, or cancel); Play splits funnel through one playDir() naming. Both ViewModel entries and UpdateCheckWorker sweep files older than 24h on startup (the worker can cold-start the process alone), covering crash leftovers plus orphaned F-Droid index work dirs. Response and image caching needed no change: downloads bypass HTTP caches and the image disk cache is already capped at 200 MB. User-visible effect: the store's on-disk footprint stays bounded to the in-flight downloads plus small bounded metadata; no action needed, and leftovers from before this change are swept on the next launch. Verification: :appstore:compileDevKotlin and :appstore:testDevUnitTest pass, including the new DownloadCacheTest. Needs on-device testing: install/cancel/update flows and a cold start confirming leftovers are removed.
Diff
appstore/src/main/java/com/vayunmathur/appstore/data/DownloadCache.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/DownloadCache.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/DownloadCache.ktnew file mode 100644index 0000000000..235e6dc410--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/DownloadCache.kt@@ -0,0 +1,121 @@+package com.vayunmathur.appstore.data++import java.io.File++/**+ * Where downloaded APKs live, and how they die (#871).+ *+ * Every install path stages its bytes in [cacheDir] before committing them to+ * a PackageInstaller session: direct downloads as `<package>.apk` (++ * `<package>.splitN.apk` siblings) in the root, Play splits under+ * `PlayDownloads/<package>/<versionCode>/` with `.tmp` resume files beside+ * each finished split. The session owns its own copy of the bytes once+ * `writeFiles` returns, so nothing here is needed after the install attempt+ * ends โ success, failure, user-cancel or crash alike.+ *+ * What actually accumulated gigabytes: `SessionInstaller` only deleted files+ * on verification *rejection*. A committed install left its APKs behind, a+ * failed/cancelled one left them behind, and every Play update left a whole+ * version dir behind (the resume cache keys per version, so it never reused+ * them). Hence three cleanups, all funnelled through here so the naming and+ * the sweep stay in one place:+ * - [deleteStagedApks]: after every direct/APK install attempt, in a+ * `finally` โ unneeded whatever the outcome.+ * - [deletePlayDownloads]: after every Play install attempt, same deal.+ * - [sweepStale]: on startup (both entries + the update worker, which can+ * cold-start the process alone), for whatever a crash orphaned. Age-gated+ * so it can never race an install this process just started.+ *+ * Everything here takes the directories as arguments and touches nothing+ * else, so it unit-tests on the JVM with temp dirs.+ */+object DownloadCache {++ /**+ * Stale-file age for [sweepStale]. An install takes minutes; anything this+ * old is debris from a dead process, not an in-flight download.+ */+ const val STALE_AFTER_MS = 24 * 60 * 60 * 1000L++ /** Direct-download staging name for [packageName]'s base APK. */+ fun apkName(packageName: String): String = "$packageName.apk"++ /** Direct-download staging name for [packageName]'s Nth split sibling. */+ fun splitApkName(packageName: String, index: Int): String = "$packageName.split$index.apk"++ /** The Play resume-cache tree: `PlayDownloads/<package>/<versionCode>/`. */+ fun playDir(cacheDir: File, packageName: String, versionCode: Long): File =+ File(cacheDir, "PlayDownloads/$packageName/$versionCode")++ /**+ * Delete [packageName]'s staged root APKs (base + split siblings). Safe to+ * call when none exist, or twice: verification rejection already deletes.+ */+ fun deleteStagedApks(cacheDir: File, packageName: String) {+ cacheDir.listFiles { file ->+ file.isFile && (file.name == apkName(packageName) ||+ file.name.startsWith("$packageName.split"))+ }?.forEach { runCatching { it.delete() } }+ }++ /**+ * Delete [packageName]'s whole Play download tree (all versions, finished+ * splits and `.tmp` resume files). Called after the install attempt ends;+ * the resume cache only ever resumes within one attempt, so keeping old+ * version dirs can never pay off.+ */+ fun deletePlayDownloads(cacheDir: File, packageName: String) {+ val dir = File(cacheDir, "PlayDownloads/$packageName")+ if (dir.exists()) runCatching { dir.deleteRecursively() }+ }++ /**+ * Delete crash leftovers older than [staleAfterMs] (default [STALE_AFTER_MS]):+ * root `*.apk` files, `*.tmp` resume files under `PlayDownloads/`, version+ * dirs under `PlayDownloads/<pkg>/` with nothing fresh in them, and+ * `fdroid-index/` work dirs (normally deleted in a `finally`, orphaned by+ * a crash mid-sync). Returns the number of files/dirs removed.+ *+ * Small verification downloads (`fdroid-verified.json`,+ * `izzy-verified-*.json`) are deliberately left alone: they are kilobytes,+ * overwritten in place each run, and bounded by construction.+ */+ fun sweepStale(+ cacheDir: File,+ nowMs: Long = System.currentTimeMillis(),+ staleAfterMs: Long = STALE_AFTER_MS,+ ): Int {+ var removed = 0+ val cutoff = nowMs - staleAfterMs+ // Root staging APKs from a dead install attempt.+ cacheDir.listFiles { file ->+ file.isFile && file.name.endsWith(".apk") && file.lastModified() < cutoff+ }?.forEach { if (runCatching { it.delete() }.getOrDefault(false)) removed++ }+ val playRoot = File(cacheDir, "PlayDownloads")+ playRoot.listFiles { file -> file.isDirectory }?.forEach { pkgDir ->+ pkgDir.listFiles { file -> file.isDirectory }?.forEach { versionDir ->+ // A version dir is stale when nothing in it was touched recently:+ // neither a finished split nor a .tmp still being resumed.+ val fresh = versionDir.walkTopDown().any { it.lastModified() >= cutoff }+ if (!fresh && runCatching { versionDir.deleteRecursively() }.getOrDefault(false)) {+ removed+++ }+ }+ // A package dir left with no versions in it is just an empty shell.+ if (pkgDir.listFiles()?.isEmpty() == true &&+ runCatching { pkgDir.delete() }.getOrDefault(false)+ ) {+ removed+++ }+ }+ // Index-sync work dirs are deleted in a finally on the normal path; a+ // crash between mkdirs and the finally leaves them behind (tens of MB).+ val indexRoot = File(cacheDir, "fdroid-index")+ if (indexRoot.isDirectory && indexRoot.lastModified() < cutoff &&+ runCatching { indexRoot.deleteRecursively() }.getOrDefault(false)+ ) {+ removed+++ }+ return removed+ }+}
appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.ktindex 4815288f16..91df946b51 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -90,6 +90,10 @@ class UpdateCheckWorker( ) private suspend fun runCheck(scope: CoroutineScope) {+ // Crash-orphaned APKs first: the worker can cold-start the process with+ // no activity alive, so it sweeps too rather than trusting the UI+ // entries to have run (#871).+ DownloadCache.sweepStale(context.cacheDir) val db = AppStoreDatabaseRepository.get(context).database val env = CheckEnv( scope = scope,
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex 2d6cc90e64..b15a41a43b 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -5,6 +5,7 @@ import com.aurora.gplayapi.exceptions.GooglePlayException import com.vayunmathur.library.log.Log import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.DownloadCache import com.vayunmathur.appstore.data.PinnedStampEntity import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.accrescent.AccrescentRepository@@ -247,7 +248,7 @@ class InstallCoordinator( ) } - val file = File(context.cacheDir, "${app.packageName}.apk")+ val file = File(context.cacheDir, DownloadCache.apkName(app.packageName)) download(apkUrl, file, app.sizeBytes) { fraction -> stage(app.packageName, InstallStage.Downloading(fraction)) }@@ -258,27 +259,37 @@ class InstallCoordinator( // Aggregate progress mirrors installFromAccrescent's split loop. // Each file is size-checked after download (a truncated 200MB base // otherwise surfaces only as a hash mismatch) and retried once.- val files = if (app.splitFiles.isEmpty()) {- downloadVerified(apkUrl, file, app.sizeBytes, app.packageName, null, null)- listOf(file)- } else {- val totalSize =- (app.sizeBytes + app.splitFiles.sumOf { it.size }).takeIf { it > 0 } ?: -1L- var downloadedBytes = 0L- downloadVerified(apkUrl, file, app.sizeBytes, app.packageName, totalSize, 0L)- downloadedBytes += file.length()- val siblings = app.splitFiles.mapIndexed { index, split ->- val splitFile = File(context.cacheDir, "${app.packageName}.split$index.apk")- val start = downloadedBytes- downloadVerified(split.url, splitFile, split.size, app.packageName, totalSize, start)- downloadedBytes += splitFile.length()- splitFile+ //+ // The staged files are deleted in the finally below whatever happens:+ // the session owns its own copy of the bytes once committed, and a+ // failed/cancelled attempt's leftovers are what grew the cache to+ // gigabytes (#871).+ try {+ val files = if (app.splitFiles.isEmpty()) {+ downloadVerified(apkUrl, file, app.sizeBytes, app.packageName, null, null)+ listOf(file)+ } else {+ val totalSize =+ (app.sizeBytes + app.splitFiles.sumOf { it.size }).takeIf { it > 0 } ?: -1L+ var downloadedBytes = 0L+ downloadVerified(apkUrl, file, app.sizeBytes, app.packageName, totalSize, 0L)+ downloadedBytes += file.length()+ val siblings = app.splitFiles.mapIndexed { index, split ->+ val splitFile =+ File(context.cacheDir, DownloadCache.splitApkName(app.packageName, index))+ val start = downloadedBytes+ downloadVerified(split.url, splitFile, split.size, app.packageName, totalSize, start)+ downloadedBytes += splitFile.length()+ splitFile+ }+ listOf(file) + siblings }- listOf(file) + siblings- } - stage(app.packageName, InstallStage.Verifying)- sessionInstaller.installSplits(app.packageName, files, requirement, files.sumOf { it.length() })+ stage(app.packageName, InstallStage.Verifying)+ sessionInstaller.installSplits(app.packageName, files, requirement, files.sumOf { it.length() })+ } finally {+ DownloadCache.deleteStagedApks(context.cacheDir, app.packageName)+ } } /**@@ -409,36 +420,45 @@ class InstallCoordinator( val totalSize = splits.sumOf { it.size }.takeIf { it > 0 } ?: -1L var downloadedBytes = 0L- val files = splits.mapIndexed { index, split ->- val file = File(context.cacheDir, "${app.packageName}.split$index.apk")- val start = downloadedBytes- download(split.url, file, split.size) { fileFraction ->- if (totalSize > 0) {- val overall = (start + fileFraction * split.size) / totalSize- stage(app.packageName, InstallStage.Downloading(overall.coerceIn(0f, 1f)))+ try {+ val files = splits.mapIndexed { index, split ->+ val file = File(+ context.cacheDir,+ DownloadCache.splitApkName(app.packageName, index),+ )+ val start = downloadedBytes+ download(split.url, file, split.size) { fileFraction ->+ if (totalSize > 0) {+ val overall = (start + fileFraction * split.size) / totalSize+ stage(app.packageName, InstallStage.Downloading(overall.coerceIn(0f, 1f)))+ } }+ downloadedBytes += file.length()+ file }- downloadedBytes += file.length()- file- } - val requirement = InstallRequirement(- expectedPackage = app.packageName,- requiredSigners = setOf(trust.signingCertHash),- expectedSha256 = emptyMap(),- minVersionCode = trust.minVersionCode,- signerOrigin = "Accrescent's signed app list",- // Server is the authority for Accrescent: it already picks splits- // per-device, so a client-side leanback refusal would second-guess- // it (mirrors the tvRefusal() exemption). Every other source keeps- // requireTvCompatible = isTv.- requireTvCompatible = false,- )+ val requirement = InstallRequirement(+ expectedPackage = app.packageName,+ requiredSigners = setOf(trust.signingCertHash),+ expectedSha256 = emptyMap(),+ minVersionCode = trust.minVersionCode,+ signerOrigin = "Accrescent's signed app list",+ // Server is the authority for Accrescent: it already picks splits+ // per-device, so a client-side leanback refusal would second-guess+ // it (mirrors the tvRefusal() exemption). Every other source keeps+ // requireTvCompatible = isTv.+ requireTvCompatible = false,+ ) - stage(app.packageName, InstallStage.Verifying)- sessionInstaller.installSplits(- app.packageName, files, requirement, files.sumOf { it.length() }- )+ stage(app.packageName, InstallStage.Verifying)+ sessionInstaller.installSplits(+ app.packageName, files, requirement, files.sumOf { it.length() }+ )+ } finally {+ // Same deal as the direct path: the session owns its copy once+ // committed, and leftovers are what grew the cache (#871).+ DownloadCache.deleteStagedApks(context.cacheDir, app.packageName)+ } } // --- Play ----------------------------------------------------------------------@@ -472,44 +492,54 @@ class InstallCoordinator( var files = purchase(app.packageName, versionCode, offerType, certHash) if (files.isEmpty()) throw java.io.IOException("Play returned no files to download") - var downloaded = playDownloader.downloadFiles(app.packageName, versionCode, files) { f ->- stage(app.packageName, InstallStage.Downloading(f))- }+ // The package's whole Play tree goes away in the finally: the resume+ // cache keys per version and is only ever resumed within one+ // attempt, so old version dirs can never pay off โ and they are+ // what grew the cache to gigabytes (#871).+ try {+ var downloaded =+ playDownloader.downloadFiles(app.packageName, versionCode, files) { f ->+ stage(app.packageName, InstallStage.Downloading(f))+ } - // Delivery URLs are short-lived; one expiry is worth a second purchase call- // rather than making the user tap install again.- if (downloaded.exceptionOrNull() is PlayDownloader.ExpiredUrlException) {- files = purchase(app.packageName, versionCode, offerType, certHash)- downloaded = playDownloader.downloadFiles(app.packageName, versionCode, files) { f ->- stage(app.packageName, InstallStage.Downloading(f))+ // Delivery URLs are short-lived; one expiry is worth a second purchase call+ // rather than making the user tap install again.+ if (downloaded.exceptionOrNull() is PlayDownloader.ExpiredUrlException) {+ files = purchase(app.packageName, versionCode, offerType, certHash)+ downloaded =+ playDownloader.downloadFiles(app.packageName, versionCode, files) { f ->+ stage(app.packageName, InstallStage.Downloading(f))+ } }- }- val localFiles = downloaded.getOrThrow()-- stage(app.packageName, InstallStage.Verifying)-- // Everything Play can actually give us, all enforced:- // - per-split SHA-256 from the delivery response (PlayFile.sha256)- // - the expected signing certificate from AppDetails.certificateSet- // - the source stamp, pinned TOFU (survives Play App Signing)- // - continuity with the installed copy (InstallVerifier, always)- val expectedHashes = files.mapNotNull { f ->- val name = f.name.takeIf { it.isNotBlank() } ?: return@mapNotNull null- f.sha256.takeIf { it.isNotBlank() }?.let { name to it }- }.toMap()-- val requirement = InstallRequirement(- expectedPackage = app.packageName,- requiredSigners = details.expectedSigners.toSet(),- expectedSha256 = expectedHashes,- signerOrigin = "Google",- pinnedStamp = db.pinnedStampDao().byPackage(app.packageName)?.stampSha256,- requireTvCompatible = isTv,- )+ val localFiles = downloaded.getOrThrow() - sessionInstaller.installSplits(- app.packageName, localFiles, requirement, localFiles.sumOf { it.length() }- )+ stage(app.packageName, InstallStage.Verifying)++ // Everything Play can actually give us, all enforced:+ // - per-split SHA-256 from the delivery response (PlayFile.sha256)+ // - the expected signing certificate from AppDetails.certificateSet+ // - the source stamp, pinned TOFU (survives Play App Signing)+ // - continuity with the installed copy (InstallVerifier, always)+ val expectedHashes = files.mapNotNull { f ->+ val name = f.name.takeIf { it.isNotBlank() } ?: return@mapNotNull null+ f.sha256.takeIf { it.isNotBlank() }?.let { name to it }+ }.toMap()++ val requirement = InstallRequirement(+ expectedPackage = app.packageName,+ requiredSigners = details.expectedSigners.toSet(),+ expectedSha256 = expectedHashes,+ signerOrigin = "Google",+ pinnedStamp = db.pinnedStampDao().byPackage(app.packageName)?.stampSha256,+ requireTvCompatible = isTv,+ )++ sessionInstaller.installSplits(+ app.packageName, localFiles, requirement, localFiles.sumOf { it.length() }+ )+ } finally {+ DownloadCache.deletePlayDownloads(context.cacheDir, app.packageName)+ } } /** Retries once without the installed-copy certificate, which Play sometimes rejects. */
appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.ktindex f9f0cd0fde..788a84cfa9 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt@@ -3,6 +3,7 @@ package com.vayunmathur.appstore.data.installer import android.content.Context import com.vayunmathur.library.log.Log import com.aurora.gplayapi.data.models.PlayFile+import com.vayunmathur.appstore.data.DownloadCache import java.io.File import java.net.HttpURLConnection import java.net.URL@@ -44,7 +45,8 @@ class PlayDownloader( progressCallback: (Float) -> Unit = {} ): Result<List<File>> { return try {- val baseDir = File(context.cacheDir, "PlayDownloads/$packageName/$versionCode").apply { mkdirs() }+ val baseDir = DownloadCache.playDir(context.cacheDir, packageName, versionCode)+ .apply { mkdirs() } val totalSize = gplayFiles.sumOf { it.size }.takeIf { it > 0 } ?: -1L var totalDownloaded = 0L val localFiles = mutableListOf<File>()
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.ktindex 4b7b47b98b..f1b1b8deb9 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt@@ -11,6 +11,7 @@ import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.CatalogRepository import com.vayunmathur.appstore.data.DefaultRepos+import com.vayunmathur.appstore.data.DownloadCache import com.vayunmathur.appstore.data.InstalledAppsRepository import com.vayunmathur.appstore.data.InstalledInfo import com.vayunmathur.appstore.data.PlayStoreLinks@@ -28,6 +29,7 @@ import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.data.security.VerificationResult import com.vayunmathur.appstore.util.SourceFilter import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted@@ -35,6 +37,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext /** * Everything the TV browse and detail screens draw.@@ -306,6 +309,12 @@ class TvStoreViewModel( init { viewModelScope.launch {+ // Crash-orphaned APKs first: a dead install attempt's staged files are+ // garbage, and the 24h age gate keeps this from racing anything+ // this process started (#871).+ withContext(Dispatchers.IO) {+ DownloadCache.sweepStale(context.cacheDir)+ } enabledSourcesFlow.value = settings.readEnabledSources() // Drop disabled sources' cached rows before anything reads the catalogue: // sync only purges when it runs, so a disabled offline source's rows would
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex 941c55c7b4..8994957e20 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -13,6 +13,7 @@ import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.DefaultRepos import com.vayunmathur.appstore.data.CatalogRepository+import com.vayunmathur.appstore.data.DownloadCache import com.vayunmathur.appstore.data.InstalledAppsRepository import com.vayunmathur.appstore.data.InstalledInfo import com.vayunmathur.appstore.data.PartitionedUpdates@@ -35,6 +36,7 @@ import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.data.security.VerificationResult import com.vayunmathur.appstore.domain.SearchRanking import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow@@ -43,6 +45,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext /** * One ViewModel, four screens, and no data-layer logic of its own.@@ -409,6 +412,12 @@ class AppStoreViewModel( init { viewModelScope.launch {+ // Crash-orphaned APKs first: a dead install attempt's staged files are+ // garbage, and the 24h age gate keeps this from racing anything+ // this process started (#871).+ withContext(Dispatchers.IO) {+ DownloadCache.sweepStale(context.cacheDir)+ } // The persisted choice rather than the flow's optimistic default: a source the // user switched off must not be contacted once on every cold start while the // stored value is still on its way.
appstore/src/test/java/com/vayunmathur/appstore/data/DownloadCacheTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/DownloadCacheTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/DownloadCacheTest.ktnew file mode 100644index 0000000000..6e13d7dc93--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/DownloadCacheTest.kt@@ -0,0 +1,162 @@+package com.vayunmathur.appstore.data++import java.io.File+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Crash leftovers are the leak (#871): every install attempt stages APKs in+ * cacheDir, and only verification rejections deleted them. These tests pin+ * the naming, the per-attempt deletion, and the age-gated startup sweep.+ */+class DownloadCacheTest {++ private lateinit var cacheDir: File++ @BeforeTest+ fun setUp() {+ cacheDir = Files.createTempDirectory("dlcache").toFile()+ }++ @AfterTest+ fun tearDown() {+ cacheDir.deleteRecursively()+ }++ @Test+ fun `staged apk names are stable`() {+ assertEquals("com.example.app.apk", DownloadCache.apkName("com.example.app"))+ assertEquals(+ "com.example.app.split2.apk",+ DownloadCache.splitApkName("com.example.app", 2),+ )+ assertEquals(+ File(cacheDir, "PlayDownloads/com.example.app/42"),+ DownloadCache.playDir(cacheDir, "com.example.app", 42),+ )+ }++ @Test+ fun `deleteStagedApks removes base and splits but keeps neighbours`() {+ val pkg = "com.example.app"+ File(cacheDir, DownloadCache.apkName(pkg)).writeBytes(ByteArray(8))+ File(cacheDir, DownloadCache.splitApkName(pkg, 0)).writeBytes(ByteArray(8))+ File(cacheDir, DownloadCache.splitApkName(pkg, 1)).writeBytes(ByteArray(8))+ val neighbour = File(cacheDir, "com.example.other.apk")+ neighbour.writeBytes(ByteArray(8))++ DownloadCache.deleteStagedApks(cacheDir, pkg)++ assertFalse(File(cacheDir, DownloadCache.apkName(pkg)).exists())+ assertFalse(File(cacheDir, DownloadCache.splitApkName(pkg, 0)).exists())+ assertFalse(File(cacheDir, DownloadCache.splitApkName(pkg, 1)).exists())+ assertTrue(neighbour.exists())+ }++ @Test+ fun `deleteStagedApks is a no-op when nothing was staged`() {+ // Must not throw: verification rejection already deletes, and the+ // install finally deletes again.+ DownloadCache.deleteStagedApks(cacheDir, "com.example.missing")+ }++ @Test+ fun `deletePlayDownloads removes every version plus resume files`() {+ val pkg = "com.example.app"+ val old = DownloadCache.playDir(cacheDir, pkg, 41).apply { mkdirs() }+ File(old, "base.apk").writeBytes(ByteArray(8))+ File(old, "base.apk.tmp").writeBytes(ByteArray(4))+ val current = DownloadCache.playDir(cacheDir, pkg, 42).apply { mkdirs() }+ File(current, "base.apk").writeBytes(ByteArray(8))+ val other = DownloadCache.playDir(cacheDir, "com.example.other", 7).apply { mkdirs() }+ File(other, "base.apk").writeBytes(ByteArray(8))++ DownloadCache.deletePlayDownloads(cacheDir, pkg)++ assertFalse(File(cacheDir, "PlayDownloads/$pkg").exists())+ assertTrue(File(other, "base.apk").exists())+ }++ @Test+ fun `sweepStale deletes old root apks but keeps fresh ones`() {+ val old = File(cacheDir, "com.example.old.apk").apply { writeBytes(ByteArray(8)) }+ old.setLastModified(1000L)+ val now = 2000L + DownloadCache.STALE_AFTER_MS + 1+ // Touched just now: an install this process started, not debris.+ val fresh = File(cacheDir, "com.example.new.apk").apply { writeBytes(ByteArray(8)) }+ fresh.setLastModified(now)++ val removed = DownloadCache.sweepStale(+ cacheDir,+ nowMs = now,+ staleAfterMs = DownloadCache.STALE_AFTER_MS,+ )++ assertEquals(1, removed)+ assertFalse(old.exists())+ assertTrue(fresh.exists())+ }++ @Test+ fun `sweepStale deletes stale version dirs and emptied package shells`() {+ val pkg = "com.example.app"+ val stale = DownloadCache.playDir(cacheDir, pkg, 41).apply { mkdirs() }+ val staleApk = File(stale, "base.apk").apply { writeBytes(ByteArray(8)) }+ staleApk.setLastModified(1000L)+ stale.setLastModified(1000L)+ val now = 1000L + DownloadCache.STALE_AFTER_MS + 1++ val removed = DownloadCache.sweepStale(cacheDir, nowMs = now)++ assertFalse(stale.exists())+ // The package dir is left with no versions: the empty shell goes too.+ assertFalse(File(cacheDir, "PlayDownloads/$pkg").exists())+ assertTrue(removed >= 1)+ }++ @Test+ fun `sweepStale keeps a version dir still being resumed`() {+ val pkg = "com.example.app"+ val active = DownloadCache.playDir(cacheDir, pkg, 42).apply { mkdirs() }+ val partial = File(active, "split.apk.tmp").apply { writeBytes(ByteArray(4)) }+ val oldApk = File(active, "base.apk").apply { writeBytes(ByteArray(8)) }+ oldApk.setLastModified(1000L)+ val now = 1000L + DownloadCache.STALE_AFTER_MS + 1+ // The .tmp was touched just now: a download is still resuming into it.+ partial.setLastModified(now)++ DownloadCache.sweepStale(cacheDir, nowMs = now)++ assertTrue(active.exists())+ assertTrue(oldApk.exists())+ }++ @Test+ fun `sweepStale deletes orphaned fdroid-index work dirs`() {+ val work = File(cacheDir, "fdroid-index/12345").apply { mkdirs() }+ File(work, "index-v2.json").writeBytes(ByteArray(8))+ val root = File(cacheDir, "fdroid-index")+ root.setLastModified(1000L)+ val now = 1000L + DownloadCache.STALE_AFTER_MS + 1++ DownloadCache.sweepStale(cacheDir, nowMs = now)++ assertFalse(root.exists())+ }++ @Test+ fun `sweepStale ignores small verification downloads`() {+ val verified = File(cacheDir, "fdroid-verified.json").apply { writeBytes(ByteArray(8)) }+ verified.setLastModified(1000L)+ val now = 1000L + DownloadCache.STALE_AFTER_MS + 1++ DownloadCache.sweepStale(cacheDir, nowMs = now)++ assertTrue(verified.exists())+ }+}