GasApiClientImpl.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:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
      Марат Ниязматов <mrusniyazmatov@sberbank.ru>, Sber - 2026
*/

package org.archtool.archloader.service.integraion.gas

import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import org.springframework.util.LinkedMultiValueMap
import org.springframework.web.client.RestClient
import org.archtool.archloader.service.integraion.gas.config.GasApiProperties
import org.archtool.archloader.service.integraion.gas.dto.GasSendRequest
import org.archtool.archloader.service.integraion.gas.dto.GasSendResponse
import org.archtool.archloader.utils.SeafHttpHeaders

class GasApiClientImpl(
    private val restClient: RestClient,
    properties: GasApiProperties,
) : GasApiClient {

    private val log = LoggerFactory.getLogger(javaClass)
    private val sendToGitUrl = properties.baseUrl.toURI().resolve("api/v1/architecture/send")

    init {
        log.info("Путь для отправки запросов в git адаптер на сохранение {}", sendToGitUrl.toString())
    }

    override fun sendArchitecture(request: GasSendRequest): GasSendResponse {
        log.debug(
            "Отправляем архитектуру в GAS: processId={}, repoName={}, file={}",
            request.processId,
            request.repoUrl,
            request.file.filename
        )

        val formData = LinkedMultiValueMap<String, Any>().apply {
            add("process_id", request.processId)
            add("repo_url", request.repoUrl)
            add("file", request.file)
            add("sub", request.sub)
            add("name", request.name)
            add("surname", request.surname)
            request.email?.let {
                add("email", it)
            }
        }
        val response = restClient.post()
            .uri(sendToGitUrl)
            .header(SeafHttpHeaders.CHECKSUM, request.fileChecksum)
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .body(formData)
            .retrieve()
            .onStatus(HttpStatusCode::isError) { request, response ->
                log.error("Ошибка при вызове GAS API ({}): статус={}", sendToGitUrl, response.statusCode)
                if (log.isDebugEnabled) {
                    log.debug("тело={}", response.body.bufferedReader().use { it.readText() })
                }
                throw RuntimeException("Ошибка GAS API: ${response.statusCode}")
            }
            .body(GasSendResponse::class.java)
            ?: throw RuntimeException("GAS API вернул пустой ответ (null), для просмотра тела ответа нужно включить debug лог")

        log.debug("Успешный ответ от GAS: {}", response)
        return response
    }
}