diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt index 5b0b69c8f0..8194cea3b3 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt @@ -129,8 +129,9 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu } } } - g.disconnect() - g.close() + // Android can refuse these (BLUETOOTH_CONNECT revoked); an exception on this thread would end the app. + runCatching { g.disconnect() }.onFailure { Log.w(TAG, "disconnect failed", it) } + runCatching { g.close() }.onFailure { Log.w(TAG, "close failed", it) } Log.i(TAG, "disconnected: $why") listener?.invoke() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionEvents.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionEvents.kt index 6c0a076456..52c7cedce5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionEvents.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionEvents.kt @@ -75,6 +75,17 @@ object SessionEvents { } } + inline fun step(name: String, block: () -> T): T { + val dir = SessionState.logDirectory ?: SessionPaths.current() + record("start.step", mapOf("step" to name, "state" to "begin"), dir) + val began = android.os.SystemClock.elapsedRealtime() + try { + return block() + } finally { + record("start.step", mapOf("step" to name, "state" to "end", "ms" to android.os.SystemClock.elapsedRealtime() - began), dir) + } + } + fun fail(code: String, message: String, status: Int? = null) { synchronized(SessionState) { SessionState.phase = SessionPhase.FAILED diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index b476c17ff1..1c34443968 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -577,7 +577,7 @@ class SessionService : Service() { val sessionDir = openSessionFolder() try { - GameEnvironmentStore.publish(this) + SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) } } catch (e: Exception) { Log.e(TAG, "could not publish the game environment", e) stopSession(-1, gen) @@ -589,22 +589,22 @@ class SessionService : Service() { runCatching { sessionLog.appendText(prootLine + "\n") } .onFailure { Log.w(TAG, "could not write the proot line to ${sessionLog.path}", it) } - Log.i(TAG, GpuClockPin.start(this)) - Log.i(TAG, GameThreadHints.start(this)) + Log.i(TAG, SessionEvents.step("gpu-clock-pin") { GpuClockPin.start(this) }) + Log.i(TAG, SessionEvents.step("thread-hints") { GameThreadHints.start(this) }) val size = SessionState.outputSize val guest = ArrayList() val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP - runCatching { ComponentsManager.republish(this) } + runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } } .onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") } .onFailure { Log.w(TAG, "component selections", it) } if (steamHere) { - runCatching { ComponentsManager.ensureForcedPackages(this) } + runCatching { SessionEvents.step("components-forced") { ComponentsManager.ensureForcedPackages(this) } } .onSuccess { if (it != null) Log.i(TAG, it) } .onFailure { Log.w(TAG, "forced components", it) } } try { - addClientEnvironment(guest, steamHere, agentEnvironment) + SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) } } catch (e: IllegalStateException) { Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e) failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1) @@ -614,8 +614,8 @@ class SessionService : Service() { if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId) val fastPathAt = guest.size - val pulse = startAudio(guest, sessionDir, directAudioPack) - startVkBridge(guest, sessionDir) + val pulse = SessionEvents.step("audio") { startAudio(guest, sessionDir, directAudioPack) } + SessionEvents.step("vk-bridge") { startVkBridge(guest, sessionDir) } if (VenusComponent.wanted(this)) { components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) }) } @@ -661,20 +661,20 @@ class SessionService : Service() { deckBinds = emptyList() inputSysfs = null if (controllersOn) { - addControllerEnvironment(guest, fakeInputDir, sessionDir) - SessionState.padBridge?.syncConnectedControllers() + SessionEvents.step("controller-environment") { addControllerEnvironment(guest, fakeInputDir, sessionDir) } + SessionEvents.step("controller-sync") { SessionState.padBridge?.syncConnectedControllers() } } val noSteamGame = noSteamGame() if (noSteamGame) guest.add("BL_PIN_CORES=0") if ((steamHere || SessionState.program == NoSteamLaunch.EPIC) && com.droiddeck.launcher.stores.epic.EpicClient.read(this).installed) { - runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) } + runCatching { SessionEvents.step("epic-library") { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) } } .onFailure { Log.w(TAG, "Epic library sync failed", it) } - runCatching { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) } + runCatching { SessionEvents.step("epic-install-dir") { com.droiddeck.launcher.stores.epic.EpicClient.prepareInstallDir(this) } } .onFailure { Log.w(TAG, "Epic install directory setup failed", it) } } if (steamHere || noSteamGame) { - val added = com.droiddeck.launcher.frontend.AddedGames.scan(this) - val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) + val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) } + val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) } guest.add("BL_ADDED_GAMES=" + listing.path) if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1") if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1") @@ -686,7 +686,7 @@ class SessionService : Service() { // Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not // an Adreno, or Setup's switch), and graphics-report.txt for every session. if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1") - GraphicsReport.begin(this, sessionDir, guest) + SessionEvents.step("graphics-report") { GraphicsReport.begin(this, sessionDir, guest) } val shellGuest = ArrayList(guest).apply { add("SHELL=/bin/bash") add("TERM=xterm-256color") @@ -714,7 +714,7 @@ class SessionService : Service() { Log.i(TAG, "run: $program (${SessionState.programArgs.size} arguments) under gamescope") } - FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) + SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) } val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir) val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this) @@ -820,7 +820,7 @@ class SessionService : Service() { watchLaunchRequests(sessionRoot) watchSyncWanted(root) EsyncPacks.fetchInBackground(this, root) - val pid = HostProcess.start(line, hostEnv.asArray(), root, { status -> + val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status -> if (gen != sessionGen) { Log.i(TAG, "an earlier session's process ended ($status); the current one carries on") return@start @@ -828,7 +828,7 @@ class SessionService : Service() { val program = programStatus(sessionRoot) Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "") stopSession(program ?: status ?: -1, gen) - }, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) + }, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) } Log.i(TAG, "session pid $pid, log ${sessionLog.path}") if (gen != sessionGen || !SessionState.running) { Log.i(TAG, "session stopped while its guest was starting; taking it down") diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt index 9d05efea50..f97ca1bf88 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt @@ -48,9 +48,16 @@ class SteamControllerBleTest { controller.start() } + /** Runs what stop() posted unless stop() already quit the looper, then quits it. */ + private fun drain(looper: android.os.Looper) { + runCatching { shadowOf(looper).idle() } + looper.quit() + } + @After fun close() { controller.stop() - handler.looper.quit() + // The stop posts a disconnect; run it now, while Robolectric's environment still exists. + drain(handler.looper) } @Test fun stopReleasesAndDetachesInputBeforeQueuedCallbacksCanPublish() { @@ -126,7 +133,7 @@ class SteamControllerBleTest { assertTrue(Writer.reports.last().all { it == 0.toByte() }) } finally { replacement.stop() - replacementHandler.looper.quit() + drain(replacementHandler.looper) } } @@ -142,7 +149,7 @@ class SteamControllerBleTest { assertEquals(reports, Writer.reports.size) } finally { unused.stop() - ReflectionHelpers.getField(unused, "handler").looper.quit() + drain(ReflectionHelpers.getField(unused, "handler").looper) } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionEventsStepTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionEventsStepTest.kt new file mode 100644 index 0000000000..5ffe9f25a8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionEventsStepTest.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.session + +import java.io.File +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class SessionEventsStepTest { + private lateinit var dir: File + + @Before fun open() { + dir = File.createTempFile("session", "").apply { delete(); mkdirs() } + SessionState.logDirectory = dir + SessionState.eventsFile = File(dir, "events.jsonl") + } + + @After fun close() { + SessionState.logDirectory = null + SessionState.eventsFile = null + dir.deleteRecursively() + } + + private fun events() = File(dir, "events.jsonl").readLines().map(::JSONObject) + + @Test fun stepRecordsBeginAndEndAroundTheBlockAndReturnsItsValue() { + assertEquals(7, SessionEvents.step("probe") { 7 }) + val lines = events() + assertEquals(listOf("begin", "end"), lines.map { it.getString("state") }) + assertTrue(lines.all { it.getString("event") == "start.step" && it.getString("step") == "probe" }) + assertTrue(lines[1].getLong("ms") >= 0) + } + + @Test fun stepStillRecordsTheEndWhenTheBlockThrows() { + runCatching { SessionEvents.step("probe") { error("boom") } } + assertEquals(listOf("begin", "end"), events().map { it.getString("state") }) + } + + @Test fun stepKeepsBothEventsInTheSessionWhereItStarted() { + val other = File.createTempFile("session", "").apply { delete(); mkdirs() } + try { + SessionEvents.step("probe") { + SessionState.logDirectory = other + SessionState.eventsFile = File(other, "events.jsonl") + } + assertEquals(listOf("begin", "end"), events().map { it.getString("state") }) + assertTrue(!File(other, "events.jsonl").exists()) + } finally { + other.deleteRecursively() + } + } + + @Test fun stepPropagatesTheOriginalExceptionUnchanged() { + val failure = IllegalStateException("boom") + val thrown = runCatching { SessionEvents.step("probe") { throw failure } }.exceptionOrNull() + assertTrue(thrown === failure) + } + + @Test fun stepsOfDifferentLaunchesAreRecordedIndependentlyInOrder() { + SessionEvents.step("controller-environment") { } + SessionEvents.step("guest-launch") { } + assertEquals( + listOf("controller-environment", "controller-environment", "guest-launch", "guest-launch"), + events().map { it.getString("step") }, + ) + } + + @Test fun stepRecordsNothingElseAndLeavesSessionStateUntouched() { + SessionState.running = false + SessionEvents.step("probe") { } + assertEquals(false, SessionState.running) + assertEquals(2, events().size) + } +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 313dc57f57..1e76859e04 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -122,6 +122,17 @@ function field(text, name) { return m ? m[1] : ""; } +function object(text, name) { + var start = new RegExp('"' + name + '"\\s*:\\s*\\{').exec(text); + if (!start) return ""; + var from = start.index + start[0].length, depth = 0; + for (var i = from - 1; i < text.length; i++) { + if (text.charAt(i) == "{") depth++; + else if (text.charAt(i) == "}" && --depth == 0) return text.substring(from, i); + } + return ""; +} + function job(text) { if (/"error"\s*:\s*[1-9]/.test(text)) return false; var bare = text.replace(/"extended_status"\s*:\s*\{[^}]*\}/, ""); @@ -147,7 +158,10 @@ function watch(path) { for (var i = 0; ; i++) { var s = call("GET", path); save(".json", s); - if (/"error"\s*:\s*[1-9]/.test(s)) break; + if (/"form"\s*:\s*\{/.test(s)) { + var refused = /"error"\s*:\s*(\d+)/.exec(object(s, "game_dir")); + if (refused && +refused[1] != 0) throw new Error(+refused[1] == 800 ? "the game folder already holds a game" : "Battle.net refused the game folder (error " + refused[1] + ")"); + } else if (/"error"\s*:\s*[1-9]/.test(s)) break; var state = /"state"\s*:\s*(\d+)/.exec(s.replace(/"extended_status"\s*:\s*\{[^}]*\}/, "")), complete = /"download_complete"\s*:\s*true/.test(s); state = state ? +state[1] : 0; if (state == 1000 || state == 1003 || job(s) && !complete) started = true; diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index ec29a48c56..40c16bfcd4 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -1709,5 +1709,12 @@ class AgentJobTest(Harness): self.assertEqual(calls, [("install", "gryphon", "gryphon", "/g/Rumble", "enUS", "USA", "US"), ("update", "wow_classic")]) +class BattleNetFormTest(Temp): + def test_the_driver_waits_on_the_install_form_and_names_a_folder_that_is_taken(self): + script = BNET["AGENT_SCRIPT"] + self.assertIn(r'if (/"form"\s*:\s*\{/.test(s)) {', script) + self.assertIn("the game folder already holds a game", script) + + if __name__ == "__main__": unittest.main()