DesktopTorrServerHostTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/torrent/DesktopTorrServerHostTest.kt
1package eu.friedcutlet.yokan.services.torrent23import com.sun.net.httpserver.HttpServer4import java.io.File5import java.net.InetSocketAddress6import java.net.ServerSocket7import java.net.URI8import java.nio.file.Files9import java.security.MessageDigest10import kotlin.test.AfterTest11import kotlin.test.Test12import kotlin.test.assertEquals13import kotlin.test.assertFailsWith14import kotlin.test.assertFalse15import kotlin.test.assertNotEquals16import kotlin.test.assertTrue17import kotlinx.coroutines.delay18import kotlinx.coroutines.flow.first19import kotlinx.coroutines.runBlocking20import kotlinx.coroutines.withTimeout2122/** Real subprocess supervision against a fake TorrServer (a Java single-file program behind a shell script). */23class DesktopTorrServerHostTest {24 private val root = Files.createTempDirectory("torrserver-host").toFile()25 private val java = ProcessHandle.current().info().command().get()26 private val cleanup = mutableListOf<() -> Unit>()2728 @AfterTest29 fun tearDown() {30 cleanup.forEach { runCatching(it) }31 root.deleteRecursively()32 }3334 private fun freePort() = ServerSocket(0).use { it.localPort }3536 private fun fakeServer(exitCode: Int? = null): File {37 val source = File(root, "FakeTorrServer.java")38 source.writeText(39 """40 import com.sun.net.httpserver.HttpServer;41 import java.net.InetSocketAddress;42 import java.nio.file.*;43 public class FakeTorrServer {44 public static void main(String[] args) throws Exception {45 ${exitCode?.let { "System.out.println(\"bad flag\"); System.exit($it);" }.orEmpty()}46 int port = Integer.parseInt(args[java.util.Arrays.asList(args).indexOf("--port") + 1]);47 String path = args[java.util.Arrays.asList(args).indexOf("--path") + 1];48 Files.writeString(Path.of(path, "args.txt"), String.join(" ", args));49 HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);50 server.createContext("/echo", ex -> { byte[] b = "MatriX.fake".getBytes(); ex.sendResponseHeaders(200, b.length); ex.getResponseBody().write(b); ex.close(); });51 server.start();52 }53 }54 """.trimIndent(),55 )56 return File(root, "TorrServer").apply {57 writeText("#!/bin/sh\nexec \"$java\" \"${source.absolutePath}\" \"$@\"\n")58 setExecutable(true)59 }60 }6162 private fun host(dataDir: File = File(root, "data"), asset: TorrServerAsset? = null, base: String = "http://127.0.0.1:1") =63 DesktopTorrServerHost(dataDir, File(root, "bin"), asset, base, startTimeoutMillis = 30_000).also { host ->64 cleanup += { runBlocking { host.stop() } }65 }6667 private fun echo(url: String) = URI.create("$url/echo").toURL().readText()6869 @Test70 fun startsWithProxyFlagsRestartsAfterCrashAndStops(): Unit = runBlocking {71 val exe = fakeServer()72 val host = host()73 val port = freePort()74 val url = host.ensureRunning(TorrServerLaunch(port, exe.path, "full", "socks5://127.0.0.1:1080"))7576 assertEquals("http://127.0.0.1:$port", url)77 assertEquals("MatriX.fake", echo(url))78 val args = File(root, "data/args.txt").readText()79 assertTrue("--proxyurl socks5://127.0.0.1:1080 --proxymode full" in args, args)80 assertTrue(File(root, "data/torrserver.pid").isFile)8182 val first = host.pid!!83 ProcessHandle.of(first).get().destroyForcibly()84 withTimeout(30_000) { host.status.first { it.startsWith("Crashed") } }85 withTimeout(30_000) { host.status.first { it.startsWith("Running") } }86 assertNotEquals(first, host.pid)87 assertEquals("MatriX.fake", echo(url))8889 host.stop()90 assertEquals("Stopped", host.status.value)91 assertFalse(File(root, "data/torrserver.pid").exists())92 assertFailsWith<Exception> { echo(url) }93 }9495 @Test96 fun optionChangeRestartsAndOrphanFromCrashedAppIsKilled(): Unit = runBlocking {97 val exe = fakeServer()98 val port = freePort()99 val dataDir = File(root, "data").apply { mkdirs() }100 // A server left by a crashed Yokan: running, with its pid file.101 val orphan = ProcessBuilder(exe.path, "--port", port.toString(), "--path", dataDir.path).start()102 cleanup += { orphan.destroyForcibly() }103 withTimeout(30_000) { while (runCatching { echo("http://127.0.0.1:$port") }.isFailure) delay(100) }104 File(dataDir, "torrserver.pid").writeText("${orphan.pid()} ${orphan.info().startInstant().get().toEpochMilli()}")105106 val host = host(dataDir)107 host.ensureRunning(TorrServerLaunch(port, exe.path, null, ""))108 assertFalse(orphan.isAlive)109 val first = host.pid!!110111 host.ensureRunning(TorrServerLaunch(port, exe.path, "tracker", "http://proxy:3128"))112 assertNotEquals(first, host.pid)113 assertTrue("--proxymode tracker" in File(dataDir, "args.txt").readText())114 }115116 @Test117 fun foreignServerOnThePortStartupCrashAndMissingBinaryFail(): Unit = runBlocking {118 val foreign = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {119 createContext("/echo") { it.sendResponseHeaders(200, -1); it.close() }120 start()121 }122 cleanup += { foreign.stop(0) }123 val exe = fakeServer()124 val busy = assertFailsWith<IllegalStateException> { host().ensureRunning(TorrServerLaunch(foreign.address.port, exe.path, null, "")) }125 assertTrue("already used" in busy.message!!, busy.message)126127 val crashing = fakeServer(exitCode = 7)128 val crashed = assertFailsWith<IllegalStateException> { host().ensureRunning(TorrServerLaunch(freePort(), crashing.path, null, "")) }129 assertTrue("exited with code 7" in crashed.message!! && "bad flag" in crashed.message!!, crashed.message)130131 val missing = assertFailsWith<IllegalStateException> { host().ensureRunning(TorrServerLaunch(freePort(), "", null, "")) }132 assertTrue("Download TorrServer" in missing.message!!)133 }134135 @Test136 fun installVerifiesSha256BeforePublishingTheBinary(): Unit = runBlocking {137 val payload = "#!/bin/sh\necho torrserver\n".encodeToByteArray()138 val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {139 createContext("/TorrServer-test") { it.sendResponseHeaders(200, payload.size.toLong()); it.responseBody.write(payload); it.close() }140 start()141 }142 cleanup += { server.stop(0) }143 val base = "http://127.0.0.1:${server.address.port}"144 val digest = MessageDigest.getInstance("SHA-256").digest(payload).toHexString()145 val target = File(root, "bin/$TorrServerVersion/TorrServer-test")146147 val bad = host(asset = TorrServerAsset("TorrServer-test", "0".repeat(64)), base = base)148 assertTrue("SHA-256 mismatch" in assertFailsWith<IllegalStateException> { bad.install { _, _ -> } }.message!!)149 assertFalse(target.exists())150 assertEquals(emptyList(), target.parentFile.listFiles().orEmpty().toList())151152 var progress = 0L153 val good = host(asset = TorrServerAsset("TorrServer-test", digest), base = base)154 assertEquals(target.path, good.install { done, _ -> progress = done })155 assertTrue(payload.contentEquals(target.readBytes()) && target.canExecute())156 assertEquals(payload.size.toLong(), progress)157 assertEquals(target.path, good.executable(""))158 assertEquals(null, good.executable("/does/not/exist"))159 }160}161