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

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2026
*/

package org.archtool.fileloader2.configuration

import java.util.concurrent.atomic.AtomicInteger
import org.slf4j.LoggerFactory
import software.amazon.awssdk.core.interceptor.Context
import software.amazon.awssdk.core.interceptor.ExecutionAttribute
import software.amazon.awssdk.core.interceptor.ExecutionAttributes
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute

/**
 * Пишет в журнал (INFO) повторные попытки запросов к S3, которые AWS SDK выполняет сам при временных сбоях.
 * Попытки считает сам: счётчик живёт в атрибутах одного вызова SDK, поэтому на обычный запрос без повторов
 * приходится только увеличение счётчика. Причину повтора SDK пишет в свой журнал software.amazon.awssdk.request
 * на уровне DEBUG.
 *
 * @param maxAttempts число попыток из настроек, для строки «попытка N из M»
 */
class S3RetryLoggingInterceptor(
    private val maxAttempts: Int,
) : ExecutionInterceptor {

    private val log = LoggerFactory.getLogger(javaClass)

    /**
     * Вызывается один раз на вызов SDK, до первой попытки: заводит счётчик попыток этого вызова.
     *
     * @param context исходный запрос, не используется
     * @param executionAttributes атрибуты вызова SDK, в них кладётся счётчик
     */
    override fun beforeExecution(context: Context.BeforeExecution, executionAttributes: ExecutionAttributes) {
        executionAttributes.putAttribute(ATTEMPT_COUNTER, AtomicInteger())
    }

    /**
     * Вызывается перед отправкой каждой попытки запроса. Первая попытка не пишется, повторные - пишутся.
     *
     * @param context запрос текущей попытки
     * @param executionAttributes атрибуты вызова SDK: счётчик попыток и название операции
     */
    override fun beforeTransmission(context: Context.BeforeTransmission, executionAttributes: ExecutionAttributes) {
        val attempt = executionAttributes.getAttribute(ATTEMPT_COUNTER)?.incrementAndGet() ?: return
        if (attempt > 1) {
            log.info(
                "Повтор запроса к S3 {} {}: попытка {} из {}. Если повторы частые, причину смотреть в журнале " +
                        "software.amazon.awssdk.request на уровне DEBUG (LOGGING_LEVEL_SOFTWARE_AMAZON_AWSSDK_REQUEST=DEBUG)",
                executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME),
                context.httpRequest().encodedPath(),
                attempt,
                maxAttempts
            )
        }
    }

    companion object {
        /** Счётчик попыток одного вызова SDK */
        private val ATTEMPT_COUNTER = ExecutionAttribute<AtomicInteger>("fileloader2.s3.attemptCounter")
    }
}