TorrServerHost.desktop.kt
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/torrent/TorrServerHost.desktop.kt
1package eu.friedcutlet.yokan.services.torrent23import eu.friedcutlet.yokan.domain.ProfileId4import eu.friedcutlet.yokan.domain.ProfileStorageNamespace5import eu.friedcutlet.yokan.services.catchingNonCancellation6import eu.friedcutlet.yokan.services.files.desktopDataRoot7import java.io.File8import java.net.URI9import java.net.http.HttpClient10import java.net.http.HttpRequest11import java.net.http.HttpResponse12import java.nio.file.Files13import java.nio.file.StandardCopyOption14import java.security.MessageDigest15import java.time.Duration16import java.util.concurrent.TimeUnit17import kotlinx.coroutines.CoroutineScope18import kotlinx.coroutines.Dispatchers19import kotlinx.coroutines.SupervisorJob20import kotlinx.coroutines.delay21import kotlinx.coroutines.flow.MutableStateFlow22import kotlinx.coroutines.flow.StateFlow23import kotlinx.coroutines.launch24import kotlinx.coroutines.runInterruptible25import kotlinx.coroutines.sync.Mutex26import kotlinx.coroutines.sync.withLock27import kotlinx.coroutines.withContext2829/** Official release pinned with its SHA-256 digests (github.com/YouROK/TorrServer, GPL-3.0, not bundled). */30internal const val TorrServerVersion = "MatriX.147"3132internal data class TorrServerAsset(val name: String, val sha256: String)3334// ponytail: pinned release; bump version + digests from the GitHub release `digest` fields when updating.35private val TorrServerAssets = mapOf(36 "darwin-arm64" to TorrServerAsset("TorrServer-darwin-arm64", "3e13a04e5e9e9bee044b15829fa13769c7c385bc71e8227f010434e1038ef172"),37 "darwin-amd64" to TorrServerAsset("TorrServer-darwin-amd64", "5cf02d76b6037a6a0f0cf8bafda0a9dbe34fb10149aed998f422cb26f7225608"),38 "linux-amd64" to TorrServerAsset("TorrServer-linux-amd64", "2f20fcb1fcacc9b61b7ca4bb6d5b7933547bd7f447b5cc77a84406faa9e6a4e8"),39 "linux-arm64" to TorrServerAsset("TorrServer-linux-arm64", "fbe0f668a2a22801db891afb52e1b96e4ec762dcbf979bec2a45917848456a1c"),40 "windows-amd64" to TorrServerAsset("TorrServer-windows-amd64.exe", "2a67f19266f111f00828857e7e37c233a509c0def4f6254fd564a1761f35b47d"),41)4243internal fun currentTorrServerAsset(): TorrServerAsset? {44 val os = System.getProperty("os.name").lowercase().let {45 when { "mac" in it || "darwin" in it -> "darwin"; "win" in it -> "windows"; "linux" in it -> "linux"; else -> return null }46 }47 val arch = when (System.getProperty("os.arch").lowercase()) { "aarch64", "arm64" -> "arm64"; "x86_64", "amd64" -> "amd64"; else -> return null }48 return TorrServerAssets["$os-$arch"]49}5051/** Per-profile state lives under the profile's owned root, so profile deletion removes it. */52actual fun createPlatformTorrServerHost(profileId: ProfileId): TorrServerHost? = DesktopTorrServerHost(53 dataDir = File(ProfileStorageNamespace(profileId).ownedRoot(desktopDataRoot.path), "torrserver"),54 installRoot = File(desktopDataRoot, "torrserver-bin"),55)5657/**58 * Supervises one TorrServer subprocess: health-checked start, automatic restart after a crash,59 * orphan cleanup after a Yokan crash (pid file + start instant), and a JVM shutdown hook.60 */61internal class DesktopTorrServerHost(62 private val dataDir: File,63 private val installRoot: File,64 private val asset: TorrServerAsset? = currentTorrServerAsset(),65 private val downloadBase: String = "https://github.com/YouROK/TorrServer/releases/download/$TorrServerVersion",66 private val startTimeoutMillis: Long = 20_000,67 private val maxRestarts: Int = 3,68) : TorrServerHost {69 private val lock = Mutex()70 private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)71 private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).followRedirects(HttpClient.Redirect.NORMAL).build()72 private val _status = MutableStateFlow("Stopped")73 override val status: StateFlow<String> = _status74 private var process: Process? = null75 private var active: TorrServerLaunch? = null76 private var restarts = 077 private val shutdownHook = Thread { process?.destroyForcibly() }78 private val pidFile get() = File(dataDir, "torrserver.pid")79 internal val logFile get() = File(dataDir, "torrserver.log")80 internal val pid: Long? get() = process?.takeIf { it.isAlive }?.pid()8182 override fun executable(userPath: String): String? =83 if (userPath.isNotBlank()) userPath.takeIf { File(it).isFile }84 else asset?.let { File(installRoot, "$TorrServerVersion/${it.name}") }?.takeIf(File::isFile)?.path8586 override suspend fun install(onProgress: (Long, Long) -> Unit): String = withContext(Dispatchers.IO) {87 val asset = checkNotNull(asset) { "TorrServer publishes no build for ${System.getProperty("os.name")} ${System.getProperty("os.arch")}; set a binary path or use a remote server." }88 val target = File(installRoot, "$TorrServerVersion/${asset.name}")89 if (target.isFile && sha256(target) == asset.sha256) return@withContext target.path90 target.parentFile.mkdirs()91 val part = File(target.parentFile, "${asset.name}.part")92 try {93 val response = runInterruptible {94 http.send(HttpRequest.newBuilder(URI.create("$downloadBase/${asset.name}")).header("User-Agent", "Yokan").build(), HttpResponse.BodyHandlers.ofInputStream())95 }96 response.body().use { input ->97 check(response.statusCode() in 200..299) { "TorrServer download failed with HTTP ${response.statusCode()}" }98 val total = response.headers().firstValueAsLong("content-length").orElse(-1)99 part.outputStream().use { output ->100 val buffer = ByteArray(DEFAULT_BUFFER_SIZE)101 var done = 0L102 while (true) {103 val read = input.read(buffer).takeIf { it >= 0 } ?: break104 output.write(buffer, 0, read)105 done += read106 onProgress(done, total)107 }108 }109 }110 val actual = sha256(part)111 check(actual == asset.sha256) { "TorrServer SHA-256 mismatch: expected ${asset.sha256}, got $actual" }112 part.setExecutable(true, true)113 Files.move(part.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)114 target.path115 } finally {116 part.delete()117 }118 }119120 override suspend fun ensureRunning(launch: TorrServerLaunch): String = lock.withLock {121 val url = "http://127.0.0.1:${launch.port}"122 restarts = 0123 if (process?.isAlive == true && active == launch && healthy(url)) return@withLock url124 stopLocked()125 startLocked(launch)126 url127 }128129 override suspend fun stop() = lock.withLock { stopLocked() }130131 private suspend fun startLocked(launch: TorrServerLaunch): Unit = withContext(Dispatchers.IO) {132 val url = "http://127.0.0.1:${launch.port}"133 val exe = executable(launch.executablePath)134 ?: error(if (launch.executablePath.isBlank()) "Download TorrServer or set its binary path first." else "TorrServer binary not found: ${launch.executablePath}")135 dataDir.mkdirs()136 killOrphan()137 if (healthy(url)) fail("Port ${launch.port} is already used by another server; change the port or use it as a remote TorrServer.")138 _status.value = "Starting on port ${launch.port}"139 val command = listOf(exe, "--port", launch.port.toString(), "--path", dataDir.absolutePath) +140 (launch.proxyMode?.let { listOf("--proxyurl", launch.proxyUrl, "--proxymode", it) } ?: emptyList())141 val started = runCatching {142 ProcessBuilder(command).directory(dataDir).redirectErrorStream(true)143 .redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)).start()144 }.getOrElse { fail("Cannot launch TorrServer ($exe): ${it.message}") }145 process = started146 active = launch147 pidFile.writeText("${started.pid()} ${started.info().startInstant().map { it.toEpochMilli() }.orElse(0)}")148 runCatching { Runtime.getRuntime().addShutdownHook(shutdownHook) }149 val deadline = System.currentTimeMillis() + startTimeoutMillis150 while (!healthy(url)) {151 if (!started.isAlive) {152 process = null153 fail("TorrServer exited with code ${started.exitValue()}: ${logFile.readLines().takeLast(3).joinToString(" ")}")154 }155 if (System.currentTimeMillis() > deadline) {156 started.destroyForcibly()157 process = null158 fail("TorrServer did not answer on port ${launch.port} within ${startTimeoutMillis / 1000} s")159 }160 delay(200)161 }162 _status.value = "Running on port ${launch.port} (pid ${started.pid()})"163 started.onExit().thenRun { scope.launch { onExit(started, launch) } }164 }165166 /** Unexpected exits restart with backoff; [maxRestarts] consecutive crashes leave it stopped until next use. */167 private suspend fun onExit(exited: Process, launch: TorrServerLaunch): Unit = lock.withLock {168 if (process !== exited) return@withLock169 process = null170 if (restarts >= maxRestarts) {171 _status.value = "Crashed (exit ${exited.exitValue()}); restarts on next use"172 return@withLock173 }174 restarts++175 _status.value = "Crashed (exit ${exited.exitValue()}); restarting ($restarts/$maxRestarts)"176 delay(500L shl restarts)177 catchingNonCancellation { startLocked(launch) }178 }179180 private suspend fun stopLocked() = withContext(Dispatchers.IO) {181 val current = process182 process = null183 active = null184 if (current != null) {185 current.destroy()186 if (!current.waitFor(5, TimeUnit.SECONDS)) current.destroyForcibly().waitFor(5, TimeUnit.SECONDS)187 }188 killOrphan()189 runCatching { Runtime.getRuntime().removeShutdownHook(shutdownHook) }190 _status.value = "Stopped"191 }192193 /** A server left behind by a crashed Yokan still holds the port and its database. */194 private fun killOrphan() {195 val (pid, started) = pidFile.takeIf(File::isFile)?.readText()?.split(' ')?.mapNotNull(String::toLongOrNull)196 ?.takeIf { it.size == 2 } ?: return197 ProcessHandle.of(pid).filter { handle -> handle.info().startInstant().map { it.toEpochMilli() }.orElse(-1) == started }198 .ifPresent { handle ->199 handle.destroy()200 runCatching { handle.onExit().get(5, TimeUnit.SECONDS) }.onFailure {201 handle.destroyForcibly()202 runCatching { handle.onExit().get(5, TimeUnit.SECONDS) }203 }204 }205 pidFile.delete()206 }207208 private fun healthy(url: String): Boolean = runCatching {209 http.send(HttpRequest.newBuilder(URI.create("$url/echo")).timeout(Duration.ofSeconds(2)).build(), HttpResponse.BodyHandlers.discarding())210 .statusCode() == 200211 }.getOrDefault(false)212213 private fun fail(message: String): Nothing {214 _status.value = message215 error(message)216 }217218 private fun sha256(file: File): String {219 val digest = MessageDigest.getInstance("SHA-256")220 file.inputStream().use { input ->221 val buffer = ByteArray(DEFAULT_BUFFER_SIZE)222 while (true) digest.update(buffer, 0, input.read(buffer).takeIf { it >= 0 } ?: break)223 }224 return digest.digest().toHexString()225 }226}227