BitbucketVcsProvider.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

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  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.

  Maintainers:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2025

  Contributors:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2025
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026
      Марат Ниязматов <mrusniyazmatov@sberbank.ru>, Sber - 2026
*/

package org.archtool.provider.bitbucket

import io.ktor.client.HttpClient
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.client.request.parameter
import io.ktor.http.HttpHeaders
import kotlinx.coroutines.withContext
import org.archtool.data.exception.ErrorCode
import org.archtool.data.exception.SeafException
import org.archtool.data.model.RepoInfoModel
import org.archtool.helper.VcsHttpClientFactory
import org.archtool.provider.FileRequest
import org.archtool.provider.RepoRef
import org.archtool.provider.VcsCredentials
import org.archtool.provider.VcsProvider
import org.archtool.provider.VcsApiUtils
import org.archtool.provider.VcsProviderType
import org.archtool.provider.bitbucket.dto.BitbucketPageDto
import org.archtool.provider.bitbucket.dto.RepoInfoDto
import org.archtool.provider.bitbucket.dto.RepoPermission
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.core.PropagationContextElement
import org.springframework.stereotype.Component

@Component
@ConditionalOnBitbucket
class BitbucketVcsProvider(
    private val properties: BitbucketProperties,
    private val vcsHttpClientFactory: VcsHttpClientFactory,
) : VcsProvider {

    private val log: Logger = LoggerFactory.getLogger(javaClass)

    init {
        if (properties.normalizedProjectKeys.isEmpty()) {
            log.info("Фильтр по проектам Bitbucket не задан, загружаются все доступные репозитории")
        } else {
            log.info(
                "Фильтр по проектам Bitbucket; исходное значение: {}, после нормализации: {}",
                properties.projectKeys,
                properties.normalizedProjectKeys,
            )
        }
    }

    private val httpClient: HttpClient = vcsHttpClientFactory.createClient(HttpHeaders.Authorization) {
        install(Auth) {
            bearer {
                loadTokens {
                    BearerTokens(properties.token, null)
                }
            }
        }
    }

    override fun parse(repoUrl: String): RepoRef {
        val (projectKey, repoSlug) = parseRepoUrl(repoUrl)
        return RepoRef(localPath = localPath(projectKey, repoSlug))
    }

    override fun tempBranchSuffix(repoUrl: String): String = parseRepoUrl(repoUrl).second

    override fun parseFileRequest(project: String?, repo: String, branch: String): FileRequest {
        val projectKey = project?.takeIf { it.isNotBlank() }
            ?: throw SeafException(ErrorCode.BAD_REQUEST, "Для Bitbucket параметр project обязателен")
        return FileRequest(
            repoRef = parse("${BitbucketLinkPatterns.REPO_PREFIX}:$projectKey:$repo"),
            branch = branch,
        )
    }

    override suspend fun listRepositories(): List<RepoInfoModel> {
        val projectKeys = properties.normalizedProjectKeys
        if (projectKeys.isEmpty()) {
            return fetchRepos(null)
        }
        return projectKeys.flatMap { projectKey ->
            fetchRepos(projectKey).also {
                if (it.isEmpty()) {
                    log.warn("Проект Bitbucket {} из фильтра не вернул ни одного репозитория", projectKey)
                }
            }
        }
    }

    override fun credentials(): VcsCredentials = VcsCredentials(
        username = properties.user,
        password = properties.token,
    )

    override fun defaultBranch(): String = properties.defaultBranch

    /**
     * Загружает репозитории с правом `REPO_READ`; при заданном [projectKey] — только репозитории этого проекта.
     */
    private suspend fun fetchRepos(projectKey: String?): List<RepoInfoModel> {
        val url = properties.reposUrl
        val repositories = mutableListOf<RepoInfoModel>()
        forAllPages { start ->
            log.debug(
                "Запрос репозиториев {}, проект {}, start {}, limit {}",
                url,
                projectKey,
                start,
                properties.pageSize,
            )
            val page = withContext(PropagationContextElement()) {
                vcsHttpClientFactory.execute(httpClient) { client ->
                    val response = client.get(url) {
                        parameter("start", start)
                        parameter("limit", properties.pageSize)
                        parameter("permission", RepoPermission.REPO_READ)
                        projectKey?.let { parameter(PROJECT_KEY_PARAMETER, it) }
                    }
                    VcsApiUtils.requireSuccess(response, VcsProviderType.BITBUCKET, url)
                    response.body<BitbucketPageDto<RepoInfoDto>>()
                }
            }
            val repos = page.values
                .filter { belongsToProject(it, projectKey) }
                .map { mapRepo(it) }
            repositories.addAll(repos)
            page
        }
        return repositories
    }

    // Страховка на случай, когда Bitbucket игнорирует параметр projectkey (версия ниже 8.0 при отключённой
    // проверке версии или ошибка Bitbucket) и возвращает репозитории других проектов.
    private fun belongsToProject(repo: RepoInfoDto, projectKey: String?): Boolean {
        if (projectKey == null || repo.project.key.equals(projectKey, ignoreCase = true)) {
            return true
        }
        log.warn(
            "Репозиторий {} проекта {} пропущен: не соответствует запрошенному проекту {}",
            repo.slug,
            repo.project.key,
            projectKey,
        )
        return false
    }

    private fun mapRepo(repo: RepoInfoDto) = RepoInfoModel(
        localPath = localPath(repo.project.key, repo.slug),
        name = repo.name,
        description = repo.description,
        cloneLink = repo.links["clone"]?.find { it.name == "http" }?.href ?: "",
        webLink = repo.links["self"]?.firstOrNull()?.href ?: "",
    )

    private suspend inline fun <reified T> forAllPages(block: suspend (start: Int) -> BitbucketPageDto<T>) {
        var start = 0
        do {
            val page = block(start)
            start = page.start + page.limit
        } while (!page.isLastPage)
    }

    private fun localPath(projectKey: String, repoSlug: String) =
        "${projectKey.uppercase()}/${repoSlug.lowercase()}"

    private fun parseRepoUrl(repoUrl: String): Pair<String, String> {
        val match = BitbucketLinkPatterns.REPO_REGEX.matchEntire(repoUrl)
            ?: throw SeafException(ErrorCode.BAD_REQUEST, "$INVALID_REPO_URL_MESSAGE: $repoUrl")
        val (projectKey, repoSlug) = match.destructured
        // Slug из одних точек (`.`, `..`) проходит REPO_URL_REGEX, но в пути ссылается на текущий
        // или родительский каталог. Такого запроса быть не должно, поэтому отказ логируем.
        if (repoSlug.matches(DOTS_ONLY_REGEX)) {
            log.warn(
                "Отклонён slug Bitbucket из одних точек: {}; ссылка: {}",
                repoSlug,
                repoUrl,
            )
            throw SeafException(ErrorCode.BAD_REQUEST, "$INVALID_REPO_URL_MESSAGE: $repoUrl")
        }
        return projectKey to repoSlug
    }

    companion object {
        private const val INVALID_REPO_URL_MESSAGE = "Неверный формат ссылки Bitbucket"
        private const val PROJECT_KEY_PARAMETER = "projectkey"
        private val DOTS_ONLY_REGEX = "\\.+".toRegex()
    }
}