66package aws.smithy.kotlin.runtime.retries.delay
77
88import aws.smithy.kotlin.runtime.retries.policy.RetryErrorType
9- import aws.smithy.kotlin.runtime.time.Clock
10- import aws.smithy.kotlin.runtime.time.epochMilliseconds
119import kotlinx.coroutines.delay
1210import kotlinx.coroutines.sync.Mutex
1311import kotlinx.coroutines.sync.withLock
1412import kotlin.math.ceil
1513import kotlin.math.floor
1614import kotlin.math.min
15+ import kotlin.time.ExperimentalTime
16+ import kotlin.time.TimeSource
1717
1818private const val MS_PER_S = 1_000
1919
2020/* *
2121 * The standard implementation of a [RetryTokenBucket].
2222 * @param options The configuration to use for this bucket.
23- * @param clock A clock to use for time calculations .
23+ * @param timeSource A monotonic time source to use for calculating the temporal token fill of the bucket .
2424 */
25- public class StandardRetryTokenBucket (
25+ @OptIn(ExperimentalTime ::class )
26+ public class StandardRetryTokenBucket constructor(
2627 public val options : StandardRetryTokenBucketOptions = StandardRetryTokenBucketOptions .Default ,
27- private val clock : Clock = Clock . System ,
28+ private val timeSource : TimeSource = TimeSource . Monotonic ,
2829) : RetryTokenBucket {
2930 internal var capacity = options.maxCapacity
3031 private set
3132
32- private var lastTimestamp = now ()
33+ private var lastTimeMark = timeSource.markNow ()
3334 private val mutex = Mutex ()
3435
3536 /* *
@@ -58,13 +59,11 @@ public class StandardRetryTokenBucket(
5859 capacity = 0
5960 }
6061
61- lastTimestamp = now ()
62+ lastTimeMark = timeSource.markNow ()
6263 }
6364
64- private fun now (): Long = clock.now().epochMilliseconds
65-
6665 private fun refillCapacity () {
67- val refillMs = now() - lastTimestamp
66+ val refillMs = lastTimeMark.elapsedNow().inWholeMilliseconds
6867 val refillSize = floor(options.refillUnitsPerSecond.toDouble() / MS_PER_S * refillMs).toInt()
6968 capacity = min(options.maxCapacity, capacity + refillSize)
7069 }
@@ -73,7 +72,7 @@ public class StandardRetryTokenBucket(
7372 refillCapacity()
7473
7574 capacity = min(options.maxCapacity, capacity + size)
76- lastTimestamp = now ()
75+ lastTimeMark = timeSource.markNow ()
7776 }
7877
7978 /* *
0 commit comments