BitbucketVersionChecker.kt

/*
  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package org.archtool.provider.bitbucket

import io.ktor.client.call.body
import io.ktor.client.plugins.auth.Auth
import io.ktor.client.plugins.auth.providers.BearerTokens
import io.ktor.client.plugins.auth.providers.bearer
import io.ktor.client.request.get
import io.ktor.http.HttpHeaders
import jakarta.annotation.PostConstruct
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.runBlocking
import org.archtool.helper.VcsHttpClientFactory
import org.archtool.provider.VcsApiUtils
import org.archtool.provider.VcsProviderType
import org.archtool.provider.bitbucket.dto.ApplicationPropertiesDto
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

/**
 * Проверяет при старте, что версия Bitbucket не ниже [MIN_MAJOR_VERSION]: с этой версии поддерживается
 * параметр `projectkey` запроса репозиториев. Неподдерживаемая или неопределённая версия останавливает запуск.
 */
@Component
@ConditionalOnBitbucket
class BitbucketVersionChecker(
    private val properties: BitbucketProperties,
    private val vcsHttpClientFactory: VcsHttpClientFactory,
) {
    @PostConstruct
    fun check() {
        if (!properties.versionCheckEnabled) {
            log.warn(
                "Проверка версии Bitbucket отключена ({}=false); корректная работа гарантируется только с Bitbucket {}.0+",
                VERSION_CHECK_PROPERTY,
                MIN_MAJOR_VERSION,
            )
            return
        }
        val version = runBlocking { fetchVersion() }
        val majorVersion = version?.substringBefore('.')?.toIntOrNull()
            ?: throw IllegalStateException(failureMessage("не удалось определить версию Bitbucket из ответа: $version"))
        if (majorVersion < MIN_MAJOR_VERSION) {
            throw IllegalStateException(
                failureMessage("версия Bitbucket $version не поддерживается, требуется $MIN_MAJOR_VERSION.0+"),
            )
        }
        log.info("Версия Bitbucket {} поддерживается", version)
    }

    private suspend fun fetchVersion(): String? {
        val url = properties.applicationPropertiesUrl
        val httpClient = vcsHttpClientFactory.createClient(HttpHeaders.Authorization) {
            install(Auth) {
                bearer {
                    loadTokens {
                        BearerTokens(properties.token, null)
                    }
                }
            }
        }
        return try {
            vcsHttpClientFactory.execute(httpClient) { client ->
                val response = client.get(url)
                VcsApiUtils.requireSuccess(response, VcsProviderType.BITBUCKET, url)
                response.body<ApplicationPropertiesDto>().version
            }
        } catch (e: CancellationException) {
            throw e
        } catch (e: Exception) {
            throw IllegalStateException(failureMessage("не удалось запросить версию Bitbucket ($url): ${e.message}"), e)
        } finally {
            vcsHttpClientFactory.closeClient(httpClient)
        }
    }

    private fun failureMessage(reason: String) =
        "Проверка версии Bitbucket не пройдена: $reason. Отключить проверку: $VERSION_CHECK_PROPERTY=false"

    companion object {
        private const val MIN_MAJOR_VERSION = 8
        private const val VERSION_CHECK_PROPERTY = "seaf.vcs.bitbucket.version-check-enabled"
        private val log: Logger = LoggerFactory.getLogger(BitbucketVersionChecker::class.java)
    }
}