fix(addons): CurseForge connects once, reuses its game instance and skips rescans after its own changes (#3081)

* fix(addons): CurseForge connects once, reuses its game instance and skips rescans after its own changes

* fix(addons): a settled list is dropped by a refresh, a later change or a newer change

* fix(curseforge): publish the report under the same lock as the turn check

An older change could report its list after a newer one had already
reported, so the fallback marks could miss add-ons the newer change
installed.
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-23 13:33:29 -05:00
1 parent 963af6df8e
commit 6ecc5a22d3
7 files changed
+217 -29

No files matched your search

@@ -72,6 +72,8 @@ object CurseForgeApp {
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val CACHE = "__droiddeckServices"
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
@@ -91,7 +93,8 @@ object CurseForgeApp {
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
val key = JSONObject.quote(service)
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
@@ -170,6 +173,7 @@ object CurseForgeApp {
}
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
private val connected = ConcurrentHashMap.newKeySet<String>()
private fun lines(context: Context, argv: List<String>): List<String> {
val out = ArrayList<String>()
@@ -232,19 +236,25 @@ object CurseForgeApp {
}
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
hold.set(true)
inspector?.let(connected::remove)
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
}
private fun connect(context: Context, inspector: String) {
if (inspector in connected) return
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
connected += inspector
}
private fun instances(context: Context, inspector: String): Any? =
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
}
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
@@ -260,34 +270,34 @@ object CurseForgeApp {
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) {
val listed = runCatching { projects(context, inspector, guid) }
val error = listed.exceptionOrNull()
if (error is Failure && error.gone) throw error
listed.getOrNull()?.let { if (done(it)) return true }
listed.getOrNull()?.let { if (done(it)) return it }
Thread.sleep(1_000)
}
return false
return null
}
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
}
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
}
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
connect(context, inspector)
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
if (failed == null || failed.length() > 0) return false
if (failed == null || failed.length() > 0) return null
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
}
}
@@ -275,12 +275,15 @@ class LinuxNetworkLinkComponent(
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
*/
private fun replace(file: File, text: String) {
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
synchronized(WRITES) {
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return
val staged = File(file.path + ".staged")
java.io.FileOutputStream(staged).use { out ->
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
}
private fun writeResolver(properties: LinkProperties?) {
@@ -333,6 +336,8 @@ class LinuxNetworkLinkComponent(
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
private val WRITES = Any()
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty()
@@ -110,6 +110,9 @@ internal class CurseLink(val app: UserApps.App) {
private val guids = HashMap<String, String>()
private val scanLock = Object()
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
private val settleLock = Object()
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
private val turns = HashMap<String, Int>()
var generation by mutableIntStateOf(0)
private set
@@ -120,7 +123,7 @@ internal class CurseLink(val app: UserApps.App) {
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
synchronized(scanLock) {
scans[target.addOns.path]?.takeIf { it.first == key }?.second
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also {
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
scans[target.addOns.path] = key to it
report(target, it)
}
@@ -131,6 +134,26 @@ internal class CurseLink(val app: UserApps.App) {
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
}
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
val path = target.addOns.path
val turn = synchronized(settleLock) {
settled.remove(path)
((turns[path] ?: 0) + 1).also { turns[path] = it }
}
val projects = call(context, target, launch, block) ?: return false
synchronized(settleLock) {
if (turns[path] == turn) {
settled[path] = generation to projects
report(target, projects)
}
}
return true
}
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target, launch) }
try {
@@ -174,11 +197,9 @@ internal class CurseLink(val app: UserApps.App) {
return Linked(url, guid)
}
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked ->
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
true
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
}
internal val stopped: Job get() = work
@@ -322,7 +343,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
scope.launch {
val done = withContext(Dispatchers.IO) {
runCatching {
via.call(context, into) {
via.change(context, into) {
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
}
@@ -1157,7 +1157,7 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
val message = withContext(Dispatchers.IO) {
if (curse != null) {
val (project, link) = curse
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
WowAddons.changed()
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
@@ -5,6 +5,7 @@ import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
@@ -158,6 +159,7 @@ class CurseForgeAppTest {
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
assertTrue(text.contains("desktop.html"))
assertTrue(text.contains("executeJavaScript("))
assertTrue(text.contains("let m = globalThis.__droiddeckServices; if (!m || !m[\\\"ProjectAppService\\\"]) m = globalThis.__droiddeckServices = "))
assertFalse(text.contains("show()"))
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
assertFalse(probe.contains("await s["))
@@ -292,6 +294,37 @@ class CurseForgeAppTest {
assertTrue(calls.isEmpty())
}
@Test
fun aGameFolderCurseForgeAlreadyKnowsSkipsTheFolderDetection() {
val flavor = "/root/Games/World of Warcraft/_retail_"
val curse = fakeCurse(flavor = flavor)
val context = org.robolectric.RuntimeEnvironment.getApplication()
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
assertFalse("detectGameFromPath" in curse.methods)
}
@Test
fun aGameFolderCurseForgeDoesNotKnowIsDetectedOnce() {
val flavor = "/root/Games/World of Warcraft/_retail_"
val curse = fakeCurse(flavor = flavor)
curse.known = false
val context = org.robolectric.RuntimeEnvironment.getApplication()
assertEquals("g", CurseForgeApp.instance(context, url, "/root/Games/World of Warcraft", flavor))
assertEquals(1, curse.methods.count { it == "detectGameFromPath" })
assertEquals(listOf("getGameInstances", "detectGameFromPath", "getGameInstances"), curse.methods.filter { it != "connect" })
}
@Test
fun curseForgeConnectsOncePerLaunch() {
val curse = fakeCurse()
val context = org.robolectric.RuntimeEnvironment.getApplication()
val launched = "ws://127.0.0.1:43118/${java.util.UUID.randomUUID()}"
CurseForgeApp.projects(context, launched, "g")
CurseForgeApp.projects(context, launched, "g")
CurseForgeApp.instance(context, launched, "/root", "")
assertEquals(1, curse.methods.count { it == "connect" })
}
@Test
fun theInspectorUrlIsRedactedFromCommandLogs() {
val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ")
@@ -305,6 +338,7 @@ class CurseForgeAppTest {
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
@Volatile var unreachableAfterDelete = false
@Volatile var unreachable = false
@Volatile var known = true
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
@@ -328,8 +362,11 @@ class CurseForgeAppTest {
projects.forEach { it.put("status", 1) }
true
}
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
"detectGameFromPath" -> {
known = true
JSONObject().put("gameInstanceGuid", "g")
}
"getGameInstances" -> if (known) JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) else JSONArray()
"deleteMods" -> {
projects.removeAll { p ->
(p.getString("installedModId") in expression).also { gone ->
@@ -467,7 +504,7 @@ class CurseForgeAppTest {
curse.add("18808", "TomTom", 1)
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
assertEquals(mapOf("298842" to true, "18808" to false), before)
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
assertNotNull(CurseForgeApp.update(context, url, "g", "298842"))
assertTrue("updateMod" in curse.methods)
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
}
@@ -479,7 +516,7 @@ class CurseForgeAppTest {
curse.add("298842", "Leatrix_Maps", 1)
curse.add("18808", "TomTom", 1)
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
assertNotNull(CurseForgeApp.uninstall(context, url, "g", project))
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
assertTrue(File(curse.addOns, "TomTom").isDirectory)
@@ -155,4 +155,37 @@ class LinuxNetworkLinkComponentTest {
})
assertEquals(before, link)
}
@Test fun parallelPublishersFromSeparateComponentsAllLandAndLeaveNoStagedCopy() {
val context = ApplicationProvider.getApplicationContext<Context>()
val link = properties("10.0.0.1/24").route("1.0.0.0", 8).route("128.0.0.0", 1)
val failures = java.util.concurrent.atomic.AtomicInteger()
val threads = (0 until 8).map {
Thread {
val component = LinuxNetworkLinkComponent(context, temporary.root)
repeat(25) {
runCatching {
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace",
from(java.io.File::class.java, temporary.root.resolve("etc/droiddeck-net").apply { parentFile!!.mkdirs() }),
from(String::class.java, "if tun0 $it\n"))
}.onFailure { failures.incrementAndGet() }
}
}.apply { start() }
}
threads.forEach { it.join() }
assertEquals(0, failures.get())
assertFalse(temporary.root.resolve("etc/droiddeck-net.staged").exists())
assertEquals("if tun0 24\n", temporary.root.resolve("etc/droiddeck-net").readText())
}
@Test fun anUnchangedFileIsNotRewritten() {
val context = ApplicationProvider.getApplicationContext<Context>()
val component = LinuxNetworkLinkComponent(context, temporary.root)
val file = temporary.root.resolve("etc/resolv.conf").apply { parentFile!!.mkdirs(); writeText("nameserver 1.1.1.1\n") }
assertTrue(file.setLastModified(1_000_000L))
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 1.1.1.1\n"))
assertEquals(1_000_000L, file.lastModified())
ReflectionHelpers.callInstanceMethod<Unit>(component, "replace", from(java.io.File::class.java, file), from(String::class.java, "nameserver 8.8.8.8\n"))
assertEquals("nameserver 8.8.8.8\n", file.readText())
}
}
@@ -133,6 +133,88 @@ class CurseLinkTabTest {
}
}
@Test
fun anInstallHandsCurseForgesSettledListToTheNextReadWithoutARescan() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
assertEquals(listOf("298842"), link.installed(context, target, 1).map { it.id })
assertEquals(1, methods.count { it == "scanGameInstance" })
link.installed(context, target, 2)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aFailedInstallLeavesTheNextReadToRescan() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertFalse(link.change(context, target) { null })
link.installed(context, target, 1)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aRefreshAfterAnInstallStillRescans() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
link.refresh()
link.installed(context, target, 1)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aFailedChangeDropsAnEarlierSettledList() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) { CurseForgeApp.install(context, it.inspector, it.guid, "298842") })
assertFalse(link.change(context, target) { null })
link.installed(context, target, 1)
assertEquals(2, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun anOlderChangeFinishingLastDoesNotReplaceTheNewerList() {
val target = wow()
tocFolder(target.addOns, "Older", "1")
tocFolder(target.addOns, "Newer", "2")
val older = CurseForgeApp.Project("1", "11", listOf("Older"), false)
val newer = CurseForgeApp.Project("2", "22", listOf("Newer"), false)
val link = CurseLink(app)
try {
link.installed(context, target, 0)
assertTrue(link.change(context, target) {
assertTrue(link.change(context, target) { listOf(older, newer) })
listOf(older)
})
assertEquals(setOf("1", "2"), CurseLink.lastReported(target).keys)
assertEquals(listOf("1", "2"), link.installed(context, target, 1).map { it.id })
assertEquals(1, methods.count { it == "scanGameInstance" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() {
val target = wow()