<commit_before>/*
 * Copyright 2014 http4s.org
 *
 * 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.http4s
package client
package middleware

import cats.effect.kernel.Resource
import cats.effect.kernel.Temporal
import cats.effect.std.Hotswap
import cats.syntax.all._
import org.http4s.Status._
import org.http4s.headers.`Idempotency-Key`
import org.http4s.headers.`Retry-After`
import org.typelevel.ci.CIString
import org.typelevel.vault.Key

import java.time.Instant
import java.time.temporal.ChronoUnit
import scala.concurrent.duration._
import scala.math.min
import scala.math.pow
import scala.math.random

object Retry {
  private[this] val logger = Platform.loggerFactory.getLogger

  /** This key tracks the attempt count, the retry middleware starts the very
    * first request with 1 as the first request, even with no retries
    * (aka the first attempt). If one wants to monitor retries
    * explicitly and not the attempts one may want to subtract the
    * value of this key by 1.
    */
  val AttemptCountKey: Key[Int] = Key.newKey[cats.effect.SyncIO, Int].unsafeRunSync()

  def apply[F[_]](
      policy: RetryPolicy[F],
      redactHeaderWhen: CIString => Boolean = Headers.SensitiveHeaders.contains,
  )(client: Client[F])(implicit F: Temporal[F]): Client[F] =
    create[F](policy, redactHeaderWhen)(client)

  def create[F[_]](
      policy: RetryPolicy[F],
      redactHeaderWhen: CIString => Boolean = Headers.SensitiveHeaders.contains,
      logRetries: Boolean = true,
  )(client: Client[F])(implicit F: Temporal[F]): Client[F] = {
    def showRequest(request: Request[F], redactWhen: CIString => Boolean): String = {
      val headers = request.headers.redactSensitive(redactWhen).headers.mkString(",")
      val uri = request.uri.renderString
      val method = request.method
      s"method=$method uri=$uri headers=$headers"
    }

    def nextAttempt(
        req: Request[F],
        attempts: Int,
        duration: FiniteDuration,
        retryHeader: Option[`Retry-After`],
        hotswap: Hotswap[F, Either[Throwable, Response[F]]],
    ): F[Response[F]] = {
      val headerDuration =
        retryHeader
          .map { h =>
            h.retry match {
              case Left(d) => Instant.now().until(d.toInstant, ChronoUnit.SECONDS)
              case Right(secs) => secs
            }
          }
          .getOrElse(0L)
      val sleepDuration = headerDuration.seconds.max(duration)<commit_msg>Use Headers#mkStringSeparatedBy in Retry#create<commit_after>/*
 * Copyright 2014 http4s.org
 *
 * 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.http4s
package client
package middleware

import cats.effect.kernel.Resource
import cats.effect.kernel.Temporal
import cats.effect.std.Hotswap
import cats.syntax.all._
import org.http4s.Status._
import org.http4s.headers.`Idempotency-Key`
import org.http4s.headers.`Retry-After`
import org.typelevel.ci.CIString
import org.typelevel.vault.Key

import java.time.Instant
import java.time.temporal.ChronoUnit
import scala.concurrent.duration._
import scala.math.min
import scala.math.pow
import scala.math.random

object Retry {
  private[this] val logger = Platform.loggerFactory.getLogger

  /** This key tracks the attempt count, the retry middleware starts the very
    * first request with 1 as the first request, even with no retries
    * (aka the first attempt). If one wants to monitor retries
    * explicitly and not the attempts one may want to subtract the
    * value of this key by 1.
    */
  val AttemptCountKey: Key[Int] = Key.newKey[cats.effect.SyncIO, Int].unsafeRunSync()

  def apply[F[_]](
      policy: RetryPolicy[F],
      redactHeaderWhen: CIString => Boolean = Headers.SensitiveHeaders.contains,
  )(client: Client[F])(implicit F: Temporal[F]): Client[F] =
    create[F](policy, redactHeaderWhen)(client)

  def create[F[_]](
      policy: RetryPolicy[F],
      redactHeaderWhen: CIString => Boolean = Headers.SensitiveHeaders.contains,
      logRetries: Boolean = true,
  )(client: Client[F])(implicit F: Temporal[F]): Client[F] = {
    def showRequest(request: Request[F], redactWhen: CIString => Boolean): String = {
      val headers = request.headers.mkStringSeparatedBy(",", redactWhen)
      val uri = request.uri.renderString
      val method = request.method
      s"method=$method uri=$uri headers=$headers"
    }

    def nextAttempt(
        req: Request[F],
        attempts: Int,
        duration: FiniteDuration,
        retryHeader: Option[`Retry-After`],
        hotswap: Hotswap[F, Either[Throwable, Response[F]]],
    ): F[Response[F]] = {
      val headerDuration =
        retryHeader
          .map { h =>
            h.retry match {
              case Left(d) => Instant.now().until(d.toInstant, ChronoUnit.SECONDS)
              case Right(secs) => secs
            }
          }
          .getOrElse(0L)
      val sleepDuration = headerDuration.seconds.max(duration)
{'fraction_non_alphanumeric': 0.10274087775348915, 'fraction_numerical': 0.0053808643013284006, 'mean_word_length': 3.376747608535688, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2893488', 'n_tokens_mistral': 1786, 'n_tokens_neox': 1744, 'n_words': 529}