VcsHttpClientFactory.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
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.
*/
package org.archtool.helper
import com.fasterxml.jackson.databind.ObjectMapper
import io.ktor.client.HttpClient
import io.ktor.client.HttpClientConfig
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.engine.okhttp.OkHttpConfig
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.HttpRequestTimeoutException
import io.ktor.client.plugins.HttpTimeout
import io.ktor.http.HttpStatusCode
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logging
import io.ktor.http.ContentType
import io.ktor.serialization.jackson.JacksonConverter
import kotlinx.coroutines.time.delay
import org.archtool.configuration.ServiceProperties
import jakarta.annotation.PreDestroy
import org.springframework.stereotype.Component
import java.io.IOException
import java.util.Collections
import java.util.concurrent.CancellationException
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
@Component
class VcsHttpClientFactory(
private val serviceProperties: ServiceProperties,
private val jsonObjectMapper: ObjectMapper,
private val trustManagerFactory: TrustManagerFactory,
private val sslContext: SSLContext,
) {
private val trustManager: X509TrustManager
get() = trustManagerFactory.trustManagers?.first { it is X509TrustManager } as X509TrustManager
private val socketFactory
get() = sslContext.socketFactory
private val clients: MutableList<HttpClient> = Collections.synchronizedList(mutableListOf())
@PreDestroy
fun close() {
clients.forEach { it.close() }
clients.clear()
}
fun createClient(
sensitiveHeader: String,
configure: HttpClientConfig<OkHttpConfig>.() -> Unit,
): HttpClient {
val client = HttpClient(OkHttp) {
configureEngine()
install(Logging) {
sanitizeHeader { header -> header == sensitiveHeader }
level = LogLevel.valueOf(serviceProperties.httpClientLogLevel)
}
configure()
installContentNegotiation()
installTimeouts()
installRetry()
}
clients.add(client)
return client
}
/**
* Закрывает клиент, созданный через [createClient], и удаляет его из списка закрываемых при остановке.
*/
fun closeClient(client: HttpClient) {
clients.remove(client)
client.close()
}
suspend fun <R> execute(client: HttpClient, block: suspend (HttpClient) -> R): R {
delay(serviceProperties.vcsDelay)
return block(client)
}
private fun HttpClientConfig<OkHttpConfig>.configureEngine() {
engine {
config {
sslSocketFactory(socketFactory, trustManager)
}
}
}
private fun HttpClientConfig<*>.installContentNegotiation() {
install(ContentNegotiation) {
register(ContentType.Application.Json, JacksonConverter(jsonObjectMapper))
}
}
private fun HttpClientConfig<*>.installTimeouts() {
install(HttpTimeout) {
requestTimeoutMillis = serviceProperties.requestTimeoutSeconds * 1000L
connectTimeoutMillis = serviceProperties.connectTimeoutSeconds * 1000L
socketTimeoutMillis = serviceProperties.socketTimeoutSeconds * 1000L
}
}
private fun HttpClientConfig<*>.installRetry() {
install(HttpRequestRetry) {
maxRetries = serviceProperties.vcsMaxRetries
retryOnExceptionIf { _, cause ->
val rootCause = if (cause is CancellationException) cause.cause else cause
rootCause is HttpRequestTimeoutException ||
rootCause is IOException
}
retryIf { _, response ->
response.status.value >= 500 || response.status == HttpStatusCode.TooManyRequests
}
delayMillis { retryCount ->
retryCount * serviceProperties.vcsRetryIntervalSeconds * 1000L
}
}
}
}