package eu.friedcutlet.yokan.ext import java.io.File import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** * [dataDir] confines the server JVM's home, temp and working directories (the server keeps * source preferences and caches there); null keeps the inherited legacy locations. */ class DesktopExtensionServer(private val dataDir: File? = null) : ExtensionServer { private val lock = Mutex() private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped) private var process: Process? = null private var activeConfig: ExtensionServerConfig? = null override val status: StateFlow = mutableStatus override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock { val running = process?.isAlive == true if (running && activeConfig == config) return mutableStatus.value stopLocked() val jar = config.serverJarPath?.takeIf { it.isNotBlank() }?.let(::File) ?: throw fail("MISSING_JAR", "An extension server JAR is required on desktop") if (!jar.isFile) throw fail("MISSING_JAR", "Extension server JAR does not exist: ${jar.path}") val java = resolveJavaExecutable(config.jvmPath) mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting local extension server") val launched = withContext(Dispatchers.IO) { runCatching { dataDir?.let { File(it, "tmp").mkdirs() } ProcessBuilder(desktopExtensionServerCommand(java, jar, config.port, dataDir)) .directory(dataDir) .redirectInput(ProcessBuilder.Redirect.PIPE) .redirectOutput(ProcessBuilder.Redirect.DISCARD) .redirectError(ProcessBuilder.Redirect.DISCARD) .start() } }.getOrElse { error -> throw fail("START_ERROR", "Failed to launch extension server with $java: ${error.message.orEmpty()}", error) } process = launched activeConfig = config mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Server started on port ${config.port}") launched.onExit().thenRun { if (process === launched) { process = null activeConfig = null mutableStatus.value = ExtensionServerStatus.Stopped.copy(message = "Extension server exited") } } mutableStatus.value } override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() } private suspend fun stopLocked(): ExtensionServerStatus { val current = process if (current == null || !current.isAlive) { process = null activeConfig = null return ExtensionServerStatus.Stopped.also { mutableStatus.value = it } } mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Stopping, activeConfig?.port, "Stopping extension server") withContext(Dispatchers.IO) { current.destroy() if (!current.waitFor(5, TimeUnit.SECONDS)) { current.destroyForcibly() current.waitFor(5, TimeUnit.SECONDS) } } process = null activeConfig = null return ExtensionServerStatus.Stopped.copy(message = "Server stopped").also { mutableStatus.value = it } } internal fun resolveJavaExecutable(rawPath: String?): String { val explicit = rawPath?.trim()?.takeIf { it.isNotEmpty() } if (explicit != null) { val path = File(explicit) val executable = if (path.isDirectory) File(path, "bin/${javaBinaryName()}") else path if (!executable.isFile) throw fail("MISSING_JAVA", "Java executable does not exist: ${executable.path}") return executable.absolutePath } val javaHome = System.getenv("JAVA_HOME")?.takeIf { it.isNotBlank() } if (javaHome != null) { val executable = File(javaHome, "bin/${javaBinaryName()}") if (executable.isFile) return executable.absolutePath } return javaBinaryName() } private fun javaBinaryName(): String = if (System.getProperty("os.name").contains("win", ignoreCase = true)) "java.exe" else "java" private fun fail(code: String, message: String, cause: Throwable? = null): ExtensionServerException { mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Failed, activeConfig?.port, message) return ExtensionServerException(code, message, cause) } } internal fun desktopExtensionServerCommand(java: String, jar: File, port: Int, dataDir: File?): List = listOfNotNull( java, dataDir?.let { "-Duser.home=${it.absolutePath}" }, dataDir?.let { "-Djava.io.tmpdir=${File(it, "tmp").absolutePath}" }, "-jar", jar.absolutePath, port.toString(), )