|
| 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 software.aws.toolkits.core.utils.deleteIfExists |
| 8 | +import software.aws.toolkits.core.utils.error |
| 9 | +import software.aws.toolkits.core.utils.exists |
| 10 | +import software.aws.toolkits.core.utils.getLogger |
| 11 | +import software.aws.toolkits.core.utils.info |
| 12 | +import software.aws.toolkits.core.utils.warn |
| 13 | +import software.aws.toolkits.jetbrains.core.saveFileFromUrl |
| 14 | +import software.aws.toolkits.jetbrains.services.amazonq.project.manifest.ManifestManager |
| 15 | +import java.nio.file.Path |
| 16 | +import java.util.concurrent.atomic.AtomicInteger |
| 17 | + |
| 18 | +class ArtifactHelper(private val lspArtifactsPath: Path = DEFAULT_ARTIFACT_PATH) { |
| 19 | + |
| 20 | + companion object { |
| 21 | + private val DEFAULT_ARTIFACT_PATH = getToolkitsCommonCacheRoot().resolve("aws").resolve("toolkits").resolve("language-servers") |
| 22 | + private val logger = getLogger<ArtifactHelper>() |
| 23 | + private const val MAX_DOWNLOAD_ATTEMPTS = 3 |
| 24 | + private val currentAttempt = AtomicInteger(0) |
| 25 | + } |
| 26 | + |
| 27 | + fun removeDeListedVersions(deListedVersions: List<ManifestManager.Version>) { |
| 28 | + val localFolders: List<Path> = getSubFolders(lspArtifactsPath) |
| 29 | + |
| 30 | + deListedVersions.forEach { deListedVersion -> |
| 31 | + val versionToDelete = deListedVersion.serverVersion ?: return |
| 32 | + |
| 33 | + localFolders |
| 34 | + .filter { folder -> folder.fileName.toString() == versionToDelete } |
| 35 | + .forEach { folder -> |
| 36 | + try { |
| 37 | + folder.toFile().deleteRecursively() |
| 38 | + logger.info { "Successfully deleted deListed version: ${folder.fileName}" } |
| 39 | + } catch (e: Exception) { |
| 40 | + logger.error(e) { "Failed to delete deListed version ${folder.fileName}: ${e.message}" } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + fun getExistingLSPArtifacts(versions: List<ManifestManager.Version>, target: ManifestManager.VersionTarget?): Boolean { |
| 47 | + if (versions.isEmpty() || target?.contents == null) return false |
| 48 | + |
| 49 | + val localLSPPath = lspArtifactsPath.resolve(versions.first().serverVersion.toString()) |
| 50 | + if (!localLSPPath.exists()) return false |
| 51 | + |
| 52 | + val hasInvalidFiles = target.contents.any { content -> |
| 53 | + content.filename?.let { filename -> |
| 54 | + val filePath = localLSPPath.resolve(filename) |
| 55 | + !filePath.exists() || generateMD5Hash(filePath) != content.hashes?.firstOrNull() |
| 56 | + } ?: false |
| 57 | + } |
| 58 | + |
| 59 | + if (hasInvalidFiles) { |
| 60 | + try { |
| 61 | + localLSPPath.toFile().deleteRecursively() |
| 62 | + logger.info { "Deleted mismatched LSP artifacts at: $localLSPPath" } |
| 63 | + } catch (e: Exception) { |
| 64 | + logger.error(e) { "Failed to delete mismatched LSP artifacts at: $localLSPPath" } |
| 65 | + } |
| 66 | + } |
| 67 | + return hasInvalidFiles |
| 68 | + } |
| 69 | + |
| 70 | + fun tryDownloadLspArtifacts(versions: List<ManifestManager.Version>, target: ManifestManager.VersionTarget?) { |
| 71 | + val temporaryDownloadPath = lspArtifactsPath.resolve("temp") |
| 72 | + val downloadPath = lspArtifactsPath.resolve(versions.first().serverVersion.toString()) |
| 73 | + |
| 74 | + while (currentAttempt.get() < MAX_DOWNLOAD_ATTEMPTS) { |
| 75 | + currentAttempt.incrementAndGet() |
| 76 | + logger.info { "Attempt ${currentAttempt.get()} of $MAX_DOWNLOAD_ATTEMPTS to download LSP artifacts" } |
| 77 | + |
| 78 | + try { |
| 79 | + if (downloadLspArtifacts(temporaryDownloadPath, target)) { |
| 80 | + moveFilesFromSourceToDestination(temporaryDownloadPath, downloadPath) |
| 81 | + logger.info { "Successfully downloaded and moved LSP artifacts to $downloadPath" } |
| 82 | + return |
| 83 | + } |
| 84 | + } catch (e: Exception) { |
| 85 | + logger.error(e) { "Failed to download/move LSP artifacts on attempt ${currentAttempt.get()}" } |
| 86 | + temporaryDownloadPath.toFile().deleteRecursively() |
| 87 | + |
| 88 | + if (currentAttempt.get() >= MAX_DOWNLOAD_ATTEMPTS) { |
| 89 | + throw LspException("Failed to download LSP artifacts after $MAX_DOWNLOAD_ATTEMPTS attempts", LspException.ErrorCode.DOWNLOAD_FAILED) |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private fun downloadLspArtifacts(downloadPath: Path, target: ManifestManager.VersionTarget?): Boolean { |
| 96 | + if (target == null || target.contents.isNullOrEmpty()) { |
| 97 | + logger.warn { "No target contents available for download" } |
| 98 | + return false |
| 99 | + } |
| 100 | + try { |
| 101 | + downloadPath.createDirectories() |
| 102 | + target.contents.forEach { content -> |
| 103 | + if (content.url == null || content.filename == null) { |
| 104 | + logger.warn { "Missing URL or filename in content" } |
| 105 | + return@forEach |
| 106 | + } |
| 107 | + val filePath = downloadPath.resolve(content.filename) |
| 108 | + val contentHash = content.hashes?.firstOrNull() ?: run { |
| 109 | + logger.warn { "No hash available for ${content.filename}" } |
| 110 | + return@forEach |
| 111 | + } |
| 112 | + downloadAndValidateFile(content.url, filePath, contentHash) |
| 113 | + } |
| 114 | + validateDownloadedFiles(downloadPath, target.contents) |
| 115 | + } catch (e: Exception) { |
| 116 | + logger.error(e) { "Failed to download LSP artifacts: ${e.message}" } |
| 117 | + downloadPath.toFile().deleteRecursively() |
| 118 | + return false |
| 119 | + } |
| 120 | + return true |
| 121 | + } |
| 122 | + |
| 123 | + private fun downloadAndValidateFile(url: String, filePath: Path, expectedHash: String) { |
| 124 | + try { |
| 125 | + if (!filePath.exists()) { |
| 126 | + logger.info { "Downloading file: ${filePath.fileName}" } |
| 127 | + saveFileFromUrl(url, filePath) |
| 128 | + } |
| 129 | + if (!validateFileHash(filePath, expectedHash)) { |
| 130 | + logger.warn { "Hash mismatch for ${filePath.fileName}, re-downloading" } |
| 131 | + filePath.deleteIfExists() |
| 132 | + saveFileFromUrl(url, filePath) |
| 133 | + if (!validateFileHash(filePath, expectedHash)) { |
| 134 | + throw LspException("Hash mismatch after re-download for ${filePath.fileName}", LspException.ErrorCode.HASH_MISMATCH) |
| 135 | + } |
| 136 | + } |
| 137 | + } catch (e: Exception) { |
| 138 | + throw IllegalStateException("Failed to download/validate file: ${filePath.fileName}", e) |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private fun validateFileHash(filePath: Path, expectedHash: String): Boolean = generateMD5Hash(filePath) == expectedHash |
| 143 | + |
| 144 | + private fun validateDownloadedFiles(downloadPath: Path, contents: List<ManifestManager.TargetContent>) { |
| 145 | + val missingFiles = contents |
| 146 | + .mapNotNull { it.filename } |
| 147 | + .filter { filename -> |
| 148 | + !downloadPath.resolve(filename).exists() |
| 149 | + } |
| 150 | + if (missingFiles.isNotEmpty()) { |
| 151 | + val errorMessage = "Missing required files: ${missingFiles.joinToString(", ")}" |
| 152 | + logger.error { errorMessage } |
| 153 | + throw LspException(errorMessage, LspException.ErrorCode.DOWNLOAD_FAILED) |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments