diff --git a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt index 4da92adb91..d4ac6697b3 100644 --- a/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/QuickBuildModule.kt @@ -31,6 +31,7 @@ import org.appdevforall.cotg.quickbuild.domain.telemetry.QuickBuildMetricsSink import org.appdevforall.cotg.quickbuild.service.deploy.DeployChannel import org.appdevforall.cotg.quickbuild.service.deploy.DeploySender import org.appdevforall.cotg.quickbuild.service.deploy.ProxyAppConnections +import org.appdevforall.cotg.quickbuild.service.provision.InstallLaunchResult import org.appdevforall.cotg.quickbuild.service.provision.InstalledPackages import org.appdevforall.cotg.quickbuild.service.provision.ProxyAppInstaller import org.appdevforall.cotg.quickbuild.service.provision.QuickBuildClobberCheck @@ -83,33 +84,53 @@ val quickBuildModule = single { val context = androidContext() - ProxyAppInstaller( - packages = get(), - // The exact call the Run button's install flow bottoms out in: - // same PackageInstaller session params, same InstallationResultReceiver, - // same MIUI intent fallback. Post-install launch is suppressed: the session - // switches to the proxy app itself on provisioning success, so the generic - // launch-after-install must not fire a duplicate launch on every install. - launchInstall = { apk -> - withContext(Dispatchers.Main) { - ApkInstaller.installApk(context, apk, suppressPostInstallLaunch = true) - } - }, - // Register before any install: the receiver's EventBus events become the - // installer's completion signal. - broadcasts = InstallationEventFlow().also { it.register() }.broadcasts, - // Whether the install-confirm dialog can be launched right now. The - // dialog-owning subscriber (BaseEditorActivity -> InstallationResultHandler) - // is EventBus lifecycle-bound - registered onStart, unregistered onStop - - // so it can show the dialog exactly while the process is STARTED. Racy - // reads err toward waiting (the installer's timeout is the backstop). - canShowConfirmDialog = { - ProcessLifecycleOwner - .get() - .lifecycle.currentState - .isAtLeast(Lifecycle.State.STARTED) - }, - ) + lateinit var installer: ProxyAppInstaller + installer = + ProxyAppInstaller( + packages = get(), + // Register before any install: the receiver's EventBus events become the + // installer's completion signal. + broadcasts = InstallationEventFlow().also { it.register() }.broadcasts, + // Whether the install-confirm dialog can be launched right now. The + // dialog-owning subscriber (BaseEditorActivity -> InstallationResultHandler) + // is EventBus lifecycle-bound - registered onStart, unregistered onStop - + // so it can show the dialog exactly while the process is STARTED. Racy + // reads err toward waiting (the installer's timeout is the backstop). + canShowConfirmDialog = { + ProcessLifecycleOwner + .get() + .lifecycle.currentState + .isAtLeast(Lifecycle.State.STARTED) + }, + // The exact call the Run button's install flow bottoms out in: + // same PackageInstaller session params, same InstallationResultReceiver, + // same MIUI intent fallback. Post-install launch is suppressed: the session + // switches to the proxy app itself on provisioning success, so the generic + // launch-after-install must not fire a duplicate launch on every install. + launchInstallSession = { apk -> + val result = + withContext(Dispatchers.Main) { + ApkInstaller.installApkSession( + context = context, + apk = apk, + suppressPostInstallLaunch = true, + ) + } + when (result) { + is ApkInstaller.SessionLaunchResult.Started -> InstallLaunchResult.Started(result.sessionId) + ApkInstaller.SessionLaunchResult.TooManySessions -> InstallLaunchResult.TooManySessions + ApkInstaller.SessionLaunchResult.Failed -> InstallLaunchResult.Failed + } + }, + abandonSession = { sessionId -> ApkInstaller.abandonSession(context, sessionId) }, + sweepStaleSessions = { + ApkInstaller.abandonMySessions( + context = context, + onBeforeAbandon = installer::recordAbandonedSession, + ) + }, + ) + installer } single { @@ -201,6 +222,13 @@ val quickBuildModule = // AssetsProvider, which is API 30+. Below that an asset edit would be // extracted and never read, so those edits rebaseline instead. assetsLiveReloadable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R, + sweepInstallSessions = { + val installer = get() + ApkInstaller.abandonMySessions( + context = androidContext(), + onBeforeAbandon = installer::recordAbandonedSession, + ) + }, ).also { manager -> // Narration must be scoped to the session, not to an activity on screen: // an activity-scoped collector misses every generation produced while the diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt index 8d1d3851de..8fca271c90 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildInstallAdapters.kt @@ -160,11 +160,14 @@ class InstallationEventFlow { InstallBroadcast.Status.OTHER } } + val sessionId = + extras.getInt(PackageInstaller.EXTRA_SESSION_ID, Int.MIN_VALUE).takeIf { it != Int.MIN_VALUE } _broadcasts.tryEmit( InstallBroadcast( packageName = extras.getString(PackageInstaller.EXTRA_PACKAGE_NAME), status = status, message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE), + sessionId = sessionId, ), ) } diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt index 6f5b065d98..fe4ce8daa3 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildMessages.kt @@ -38,6 +38,10 @@ fun QuickBuildMessage.resolve(context: Context): String = context.getString(R.string.quick_build_install_could_not_start) } + QuickBuildMessage.TooManyInstallSessions -> { + context.getString(R.string.quick_build_too_many_install_sessions) + } + QuickBuildMessage.InstallFailed -> { context.getString(R.string.quick_build_install_failed) } diff --git a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt index a121e32ae1..81b0a25a13 100644 --- a/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt +++ b/app/src/main/java/com/itsaky/androidide/services/InstallationResultReceiver.kt @@ -22,6 +22,7 @@ import android.content.Context import android.content.Intent import com.itsaky.androidide.buildinfo.BuildInfo import com.itsaky.androidide.events.InstallationEvent.InstallationResultEvent +import com.itsaky.androidide.utils.ApkInstaller import org.greenrobot.eventbus.EventBus /** @@ -38,6 +39,7 @@ class InstallationResultReceiver : BroadcastReceiver() { context: Context, intent: Intent, ) { + ApkInstaller.onInstallStatusBroadcast(intent, context) EventBus.getDefault().post(InstallationResultEvent(intent)) } } diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt index 97f7466740..ce7d347bc8 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkInstaller.kt @@ -15,6 +15,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory import java.io.File +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap /** * Utility class for installing APKs. @@ -24,6 +26,38 @@ import java.io.File object ApkInstaller { private val log = LoggerFactory.getLogger(ApkInstaller::class.java) private const val DEBUG_FALLBACK_INSTALLER = false + private const val PREFS_INSTALLER_SESSIONS = "ide.installer.sessions" + private const val KEY_QUICK_BUILD_SESSIONS = "quick_build_session_ids" + private const val KEY_IN_FLIGHT_USER_SESSIONS = "in_flight_user_session_ids" + private const val MAX_ACTIVE_SESSIONS = 50 + + /** + * Session IDs of Quick Build proxy-app installs created by this app, persisted across + * process restarts in `SharedPreferences` so [abandonMySessions] can identify and sweep + * stale Quick Build sessions without abandoning Standard Run installs. + */ + private val quickBuildSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + + /** + * Session IDs of active non-Quick-Build installs (Standard Run and `InstallFileAction`) + * recorded immediately at [PackageInstaller.createSession] (covering both APK staging and + * user confirmation) until a terminal status broadcast or explicit abandonment. Persisted + * to `SharedPreferences` so a Quick Build sweep excludes Standard Run sessions even across + * configuration changes or process restarts. + */ + private val inFlightUserSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + + /** + * Session IDs of active Standard Run or `InstallFileAction` installs created in the current + * process (never loaded from `SharedPreferences`). Even when the 50-session cap is reached, + * these belong to a live install in this process and are never swept. + */ + private val liveInFlightUserSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + + private val sessionTrackingLock = Any() /** * Boolean extra riding the install callback intent: on STATUS_SUCCESS, do not run the @@ -40,6 +74,28 @@ object ApkInstaller { */ const val EXTRA_SUPPRESS_POST_INSTALL_LAUNCH = "ide.installer.suppressPostInstallLaunch" + /** + * Outcome of starting an APK install session. + */ + sealed interface SessionLaunchResult { + /** + * The install was handed off to Android. [sessionId] is the committed + * [PackageInstaller] session ID, or `null` when the intent-based fallback was used. + */ + data class Started( + val sessionId: Int?, + ) : SessionLaunchResult + + /** + * [PackageInstaller.createSession] rejected the request because this app UID already + * has the maximum number of active sessions (`MAX_ACTIVE_SESSIONS = 50`). + */ + data object TooManySessions : SessionLaunchResult + + /** Any other failure before or during session creation/commit. */ + data object Failed : SessionLaunchResult + } + /** * Starts a session-based package installation workflow. * @@ -55,14 +111,35 @@ object ApkInstaller { launchInDebugMode: Boolean = false, debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, suppressPostInstallLaunch: Boolean = false, - ): Boolean { + ): Boolean = + installApkSession( + context = context, + apk = apk, + launchInDebugMode = launchInDebugMode, + debugFallbackInstaller = debugFallbackInstaller, + suppressPostInstallLaunch = suppressPostInstallLaunch, + ) is SessionLaunchResult.Started + + /** + * Starts a session-based package installation workflow and returns a [SessionLaunchResult] + * with the committed `sessionId` (or a distinct [SessionLaunchResult.TooManySessions] + * when the UID's active session quota is exhausted). + */ + @JvmStatic + suspend fun installApkSession( + context: Context, + apk: File, + launchInDebugMode: Boolean = false, + debugFallbackInstaller: Boolean = DEBUG_FALLBACK_INSTALLER, + suppressPostInstallLaunch: Boolean = false, + ): SessionLaunchResult { val isValidApk = withContext(Dispatchers.IO) { apk.exists() && apk.isFile && apk.extension.equals("apk", ignoreCase = true) } if (!isValidApk) { log.error("File is not an APK: {}", apk) - return false + return SessionLaunchResult.Failed } log.info("Installing APK: {}", apk) @@ -83,43 +160,326 @@ object ApkInstaller { " Falling back to intent-based installer.", ) - installUsingIntent(context, apk, baseIntent) - return true + return if (installUsingIntent(context, apk, baseIntent)) { + SessionLaunchResult.Started(sessionId = null) + } else { + SessionLaunchResult.Failed + } } return installUsingSession(context, apk, baseIntent) } + /** + * Abandons a single [PackageInstaller] session if it is still active. Safe to call after + * the session has already succeeded, failed, or been abandoned. + */ + @JvmStatic + fun abandonSession( + context: Context, + sessionId: Int, + ): Boolean { + val installer = context.packageManager.packageInstaller + return synchronized(sessionTrackingLock) { + var abandonError: Throwable? = null + val abandoned = + runCatching { + installer.abandonSession(sessionId) + }.onFailure { error -> + abandonError = error + log.debug("Session {} already finalized or could not be abandoned", sessionId, error) + }.isSuccess + if (abandoned || isSessionFinalized(installer, sessionId, abandonError)) { + removeTrackedSession(context, sessionId) + } + abandoned + } + } + + /** + * Abandons [sessionId] on [installer], returning `true` if `abandonSession` succeeded and + * `false` if the session was already finalized or could not be abandoned. + */ + internal fun abandonSession( + installer: PackageInstaller, + sessionId: Int, + ): Boolean = + synchronized(sessionTrackingLock) { + var abandonError: Throwable? = null + val abandoned = + runCatching { + installer.abandonSession(sessionId) + }.onFailure { error -> + abandonError = error + log.debug("Session {} already finalized or could not be abandoned", sessionId, error) + }.isSuccess + if (abandoned || isSessionFinalized(installer, sessionId, abandonError)) { + removeTrackedSession(context = null, sessionId = sessionId) + } + abandoned + } + + /** + * Returns `true` when [sessionId] is confirmed to no longer exist or have already been + * finalized in [installer]. + */ + internal fun isSessionFinalized( + installer: PackageInstaller, + sessionId: Int, + error: Throwable? = null, + ): Boolean { + if (error is SecurityException && error.message?.contains("finalized", ignoreCase = true) == true) { + return true + } + return runCatching { + installer.getSessionInfo(sessionId) == null + }.getOrDefault(false) + } + + /** + * Records a status broadcast from [InstallationResultReceiver] so any session that reaches + * a terminal outcome is removed from tracked session sets and persisted storage. + */ + @JvmOverloads + internal fun onInstallStatusBroadcast( + intent: Intent?, + context: Context? = null, + ) { + val extras = intent?.extras ?: return + if (!extras.containsKey(PackageInstaller.EXTRA_STATUS)) return + val status = extras.getInt(PackageInstaller.EXTRA_STATUS) + if (status != PackageInstaller.STATUS_PENDING_USER_ACTION && + extras.containsKey(PackageInstaller.EXTRA_SESSION_ID) + ) { + removeTrackedSession(context, extras.getInt(PackageInstaller.EXTRA_SESSION_ID)) + } + } + + /** + * Clears in-memory tracked session IDs (and persisted preferences when [context] is given) + * between unit tests. + */ + internal fun clearInFlightUserSessionsForTesting(context: Context? = null) { + liveInFlightUserSessionIds.clear() + inFlightUserSessionIds.clear() + quickBuildSessionIds.clear() + if (context != null) { + runCatching { + context.applicationContext + .getSharedPreferences(PREFS_INSTALLER_SESSIONS, Context.MODE_PRIVATE) + .edit() + .remove(KEY_IN_FLIGHT_USER_SESSIONS) + .remove(KEY_QUICK_BUILD_SESSIONS) + .commit() + } + } + } + + /** + * Clears only the in-memory session sets to simulate an app process restart in unit tests + * while keeping `SharedPreferences` state intact. + */ + internal fun clearInMemorySessionsForTesting() { + liveInFlightUserSessionIds.clear() + inFlightUserSessionIds.clear() + quickBuildSessionIds.clear() + } + + private fun recordQuickBuildSession( + context: Context, + sessionId: Int, + ) = synchronized(sessionTrackingLock) { + loadPersistedSessions(context) + liveInFlightUserSessionIds.remove(sessionId) + inFlightUserSessionIds.remove(sessionId) + quickBuildSessionIds.add(sessionId) + persistTrackedSessions(context) + } + + private fun recordInFlightUserSession( + context: Context, + sessionId: Int, + ) = synchronized(sessionTrackingLock) { + loadPersistedSessions(context) + quickBuildSessionIds.remove(sessionId) + liveInFlightUserSessionIds.add(sessionId) + inFlightUserSessionIds.add(sessionId) + persistTrackedSessions(context) + } + + private fun removeTrackedSession( + context: Context?, + sessionId: Int, + ) = synchronized(sessionTrackingLock) { + if (context != null) { + loadPersistedSessions(context) + } + liveInFlightUserSessionIds.remove(sessionId) + val removedUser = inFlightUserSessionIds.remove(sessionId) + val removedQb = quickBuildSessionIds.remove(sessionId) + if (context != null && (removedUser || removedQb)) { + persistTrackedSessions(context) + } + } + + private fun loadPersistedSessions(context: Context) { + runCatching { + val prefs = + context.applicationContext.getSharedPreferences( + PREFS_INSTALLER_SESSIONS, + Context.MODE_PRIVATE, + ) + prefs + .getStringSet(KEY_IN_FLIGHT_USER_SESSIONS, emptySet()) + .orEmpty() + .mapNotNullTo(inFlightUserSessionIds) { it.toIntOrNull() } + prefs + .getStringSet(KEY_QUICK_BUILD_SESSIONS, emptySet()) + .orEmpty() + .mapNotNullTo(quickBuildSessionIds) { it.toIntOrNull() } + }.onFailure { error -> + log.debug("Unable to read persisted installer session IDs", error) + } + } + + private fun persistTrackedSessions(context: Context) { + runCatching { + val userSnapshot = inFlightUserSessionIds.mapTo(HashSet()) { it.toString() } + val qbSnapshot = quickBuildSessionIds.mapTo(HashSet()) { it.toString() } + context.applicationContext + .getSharedPreferences(PREFS_INSTALLER_SESSIONS, Context.MODE_PRIVATE) + .edit() + .putStringSet(KEY_IN_FLIGHT_USER_SESSIONS, userSnapshot) + .putStringSet(KEY_QUICK_BUILD_SESSIONS, qbSnapshot) + .apply() + }.onFailure { error -> + log.debug("Unable to persist installer session IDs", error) + } + } + + /** + * Abandons stale Quick Build [PackageInstaller] sessions owned by this installer package + * while excluding any active Standard Run or `InstallFileAction` install sessions + * ([inFlightUserSessionIds]), including sessions that are currently staging APK bytes or + * awaiting user confirmation across a restart. + * + * Called at Quick Build startup and before Quick Build provisioning so that unconfirmed + * Quick Build sessions from earlier runs cannot accumulate to Android's 50-session per-UID + * cap (`PackageInstallerService.MAX_ACTIVE_SESSIONS`) or leave a stale confirmation dialog + * in the system `packageinstaller` task, without cancelling a concurrent Standard Run or + * `InstallFileAction` install. + * + * @param onBeforeAbandon invoked with each session ID before `abandonSession` runs so + * callers can ignore the `STATUS_FAILURE_ABORTED` broadcast Android emits on abandonment. + * @return the number of sessions abandoned. + */ + @JvmStatic + @JvmOverloads + fun abandonMySessions( + context: Context, + onBeforeAbandon: (Int) -> Unit = {}, + ): Int { + loadPersistedSessions(context) + val abandoned = abandonMySessions(context.packageManager.packageInstaller, onBeforeAbandon) + persistTrackedSessions(context) + return abandoned + } + + /** + * Queries [PackageInstaller.getMySessions] on [installer] and abandons each stale Quick Build + * session (or legacy cap-overflow session when the 50-session limit is reached), always + * excluding [inFlightUserSessionIds], after notifying [onBeforeAbandon]. + */ + internal fun abandonMySessions( + installer: PackageInstaller, + onBeforeAbandon: (Int) -> Unit = {}, + ): Int = + synchronized(sessionTrackingLock) { + val sessions = + runCatching { installer.mySessions } + .onFailure { error -> log.warn("Failed to query existing PackageInstaller sessions", error) } + .getOrNull() + ?: return 0 + + val activeIds = sessions.mapTo(HashSet(sessions.size)) { it.sessionId } + liveInFlightUserSessionIds.retainAll(activeIds) + inFlightUserSessionIds.retainAll(activeIds) + quickBuildSessionIds.retainAll(activeIds) + + val isAtSessionCap = sessions.size >= MAX_ACTIVE_SESSIONS + var abandoned = 0 + for (info in sessions) { + val id = info.sessionId + if (id in liveInFlightUserSessionIds) { + continue + } + if (id in inFlightUserSessionIds && !isAtSessionCap) { + continue + } + if (id !in quickBuildSessionIds && !isAtSessionCap) { + continue + } + runCatching { onBeforeAbandon(id) } + if (abandonSession(installer, id)) { + abandoned++ + } + } + if (abandoned > 0) { + log.info("Abandoned {} stale PackageInstaller session(s)", abandoned) + } + abandoned + } + + /** + * Launches a fallback `ACTION_INSTALL_PACKAGE` activity intent for devices where + * session-based installation is disabled, returning `true` if the activity started. + */ @Suppress("DEPRECATION", "RequestInstallPackagesPolicy") private fun installUsingIntent( context: Context, apk: File, intent: Intent, - ) { + ): Boolean { val uri = context.fileProviderUriFor(apk) intent.setAction(Intent.ACTION_INSTALL_PACKAGE) intent.setDataAndType(uri, "application/vnd.android.package-archive") intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK - try { + return try { context.startActivity(intent) + true } catch (e: Exception) { log.warn("Failed to start installation intent", e) + false } } + /** + * Creates, populates, and commits a [PackageInstaller] session for [apk], returning + * a [SessionLaunchResult] with the committed session ID or failure classification. + */ @Suppress("RequestInstallPackagesPolicy") - private suspend fun installUsingSession( + internal suspend fun installUsingSession( context: Context, apk: File, intent: Intent, - ): Boolean { + ): SessionLaunchResult { val installer = context.packageManager.packageInstaller val params = createSessionParams() + val isQuickBuildInstall = intent.getBooleanExtra(EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, false) return runCatching { withContext(Dispatchers.IO) { - val sessionId = installer.createSession(params) + val sessionId = + synchronized(sessionTrackingLock) { + val id = installer.createSession(params) + if (isQuickBuildInstall) { + recordQuickBuildSession(context, id) + } else { + recordInFlightUserSession(context, id) + } + id + } var session: PackageInstaller.Session? = null try { @@ -130,18 +490,37 @@ object ApkInstaller { } addToSession(session, apk) session.commit(callback.intentSender) + sessionId } catch (t: Throwable) { - runCatching { installer.abandonSession(sessionId) } + abandonSession(context, sessionId) throw t } finally { session?.close() } } - }.onFailure { error -> - log.error("Package installation failed", error) - }.isSuccess + }.fold( + onSuccess = { sessionId -> SessionLaunchResult.Started(sessionId) }, + onFailure = { error -> + log.error("Package installation failed", error) + if (isTooManyActiveSessions(error)) { + SessionLaunchResult.TooManySessions + } else { + SessionLaunchResult.Failed + } + }, + ) } + /** + * Returns `true` when [error] or any cause in its chain is the `IllegalStateException` + * thrown by Android's `PackageInstallerService` when the per-UID session cap is reached. + */ + internal fun isTooManyActiveSessions(error: Throwable): Boolean = + generateSequence(error) { it.cause }.any { cause -> + cause is IllegalStateException && + cause.message?.contains("Too many active sessions", ignoreCase = true) == true + } + private fun createSessionParams(appPackageName: String? = null): PackageInstaller.SessionParams = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { if (appPackageName != null) { diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt index 68784cbbbc..e883f71f68 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/ApkInstallationViewModel.kt @@ -208,7 +208,7 @@ class ApkInstallationViewModel : ViewModel() { } try { - packageInstaller.abandonSession(sessionId) + ApkInstaller.abandonSession(context, sessionId) } catch (e: Exception) { logger.error("Failed to abandon session with ID: {}", sessionId, e) } finally { diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt index d0231e646a..0c74b3e3ac 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/InstallationEventFlowTest.kt @@ -25,11 +25,15 @@ class InstallationEventFlowTest { status: Int?, packageName: String? = "com.example.app", message: String? = null, + sessionId: Int? = null, ): InstallationEvent.InstallationResultEvent { val extras = mockk() every { extras.getInt(PackageInstaller.EXTRA_STATUS, any()) } answers { status ?: secondArg() } + every { extras.getInt(PackageInstaller.EXTRA_SESSION_ID, any()) } answers { + sessionId ?: secondArg() + } every { extras.getString(PackageInstaller.EXTRA_PACKAGE_NAME) } returns packageName every { extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE) } returns message val intent = mockk() @@ -144,4 +148,17 @@ class InstallationEventFlowTest { assertThat(broadcasts).isEmpty() } + + @Test + fun `sessionId extra is forwarded on InstallBroadcast when present and null when absent`() { + val broadcasts = + broadcastsFor( + resultEvent(PackageInstaller.STATUS_SUCCESS, sessionId = 987654), + resultEvent(PackageInstaller.STATUS_PENDING_USER_ACTION, sessionId = null), + ) + + assertThat(broadcasts).hasSize(2) + assertThat(broadcasts[0].sessionId).isEqualTo(987654) + assertThat(broadcasts[1].sessionId).isNull() + } } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt index afd70825e9..5d27db1fb7 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildMessagesTest.kt @@ -46,6 +46,7 @@ class QuickBuildMessagesTest { assertResolvesTo(QuickBuildMessage.ReinstallDeclined, R.string.quick_build_reinstall_declined) assertResolvesTo(QuickBuildMessage.ReinstallWaitingForGradle, R.string.quick_build_reinstall_waiting_for_gradle) assertResolvesTo(QuickBuildMessage.InstallCouldNotStart, R.string.quick_build_install_could_not_start) + assertResolvesTo(QuickBuildMessage.TooManyInstallSessions, R.string.quick_build_too_many_install_sessions) assertResolvesTo(QuickBuildMessage.InstallFailed, R.string.quick_build_install_failed) assertResolvesTo(QuickBuildMessage.RebuildFailed, R.string.quick_build_rebuild_failed) assertResolvesTo(QuickBuildMessage.ProvisioningFailedUnexpectedly, R.string.quick_build_provisioning_failed_unexpectedly) @@ -112,6 +113,7 @@ class QuickBuildMessagesTest { QuickBuildMessage.ReinstallTimedOut(180), QuickBuildMessage.ReinstallWaitingForGradle, QuickBuildMessage.InstallCouldNotStart, + QuickBuildMessage.TooManyInstallSessions, QuickBuildMessage.InstallFailed, QuickBuildMessage.InstalledButUnresolvable("com.example.app"), QuickBuildMessage.ForeignAppInstalled("com.example.other"), diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt new file mode 100644 index 0000000000..b3123637af --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkInstallerSessionTest.kt @@ -0,0 +1,356 @@ +package com.itsaky.androidide.utils + +import android.app.Application +import android.content.Context +import android.content.Intent +import android.content.pm.PackageInstaller +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import io.mockk.every +import io.mockk.justRun +import io.mockk.mockk +import io.mockk.spyk +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.ByteArrayOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(application = Application::class) +class ApkInstallerSessionTest { + @get:Rule + val tempFolder = TemporaryFolder() + + @Before + @After + fun resetInFlightSessions() { + ApkInstaller.clearInFlightUserSessionsForTesting( + ApplicationProvider.getApplicationContext(), + ) + } + + private fun sessionInfo(id: Int): PackageInstaller.SessionInfo = + mockk { + every { sessionId } returns id + } + + @Test + fun `abandonMySessions abandons all 50 sessions and tolerates already-finalized ones`() { + val active = (1..50).toMutableSet() + val installer = mockk() + every { installer.mySessions } answers { active.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + val id = firstArg() + if (id == 25) { + throw SecurityException("Session 25 already finalized") + } + active.remove(id) + } + + val abandoned = ApkInstaller.abandonMySessions(installer) + + assertThat(abandoned).isEqualTo(49) + assertThat(active).containsExactly(25) + } + + @Test + fun `installUsingSession does not abandon other in-flight sessions and abandonMySessions preserves pending user installs`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val activeSessions = (1..49).toMutableSet() + var nextId = 100 + + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + justRun { session.fsync(any()) } + justRun { session.commit(any()) } + justRun { session.close() } + + val installer = mockk() + every { installer.mySessions } answers { activeSessions.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + activeSessions.remove(firstArg()) + } + every { installer.createSession(any()) } answers { + if (activeSessions.size >= 50) { + throw IllegalStateException("Too many active sessions for UID 10600") + } + val id = nextId++ + activeSessions += id + id + } + every { installer.openSession(any()) } returns session + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + // 1. Start a Run-button / InstallFileAction install (session 100); it is now waiting for confirmation. + val runButtonResult = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(runButtonResult).isEqualTo(ApkInstaller.SessionLaunchResult.Started(100)) + assertThat(activeSessions).contains(100) + + // 2. Quick Build sweeps stale sessions before provisioning: all 49 stale sessions are + // abandoned, but the pending Run-button session (100) is preserved. + val swept = ApkInstaller.abandonMySessions(installer) + assertThat(swept).isEqualTo(49) + assertThat(activeSessions).containsExactly(100) + + // 3. Quick Build starts its proxy install (session 101): session 100 is still not abandoned. + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + val quickBuildResult = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(quickBuildResult).isEqualTo(ApkInstaller.SessionLaunchResult.Started(101)) + assertThat(activeSessions).containsExactly(100, 101) + + // 4. Reverse direction: another Run-button / InstallFileAction install (session 102) + // does not abandon the pending Quick Build session (101). + val secondUserInstall = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(secondUserInstall).isEqualTo(ApkInstaller.SessionLaunchResult.Started(102)) + assertThat(activeSessions).containsExactly(100, 101, 102) + + // 5. Once session 100 finishes with a terminal broadcast, sweeping abandons the stale + // Quick Build session (101) while preserving the active Standard Run session (102). + activeSessions.remove(100) + ApkInstaller.onInstallStatusBroadcast( + Intent() + .putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE_ABORTED) + .putExtra(PackageInstaller.EXTRA_SESSION_ID, 100), + context, + ) + ApkInstaller.abandonMySessions(context) + assertThat(activeSessions).containsExactly(102) + } + + @Test + fun `abandonMySessions tracks Quick Build ownership across restarts and excludes staging or active Standard Run sessions`() = + runTest { + val apk = tempFolder.newFile("staging.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val activeSessions = mutableSetOf() + var nextId = 200 + + val installer = mockk() + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + var sweepDuringStaging = false + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } answers { + if (sweepDuringStaging) { + // Simulate Quick Build's startup sweep running WHILE Standard Run is actively + // staging APK bytes (after createSession, before session.commit). + ApkInstaller.abandonMySessions(context) + } + ByteArrayOutputStream() + } + justRun { session.fsync(any()) } + justRun { session.commit(any()) } + justRun { session.close() } + + every { installer.mySessions } answers { activeSessions.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + activeSessions.remove(firstArg()) + } + every { installer.createSession(any()) } answers { + val id = nextId++ + activeSessions += id + id + } + every { installer.openSession(any()) } returns session + + // 1. Create a Quick Build session (200) before Standard Run starts. + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + val firstQuickBuild = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(firstQuickBuild).isEqualTo(ApkInstaller.SessionLaunchResult.Started(200)) + assertThat(activeSessions).containsExactly(200) + + // 2. Start a Standard Run install (201) whose openWrite triggers a Quick Build sweep + // mid-staging: stale Quick Build session 200 is abandoned, while staging Standard Run + // session 201 is preserved. + sweepDuringStaging = true + val standardRunResult = ApkInstaller.installUsingSession(context, apk, Intent()) + sweepDuringStaging = false + assertThat(standardRunResult).isEqualTo(ApkInstaller.SessionLaunchResult.Started(201)) + assertThat(activeSessions).containsExactly(201) + + // 3. Create another Quick Build session (202) and an untracked non-Quick-Build session (203), + // then clear in-memory state to simulate an app process restart. + val secondQuickBuild = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(secondQuickBuild).isEqualTo(ApkInstaller.SessionLaunchResult.Started(202)) + activeSessions += 203 + assertThat(activeSessions).containsExactly(201, 202, 203) + + ApkInstaller.clearInMemorySessionsForTesting() + + // 4. After restart, startup sweep abandons only the persisted Quick Build session (202) + // and excludes both the persisted Standard Run session (201) and untracked session (203). + val sweptAfterRestart = ApkInstaller.abandonMySessions(context) + assertThat(sweptAfterRestart).isEqualTo(1) + assertThat(activeSessions).containsExactly(201, 203) + } + + @Test + fun `installUsingSession reports TooManySessions distinctly from Failed when cap remains full`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + + val installer = mockk() + every { installer.mySessions } returns emptyList() + every { installer.createSession(any()) } throws + IllegalStateException("Too many active sessions for UID 10600") + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val capResult = ApkInstaller.installUsingSession(context, apk, Intent()) + + every { installer.createSession(any()) } throws IllegalStateException("Some other error") + val genericResult = ApkInstaller.installUsingSession(context, apk, Intent()) + + assertThat(capResult).isEqualTo(ApkInstaller.SessionLaunchResult.TooManySessions) + assertThat(genericResult).isEqualTo(ApkInstaller.SessionLaunchResult.Failed) + } + + @Test + fun `abandonMySessions at 50-session cap sweeps persisted user sessions from dead process but preserves live ones`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val activeSessions = mutableListOf() + + fun sessionInfo(id: Int): PackageInstaller.SessionInfo = + mockk().apply { + every { sessionId } returns id + } + + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } answers { java.io.ByteArrayOutputStream() } + justRun { session.fsync(any()) } + justRun { session.commit(any()) } + justRun { session.close() } + + val installer = mockk() + every { installer.mySessions } answers { activeSessions.map(::sessionInfo) } + every { installer.abandonSession(any()) } answers { + activeSessions.remove(firstArg()) + } + var nextId = 1 + every { installer.createSession(any()) } answers { + val id = nextId++ + activeSessions += id + id + } + every { installer.openSession(any()) } returns session + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + // 1. Standard Run session (1) from a previous process, persisted before restart. + val deadProcessSession = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(deadProcessSession).isEqualTo(ApkInstaller.SessionLaunchResult.Started(1)) + ApkInstaller.clearInMemorySessionsForTesting() + + // 2. Fill up to 49 sessions with untracked sessions, then start a live Standard Run (50). + for (id in 2..49) { + activeSessions += id + } + nextId = 50 + val liveSession = ApkInstaller.installUsingSession(context, apk, Intent()) + assertThat(liveSession).isEqualTo(ApkInstaller.SessionLaunchResult.Started(50)) + assertThat(activeSessions).hasSize(50) + + // 3. At the 50-session cap, sweep abandons the persisted dead-process session (1) and + // untracked sessions (2..49), while preserving the live Standard Run session (50). + val swept = ApkInstaller.abandonMySessions(context) + assertThat(swept).isEqualTo(49) + assertThat(activeSessions).containsExactly(50) + } + + @Test + fun `abandonSession retains tracking when abandonment throws and session is not finalized`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val installer = mockk() + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + + every { installer.createSession(any()) } returns 77 + every { installer.openSession(77) } returns session + every { installer.abandonSession(77) } throws RuntimeException("transient IPC binder failure") + every { installer.getSessionInfo(77) } returns sessionInfo(77) + every { installer.mySessions } returns listOf(sessionInfo(77)) + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + val launch = ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + assertThat(launch).isEqualTo(ApkInstaller.SessionLaunchResult.Started(77)) + + val abandonedContext = ApkInstaller.abandonSession(context, 77) + assertThat(abandonedContext).isFalse() + + var sweptId: Int? = null + every { installer.abandonSession(77) } answers { + sweptId = 77 + } + val swept = ApkInstaller.abandonMySessions(installer) + assertThat(swept).isEqualTo(1) + assertThat(sweptId).isEqualTo(77) + } + + @Test + fun `abandonSession removes tracking when abandonment throws but session is confirmed finalized`() = + runTest { + val apk = tempFolder.newFile("app-debug.apk").apply { writeBytes(byteArrayOf(1, 2, 3, 4)) } + val installer = mockk() + val session = mockk(relaxed = true) + every { session.openWrite(any(), any(), any()) } returns ByteArrayOutputStream() + + every { installer.createSession(any()) } returns 88 + every { installer.openSession(88) } returns session + every { installer.abandonSession(88) } throws SecurityException("Session 88 already finalized") + every { installer.getSessionInfo(88) } returns null + every { installer.mySessions } returns listOf(sessionInfo(88)) + + val baseContext = ApplicationProvider.getApplicationContext() + val pm = spyk(baseContext.packageManager) + every { pm.packageInstaller } returns installer + val context = spyk(baseContext) + every { context.packageManager } returns pm + + val quickBuildIntent = + Intent().putExtra(ApkInstaller.EXTRA_SUPPRESS_POST_INSTALL_LAUNCH, true) + ApkInstaller.installUsingSession(context, apk, quickBuildIntent) + + val abandoned = ApkInstaller.abandonSession(context, 88) + assertThat(abandoned).isFalse() + + var sweepCalled = false + every { installer.abandonSession(88) } answers { sweepCalled = true } + val swept = ApkInstaller.abandonMySessions(installer) + assertThat(swept).isEqualTo(0) + assertThat(sweepCalled).isFalse() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt b/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt index e80bdd374c..b0ec2d2d7a 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/InstallationResultHandlerSuppressLaunchTest.kt @@ -88,5 +88,6 @@ class InstallationResultHandlerSuppressLaunchTest { val started = Shadows.shadowOf(activity).nextStartedActivity assertThat(started).isNotNull() assertThat(started.action).isEqualTo("com.android.packageinstaller.CONFIRM") + assertThat(started.flags and Intent.FLAG_ACTIVITY_NEW_TASK).isEqualTo(Intent.FLAG_ACTIVITY_NEW_TASK) } } diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt index b6f9f2774e..325344d2fe 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/domain/session/QuickBuildMessage.kt @@ -47,6 +47,12 @@ sealed interface QuickBuildMessage { /** The installer could not even launch the install. */ data object InstallCouldNotStart : QuickBuildMessage + /** + * Android's PackageInstaller rejected session creation because this app UID has reached the + * per-UID active-session cap (`MAX_ACTIVE_SESSIONS = 50`). + */ + data object TooManyInstallSessions : QuickBuildMessage + /** The install ran and the OS reported a failure with nothing more specific to say. */ data object InstallFailed : QuickBuildMessage diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt index 9951eaba05..995385c41d 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstaller.kt @@ -1,14 +1,16 @@ package org.appdevforall.cotg.quickbuild.service.provision import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull @@ -16,7 +18,10 @@ import org.appdevforall.cotg.quickbuild.domain.session.QuickBuildMessage import org.slf4j.LoggerFactory import java.io.File import java.security.MessageDigest +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference /** * What the installer needs to know about installed packages; implemented over @@ -79,11 +84,14 @@ interface InstalledPackages { * failure broadcasts often do not; a waiter must then accept it as its own * @property status the mapped status; anything unrecognized arrives as [Status.OTHER] * @property message the OS failure text when there is one, shown to the user verbatim + * @property sessionId the PackageInstaller EXTRA_SESSION_ID when the broadcast carried one, + * used to ignore stale broadcasts from earlier sessions */ data class InstallBroadcast( val packageName: String?, val status: Status, val message: String? = null, + val sessionId: Int? = null, ) { /** ABORTED is STATUS_FAILURE_ABORTED: the user cancelled the confirm dialog. */ enum class Status { SUCCESS, FAILURE, ABORTED, PENDING_USER_ACTION, OTHER } @@ -103,6 +111,30 @@ data class InstallBroadcast( get() = status == Status.SUCCESS || status == Status.FAILURE || status == Status.ABORTED } +/** + * What became of launching an APK install session. + */ +sealed interface InstallLaunchResult { + /** + * The install was handed off to Android. + * + * @property sessionId the committed PackageInstaller session ID, or null when the + * intent-based fallback was used (or when the caller only reports a boolean start) + */ + data class Started( + val sessionId: Int? = null, + ) : InstallLaunchResult + + /** + * PackageInstaller refused to create a session because this UID has reached the + * system's active-session cap (`MAX_ACTIVE_SESSIONS = 50`). + */ + data object TooManySessions : InstallLaunchResult + + /** Any other failure before or during session creation/commit. */ + data object Failed : InstallLaunchResult +} + /** What became of a [ProxyAppInstaller.ensureInstalled]. */ sealed interface InstallOutcome { /** @@ -165,7 +197,7 @@ class ProxyAppInstaller( /** Installed-package facts; every read goes through here so tests need no PackageManager. */ private val packages: InstalledPackages, /** Starts the install (ApkInstaller.installApk); false when it could not start. */ - private val launchInstall: suspend (File) -> Boolean, + private val launchInstall: suspend (File) -> Boolean = { false }, /** InstallationResultReceiver broadcasts, adapted app-side. */ private val broadcasts: Flow, /** @@ -187,9 +219,40 @@ class ProxyAppInstaller( * always-true keeps the plain wait-for-the-user behavior for callers without a probe. */ private val canShowConfirmDialog: () -> Boolean = { true }, + /** Starts the install and returns its session ID or launch failure reason. */ + private val launchInstallSession: suspend (File) -> InstallLaunchResult = { file -> + if (launchInstall(file)) { + InstallLaunchResult.Started() + } else { + InstallLaunchResult.Failed + } + }, + /** + * Abandons a committed PackageInstaller session by its ID. Called before re-issuing a + * silent prompt and in `finally` on every exit path from [ensureInstalled] so unconfirmed + * sessions never accumulate or intercept subsequent confirm dialogs. + */ + private val abandonSession: (Int) -> Unit = {}, + /** + * Sweeps any stale PackageInstaller sessions owned by this UID before launching a new + * install, reclaiming the 50-session pool and dismissing leftover confirm dialogs. + */ + private val sweepStaleSessions: () -> Unit = {}, /** Where the blocking work (APK hashing, PackageManager reads) runs; injectable for tests. */ private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ) { + private val abandonedSessionIds: MutableSet = + Collections.newSetFromMap(ConcurrentHashMap()) + + /** + * Records [sessionId] as abandoned before `PackageInstaller.abandonSession` runs so that + * Android's resulting `STATUS_FAILURE_ABORTED` broadcast cannot match an in-flight install + * while `activeSessionId` is still `null`. + */ + fun recordAbandonedSession(sessionId: Int) { + abandonedSessionIds.add(sessionId) + } + /** * Gets [packageName] installed from [apk], skipping the install when the bytes on * device already match. @@ -211,119 +274,285 @@ class ProxyAppInstaller( return InstallOutcome.Installed(existingUid) } + try { + withContext(ioDispatcher) { sweepStaleSessions() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("failed to sweep stale install sessions before installing {}", packageName, e) + } + return coroutineScope { // Set when the OS reported PENDING_USER_ACTION, which means a confirm dialog // exists; re-issuing the prompt then would stack a second dialog on it. Atomic // because the write happens in the collector child and the read on this // coroutine while that child is still running, so nothing else orders them. val pendingUserActionSeen = AtomicBoolean(false) - // Subscribe before committing the install so a fast broadcast cannot slip - // past us. PENDING_USER_ACTION is decisive too when no confirm dialog can be - // launched, since nobody will ever tap. - val verdict = - async(start = CoroutineStart.UNDISPATCHED) { + val activeSessionId = AtomicReference(null) + val launchedSessionIds = Collections.newSetFromMap(ConcurrentHashMap()) + val stateLock = Any() + var expectedSession: ExpectedSession = ExpectedSession.AwaitingLaunch + val earlyBroadcasts = mutableListOf() + val verdictDeferred = CompletableDeferred() + + fun isBroadcastDecisive(broadcast: InstallBroadcast): Boolean = + broadcast.isTerminal || + ( + broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION && + !canShowConfirmDialog() + ) + + fun matchesExpectedSession( + broadcast: InstallBroadcast, + state: ExpectedSession, + ): Boolean { + val packageMatches = broadcast.packageName == null || broadcast.packageName == packageName + if (!packageMatches) return false + return when (state) { + is ExpectedSession.AwaitingLaunch -> { + false + } + + is ExpectedSession.Session -> { + broadcast.sessionId == state.id && state.id !in abandonedSessionIds + } + + is ExpectedSession.FallbackWithoutSession -> { + broadcast.sessionId == null + } + } + } + + fun handleMatchingBroadcast(broadcast: InstallBroadcast) { + if (broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION) { + pendingUserActionSeen.set(true) + } + if (isBroadcastDecisive(broadcast)) { + verdictDeferred.complete(classify(broadcast)) + } + } + + fun onLaunchStarted(launchResult: InstallLaunchResult.Started) { + synchronized(stateLock) { + val sessionId = launchResult.sessionId + val state = + if (sessionId != null) { + abandonedSessionIds.remove(sessionId) + activeSessionId.set(sessionId) + launchedSessionIds.add(sessionId) + ExpectedSession.Session(sessionId) + } else { + activeSessionId.set(null) + ExpectedSession.FallbackWithoutSession + } + expectedSession = state + val iterator = earlyBroadcasts.iterator() + while (iterator.hasNext()) { + val broadcast = iterator.next() + iterator.remove() + if (matchesExpectedSession(broadcast, state)) { + handleMatchingBroadcast(broadcast) + if (verdictDeferred.isCompleted) { + break + } + } + } + } + } + + val collector = + launch(start = CoroutineStart.UNDISPATCHED) { try { - Result.success( - broadcasts.first { broadcast -> - val ours = - broadcast.packageName == null || broadcast.packageName == packageName - if (ours && broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION) { - pendingUserActionSeen.set(true) + broadcasts.collect { broadcast -> + synchronized(stateLock) { + if (verdictDeferred.isCompleted) return@collect + val state = expectedSession + if (state is ExpectedSession.AwaitingLaunch) { + earlyBroadcasts.add(broadcast) + } else if (matchesExpectedSession(broadcast, state)) { + handleMatchingBroadcast(broadcast) } - ours && - ( - broadcast.isTerminal || - ( - broadcast.status == InstallBroadcast.Status.PENDING_USER_ACTION && - !canShowConfirmDialog() - ) - ) - }, - ) + } + } + // If the flow completes without a match, complete as Failed so that + // ensureInstalled still never throws or hangs indefinitely. + synchronized(stateLock) { + if (!verdictDeferred.isCompleted) { + verdictDeferred.complete( + Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)), + ) + } + } } catch (e: CancellationException) { throw e } catch (e: Exception) { - // If the flow completes without a match, first() throws and no - // verdict can arrive this way. Captured as a failure so that - // ensureInstalled still never throws. - Result.failure(e) + log.warn("broadcast collector failed", e) + verdictDeferred.complete( + Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)), + ) } } - val stampChanged = async { awaitStampChange(packageName, initialStamp) } - - val started = - try { - launchInstall(apk) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - log.error("could not start the install of {}", packageName, e) - false - } - if (!started) { - log.warn("install of {} from {} did not start; reporting InstallCouldNotStart", packageName, apk) - verdict.cancel() - stampChanged.cancel() - return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) - } - val awaitVerdict: suspend () -> Verdict = { - select { - verdict.onAwait { result -> - result.fold( - onSuccess = { broadcast -> classify(broadcast) }, - onFailure = { Verdict.Settled(InstallOutcome.Failed(QuickBuildMessage.InstallFailed)) }, + try { + val stampChanged = async { awaitStampChange(packageName, initialStamp) } + + val launchResult = + try { + launchInstallSession(apk) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.error("could not start the install of {}", packageName, e) + InstallLaunchResult.Failed + } + when (launchResult) { + is InstallLaunchResult.Started -> { + onLaunchStarted(launchResult) + } + + InstallLaunchResult.TooManySessions -> { + log.warn( + "install of {} from {} hit PackageInstaller session limit; reporting TooManyInstallSessions", + packageName, + apk, ) + collector.cancel() + verdictDeferred.cancel() + stampChanged.cancel() + return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions) + } + + InstallLaunchResult.Failed -> { + log.warn("install of {} from {} did not start; reporting InstallCouldNotStart", packageName, apk) + collector.cancel() + verdictDeferred.cancel() + stampChanged.cancel() + return@coroutineScope InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart) } - stampChanged.onAwait { Verdict.InstalledPendingUid } } - } - val outcome = - withTimeoutOrNull(timeoutMillis) { - // A commit whose confirm dialog never reached the user is indistinguishable - // from one the user is still reading, so the first wait is bounded rather than - // the whole budget. Re-committing costs a second dialog at worst and is the - // only way back from a prompt nobody was shown - what a CoGo process death does - // to the next session's first install, the dialog-owning subscriber being - // lifecycle-bound. The deferreds are reused, so a late verdict still resolves. - withTimeoutOrNull(promptTimeoutMillis) { awaitVerdict() } - ?: run { - // A seen PENDING_USER_ACTION means the OS confirmed a dialog - // exists - the user is reading it, and a re-commit would put a - // second dialog over the first. Only the silent case (no status - // at all) is the lost-prompt one the re-issue repairs. - if (canShowConfirmDialog() && !pendingUserActionSeen.get()) { - log.info( - "no install verdict for {} in {}ms; re-issuing the prompt", - packageName, - promptTimeoutMillis, - ) - try { - launchInstall(apk) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - // The first commit is still pending; keep waiting on it. - log.error("could not re-issue the install of {}", packageName, e) + + val awaitVerdict: suspend () -> Verdict = { + select { + verdictDeferred.onAwait { it } + stampChanged.onAwait { Verdict.InstalledPendingUid } + } + } + val outcome = + withTimeoutOrNull(timeoutMillis) { + // A commit whose confirm dialog never reached the user is indistinguishable + // from one the user is still reading, so the first wait is bounded rather than + // the whole budget. Re-committing costs a second dialog at worst and is the + // only way back from a prompt nobody was shown - what a CoGo process death does + // to the next session's first install, the dialog-owning subscriber being + // lifecycle-bound. The deferreds are reused, so a late verdict still resolves. + withTimeoutOrNull(promptTimeoutMillis) { awaitVerdict() } + ?: run { + // A seen PENDING_USER_ACTION means the OS confirmed a dialog + // exists - the user is reading it, and a re-commit would put a + // second dialog over the first. Only the silent case (no status + // at all) is the lost-prompt one the re-issue repairs. + if (canShowConfirmDialog() && !pendingUserActionSeen.get()) { + log.info( + "no install verdict for {} in {}ms; re-issuing the prompt", + packageName, + promptTimeoutMillis, + ) + activeSessionId.get()?.let { staleSessionId -> + abandonedSessionIds.add(staleSessionId) + activeSessionId.set(null) + withContext(ioDispatcher + NonCancellable) { + abandonSessionSafely(staleSessionId) + } + launchedSessionIds.remove(staleSessionId) + } + synchronized(stateLock) { + expectedSession = ExpectedSession.AwaitingLaunch + earlyBroadcasts.clear() + } + val reissued = + try { + launchInstallSession(apk) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.error("could not re-issue the install of {}", packageName, e) + InstallLaunchResult.Failed + } + when (reissued) { + is InstallLaunchResult.Started -> { + onLaunchStarted(reissued) + } + + InstallLaunchResult.TooManySessions -> { + log.warn( + "re-issued install of {} from {} hit PackageInstaller session limit; reporting TooManyInstallSessions", + packageName, + apk, + ) + return@run Verdict.Settled( + InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions), + ) + } + + InstallLaunchResult.Failed -> { + log.warn( + "re-issued install of {} from {} did not start; reporting InstallCouldNotStart", + packageName, + apk, + ) + return@run Verdict.Settled( + InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart), + ) + } + } } + awaitVerdict() } - awaitVerdict() + } + collector.cancel() + verdictDeferred.cancel() + stampChanged.cancel() + // The uid is resolved here, OUTSIDE both timeout windows. It retries over + // PackageManager's post-install lag, and inside the prompt budget a plain SUCCESS + // arriving late had that retry cut short - which read as "no verdict yet" and + // re-prompted the user for an install that had already succeeded. + when (outcome) { + null -> confirmationNotGivenAtTimeout() + Verdict.InstalledPendingUid -> resolveUid(packageName) + is Verdict.Settled -> outcome.outcome + } + } finally { + if (launchedSessionIds.isNotEmpty()) { + withContext(ioDispatcher + NonCancellable) { + for (sessionId in launchedSessionIds) { + abandonSessionSafely(sessionId) } + } } - verdict.cancel() - stampChanged.cancel() - // The uid is resolved here, OUTSIDE both timeout windows. It retries over - // PackageManager's post-install lag, and inside the prompt budget a plain SUCCESS - // arriving late had that retry cut short - which read as "no verdict yet" and - // re-prompted the user for an install that had already succeeded. - when (outcome) { - null -> confirmationNotGivenAtTimeout() - Verdict.InstalledPendingUid -> resolveUid(packageName) - is Verdict.Settled -> outcome.outcome } } } + /** + * Marks [sessionId] as abandoned and invokes [abandonSession], swallowing any exception so + * cleanup in `finally` never masks the install outcome. + */ + private fun abandonSessionSafely(sessionId: Int) { + abandonedSessionIds.add(sessionId) + runCatching { abandonSession(sessionId) } + .onFailure { log.warn("failed to abandon install session {}", sessionId, it) } + } + + private sealed interface ExpectedSession { + data object AwaitingLaunch : ExpectedSession + + data class Session( + val id: Int, + ) : ExpectedSession + + data object FallbackWithoutSession : ExpectedSession + } + /** * What one wait for an install verdict produced, before the uid read. * diff --git a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt index 353850626e..e9965a25e1 100644 --- a/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt +++ b/quickbuild/core/src/main/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManager.kt @@ -1,6 +1,7 @@ package org.appdevforall.cotg.quickbuild.service.session import android.content.ComponentCallbacks2 +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope @@ -158,6 +159,12 @@ class QuickBuildSessionManager( * Defaults to the capable path so this module's unit tests need no Android runtime. */ private val assetsLiveReloadable: Boolean = true, + /** + * Sweeps stale Quick Build PackageInstaller sessions at Quick Build startup (excluding any + * active Standard Run or `InstallFileAction` install sessions) so an already-capped phone + * (MAX_ACTIVE_SESSIONS = 50) recovers without clearing app data. + */ + private val sweepInstallSessions: () -> Unit = {}, ) { /** Builds the project watcher for a live session; overridden with a fake in tests. */ fun interface WatcherFactory { @@ -461,13 +468,25 @@ class QuickBuildSessionManager( } /** - * The stale-tree sweep. Nothing is live at construction - this manager is the process's - * only session owner - so every tree under the scratch root belongs to a dead session or - * a deleted project. Launched before any tap can dispatch, but sweep() hops to IO and - * frees the dispatcher, so [provision] joins it rather than trusting the launch order: a - * prepare that overtook it would have its fresh tree swept as stale. + * The stale-tree and stale-install-session sweep. No Quick Build session is live at + * construction - this manager is the process's only Quick Build session owner - so every + * tree under the scratch root and every stale Quick Build PackageInstaller session + * (excluding any active Standard Run or `InstallFileAction` install) can be reclaimed. + * Launched before any tap can dispatch, but sweep() hops to IO and frees the dispatcher, + * so [provision] joins it rather than trusting the launch order: a prepare that overtook + * it would have its fresh tree swept as stale. */ - private val sweepJob = scope.launch { scratch.sweep() } + private val sweepJob = + scope.launch { + try { + withContext(ioDispatcher) { sweepInstallSessions() } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("Could not sweep stale PackageInstaller sessions at startup", e) + } + scratch.sweep() + } /** * Handles the Quick Build tap: starts a session from Idle, triggers a build when live, diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt index 90501bba9b..7fef6713a5 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/provision/ProxyAppInstallerTest.kt @@ -79,6 +79,9 @@ class ProxyAppInstallerTest { /** Scripted "can the confirm dialog be launched right now" probe. */ private var confirmDialogShowable = true + private val abandonedSessionIds = mutableListOf() + private var sweepCount = 0 + // A TestScope extension so the installer's IO hops run on the test scheduler's // virtual time instead of a real Dispatchers.IO thread. private fun TestScope.installer( @@ -96,6 +99,31 @@ class ProxyAppInstallerTest { timeoutMillis = timeoutMillis, promptTimeoutMillis = promptTimeoutMillis, canShowConfirmDialog = { confirmDialogShowable }, + abandonSession = { abandonedSessionIds += it }, + sweepStaleSessions = { sweepCount++ }, + ioDispatcher = StandardTestDispatcher(testScheduler), + ) + + private fun TestScope.sessionInstaller( + timeoutMillis: Long = 180_000L, + promptTimeoutMillis: Long = 45_000L, + broadcastFlow: Flow = broadcasts, + launchSession: suspend (File) -> InstallLaunchResult, + onAbandon: (Int) -> Unit = { abandonedSessionIds += it }, + onSweep: () -> Unit = { sweepCount++ }, + ) = ProxyAppInstaller( + packages = packages, + broadcasts = broadcastFlow, + timeoutMillis = timeoutMillis, + promptTimeoutMillis = promptTimeoutMillis, + canShowConfirmDialog = { confirmDialogShowable }, + launchInstallSession = { file -> + installLaunches += file + onLaunch() + launchSession(file) + }, + abandonSession = onAbandon, + sweepStaleSessions = onSweep, ioDispatcher = StandardTestDispatcher(testScheduler), ) @@ -694,4 +722,495 @@ class ProxyAppInstallerTest { assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) } + + @Test + fun `a committed session is abandoned in every terminal outcome and on cancellation`() = + runTest { + // 1. SUCCESS + val r1 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(101) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 101)) + advanceUntilIdle() + assertThat(r1.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(101) + + // Reset package so subsequent calls don't skip as identical bytes + packages.uid = null + abandonedSessionIds.clear() + + // 2. FAILURE + val r2 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(102) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.FAILURE, "INSTALL_FAILED", sessionId = 102)) + advanceUntilIdle() + assertThat(r2.await()).isInstanceOf(InstallOutcome.Failed::class.java) + assertThat(abandonedSessionIds).containsExactly(102) + abandonedSessionIds.clear() + + // 3. DECLINED (ABORTED) + val r3 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(103) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 103)) + advanceUntilIdle() + assertThat(r3.await()) + .isEqualTo( + InstallOutcome.ConfirmationNotGiven( + QuickBuildMessage.ReinstallDeclined, + InstallOutcome.ConfirmationNotGiven.Reason.DECLINED, + ), + ) + assertThat(abandonedSessionIds).containsExactly(103) + abandonedSessionIds.clear() + + // 4. DIALOG_NOT_SHOWN (backgrounded when PENDING_USER_ACTION arrives) + confirmDialogShowable = false + val r4 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(104) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.PENDING_USER_ACTION, sessionId = 104)) + advanceUntilIdle() + assertThat(r4.await()) + .isEqualTo( + InstallOutcome.ConfirmationNotGiven( + QuickBuildMessage.ReinstallReturnToCoGo, + InstallOutcome.ConfirmationNotGiven.Reason.DIALOG_NOT_SHOWN, + ), + ) + assertThat(abandonedSessionIds).containsExactly(104) + confirmDialogShowable = true + abandonedSessionIds.clear() + + // 5. TIMED_OUT (user never confirms) + val r5 = + async { + sessionInstaller( + timeoutMillis = 10_000L, + promptTimeoutMillis = 5_000L, + launchSession = { InstallLaunchResult.Started(105) }, + ).ensureInstalled(apk, PKG) + } + runCurrent() + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.PENDING_USER_ACTION, sessionId = 105)) + advanceTimeBy(11_000L) + advanceUntilIdle() + assertThat(r5.await()) + .isEqualTo( + InstallOutcome.ConfirmationNotGiven( + QuickBuildMessage.ReinstallTimedOut(10), + InstallOutcome.ConfirmationNotGiven.Reason.TIMED_OUT, + ), + ) + assertThat(abandonedSessionIds).containsExactly(105) + abandonedSessionIds.clear() + + // 6. Coroutine cancellation while waiting for user confirmation + val r6 = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(106) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + r6.cancel() + advanceUntilIdle() + assertThat(abandonedSessionIds).containsExactly(106) + } + + @Test + fun `re-issuing a silent prompt abandons the first session before committing the second`() = + runTest { + var nextId = 201 + val events = mutableListOf() + + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + val id = nextId++ + events += "launch:$id" + InstallLaunchResult.Started(id) + }, + onAbandon = { id -> + abandonedSessionIds += id + events += "abandon:$id" + }, + ).ensureInstalled(apk, PKG) + } + runCurrent() + assertThat(events).containsExactly("launch:201") + + advanceTimeBy(46_000L) + runCurrent() + + // Session 201 must be abandoned BEFORE session 202 is launched so two + // confirm dialogs / sessions are never active at the same time. + assertThat(events).containsExactly("launch:201", "abandon:201", "launch:202").inOrder() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 202)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(events) + .containsExactly("launch:201", "abandon:201", "launch:202", "abandon:202") + .inOrder() + } + + @Test + fun `broadcasts from a stale sessionId for the same package are ignored`() = + runTest { + val result = + async { + sessionInstaller(launchSession = { InstallLaunchResult.Started(302) }) + .ensureInstalled(apk, PKG) + } + runCurrent() + + // A leftover dialog from an earlier session (301) for the SAME package is + // cancelled by the user; it must not abort session 302. + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 301)) + runCurrent() + assertThat(result.isCompleted).isFalse() + + // Now session 302's own confirmation succeeds. + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 302)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(302) + } + + @Test + fun `TooManySessions launch result reports TooManyInstallSessions distinctly from InstallCouldNotStart`() = + runTest { + val outcome = + sessionInstaller(launchSession = { InstallLaunchResult.TooManySessions }) + .ensureInstalled(apk, PKG) + + assertThat(outcome) + .isEqualTo(InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions)) + assertThat(outcome) + .isNotEqualTo(InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart)) + } + + @Test + fun `provisioning still installs when 50 committed sessions are outstanding at the start`() = + runTest { + // Models Android's PackageInstallerService.MAX_ACTIVE_SESSIONS = 50 cap. + val activeSessions = (1..50).toMutableSet() + var nextSessionId = 51 + + val result = + async { + sessionInstaller( + launchSession = { + if (activeSessions.size >= 50) { + InstallLaunchResult.TooManySessions + } else { + val id = nextSessionId++ + activeSessions += id + InstallLaunchResult.Started(id) + } + }, + onAbandon = { id -> + activeSessions -= id + abandonedSessionIds += id + }, + onSweep = { + sweepCount++ + activeSessions.clear() + }, + ).ensureInstalled(apk, PKG) + } + runCurrent() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 51)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(sweepCount).isEqualTo(1) + assertThat(activeSessions).isEmpty() + assertThat(abandonedSessionIds).containsExactly(51) + } + + @Test + fun `ABORTED broadcasts triggered by abandoning committed sessions during sweep or re-issue do not cause false ReinstallDeclined`() = + runTest { + var nextId = 401 + lateinit var installerUnderTest: ProxyAppInstaller + + installerUnderTest = + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + val id = nextId++ + if (id == 401) { + // Delayed ABORTED for the swept session arrives after the broadcast + // collector is subscribed and while activeSessionId is still null. + broadcasts.tryEmit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 400), + ) + } + InstallLaunchResult.Started(id) + }, + onAbandon = { id -> + abandonedSessionIds += id + // Android's PackageInstallerSession.abandon() dispatches + // STATUS_FAILURE_ABORTED when a committed session is abandoned. + broadcasts.tryEmit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = id), + ) + }, + onSweep = { + sweepCount++ + // Sweep records a pre-existing committed session (400) before + // activeSessionId is assigned. + installerUnderTest.recordAbandonedSession(400) + }, + ) + + val result = async { installerUnderTest.ensureInstalled(apk, PKG) } + runCurrent() + + // Neither the sweep's ABORTED(400) nor the 45s re-issue's ABORTED(401) + // (emitted while activeSessionId is null) may terminate ensureInstalled as ReinstallDeclined. + assertThat(result.isCompleted).isFalse() + + advanceTimeBy(46_000L) + runCurrent() + assertThat(result.isCompleted).isFalse() + + // Session 402 succeeds. + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 402)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(401, 402).inOrder() + } + + @Test + fun `re-issue returning Failed fails immediately with InstallCouldNotStart instead of timing out`() = + runTest { + var launchCount = 0 + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + launchCount++ + if (launchCount == 1) { + InstallLaunchResult.Started(501) + } else { + InstallLaunchResult.Failed + } + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + assertThat(result.isCompleted).isFalse() + + advanceTimeBy(45_001L) + runCurrent() + + // Must fail immediately after re-issue without waiting out the remaining 75s budget. + assertThat(result.isCompleted).isTrue() + assertThat(result.await()).isEqualTo(InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart)) + assertThat(abandonedSessionIds).containsExactly(501) + } + + @Test + fun `re-issue returning TooManySessions fails immediately with TooManyInstallSessions instead of timing out`() = + runTest { + var launchCount = 0 + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + launchCount++ + if (launchCount == 1) { + InstallLaunchResult.Started(502) + } else { + InstallLaunchResult.TooManySessions + } + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + advanceTimeBy(45_001L) + runCurrent() + + assertThat(result.isCompleted).isTrue() + assertThat(result.await()).isEqualTo(InstallOutcome.Failed(QuickBuildMessage.TooManyInstallSessions)) + assertThat(abandonedSessionIds).containsExactly(502) + } + + @Test + fun `re-issue throwing fails immediately with InstallCouldNotStart instead of timing out`() = + runTest { + var launchCount = 0 + val result = + async { + sessionInstaller( + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + launchSession = { + launchCount++ + if (launchCount == 1) { + InstallLaunchResult.Started(503) + } else { + error("boom during re-issue") + } + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + advanceTimeBy(45_001L) + runCurrent() + + assertThat(result.isCompleted).isTrue() + assertThat(result.await()).isEqualTo(InstallOutcome.Failed(QuickBuildMessage.InstallCouldNotStart)) + assertThat(abandonedSessionIds).containsExactly(503) + } + + @Test + fun `re-issue and finally abandonSession calls dispatch through ioDispatcher`() = + runTest { + val abandonedOnIoDispatcher = mutableListOf() + val inIoDispatcher = + java.util.concurrent.atomic + .AtomicBoolean(false) + val delegate = StandardTestDispatcher(testScheduler) + val trackingIoDispatcher = + object : kotlinx.coroutines.CoroutineDispatcher() { + override fun isDispatchNeeded(context: kotlin.coroutines.CoroutineContext): Boolean = true + + override fun dispatch( + context: kotlin.coroutines.CoroutineContext, + block: Runnable, + ) { + delegate.dispatch(context) { + val prev = inIoDispatcher.getAndSet(true) + try { + block.run() + } finally { + inIoDispatcher.set(prev) + } + } + } + } + var nextId = 601 + val installerUnderTest = + ProxyAppInstaller( + packages = packages, + broadcasts = broadcasts, + timeoutMillis = 120_000L, + promptTimeoutMillis = 45_000L, + canShowConfirmDialog = { true }, + launchInstallSession = { InstallLaunchResult.Started(nextId++) }, + abandonSession = { id -> + abandonedSessionIds += id + abandonedOnIoDispatcher += inIoDispatcher.get() + }, + sweepStaleSessions = { sweepCount++ }, + ioDispatcher = trackingIoDispatcher, + ) + + val result = async { installerUnderTest.ensureInstalled(apk, PKG) } + runCurrent() + + // Trigger prompt-timeout re-issue (abandons 601 on ioDispatcher). + advanceTimeBy(45_001L) + runCurrent() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 602)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(601, 602).inOrder() + assertThat(abandonedOnIoDispatcher).containsExactly(true, true) + } + + @Test + fun `broadcasts from unrelated sessions while launchInstallSession is running are not matched`() = + runTest { + val result = + async { + sessionInstaller( + launchSession = { + // While launchInstallSession is running for session 302, an unrelated session 301 + // emits ABORTED. This must not match session 302 or fail the install as DECLINED. + broadcasts.emit( + InstallBroadcast(PKG, InstallBroadcast.Status.ABORTED, sessionId = 301), + ) + InstallLaunchResult.Started(302) + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + assertThat(result.isCompleted).isFalse() + + // Session 302 succeeds. + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 302)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(302) + } + + @Test + fun `early broadcast for the launched session emitted during launch is buffered and matched`() = + runTest { + val result = + async { + sessionInstaller( + launchSession = { + // Early PENDING_USER_ACTION arrives for session 303 before launchInstallSession returns. + broadcasts.emit( + InstallBroadcast(PKG, InstallBroadcast.Status.PENDING_USER_ACTION, sessionId = 303), + ) + InstallLaunchResult.Started(303) + }, + ).ensureInstalled(apk, PKG) + } + + runCurrent() + assertThat(result.isCompleted).isFalse() + + packages.uid = 10123 + broadcasts.emit(InstallBroadcast(PKG, InstallBroadcast.Status.SUCCESS, sessionId = 303)) + advanceUntilIdle() + + assertThat(result.await()).isEqualTo(InstallOutcome.Installed(10123)) + assertThat(abandonedSessionIds).containsExactly(303) + } } diff --git a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt index ae7120ce84..61da2de072 100644 --- a/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt +++ b/quickbuild/core/src/test/java/org/appdevforall/cotg/quickbuild/service/session/QuickBuildSessionManagerTest.kt @@ -308,6 +308,7 @@ class QuickBuildSessionManagerTest { // The layout's tree walks hop off the session dispatcher; keep them on the test // scheduler so they stay inside virtual time rather than on a real IO thread. ioDispatcher: CoroutineDispatcher = StandardTestDispatcher(testScheduler), + sweepInstallSessions: () -> Unit = {}, ): QuickBuildSessionManager { val provisioner = object : QuickBuildProvisioner { @@ -407,6 +408,7 @@ class QuickBuildSessionManagerTest { FakePaths(projectRoot).projectScratchRoot, ioDispatcher = StandardTestDispatcher(testScheduler), ), + sweepInstallSessions = sweepInstallSessions, ).also { manager -> // Same hazard [recordNotices] documents, and the same reason for Unconfined. if (collectUserMessages) { @@ -5480,4 +5482,26 @@ class QuickBuildSessionManagerTest { assertThat(io.dispatches).isEqualTo(hopsBefore + 1) assertThat(proxyAppRebuildCount).isEqualTo(0) } + + @Test + fun `startup sweeps stale PackageInstaller sessions before provisioning runs`() = + runTest { + val staleSessions = (1..50).toMutableSet() + var sweptBeforeProvision = false + provisionOutcome = { + sweptBeforeProvision = staleSessions.isEmpty() + defaultProvisionOutcome() + } + + val manager = + createManager( + sweepInstallSessions = { staleSessions.clear() }, + ) + manager.onQuickBuildTapped() + advanceUntilIdle() + + assertThat(staleSessions).isEmpty() + assertThat(sweptBeforeProvision).isTrue() + assertThat(manager.state.value).isEqualTo(QuickBuildSessionState.Ready(0)) + } } diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 49f1ed7302..2e81fa17c6 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1242,6 +1242,7 @@ Your app needs a reinstall - the install prompt went unanswered for %1$d seconds. Tap Quick Build to try again. Waiting for the current Gradle build to finish - your app still needs a reinstall. Tap Quick Build to retry. Quick Build could not start installing your app. + Quick Build could not start installing your app because too many previous install prompts are still open. Tap Quick Build to try again. Quick Build could not install your app. Quick Build installed %1$s, but Android will not open it. Restarting the session reinstalls it. %1$s is already installed on this device and was not built here, so Quick Build cannot replace it without deleting its data. Back it up and uninstall it yourself first.