|
| 1 | +// Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package software.aws.toolkits.jetbrains.services.amazonq.lsp.artifacts |
| 5 | + |
| 6 | +import com.intellij.util.io.createDirectories |
| 7 | +import com.intellij.util.text.SemVer |
| 8 | +import software.aws.toolkits.core.utils.deleteIfExists |
| 9 | +import software.aws.toolkits.core.utils.error |
| 10 | +import software.aws.toolkits.core.utils.exists |
| 11 | +import software.aws.toolkits.core.utils.getLogger |
| 12 | +import software.aws.toolkits.core.utils.info |
| 13 | +import software.aws.toolkits.core.utils.warn |
| 14 | +import software.aws.toolkits.jetbrains.core.saveFileFromUrl |
| 15 | +import software.aws.toolkits.jetbrains.services.amazonq.project.manifest.ManifestManager |
| 16 | +import java.nio.file.Path |
| 17 | +import java.util.concurrent.atomic.AtomicInteger |
| 18 | + |
| 19 | +class ArtifactHelper(private val lspArtifactsPath: Path = DEFAULT_ARTIFACT_PATH, private val maxDownloadAttempts: Int = MAX_DOWNLOAD_ATTEMPTS) { |
| 20 | + |
| 21 | + companion object { |
| 22 | + private val DEFAULT_ARTIFACT_PATH = getToolkitsCommonCacheRoot().resolve("aws").resolve("toolkits").resolve("language-servers") |
| 23 | + private val logger = getLogger<ArtifactHelper>() |
| 24 | + private const val MAX_DOWNLOAD_ATTEMPTS = 3 |
| 25 | + } |
| 26 | + private val currentAttempt = AtomicInteger(0) |
| 27 | + |
| 28 | + fun removeDelistedVersions(delistedVersions: List<ManifestManager.Version>) { |
| 29 | + val localFolders = getSubFolders(lspArtifactsPath) |
| 30 | + |
| 31 | + delistedVersions.forEach { delistedVersion -> |
| 32 | + val versionToDelete = delistedVersion.serverVersion ?: return@forEach |
| 33 | + |
| 34 | + localFolders |
| 35 | + .filter { folder -> folder.fileName.toString() == versionToDelete } |
| 36 | + .forEach { folder -> |
| 37 | + try { |
| 38 | + folder.toFile().deleteRecursively() |
| 39 | + logger.info { "Successfully deleted deListed version: ${folder.fileName}" } |
| 40 | + } catch (e: Exception) { |
| 41 | + logger.error(e) { "Failed to delete deListed version ${folder.fileName}: ${e.message}" } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + fun deleteOlderLspArtifacts(manifestVersionRanges: ArtifactManager.SupportedManifestVersionRange) { |
| 48 | + val localFolders = getSubFolders(lspArtifactsPath) |
| 49 | + |
| 50 | + val validVersions = localFolders |
| 51 | + .mapNotNull { localFolder -> |
| 52 | + SemVer.parseFromText(localFolder.fileName.toString())?.let { semVer -> |
| 53 | + if (semVer in manifestVersionRanges.startVersion..manifestVersionRanges.endVersion) { |
| 54 | + localFolder to semVer |
| 55 | + } else { |
| 56 | + null |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + .sortedByDescending { (_, semVer) -> semVer } |
| 61 | + |
| 62 | + // Keep the latest 2 versions, delete others |
| 63 | + validVersions.drop(2).forEach { (folder, _) -> |
| 64 | + try { |
| 65 | + folder.toFile().deleteRecursively() |
| 66 | + logger.info { "Deleted older LSP artifact: ${folder.fileName}" } |
| 67 | + } catch (e: Exception) { |
| 68 | + logger.error(e) { "Failed to delete older LSP artifact: ${folder.fileName}" } |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + fun getExistingLspArtifacts(versions: List<ManifestManager.Version>, target: ManifestManager.VersionTarget?): Boolean { |
| 74 | + if (versions.isEmpty() || target?.contents == null) return false |
| 75 | + |
| 76 | + val localLSPPath = lspArtifactsPath.resolve(versions.first().serverVersion.toString()) |
| 77 | + if (!localLSPPath.exists()) return false |
| 78 | + |
| 79 | + val hasInvalidFiles = target.contents.any { content -> |
| 80 | + content.filename?.let { filename -> |
| 81 | + val filePath = localLSPPath.resolve(filename) |
| 82 | + !filePath.exists() || !validateFileHash(filePath, content.hashes?.firstOrNull()) |
| 83 | + } ?: false |
| 84 | + } |
| 85 | + |
| 86 | + if (hasInvalidFiles) { |
| 87 | + try { |
| 88 | + localLSPPath.toFile().deleteRecursively() |
| 89 | + logger.info { "Deleted mismatched LSP artifacts at: $localLSPPath" } |
| 90 | + } catch (e: Exception) { |
| 91 | + logger.error(e) { "Failed to delete mismatched LSP artifacts at: $localLSPPath" } |
| 92 | + } |
| 93 | + } |
| 94 | + return !hasInvalidFiles |
| 95 | + } |
| 96 | + |
| 97 | + fun tryDownloadLspArtifacts(versions: List<ManifestManager.Version>, target: ManifestManager.VersionTarget?) { |
| 98 | + val temporaryDownloadPath = lspArtifactsPath.resolve("temp") |
| 99 | + val downloadPath = lspArtifactsPath.resolve(versions.first().serverVersion.toString()) |
| 100 | + |
| 101 | + while (currentAttempt.get() < maxDownloadAttempts) { |
| 102 | + currentAttempt.incrementAndGet() |
| 103 | + logger.info { "Attempt ${currentAttempt.get()} of $maxDownloadAttempts to download LSP artifacts" } |
| 104 | + |
| 105 | + try { |
| 106 | + if (downloadLspArtifacts(temporaryDownloadPath, target)) { |
| 107 | + moveFilesFromSourceToDestination(temporaryDownloadPath, downloadPath) |
| 108 | + logger.info { "Successfully downloaded and moved LSP artifacts to $downloadPath" } |
| 109 | + return |
| 110 | + } |
| 111 | + } catch (e: Exception) { |
| 112 | + logger.error(e) { "Failed to download/move LSP artifacts on attempt ${currentAttempt.get()}" } |
| 113 | + temporaryDownloadPath.toFile().deleteRecursively() |
| 114 | + |
| 115 | + if (currentAttempt.get() >= maxDownloadAttempts) { |
| 116 | + throw LspException("Failed to download LSP artifacts after $maxDownloadAttempts attempts", LspException.ErrorCode.DOWNLOAD_FAILED) |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private fun downloadLspArtifacts(downloadPath: Path, target: ManifestManager.VersionTarget?): Boolean { |
| 123 | + if (target == null || target.contents.isNullOrEmpty()) { |
| 124 | + logger.warn { "No target contents available for download" } |
| 125 | + return false |
| 126 | + } |
| 127 | + try { |
| 128 | + downloadPath.createDirectories() |
| 129 | + target.contents.forEach { content -> |
| 130 | + if (content.url == null || content.filename == null) { |
| 131 | + logger.warn { "Missing URL or filename in content" } |
| 132 | + return@forEach |
| 133 | + } |
| 134 | + val filePath = downloadPath.resolve(content.filename) |
| 135 | + val contentHash = content.hashes?.firstOrNull() ?: run { |
| 136 | + logger.warn { "No hash available for ${content.filename}" } |
| 137 | + return@forEach |
| 138 | + } |
| 139 | + downloadAndValidateFile(content.url, filePath, contentHash) |
| 140 | + } |
| 141 | + validateDownloadedFiles(downloadPath, target.contents) |
| 142 | + } catch (e: Exception) { |
| 143 | + logger.error(e) { "Failed to download LSP artifacts: ${e.message}" } |
| 144 | + downloadPath.toFile().deleteRecursively() |
| 145 | + return false |
| 146 | + } |
| 147 | + return true |
| 148 | + } |
| 149 | + |
| 150 | + private fun downloadAndValidateFile(url: String, filePath: Path, expectedHash: String) { |
| 151 | + try { |
| 152 | + if (!filePath.exists()) { |
| 153 | + logger.info { "Downloading file: ${filePath.fileName}" } |
| 154 | + saveFileFromUrl(url, filePath) |
| 155 | + } |
| 156 | + if (!validateFileHash(filePath, expectedHash)) { |
| 157 | + logger.warn { "Hash mismatch for ${filePath.fileName}, re-downloading" } |
| 158 | + filePath.deleteIfExists() |
| 159 | + saveFileFromUrl(url, filePath) |
| 160 | + if (!validateFileHash(filePath, expectedHash)) { |
| 161 | + throw LspException("Hash mismatch after re-download for ${filePath.fileName}", LspException.ErrorCode.HASH_MISMATCH) |
| 162 | + } |
| 163 | + } |
| 164 | + } catch (e: Exception) { |
| 165 | + throw IllegalStateException("Failed to download/validate file: ${filePath.fileName}", e) |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + private fun validateFileHash(filePath: Path, expectedHash: String?): Boolean { |
| 170 | + if (expectedHash == null) return false |
| 171 | + val contentHash = generateSHA384Hash(filePath) |
| 172 | + return "sha384:$contentHash" == expectedHash |
| 173 | + } |
| 174 | + |
| 175 | + private fun validateDownloadedFiles(downloadPath: Path, contents: List<ManifestManager.TargetContent>) { |
| 176 | + val missingFiles = contents |
| 177 | + .mapNotNull { it.filename } |
| 178 | + .filter { filename -> |
| 179 | + !downloadPath.resolve(filename).exists() |
| 180 | + } |
| 181 | + if (missingFiles.isNotEmpty()) { |
| 182 | + val errorMessage = "Missing required files: ${missingFiles.joinToString(", ")}" |
| 183 | + logger.error { errorMessage } |
| 184 | + throw LspException(errorMessage, LspException.ErrorCode.DOWNLOAD_FAILED) |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments