in build.gradle.kts [254:348]
fun waitForUploadToSucceed(
uriBase: String,
deploymentId: String,
isUserManaged: Boolean,
userName: String,
accessToken: String,
maxTimeout: Duration,
minTimeBetweenAttempts: Duration
) {
val uri = uriBase.trimEnd('/') + "/api/v1/publisher/status?id=$deploymentId"
val base64Auth = base64Auth(userName, accessToken)
var timeSpent = Duration.ZERO
var attemptNumber = 1
var terminatingState = false
println("Polling for deployment status for $maxTimeout: $uri")
while (timeSpent < maxTimeout) {
val remainingTime = maxTimeout - timeSpent
println("Polling attempt ${attemptNumber++}, remaining time ${remainingTime}.")
val client = OkHttpClient().newBuilder()
.callTimeout(remainingTime.toJavaDuration())
.build()
val beforeMs = System.currentTimeMillis()
try {
val request = Request.Builder()
.url(uri)
.header("Authorization", "Bearer $base64Auth")
.post("".toRequestBody())
.build()
val response = client.newCall(request).execute()
val code = response.code
if (code != 200) {
error("Response code $code: ${response.body?.string()}")
}
val jsonResult = JsonSlurper().parse(response.body?.bytes() ?: error("Empty response body.")) as Map<*, *>
val state = jsonResult["deploymentState"]
println("Current state: $state.")
when(state) {
"PENDING", "VALIDATING", "PUBLISHING" -> {}
"VALIDATED" -> {
terminatingState = true
if (isUserManaged) {
println("Validated successfully.")
return
}
error("State error: deployment is not user managed, but signals it requires a UI interaction.")
}
"PUBLISHED" -> {
terminatingState = true
if (!isUserManaged) {
println("Published successfully.")
return
}
error("State error: deployment is user managed, but signals it has been published.")
}
"FAILED" -> {
terminatingState = true
// The documentation provides no type information for the errors field, so we have to treat
// them as opaque.
val errors = jsonResult["errors"]
val errorsAsString = JsonBuilder(errors).toPrettyString()
error("Deployment failed. Errors: $errorsAsString")
}
else -> logger.warn("Unknown deployment state: $state")
}
} catch (e: Exception) {
if (terminatingState) {
throw e
}
logger.warn("Error during HTTP request: ${e.message}")
} finally {
val afterMs = System.currentTimeMillis()
var attemptTime = (afterMs - beforeMs).coerceAtLeast(0L).milliseconds
if (attemptTime < minTimeBetweenAttempts) {
val sleepTime = minTimeBetweenAttempts - attemptTime
Thread.sleep(sleepTime.inWholeMilliseconds)
attemptTime = minTimeBetweenAttempts
}
timeSpent += attemptTime
}
}
}