|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package aws.sdk.kotlin.gradle.publishing |
| 7 | + |
| 8 | +import kotlinx.serialization.Serializable |
| 9 | +import kotlinx.serialization.json.Json |
| 10 | +import okhttp3.* |
| 11 | +import okhttp3.HttpUrl.Companion.toHttpUrl |
| 12 | +import okhttp3.MediaType.Companion.toMediaType |
| 13 | +import okhttp3.RequestBody.Companion.asRequestBody |
| 14 | +import okhttp3.RequestBody.Companion.toRequestBody |
| 15 | +import java.io.File |
| 16 | +import java.time.Duration |
| 17 | +import java.util.Base64 |
| 18 | +import kotlin.time.Clock |
| 19 | +import kotlin.time.ExperimentalTime |
| 20 | + |
| 21 | +/** |
| 22 | + * A client used for interacting with the Sonatype Publish Portal API |
| 23 | + * https://central.sonatype.org/publish/publish-portal-api/ |
| 24 | + */ |
| 25 | +class SonatypeCentralPortalClient( |
| 26 | + private val authHeader: String, |
| 27 | + private val client: OkHttpClient = OkHttpClient.Builder() |
| 28 | + .connectTimeout(Duration.ofSeconds(30)) |
| 29 | + .readTimeout(Duration.ofSeconds(60)) |
| 30 | + .writeTimeout(Duration.ofSeconds(60)) |
| 31 | + .retryOnConnectionFailure(true) |
| 32 | + .build(), |
| 33 | + private val json: Json = Json { |
| 34 | + ignoreUnknownKeys = true |
| 35 | + prettyPrint = true |
| 36 | + }, |
| 37 | +) { |
| 38 | + companion object { |
| 39 | + const val CENTRAL_PORTAL_USERNAME = "SONATYPE_CENTRAL_PORTAL_USERNAME" |
| 40 | + const val CENTRAL_PORTAL_PASSWORD = "SONATYPE_CENTRAL_PORTAL_PASSWORD" |
| 41 | + const val CENTRAL_PORTAL_BASE_URL = "https://central.sonatype.com" |
| 42 | + |
| 43 | + fun buildAuthHeader(user: String, password: String): String { |
| 44 | + val b64 = Base64.getEncoder().encodeToString("$user:$password".toByteArray(Charsets.UTF_8)) |
| 45 | + return "Bearer $b64" |
| 46 | + } |
| 47 | + |
| 48 | + fun fromEnvironment(): SonatypeCentralPortalClient { |
| 49 | + val user = System.getenv(CENTRAL_PORTAL_USERNAME)?.takeIf { it.isNotBlank() } ?: error("$CENTRAL_PORTAL_USERNAME not configured") |
| 50 | + val pass = System.getenv(CENTRAL_PORTAL_PASSWORD)?.takeIf { it.isNotBlank() } ?: error("$CENTRAL_PORTAL_PASSWORD not configured") |
| 51 | + return SonatypeCentralPortalClient(buildAuthHeader(user, pass)) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private val apiBase = CENTRAL_PORTAL_BASE_URL.toHttpUrl() |
| 56 | + |
| 57 | + @Serializable |
| 58 | + data class StatusResponse( |
| 59 | + val deploymentId: String, |
| 60 | + val deploymentName: String? = null, |
| 61 | + val deploymentState: String, |
| 62 | + val purls: List<String>? = null, |
| 63 | + val errors: Map<String, List<String>>? = null, |
| 64 | + ) |
| 65 | + |
| 66 | + /** Uploads a bundle and returns deploymentId. */ |
| 67 | + fun uploadBundle(bundle: File, deploymentName: String): String { |
| 68 | + require(bundle.isFile && bundle.length() > 0L) { "Bundle does not exist or is empty: $bundle" } |
| 69 | + |
| 70 | + val url = apiBase.newBuilder() |
| 71 | + .addPathSegments("api/v1/publisher/upload") |
| 72 | + .addQueryParameter("name", deploymentName) |
| 73 | + .addQueryParameter("publishingType", "AUTOMATIC") // set USER_MANAGED to upload the deployment, but not release it |
| 74 | + .build() |
| 75 | + |
| 76 | + val body = MultipartBody.Builder() |
| 77 | + .setType(MultipartBody.FORM) |
| 78 | + .addFormDataPart( |
| 79 | + "bundle", |
| 80 | + bundle.name, |
| 81 | + bundle.asRequestBody("application/octet-stream".toMediaType()), |
| 82 | + ) |
| 83 | + .build() |
| 84 | + |
| 85 | + val request = Request.Builder() |
| 86 | + .url(url) |
| 87 | + .header("Authorization", authHeader) |
| 88 | + .post(body) |
| 89 | + .build() |
| 90 | + |
| 91 | + client.newCall(request).execute().use { resp -> |
| 92 | + if (!resp.isSuccessful) throw httpError("upload", resp) |
| 93 | + val id = resp.body?.string()?.trim().orEmpty() |
| 94 | + if (resp.code != 201 || id.isEmpty()) { |
| 95 | + throw RuntimeException("Upload returned ${resp.code} but no deploymentId body; body=$id") |
| 96 | + } |
| 97 | + return id |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /** Returns current deployment status. */ |
| 102 | + fun getStatus(deploymentId: String): StatusResponse { |
| 103 | + val url = apiBase.newBuilder() |
| 104 | + .addPathSegments("api/v1/publisher/status") |
| 105 | + .addQueryParameter("id", deploymentId) |
| 106 | + .build() |
| 107 | + |
| 108 | + val request = Request.Builder() |
| 109 | + .url(url) |
| 110 | + .header("Authorization", authHeader) |
| 111 | + .post("".toRequestBody(null)) |
| 112 | + .build() |
| 113 | + |
| 114 | + client.newCall(request).execute().use { resp -> |
| 115 | + if (!resp.isSuccessful) throw httpError("status", resp) |
| 116 | + val payload = resp.body?.string().orEmpty() |
| 117 | + return try { |
| 118 | + json.decodeFromString<StatusResponse>(payload) |
| 119 | + } catch (e: Exception) { |
| 120 | + throw RuntimeException("Failed to parse status JSON (HTTP ${resp.code}): $payload", e) |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + /** Polls until one of [terminalStates] is reached, returning the final StatusResponse. */ |
| 126 | + @OptIn(ExperimentalTime::class) // for Clock.System.now() |
| 127 | + fun waitForStatus( |
| 128 | + deploymentId: String, |
| 129 | + terminalStates: Set<String>, |
| 130 | + pollInterval: kotlin.time.Duration, |
| 131 | + timeout: kotlin.time.Duration, |
| 132 | + onStateChange: (old: String?, new: String) -> Unit = { _, _ -> }, |
| 133 | + ): StatusResponse { |
| 134 | + val deadline = Clock.System.now() + timeout |
| 135 | + var lastState: String? = null |
| 136 | + |
| 137 | + while (Clock.System.now() < deadline) { |
| 138 | + val status = getStatus(deploymentId) |
| 139 | + if (status.deploymentState != lastState) { |
| 140 | + onStateChange(lastState, status.deploymentState) |
| 141 | + lastState = status.deploymentState |
| 142 | + } |
| 143 | + if (status.deploymentState in terminalStates) return status |
| 144 | + Thread.sleep(pollInterval.inWholeMilliseconds) |
| 145 | + } |
| 146 | + throw RuntimeException("Timed out waiting for deployment $deploymentId to reach one of $terminalStates") |
| 147 | + } |
| 148 | + |
| 149 | + private fun httpError(context: String, resp: Response): RuntimeException { |
| 150 | + val body = resp.body?.string().orEmpty() |
| 151 | + return RuntimeException("HTTP error during $context: ${resp.code}.\nResponse: $body") |
| 152 | + } |
| 153 | +} |
0 commit comments