S3Config.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.fileloader2.configuration

import java.net.URI
import org.archtool.fileloader2.configuration.properties.S3Properties
import org.archtool.fileloader2.service.storage.S3ObjectKeyGenerator
import org.archtool.security.TrustStoreSupport
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials
import software.amazon.awssdk.awscore.retry.AwsRetryStrategy
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation
import software.amazon.awssdk.http.apache5.Apache5HttpClient
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.s3.S3Client

/**
 * Клиент S3. Используется обычный TLS: сервис проверяет сертификат хранилища. Взаимная аутентификация по сертификатам
 * (mTLS) не поддерживается, если она нужна - её настраивает прокси между сервисом и хранилищем.
 */
@Configuration
class S3Config(
    private val s3Properties: S3Properties,
    private val objectKeyGenerator: S3ObjectKeyGenerator,
) {
    private val log = LoggerFactory.getLogger(javaClass)

    /**
     * Создаёт синхронный клиент S3 по настройкам seaf.fileloader.s3: адрес, регион, ключи доступа, path-style,
     * число попыток и хранилище доверенных сертификатов. Клиент закрывается при остановке сервиса.
     *
     * @return клиент S3
     * @throws IllegalArgumentException хранилище доверенных сертификатов задано, но файл не читается
     * @throws java.io.IOException файл хранилища доверенных сертификатов повреждён или пароль неверный
     */
    @Bean(destroyMethod = "close")
    fun s3Client(): S3Client {
        val httpClient = Apache5HttpClient.builder()
        // если keystore задан, доверие определяется только им; пустое значение - стандартные корневые сертификаты JVM
        val trustManagerFactory = TrustStoreSupport.createTrustManagerFactory(
            trustStoreLocation = s3Properties.trustKeyStoreLocation,
            trustStorePassword = s3Properties.trustKeyStorePassword,
        )
        httpClient.tlsTrustManagersProvider { trustManagerFactory.trustManagers }
        log.info("Клиент S3: {}", s3Properties)
        log.info(
            "Адрес объекта в S3 ({}): {}",
            if (s3Properties.pathStyleAccessEnabled) "bucket в пути" else "bucket в имени хоста",
            objectUrlExample(s3Properties)
        )
        return S3Client.builder()
            .endpointOverride(URI.create(s3Properties.url))
            .region(Region.of(s3Properties.region))
            .credentialsProvider(
                StaticCredentialsProvider.create(AwsBasicCredentials.create(s3Properties.accessKeyId, s3Properties.secretAccessKey))
            )
            .forcePathStyle(s3Properties.pathStyleAccessEnabled)
            // хранилище S3-совместимое, а не AWS: контрольные суммы только там, где они обязательны по протоколу.
            // Иначе SDK передаёт содержимое в формате aws-chunked с CRC в trailer, его поддерживают не все хранилища
            .requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
            .responseChecksumValidation(ResponseChecksumValidation.WHEN_REQUIRED)
            .httpClientBuilder(httpClient)
            // повторы при временных сбоях (сеть, 5xx, таймауты) внутри одного вызова S3; ошибки вроде NoSuchKey
            // и AccessDenied не повторяются
            .overrideConfiguration { config ->
                config.retryStrategy(AwsRetryStrategy.standardRetryStrategy().toBuilder().maxAttempts(s3Properties.maxAttempts).build())
                config.addExecutionInterceptor(S3RetryLoggingInterceptor(s3Properties.maxAttempts))
            }
            .build()
    }

    /**
     * Пример адреса объекта, по которому клиент будет обращаться к хранилищу. Нужен в журнале при старте: по нему видно,
     * что при выключенном path-style bucket попадает в имя хоста и для него нужна DNS-запись.
     *
     * @param s3 настройки S3
     * @return адрес объекта с подстановкой <id> вместо идентификатора файла
     */
    private fun objectUrlExample(s3: S3Properties): String {
        val endpoint = URI.create(s3.url)
        val port = if (endpoint.port == -1) "" else ":${endpoint.port}"
        val basePath = endpoint.rawPath.orEmpty().trimEnd('/')
        // префикс из генератора ключей: он уже дополнен слешем, как в настоящих ключах
        val key = "${objectKeyGenerator.keyPrefix}<id>"
        return if (s3.pathStyleAccessEnabled) {
            "${endpoint.scheme}://${endpoint.host}$port$basePath/${s3.bucketName}/$key"
        } else {
            "${endpoint.scheme}://${s3.bucketName}.${endpoint.host}$port$basePath/$key"
        }
    }
}