DesktopExtensionServer.kt
vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServer.kt
1package eu.friedcutlet.yokan.ext23import java.io.File4import java.util.concurrent.TimeUnit5import kotlinx.coroutines.Dispatchers6import kotlinx.coroutines.flow.MutableStateFlow7import kotlinx.coroutines.flow.StateFlow8import kotlinx.coroutines.sync.Mutex9import kotlinx.coroutines.sync.withLock10import kotlinx.coroutines.withContext1112/**13 * [dataDir] confines the server JVM's home, temp and working directories (the server keeps14 * source preferences and caches there); null keeps the inherited legacy locations.15 */16class DesktopExtensionServer(private val dataDir: File? = null) : ExtensionServer {17 private val lock = Mutex()18 private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)19 private var process: Process? = null20 private var activeConfig: ExtensionServerConfig? = null2122 override val status: StateFlow<ExtensionServerStatus> = mutableStatus2324 override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {25 val running = process?.isAlive == true26 if (running && activeConfig == config) return mutableStatus.value27 stopLocked()2829 val jar = config.serverJarPath?.takeIf { it.isNotBlank() }?.let(::File)30 ?: throw fail("MISSING_JAR", "An extension server JAR is required on desktop")31 if (!jar.isFile) throw fail("MISSING_JAR", "Extension server JAR does not exist: ${jar.path}")32 val java = resolveJavaExecutable(config.jvmPath)33 mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting local extension server")3435 val launched = withContext(Dispatchers.IO) {36 runCatching {37 dataDir?.let { File(it, "tmp").mkdirs() }38 ProcessBuilder(desktopExtensionServerCommand(java, jar, config.port, dataDir))39 .directory(dataDir)40 .redirectInput(ProcessBuilder.Redirect.PIPE)41 .redirectOutput(ProcessBuilder.Redirect.DISCARD)42 .redirectError(ProcessBuilder.Redirect.DISCARD)43 .start()44 }45 }.getOrElse { error ->46 throw fail("START_ERROR", "Failed to launch extension server with $java: ${error.message.orEmpty()}", error)47 }48 process = launched49 activeConfig = config50 mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Server started on port ${config.port}")51 launched.onExit().thenRun {52 if (process === launched) {53 process = null54 activeConfig = null55 mutableStatus.value = ExtensionServerStatus.Stopped.copy(message = "Extension server exited")56 }57 }58 mutableStatus.value59 }6061 override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }6263 private suspend fun stopLocked(): ExtensionServerStatus {64 val current = process65 if (current == null || !current.isAlive) {66 process = null67 activeConfig = null68 return ExtensionServerStatus.Stopped.also { mutableStatus.value = it }69 }70 mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Stopping, activeConfig?.port, "Stopping extension server")71 withContext(Dispatchers.IO) {72 current.destroy()73 if (!current.waitFor(5, TimeUnit.SECONDS)) {74 current.destroyForcibly()75 current.waitFor(5, TimeUnit.SECONDS)76 }77 }78 process = null79 activeConfig = null80 return ExtensionServerStatus.Stopped.copy(message = "Server stopped").also { mutableStatus.value = it }81 }8283 internal fun resolveJavaExecutable(rawPath: String?): String {84 val explicit = rawPath?.trim()?.takeIf { it.isNotEmpty() }85 if (explicit != null) {86 val path = File(explicit)87 val executable = if (path.isDirectory) File(path, "bin/${javaBinaryName()}") else path88 if (!executable.isFile) throw fail("MISSING_JAVA", "Java executable does not exist: ${executable.path}")89 return executable.absolutePath90 }91 val javaHome = System.getenv("JAVA_HOME")?.takeIf { it.isNotBlank() }92 if (javaHome != null) {93 val executable = File(javaHome, "bin/${javaBinaryName()}")94 if (executable.isFile) return executable.absolutePath95 }96 return javaBinaryName()97 }9899 private fun javaBinaryName(): String = if (System.getProperty("os.name").contains("win", ignoreCase = true)) "java.exe" else "java"100101 private fun fail(code: String, message: String, cause: Throwable? = null): ExtensionServerException {102 mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Failed, activeConfig?.port, message)103 return ExtensionServerException(code, message, cause)104 }105}106107internal fun desktopExtensionServerCommand(java: String, jar: File, port: Int, dataDir: File?): List<String> =108 listOfNotNull(109 java,110 dataDir?.let { "-Duser.home=${it.absolutePath}" },111 dataDir?.let { "-Djava.io.tmpdir=${File(it, "tmp").absolutePath}" },112 "-jar",113 jar.absolutePath,114 port.toString(),115 )116