GasOrgInfoLoader.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.helper

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.http.appendPathSegments
import org.archtool.configuration.ServiceProperties
import org.archtool.data.model.OrgInfoModel
import org.archtool.data.yaml.OrgInfoYaml
import org.archtool.vcs.provider.OrgAccessPath
import org.archtool.vcs.provider.VcsRepoLinkFormat
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Component
import java.time.Instant
import java.util.UUID

@Component
class GasOrgInfoLoader(
    private val internalHttpClient: InternalHttpClient,
    private val serviceProperties: ServiceProperties,
    @param:Qualifier("yamlObjectMapper")
    private val yamlObjectMapper: ObjectMapper,
    private val vcsRepoLinkFormat: VcsRepoLinkFormat,
) {

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

    suspend fun load(repoPathString: String): Map<UUID, OrgInfoModel> =
        load(repoPathString, mutableSetOf(), mutableSetOf())

    private suspend fun load(
        repoPathString: String,
        visited: MutableSet<String>,
        processing: MutableSet<String>,
    ): Map<UUID, OrgInfoModel> {
        if (repoPathString in processing) {
            log.warn("Обнаружен циклический импорт файла организаций: {}, пропускаем", repoPathString)
            return emptyMap()
        }
        if (!visited.add(repoPathString)) {
            log.debug("Повторный импорт файла организаций (дедупликация): {}, пропускаем", repoPathString)
            return emptyMap()
        }

        processing.add(repoPathString)
        try {
            log.debug("Грузим информацию об организациях из файла {}", repoPathString)
            val access = vcsRepoLinkFormat.parseOrgAccess(repoPathString)
            if (access == null) {
                log.warn("{} не валидный путь к vcs", repoPathString)
                return emptyMap()
            }
            val yamlFile = getFileFromGas(access)
            log.trace("{}: сырые данные в файле с организациями {}", repoPathString, yamlFile.toString(Charsets.UTF_8))
            val yaml: OrgInfoYaml = yamlObjectMapper.readValue(yamlFile)
            val organizations = toOrgInfoModels(yaml)
            log.trace("{}: Данные по организациям из файла {}", repoPathString, organizations)
            yaml.imports?.forEach { import ->
                organizations.putAll(load(import, visited, processing))
            }
            return organizations
        } finally {
            processing.remove(repoPathString)
        }
    }

    private suspend fun getFileFromGas(access: OrgAccessPath): ByteArray =
        internalHttpClient { client ->
            val response = client.get(serviceProperties.gasUrl) {
                access.project?.let { parameter("project", it) }
                parameter("repo", access.repo)
                parameter("branch", access.branch)
                url {
                    appendPathSegments("api", "v1", "vcs", "file", access.subpath.trimStart('/'))
                }
            }
            response.body()
        }

    private fun toOrgInfoModels(yaml: OrgInfoYaml) = yaml.organizations?.associate {
        it.orgId to OrgInfoModel(
            it.orgName,
            it.repos,
            Instant.now(),
        )
    }?.toMutableMap() ?: mutableMapOf()
}