RestClientConfig.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 - 2026

  Contributors:
      Alexander Romashin <romashin.a.va@sberbank.ru>, Sber - 2026

*/

package org.archtool.configuration

import org.archtool.data.model.BackendBaseUrlModel
import org.archtool.helper.BackendServiceClient
import org.archtool.helper.UpdateServiceClient
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory
import org.springframework.web.client.RestClient
import tools.jackson.dataformat.yaml.YAMLMapper
import tools.jackson.module.kotlin.readValue
import java.nio.file.Path

@Configuration
class RestClientConfig {

    companion object {
        // Один backend (физический seaf-core) может выполнять только одну перезагрузку манифеста одновременно —
        // блокировка в ReloadTaskConfig строится по ключу конфигурации, поэтому два разных ключа с одним и тем же
        // URL не защитили бы друг друга от параллельного запуска (ручного или по расписанию).
        internal fun validateNoDuplicateBackendUrls(baseUrls: Map<String, BackendBaseUrlModel>, location: String) {
            val duplicates = baseUrls.entries
                .groupBy { it.value.backend }
                .filterValues { it.size > 1 }
            require(duplicates.isEmpty()) {
                val details = duplicates.entries.joinToString("; ") { (url, entries) ->
                    "$url -> ${entries.map { it.key }}"
                }
                "В файле конфигурации базовых URL бэкендов '$location' обнаружено несколько дублей для backend URL '$details', что недопустимо"
            }
        }
    }

    @Bean
    fun seafGasServiceClient(builder: RestClient.Builder, serviceProperties: ServiceProperties): UpdateServiceClient {
        val requestFactory = HttpComponentsClientHttpRequestFactory().apply {
            setConnectionRequestTimeout(serviceProperties.connectTimeout)
            setReadTimeout(serviceProperties.readTimeout)
        }
        val restClient = builder
            .baseUrl(serviceProperties.gasUrl)
            .requestFactory(requestFactory)
            .build()
        return UpdateServiceClient(restClient)
    }

    @Bean
    fun seafAmsServiceClient(builder: RestClient.Builder, serviceProperties: ServiceProperties): UpdateServiceClient {
        val requestFactory = HttpComponentsClientHttpRequestFactory().apply {
            setConnectionRequestTimeout(serviceProperties.connectTimeout)
            setReadTimeout(serviceProperties.readTimeout)
        }
        val restClient = builder
            .baseUrl(serviceProperties.amsUrl)
            .requestFactory(requestFactory)
            .build()
        return UpdateServiceClient(restClient)
    }

    @Bean
    fun backendServiceClient(
        builder: RestClient.Builder,
        serviceProperties: ServiceProperties,
        @Qualifier("jacksonYamlMapper") objectMapper: YAMLMapper
    ): BackendServiceClient {
        val baseUrls = objectMapper.readValue<Map<String, BackendBaseUrlModel>>(
            Path.of(serviceProperties.backendBaseUrlsLocation).toFile()
        )
        validateNoDuplicateBackendUrls(baseUrls, serviceProperties.backendBaseUrlsLocation)
        val requestFactory = HttpComponentsClientHttpRequestFactory().apply {
            setConnectionRequestTimeout(serviceProperties.connectTimeout)
            setReadTimeout(serviceProperties.readTimeout)
        }
        val restClient = builder
            .requestFactory(requestFactory)
            .build()
        return BackendServiceClient(restClient, baseUrls)
    }
}