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

import org.archtool.data.dto.BackendHealthDto
import org.archtool.data.dto.BackendReloadDto
import org.archtool.data.model.BackendBaseUrlModel
import org.springframework.web.client.RestClient
import org.springframework.web.client.body
import org.springframework.web.util.UriComponentsBuilder
import java.net.URI

class BackendServiceClient(
    private val restClient: RestClient,
    private val baseUrls: Map<String, BackendBaseUrlModel>,
    private val reloadPath: String = "/seaf-core/internal/core/storage/reload",
    private val statusPath: String = "/health"
) {
    fun backends(): Map<String, BackendBaseUrlModel> = baseUrls

    fun reload(backend: String, secret: String? = null, reloadRoot: Boolean?, mode: String?, aliases: List<String>?) =
        restClient.put()
            .uri(reloadUri(backend, secret, reloadRoot, mode, aliases))
            .retrieve()
            .body<BackendReloadDto>()!!

    // Значения передаются через URI-переменные: только так UriComponentsBuilder кодирует символы,
    // допустимые в query, но значимые для него ('+', '&', '=', '/'). Иначе, например, secret "a+b"
    // seaf-core декодирует как "a b" и отвечает 403.
    internal fun reloadUri(backend: String, secret: String?, reloadRoot: Boolean?, mode: String?, aliases: List<String>?): URI {
        val builder = UriComponentsBuilder.fromUriString(baseUrl(backend))
            .path(reloadPath)
        val variables = mutableMapOf<String, Any>()
        if (secret != null) {
            builder.queryParam("secret", "{secret}")
            variables["secret"] = secret
        }
        if (reloadRoot != null) {
            builder.queryParam("reloadRoot", "{reloadRoot}")
            variables["reloadRoot"] = reloadRoot
        }
        if (mode != null) {
            builder.queryParam("mode", "{mode}")
            variables["mode"] = mode
        }
        aliases?.forEachIndexed { index, alias ->
            builder.queryParam("alias", "{alias$index}")
            variables["alias$index"] = alias
        }
        return builder.encode().buildAndExpand(variables).toUri()
    }

    fun status(backend: String) =
        restClient.get()
            .uri(
                UriComponentsBuilder.fromUriString(baseUrl(backend))
                    .path(statusPath).build().toUri()
            )
            .retrieve()
            .body<BackendHealthDto>()!!

    private fun baseUrl(backend: String): String =
        baseUrls[backend]?.backend ?: error("unknown backend $backend")
}