diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index c154b83f2c..8f19c9d17a 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -79,6 +79,7 @@ object StoresState { fun refresh(context: Context) { val app = context.applicationContext com.droiddeck.launcher.stores.download.SavedQueue.restore(app) + com.droiddeck.launcher.stores.battlenet.BattleNetInstall.reconcile(app) if (refreshRequests.getAndIncrement() > 0) return var seen = 0 background("stores-refresh", onFailure = { if (refreshRequests.getAndSet(0) > seen) main.post { refresh(app) } }) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetCleanup.kt b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetCleanup.kt new file mode 100644 index 0000000000..d7beeed42e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetCleanup.kt @@ -0,0 +1,129 @@ +package com.droiddeck.launcher.stores.battlenet + +import android.content.Context +import android.util.Log +import org.json.JSONObject +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.security.MessageDigest + +/** + * A cancelled Battle.net install that could not be cleaned up yet. The marker is written before + * the cleanup starts and removed only after the registration and the folder are both gone, so a + * restart can reconcile a registration that the client writes late. + */ +internal object BattleNetCleanup { + private const val TAG = "BattleNetCleanup" + private const val DIR = "battlenet-cleanup" + internal const val ACTIVE = "active" + internal const val PENDING = "pending" + internal const val WATCHING = "watching" + + internal data class Pending( + val folder: File, + val id: String, + val createdFolder: Boolean, + val state: String, + val attempts: Int, + val nextAt: Long, + val stamp: Long, + ) + + internal fun dir(context: Context): File = File(context.filesDir, DIR) + + @Synchronized + internal fun mark(context: Context, folder: File, id: String, createdFolder: Boolean, state: String = ACTIVE) { + val current = get(context, folder) + write( + context, + Pending(folder, id, createdFolder || current?.createdFolder == true, state, current?.attempts ?: 0, current?.nextAt ?: 0L, System.nanoTime()), + ) + } + + @Synchronized + internal fun markActive(context: Context, folder: File, id: String, createdFolder: Boolean) { + val current = get(context, folder) + write( + context, + Pending( + folder, id, createdFolder || current?.createdFolder == true, + current?.state?.takeIf { it != ACTIVE } ?: ACTIVE, + current?.attempts ?: 0, current?.nextAt ?: 0L, System.nanoTime(), + ), + ) + } + + @Synchronized + internal fun update(context: Context, folder: File, state: String, attempts: Int, nextAt: Long) { + val current = get(context, folder) ?: return + write(context, current.copy(state = state, attempts = attempts, nextAt = nextAt)) + } + + @Synchronized + internal fun get(context: Context, folder: File): Pending? { + val file = file(context, folder) + val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return null + return runCatching { + Pending( + folder = File(json.getString("folder")), + id = json.getString("id"), + createdFolder = json.optBoolean("createdFolder"), + state = json.optString("state", PENDING), + attempts = json.optInt("attempts"), + nextAt = json.optLong("nextAt"), + stamp = json.optLong("stamp"), + ) + }.getOrNull() + } + + internal fun pending(context: Context): List = dir(context).listFiles() + ?.filter { it.isFile && it.name.endsWith(".json") } + ?.mapNotNull { file -> runCatching { JSONObject(file.readText()) }.getOrNull() } + ?.mapNotNull { json -> + runCatching { + Pending( + folder = File(json.getString("folder")), + id = json.getString("id"), + createdFolder = json.optBoolean("createdFolder"), + state = json.optString("state", PENDING), + attempts = json.optInt("attempts"), + nextAt = json.optLong("nextAt"), + stamp = json.optLong("stamp"), + ) + }.getOrNull() + } + ?.filter { it.state != ACTIVE } + ?.sortedBy { it.nextAt } + .orEmpty() + + @Synchronized + internal fun clear(context: Context, folder: File) { + file(context, folder).delete() + } + + private fun file(context: Context, folder: File) = + File(dir(context), MessageDigest.getInstance("SHA-256").run { + update(folder.absolutePath.toByteArray()) + digest().joinToString("") { "%02x".format(it.toInt() and 0xff) } + } + ".json") + + private fun write(context: Context, pending: Pending) { + val target = file(context, pending.folder) + target.parentFile?.mkdirs() + val json = JSONObject().apply { + put("folder", pending.folder.absolutePath) + put("id", pending.id) + put("createdFolder", pending.createdFolder) + put("state", pending.state) + put("attempts", pending.attempts) + put("nextAt", pending.nextAt) + put("stamp", pending.stamp) + } + val tmp = File(target.parentFile, "${target.name}.tmp") + runCatching { + tmp.writeText(json.toString()) + Files.move(tmp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) + }.onFailure { Log.w(TAG, "could not write ${target.path}", it) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt index d863ad30f8..9425b8d920 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/battlenet/BattleNetInstall.kt @@ -40,6 +40,7 @@ object BattleNetInstall { private const val CHECK_RETRY_MS = 30_000L private const val CHECK_RETRY_MAX = 2 private const val START_WAIT_MS = 60_000L + private val reconciling = AtomicBoolean(false) /** Blizzard serves China from battlenet.com.cn; its global version hostnames do not answer for that region. */ internal fun versionsUrl(region: String, product: String): String = @@ -160,8 +161,108 @@ object BattleNetInstall { if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false val uid = installUid(context, game) ?: return false val done = agentUninstall(context, uid) - if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) } - return done + val gone = registrationsGone(context, game.sidecar.id, game.folder, UNINSTALL_VERIFY_MS) + if (gone == null || gone.isNotEmpty()) { + Log.w(TAG, "uninstall $uid: the registration in ${game.folder.path} is still there") + return false + } + if (!done) Log.i(TAG, "uninstall $uid: registration gone after the Agent stopped") + BattleNetCleanup.clear(context, game.folder) + StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) } + return true + } + + internal fun registrationsGone(context: Context, id: String, folder: File, timeoutMs: Long): List? { + val deadline = System.currentTimeMillis() + timeoutMs + while (true) { + val found = runCatching { BattleNet.registrationsAt(context, id, folder) }.getOrNull() ?: return null + if (found.isEmpty() || System.currentTimeMillis() >= deadline) return found + Thread.sleep(250) + } + } + + /** + * Retries the markers a cancelled install leaves when the registration it wrote is still + * present, or when it wrote one after the cancellation had already looked. + */ + fun reconcile(context: Context) { + val app = context.applicationContext + if (BattleNetCleanup.pending(app).isEmpty()) return + if (!reconciling.compareAndSet(false, true)) return + Thread({ + try { + reconcileNow(app) + } finally { + reconciling.set(false) + } + }, "battlenet-cleanup-reconcile").start() + } + + internal fun reconcileNow( + context: Context, + uninstall: (String) -> Boolean = { agentUninstall(context, it) }, + verifyMs: Long = CLEANUP_VERIFY_MS, + watchMs: Long = CLEANUP_WATCH_MS, + ) { + val now = System.currentTimeMillis() + for (pending in BattleNetCleanup.pending(context)) { + if (pending.nextAt > now) continue + if (pending.folder.absolutePath in cleanupRunning) continue + if (StoreInstalls.isDiscarding(pending.folder)) continue + val key = DownloadEntry(Store.BATTLENET, pending.id, pending.id).key + if (!DownloadQueue.holdForRemoval(key)) continue + try { + val current = BattleNetCleanup.get(context, pending.folder) + if (current == null || current.stamp != pending.stamp || current.id != pending.id || + current.createdFolder != pending.createdFolder || current.state != pending.state || + current.attempts != pending.attempts || current.nextAt != pending.nextAt + ) continue + val found = runCatching { BattleNet.registrationsAt(context, pending.id, pending.folder) }.getOrNull() + if (found == null) { + retry(context, pending, "the registrations could not be read") + continue + } + if (found.isEmpty()) { + if (pending.createdFolder && pending.folder.exists() && !deleteFolder(pending.folder)) { + retry(context, pending, "the folder could not be deleted") + continue + } + if (pending.state == BattleNetCleanup.WATCHING && pending.attempts < CLEANUP_MAX_ATTEMPTS) { + BattleNetCleanup.update(context, pending.folder, BattleNetCleanup.WATCHING, pending.attempts + 1, now + watchMs) + continue + } + BattleNetCleanup.clear(context, pending.folder) + Log.i(TAG, "cleanup of ${pending.folder.path}: no registration remains") + continue + } + for (uid in found) uninstall(uid) + val left = registrationsGone(context, pending.id, pending.folder, verifyMs) + if (left == null || left.isNotEmpty()) { + retry(context, pending, "the registration in ${pending.folder.path} is still there") + continue + } + if (pending.createdFolder && pending.folder.exists() && !deleteFolder(pending.folder)) { + retry(context, pending, "the folder could not be deleted") + continue + } + BattleNetCleanup.clear(context, pending.folder) + Log.i(TAG, "cleanup of ${pending.folder.path}: ${if (pending.createdFolder) "removed" else "registration removed; folder kept"}") + } finally { + DownloadQueue.releaseRemoval(key) + } + } + } + + private fun retry(context: Context, pending: BattleNetCleanup.Pending, reason: String) { + val attempts = pending.attempts + 1 + val delay = if (attempts >= CLEANUP_MAX_ATTEMPTS) 10 * 60_000L else CLEANUP_RETRY_MS + BattleNetCleanup.update(context, pending.folder, pending.state, attempts, System.currentTimeMillis() + delay) + Log.w(TAG, "cleanup of ${pending.folder.path} is pending: $reason") + } + + internal fun deleteFolder(folder: File): Boolean { + com.droiddeck.launcher.core.FileUtils.delete(folder) + return !folder.exists() } internal fun agentUninstall(context: Context, uid: String): Boolean { @@ -303,6 +404,8 @@ internal class BattleNetInstaller( private val folder: File, private val update: Boolean, private val ownership: Ownership = Ownership(item), + private val registrationWaitMs: Long = REGISTRATION_WAIT_MS, + private val cleanupVerifyMs: Long = CLEANUP_VERIFY_MS, private val uninstall: (String) -> Boolean = { BattleNetInstall.agentUninstall(app, it) }, private val registration: () -> List? = { BattleNet.registrationsAt(app, item.id, folder) @@ -313,6 +416,7 @@ internal class BattleNetInstaller( private val started = AtomicBoolean(false) private val queueKey = DownloadEntry(Store.BATTLENET, item.id, item.title).key private val ended = java.util.concurrent.CountDownLatch(1) + private var before = 0L private var kept = -1L @@ -332,6 +436,9 @@ internal class BattleNetInstaller( started.set(true) try { return if (cancelled.get()) null else work(handle) + } catch (t: Throwable) { + if (!cancelled.get()) BattleNetCleanup.clear(app, folder) + throw t } finally { ended.countDown() } @@ -344,7 +451,10 @@ internal class BattleNetInstaller( val title = BattleNet.title(item.id) val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id)) val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid - if (!update && folder.mkdirs()) ownership.createdFolder.set(true) + if (!update && folder.mkdirs()) { + ownership.createdFolder.set(true) + BattleNetCleanup.markActive(app, folder, item.id, createdFolder = true) + } val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path)) val (country, region) = BattleNetInstall.country(Locale.getDefault()) val args = if (update) listOf("agent-update", uid) @@ -370,6 +480,7 @@ internal class BattleNetInstaller( StoresState.notifyLibraryChanged(app) } BattleNetInstall.check(item.id, folder, force = true) + BattleNetCleanup.clear(app, folder) return folder.absolutePath } @@ -386,6 +497,19 @@ internal class BattleNetInstaller( } } + /** + * The client writes the install registration a little after the download starts; a cancel + * right after the request would otherwise read an empty list and leave the registration behind. + */ + private fun registrationsWaiting(): List? { + val deadline = System.currentTimeMillis() + registrationWaitMs + while (true) { + val found = runCatching { registration() }.getOrNull() ?: return null + if (found.isNotEmpty() || System.currentTimeMillis() >= deadline) return found + Thread.sleep(250) + } + } + override fun cancel(deleteFiles: Boolean) { cancelled.set(true) if (!deleteFiles || update) { @@ -394,30 +518,49 @@ internal class BattleNetInstaller( } if (!cleanupStarted.compareAndSet(false, true)) return if (!started.get() && !ownership.known) ownership.preexisting = true + val initialCreated = BattleNetCleanup.get(app, folder)?.createdFolder ?: ownership.createdFolder.get() val path = folder.absolutePath cleanupRunning.add(path) + if (!ownership.preexisting) { + BattleNetCleanup.mark(app, folder, item.id, initialCreated, BattleNetCleanup.PENDING) + } val cleanup = Thread({ var discarding = false try { val stopped = !started.get() || ended.await(END_WAIT_S, TimeUnit.SECONDS) + val createdFolder = ownership.createdFolder.get() || (BattleNetCleanup.get(app, folder)?.createdFolder ?: false) + if (!ownership.preexisting && createdFolder != initialCreated) { + BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.PENDING) + } if (ownership.preexisting) { - Log.i("BattleNetInstall", "cancelled install of ${item.id}: ${path} keeps the registration that existed before the task") + BattleNetCleanup.clear(app, folder) + Log.i("BattleNetInstall", "cancelled install left the pre-existing registration in ${folder.path}") } else if (!stopped) { - Log.w("BattleNetInstall", "the cancelled install of ${item.id} is still stopping; ${path} is left for Battle.net") + pending(createdFolder, "the cancelled install is still stopping") } else { StoreInstalls.beginDiscard(folder) discarding = true - val found = runCatching { registration() }.getOrNull() - if (found == null) { - Log.w("BattleNetInstall", "cancelled install of ${item.id}: the registration could not be read; ${path} is left for Battle.net") - } else if (found.isEmpty()) { - if (ownership.createdFolder.get() && !deleteFolder()) { - Log.w("BattleNetInstall", "cancelled install of ${item.id}: ${path} could not be deleted") + val created = registrationsWaiting() + if (created == null) { + pending(createdFolder, "the registrations could not be read") + } else if (created.isEmpty()) { + if (createdFolder && !BattleNetInstall.deleteFolder(folder)) { + pending(createdFolder, "the folder could not be deleted") + } else { + BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.WATCHING) + BattleNetCleanup.update(app, folder, BattleNetCleanup.WATCHING, 0, System.currentTimeMillis() + CLEANUP_WATCH_MS) + Log.i("BattleNetInstall", "cancelled install of ${item.id}: no registration yet; watching ${folder.path}") } } else { - for (uid in found.distinct()) uninstall(uid) - if (ownership.createdFolder.get() && !deleteFolder()) { - Log.w("BattleNetInstall", "cancelled install of ${item.id}: ${path} could not be deleted") + for (uid in created.distinct()) uninstall(uid) + val left = registrationsGoneHere(cleanupVerifyMs) + if (left == null || left.isNotEmpty()) { + pending(createdFolder, "the registration in ${folder.path} is still there") + } else if (createdFolder && !BattleNetInstall.deleteFolder(folder)) { + pending(createdFolder, "the folder could not be deleted") + } else { + BattleNetCleanup.clear(app, folder) + Log.i("BattleNetInstall", "cancelled install of ${created.first()}: ${if (createdFolder) "removed" else "registration removed; folder kept"}") } } } @@ -436,11 +579,27 @@ internal class BattleNetInstaller( } } - private fun deleteFolder(): Boolean { - com.droiddeck.launcher.core.FileUtils.delete(folder) - return !folder.exists() + private fun pending(createdFolder: Boolean, reason: String) { + BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.PENDING) + BattleNetCleanup.update(app, folder, BattleNetCleanup.PENDING, 1, System.currentTimeMillis() + CLEANUP_RETRY_MS) + Log.w("BattleNetInstall", "cleanup of ${folder.path} is pending: $reason") + } + + private fun registrationsGoneHere(timeoutMs: Long): List? { + val deadline = System.currentTimeMillis() + timeoutMs + while (true) { + val found = runCatching { registration() }.getOrNull() ?: return null + if (found.isEmpty() || System.currentTimeMillis() >= deadline) return found + Thread.sleep(250) + } } } -private val cleanupRunning = java.util.concurrent.ConcurrentHashMap.newKeySet() private const val END_WAIT_S = 120L +private const val REGISTRATION_WAIT_MS = 5_000L +private val cleanupRunning = java.util.concurrent.ConcurrentHashMap.newKeySet() +private const val CLEANUP_VERIFY_MS = 30_000L +private const val CLEANUP_WATCH_MS = 15_000L +private const val CLEANUP_RETRY_MS = 60_000L +private const val CLEANUP_MAX_ATTEMPTS = 4 +private const val UNINSTALL_VERIFY_MS = 30_000L diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index 19ce8c8504..2ae191a073 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -9,6 +9,7 @@ import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreInstalls import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.battlenet.BattleNetCleanup import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import com.droiddeck.launcher.stores.battlenet.BattleNetInstaller import com.droiddeck.launcher.stores.battlenet.Ownership @@ -79,6 +80,7 @@ class BattleNetTest { @Before fun setUp() { context = RuntimeEnvironment.getApplication() File(context.filesDir, "components").deleteRecursively() + File(context.filesDir, "battlenet-cleanup").deleteRecursively() LinuxRuntime.rootDir(context).deleteRecursively() } @@ -542,7 +544,7 @@ class BattleNetTest { ) val seen = AtomicReference(null) val done = CountDownLatch(1) - val installer = BattleNetInstaller(context, item, folder, false, uninstall = { uid -> + val installer = BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { uid -> seen.set(uid) done.countDown() true @@ -563,7 +565,7 @@ class BattleNetTest { val ownership = Ownership(item) ownership.createdFolder.set(true) var registered = true - val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, uninstall = { uid -> + val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { uid -> holding.set(StoreInstalls.isDiscarding(folder)) registered = false done.countDown() @@ -578,6 +580,30 @@ class BattleNetTest { assertFalse(folder.exists()) } + @Test fun aLateRegistrationReportedWhileTheWorkerStopsIsUsedForCancellation() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null) + var visible = false + val seen = AtomicReference(null) + val done = CountDownLatch(1) + val installer = BattleNetInstaller(context, item, folder, false, registrationWaitMs = 1000, cleanupVerifyMs = 0, uninstall = { uid -> + seen.set(uid) + done.countDown() + true + }) { + if (visible) listOf("osic") else emptyList() + } + val started = BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true } + (started.get(installer) as AtomicBoolean).set(true) + val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true } + .get(installer) as CountDownLatch + installer.cancel(true) + visible = true + ended.countDown() + assertTrue(done.await(5, TimeUnit.SECONDS)) + assertEquals("osic", seen.get()) + } + @Test fun aCancelledInstallRemovesAFolderItCreatedWithoutARegistration() { val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected") assertFalse(folder.exists()) @@ -589,7 +615,7 @@ class BattleNetTest { ) val ownership = Ownership(item) val uninstalled = AtomicBoolean(false) - val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, uninstall = { + val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, registrationWaitMs = 0, uninstall = { uninstalled.set(true) false }) { emptyList() } @@ -606,6 +632,123 @@ class BattleNetTest { assertFalse(uninstalled.get()) } + @Test fun aCancelledInstallKeepsTheFolderWhileItsRegistrationRemains() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3)) + val item = CatalogItem( + Store.BATTLENET, "osi", "Diablo II: Resurrected", null, + extra = mapOf(BattleNetInstall.PREEXISTING to "0"), + ) + val installer = BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { true }) { + listOf("osic") + } + BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true } + .set(installer, AtomicBoolean(true)) + val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true } + .get(installer) as CountDownLatch + installer.cancel(true) + ended.countDown() + val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(3) + while (BattleNetCleanup.get(context, folder) == null && System.nanoTime() < until) Thread.sleep(10) + assertTrue("the folder must stay while the registration exists", folder.exists()) + assertEquals(BattleNetCleanup.PENDING, BattleNetCleanup.get(context, folder)?.state) + } + + @Test fun aCancelledInstallDeletesTheFolderOnceItsRegistrationGoes() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3)) + val item = CatalogItem( + Store.BATTLENET, "osi", "Diablo II: Resurrected", null, + extra = mapOf(BattleNetInstall.PREEXISTING to "0"), + ) + val ownership = Ownership(item) + ownership.createdFolder.set(true) + var registered = true + val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { + registered = false + true + }) { if (registered) listOf("osic") else emptyList() } + BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true } + .set(installer, AtomicBoolean(true)) + val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true } + .get(installer) as CountDownLatch + installer.cancel(true) + ended.countDown() + val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (folder.exists() && System.nanoTime() < until) Thread.sleep(10) + assertFalse(folder.exists()) + assertNull(BattleNetCleanup.get(context, folder)) + } + + @Test fun reconcileCleansAMarkerAfterItsRegistrationGoes() { + val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() } + File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs() + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III").apply { mkdirs() } + File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3)) + val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db") + db.writeBytes(message( + field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))), + )) + BattleNetCleanup.mark(context, folder, "diablo3", createdFolder = true, state = BattleNetCleanup.PENDING) + BattleNetInstall.reconcileNow(context, uninstall = { uid -> + assertEquals("d3cn", uid) + db.writeBytes(ByteArray(0)) + true + }, verifyMs = 0, watchMs = 0) + assertFalse(folder.exists()) + assertNull(BattleNetCleanup.get(context, folder)) + } + + @Test fun aCancellationRecordsItsMarkerBeforeItWaitsForTheWorker() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + val item = CatalogItem( + Store.BATTLENET, "osi", "Diablo II: Resurrected", null, + extra = mapOf(BattleNetInstall.PREEXISTING to "0"), + ) + val installer = BattleNetInstaller(context, item, folder, false, registrationWaitMs = 0, cleanupVerifyMs = 0) { + emptyList() + } + BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true } + .set(installer, AtomicBoolean(true)) + val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true } + .get(installer) as CountDownLatch + installer.cancel(true) + assertEquals(BattleNetCleanup.PENDING, BattleNetCleanup.get(context, folder)?.state) + ended.countDown() + val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(2) + while (BattleNetCleanup.get(context, folder)?.state == BattleNetCleanup.PENDING && System.nanoTime() < until) Thread.sleep(10) + } + + @Test fun anActiveMarkerCannotOverwriteACancellation() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + BattleNetCleanup.mark(context, folder, "osi", createdFolder = false, state = BattleNetCleanup.PENDING) + BattleNetCleanup.markActive(context, folder, "osi", createdFolder = true) + val pending = BattleNetCleanup.get(context, folder)!! + assertEquals(BattleNetCleanup.PENDING, pending.state) + assertTrue(pending.createdFolder) + } + + @Test fun aCleanupMarkerRewrittenForAReplacementHasANewStamp() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + BattleNetCleanup.mark(context, folder, "osi", createdFolder = false, state = BattleNetCleanup.PENDING) + val first = BattleNetCleanup.get(context, folder)!! + BattleNetCleanup.mark(context, folder, "osi", createdFolder = true, state = BattleNetCleanup.PENDING) + val second = BattleNetCleanup.get(context, folder)!! + assertTrue(second.stamp > first.stamp) + } + + @Test fun aCleanupMarkerIsRestoredWithoutTheTask() { + val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() } + BattleNetCleanup.mark(context, folder, "osi", createdFolder = true, state = BattleNetCleanup.PENDING) + val pending = BattleNetCleanup.pending(context).single() + assertEquals(folder.absolutePath, pending.folder.absolutePath) + assertEquals("osi", pending.id) + assertTrue(pending.createdFolder) + assertEquals(BattleNetCleanup.PENDING, pending.state) + BattleNetCleanup.clear(context, folder) + assertTrue(BattleNetCleanup.pending(context).isEmpty()) + } + @Test fun aRegistrationSourceFailureMakesOwnershipUnknown() { val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() } File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs() @@ -654,7 +797,7 @@ class BattleNetTest { ownership.preexisting = false val seen = AtomicReference(null) val done = CountDownLatch(1) - BattleNetInstaller(context, item, folder, false, ownership = ownership, uninstall = { uid -> + BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { uid -> seen.set(uid) done.countDown() true @@ -671,7 +814,7 @@ class BattleNetTest { ) val seen = AtomicReference(null) val done = CountDownLatch(1) - BattleNetInstaller(context, item, folder, false, uninstall = { uid -> + BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { uid -> seen.set(uid) done.countDown() true diff --git a/docs/development/battlenet-china.md b/docs/development/battlenet-china.md new file mode 100644 index 0000000000..9a1e7a2bd7 --- /dev/null +++ b/docs/development/battlenet-china.md @@ -0,0 +1,170 @@ +# Battle.net China install, update and cleanup mapping + +Last reviewed: 2026-11-16, against `main` `a20528c` with this change applied. The China +version rows were observed on 2026-11-06 at +`cn.version.battlenet.com.cn/v2/products//versions`; installs use +`cn.patch.battlenet.com.cn`. #1660 added the China uid aliases to the catalogue and #1661 +made the Agent driver report Battle.net's own refusal reason instead of `exit 0`; #1705 was +closed in favour of this change. This document describes the merged state and supersedes the +earlier plan that treated #1705 as pending. + +## Product mapping + +| Game | Store uid | China uid | China product | China version | Handling | +|---|---|---|---|---|---| +| World of Warcraft | `wow` | same uid | `wow` | 12.1.5.70783 | none | +| World of Warcraft Classic | `wow_classic` | same uid | `wow_classic` | 5.5.4.70631 | none | +| World of Warcraft Classic Era | `wow_classic_era` | same uid | `wow_classic_era` | 1.15.9.70576 | none | +| World of Warcraft Classic Anniversary | `wow_classic_anniversary` | same uid | `wow_anniversary` | 2.5.6.70577 | none | +| World of Warcraft: Forever | `wow_forever` | same uid, or unknown uid with product `wowf` | `wowf` | 1.60.1.70790 | in `TITLES`, excluded from `STORE` | +| Diablo III | `diablo3` | `d3cn` | `d3cn` | 2.8.1.101167 | alias; install and update use `d3cn` | +| Diablo II: Resurrected | `osi` | `osic` | `osic` | 3.3.93854 | alias; install and update use `osic` | +| StarCraft II | `s2` | `s2_cn` | `s2c` | 5.0.17.98370 | alias; install maps uid to `s2_cn` and product to `s2c` | +| Diablo Immortal | `anbs` | `anbs_cn` | `anbs` | no `cn` row | uid alias only; unverified | +| Hearthstone | `hs_beta` | same uid | `hsb` | 37.0.2.256589.255790 | none | +| Heroes of the Storm | `heroes` | same uid | `hero` | 2.55.3.89566 | none | +| Overwatch 2 | `prometheus` | same uid | `pro` | 2.25.1.0.155284N | none | +| StarCraft: Remastered | `s1` | same uid | `s1` | 1.23.10.11269 | none | +| Warcraft III: Reforged | `w3` | same uid | `w3` | no `cn` row | none | +| `wow_classic_titan` | not in the catalogue | unconfirmed | `wow_classic_titan` | not checked | out of scope | + +No separate China uid has been observed for `wow`, the Classic flavors, `hs_beta`, +`heroes`, `prometheus`, `s1` or `w3`; the client reports the store uid for those. + +## What the change does + +### Catalogue + +`BattleNet.CN_UIDS` maps the China uids to the existing cards instead of adding titles of +their own: + +- `d3cn` resolves to the `diablo3` card with launch code `D3CN` and product `d3cn`. The + standalone `d3cn` title and the `STORE`/`fetchCovers` filters for it are gone. +- `osic` resolves to `osi` with product `osic`; `s2_cn` resolves to `s2` with product + `s2c`; `anbs_cn` resolves to `anbs` with product `anbs`. +- Locale suffixes resolve through the base alias, so `osic_zhcn` and `s2_cn_zhcn` name the + same cards. + +A `BattleNet.Game` keeps the store uid in `uid` and the Agent's uid in `installUid`. The +Library, the desktop shortcut, the store "installed" state, covers and the launch code +therefore agree; a China Diablo III install still lands on the `diablo3` card and launches +with `D3CN`. + +### Install driver + +On a China agent (`region == "cn"`) every install sends `account_country = CHN` and +`geo_ip_country = CN`, not only the remapped products. Products `osi`, `s2` and `diablo3` +become `osic`, `s2c` and `d3cn`; uids become `osic`, `s2_cn` and `d3cn` (`anbs` becomes +`anbs_cn`). Updates and uninstalls use the uid the Agent recorded, so they are not +remapped. + +### Update checks + +`BattleNetInstall.check()` reads `.build.info`. When its active branch is `cn`, the version +query uses the China product (`osic`, `s2c`, `d3cn`); other branches keep the store +product. `checkedAt` and `updates` are keyed by `id@folder` (`updateKey`), so an +international and a China copy of Diablo III neither suppress nor offer each other's +update. `anbs` has no China product mapping, so its China check still asks `anbs`, which +has no `cn` row. + +### Install identity + +Update and uninstall select the installed record by its exact folder and use the Agent uid +recorded for that folder. A folder with no matching registration is not retargeted to +another copy; a game detail opened from a shortcut passes its folder through, so two +Diablo III installs, or WoW flavors sharing one folder, do not act on each other. + +### Cancellation ownership + +Before an install starts, a raw `product.db` and `system.reg` query records whether the +target folder already has a registration. The query does not require the folder to exist +and does not deduplicate by launch code. The result is `PREEXISTING = pending | 0 | 1`; the +installer worker resolves it once, persists it through `SavedQueue`, and a shared +`Ownership` holder keeps the decision across pause and resume. `SavedQueue` only receives +the item after `DownloadQueue.enqueue()` accepts it (`onAccepted`), so a rejected enqueue +cannot leave ownership for a task that will not run. + +Cancel uninstalls only a registration that appeared after the task recorded "no +registration"; a pre-existing registration is never removed. If either registration source +cannot be read, the decision stays conservative (no destructive cleanup) and is not +persisted as final. Cleanup is skipped when the worker has not stopped after the wait. +`clear()` and `cancel()` share one cleanup claim, and a new enqueue for the same game is +rejected while that cleanup runs. + +## Why the version lines differ + +| Product | Observed rows | Build | Note | +|---|---|---|---| +| `osi` | `us`, `eu`, `kr` | 3.3.93847 | no `cn` row | +| `osic` | `cn` | 3.3.93854 | China only | +| `s2` | `cn` | 5.0.14.93333 | older China line | +| `s2c` | `cn` | 5.0.17.98370 | current China line | +| `d3` | `us`, `eu`, `kr`, `tw` | 2.8.0.99920 | no `cn` row | +| `d3cn` | `cn` | 2.8.1.101167 | China only | +| `anbs` | no `cn` row | - | no separate `anbs_cn` product | +| `w3` | no `cn` row | - | keeps the global build | + +### Products without a `cn` row + +`osi`, `d3`, `anbs` and `w3` have no `cn` row, and `anbs_cn` has no product or repository +of its own. For `osi` and `d3`, an install made with the store product in a clean folder +misses the China line and the Agent falls back to the international build: for Diablo II: +Resurrected that is 3.3.93847 instead of the China 3.3.93854. The install succeeds, but +`.build.info` and `product.db` now follow the international line, and the BuildConfig +differs, so renaming the folder cannot migrate it. `w3` has no China line at all and keeps +the global build; `anbs` is unverified (see below). + +### The two sides then disagree + +When the wrong product is installed, `product.db` records `osi` while the China client +enumerates `osic`. DroidDeck shows the game as installed, the client shows it as missing, +and update, repair and uninstall each follow a different product. No error is reported, +which makes this state harder to notice than a visible failure. `s2` is the milder variant: +it does have a `cn` row, but that row is the older 5.0.14.93333 line, while `s2c` is the +current 5.0.17.98370. + +### Error 800 + +Error 800 is not only a China-copy conflict. A folder registered in `product.db`, an empty +directory, a directory with residual files from an earlier attempt, or a path earlier +registered by a different product can trigger it. This change does not alter those triggers +and does not clean them automatically; #1661 now surfaces Battle.net's own refusal reason, +so the failure is reported instead of looking like `exit 0`. + +## Automated coverage + +- `BattleNetTest`: China uid aliases including locale suffixes, the `d3cn` alias on the + `diablo3` card, folder selection between two Diablo III installs, WoW flavors in one folder, + registrations for a missing folder, pre-existing registration protection, + created-registration cleanup, registration read failure, restored ownership, per-folder + update state, and the cancelled install's folder hold against uninstall. +- `BattleNetInstallTest`: `chinaProduct()`, the `s2c` version URL, the `osic`, `s2c` and + `anbs` version rows, and per-folder update keys. +- `DownloadQueueRetryTest`: double `clear()` single-flight, a rejected enqueue not running + its accepted callback, a rejected update preserving the saved ownership snapshot, + factoryless cleanup, client-download exclusion, a removal hold waiting for a cancelled + Battle.net cleanup, and the restore, install, enqueue chain. +- `tools/tests/test_battlenet.py`: the driver's China uid and product maps, the + install-only condition, and the `CHN`/`CN` request fields. + +## Not covered + +- Migration of existing wrong-product installs (`osi`, `d3`, `s2`): uninstall through + DroidDeck (it calls the Agent with the uid recorded for the folder) and install again; + renaming or deleting the folder alone leaves the `product.db` registration behind and can + hit 800 on the next attempt. +- Automatic cleanup of the wider 800 triggers; #1661 surfaces the reason, it does not + remove the registration or the folder. +- Diablo Immortal: `anbs` has no `cn` row and `anbs_cn` has no separate product, so whether + the Agent falls back to the international build and whether the client accepts `anbs_cn` + is unverified. This change does not claim to fix it. +- Store region filtering: the store is a static global catalogue and there is no separate + China "owned" feed. +- WoW Classic family cards and deduplication: `STORE` keeps one `WoWC` card and the game + list keeps one folder per launch code. This is an existing design, not a China uid issue. +- `wow_forever` (in `TITLES`, excluded from `STORE`) and `wow_classic_titan` (not in + `TITLES`) catalogue entries. +- Covers for titles without a Steam app id still depend on `us.shop.battle.net`. +- The Battle.net client installer's region; it is pinned to `downloader.battle.net`. + +Refs: #1660, #1661, #1705 (closed).