IosExtensionServerInstaller.kt
vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstaller.kt
1@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)23package eu.friedcutlet.yokan.ext45import io.ktor.client.HttpClient6import io.ktor.client.engine.darwin.Darwin7import io.ktor.client.request.prepareGet8import io.ktor.client.statement.bodyAsChannel9import io.ktor.http.isSuccess10import io.ktor.utils.io.readAvailable11import okio.Buffer12import okio.FileSystem13import okio.HashingSource14import okio.Path15import okio.Path.Companion.toPath16import okio.buffer17import okio.openZip18import platform.Foundation.NSURL1920/** Installs only the architecture-independent server JAR; iOS JVM binaries stay build-provisioned. */21class IosExtensionServerInstaller private constructor(22 installRoot: String,23 private val bundledJvmPath: String,24 private val fileSystem: FileSystem,25 private val archiveDownloader: (suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit)?,26 private val trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String,27) {28 constructor(29 installRoot: String,30 bundledJvmPath: String,31 ) : this(32 installRoot = installRoot,33 bundledJvmPath = bundledJvmPath,34 fileSystem = FileSystem.SYSTEM,35 archiveDownloader = null,36 trustedDigest = { release, asset -> release.trustedSha256(asset) },37 )3839 private val installRoot = installRoot.toPath(normalize = true)4041 suspend fun install(42 release: ExtensionServerRelease,43 asset: ExtensionServerReleaseAsset,44 onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },45 ): InstalledExtensionServerBundle {46 if (!asset.name.endsWith(".zip", ignoreCase = true)) {47 throw ExtensionServerException("UNSUPPORTED_ARCHIVE", "Only ZIP bundles are supported")48 }49 val expectedDigest = trustedDigest(release, asset)50 fileSystem.createDirectories(installRoot)51 val archive = installRoot / ".download-${release.version}.zip"52 val staging = installRoot / ".install-${release.version}"53 val destination = installRoot / release.version54 try {55 fileSystem.delete(archive, mustExist = false)56 fileSystem.deleteRecursively(staging, mustExist = false)57 download(asset, archive, onProgress)58 verifyIosExtensionServerArchiveSha256(fileSystem, archive, expectedDigest)59 fileSystem.createDirectories(staging)60 extractIosExtensionServerJar(fileSystem, archive, staging)61 fileSystem.deleteRecursively(destination, mustExist = false)62 fileSystem.atomicMove(staging, destination)63 return resolveBundle(destination, release.version)64 } finally {65 fileSystem.delete(archive, mustExist = false)66 fileSystem.deleteRecursively(staging, mustExist = false)67 }68 }6970 fun importJar(sourcePath: String): InstalledExtensionServerBundle {71 val source = sourcePath.removePrefix("file://").toPath(normalize = true)72 if (source.name.substringAfterLast('.', "").lowercase() != "jar" || fileSystem.metadataOrNull(source) == null) {73 throw ExtensionServerException("MISSING_JAR", "Selected extension server JAR does not exist: $source")74 }75 val destinationDirectory = installRoot / "manual"76 val destination = destinationDirectory / source.name77 val staging = destinationDirectory / ".${source.name}.import"78 fileSystem.createDirectories(destinationDirectory)79 fileSystem.delete(staging, mustExist = false)80 try {81 copy(source, staging)82 fileSystem.delete(destination, mustExist = false)83 fileSystem.atomicMove(staging, destination)84 } finally {85 fileSystem.delete(staging, mustExist = false)86 }87 return InstalledExtensionServerBundle(88 version = versionFromPath(destination),89 rootPath = destinationDirectory.toString(),90 jvmPath = bundledJvmPath,91 serverJarPath = destination.toString(),92 )93 }9495 private suspend fun download(96 asset: ExtensionServerReleaseAsset,97 target: Path,98 onProgress: (Long, Long) -> Unit,99 ) {100 archiveDownloader?.let { downloader ->101 downloader(asset, target, onProgress)102 return103 }104 NSURL.URLWithString(asset.downloadUrl)105 ?: throw ExtensionServerException("INVALID_DOWNLOAD_URL", "Invalid bundle URL: ${asset.downloadUrl}")106 val client = HttpClient(Darwin)107 try {108 client.prepareGet(asset.downloadUrl).execute { response ->109 if (!response.status.isSuccess()) {110 throw ExtensionServerException(111 "DOWNLOAD_HTTP_ERROR",112 "Bundle download failed with HTTP ${response.status.value}",113 )114 }115 val channel = response.bodyAsChannel()116 val expected = response.headers["Content-Length"]?.toLongOrNull() ?: asset.size117 val output = fileSystem.sink(target).buffer()118 val buffer = ByteArray(8_192)119 var downloaded = 0L120 try {121 while (true) {122 val count = channel.readAvailable(buffer)123 if (count < 0) break124 if (count == 0) continue125 output.write(buffer, 0, count)126 downloaded += count127 onProgress(downloaded, expected)128 }129 } finally {130 output.close()131 }132 }133 } finally {134 client.close()135 }136 }137138139 private fun resolveBundle(directory: Path, version: String): InstalledExtensionServerBundle {140 val jar = fileSystem.listRecursively(directory)141 .firstOrNull { path ->142 val name = path.name.lowercase()143 name.endsWith(".jar") && "extensionserver" in name && fileSystem.metadata(path).isRegularFile144 }145 ?: throw ExtensionServerException("BUNDLE_INVALID", "Installed bundle has no extension server JAR")146 return InstalledExtensionServerBundle(147 version = version,148 rootPath = directory.toString(),149 jvmPath = bundledJvmPath,150 serverJarPath = jar.toString(),151 )152 }153154 private fun copy(source: Path, destination: Path) = copy(fileSystem, source, destination)155156 private fun copy(sourceFileSystem: FileSystem, source: Path, destination: Path) {157 val input = sourceFileSystem.source(source).buffer()158 val output = fileSystem.sink(destination).buffer()159 try {160 output.writeAll(input)161 } finally {162 output.close()163 input.close()164 }165 }166167 companion object {168 internal fun createForTesting(169 installRoot: String,170 bundledJvmPath: String,171 fileSystem: FileSystem,172 archiveDownloader: suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit,173 trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String,174 ): IosExtensionServerInstaller = IosExtensionServerInstaller(175 installRoot = installRoot,176 bundledJvmPath = bundledJvmPath,177 fileSystem = fileSystem,178 archiveDownloader = archiveDownloader,179 trustedDigest = trustedDigest,180 )181 }182183 private fun versionFromPath(path: Path): String =184 Regex("""v?(\d+\.\d+\.\d+)""").find(path.name)?.groupValues?.getOrNull(1) ?: "manual"185}186187internal fun verifyIosExtensionServerArchiveSha256(188 fileSystem: FileSystem,189 path: Path,190 expected: String?,191) {192 if (expected == null) {193 throw ExtensionServerException("MISSING_DIGEST", "Release asset has no trusted SHA-256 digest")194 }195 val hashingSource = HashingSource.sha256(fileSystem.source(path))196 val buffer = Buffer()197 try {198 while (hashingSource.read(buffer, 8_192) != -1L) buffer.clear()199 } finally {200 hashingSource.close()201 }202 val actual = hashingSource.hash.hex()203 if (!actual.equals(expected, ignoreCase = true)) {204 throw ExtensionServerException(205 "CHECKSUM_MISMATCH",206 "Bundle checksum mismatch: expected $expected, received $actual",207 )208 }209}210211internal fun extractIosExtensionServerJar(212 fileSystem: FileSystem,213 archive: Path,214 destination: Path,215): Path {216 val zip = fileSystem.openZip(archive)217 val jar = zip.listRecursively("/".toPath())218 .firstOrNull { path ->219 val name = path.name.lowercase()220 name.endsWith(".jar") && "extensionserver" in name && zip.metadata(path).isRegularFile221 }222 ?: throw ExtensionServerException("BUNDLE_INVALID", "Downloaded bundle has no extension server JAR")223 val extracted = destination / jar.name224 val input = zip.source(jar).buffer()225 val output = fileSystem.sink(extracted).buffer()226 try {227 output.writeAll(input)228 } finally {229 output.close()230 input.close()231 }232 return extracted233}234