scoop:scoop.http.client:0.1.0
src/retry/wait.scoop
Selected production source · src/retry/wait.scoop
1
package scoop.http.client3
import scoop.platform.time.MonotonicTimeSource4
import scoop.time.Duration6
internal suspend fun awaitClientRetry(7
state: ClientState,8
caller: Job,9
sequence: ClientRequestSequence,10
delay: Duration11
) {12
caller.ensureActive()13
val failure =14
try {15
coroutineScope<Throwable?> {16
val scope = this18
val registered =19
state.lock.withLock {20
if (state.closing)21
false22
else {23
state.retryWaits.add(scope.job);24
true25
}26
}27
if (!registered)28
return@coroutineScope Some(HttpClientClosedException())29
try {30
scope.job.ensureActive()31
val remaining = clientRetryRemainingTotal(sequence)32
val wait =33
if (clientPresent(remaining) && remaining!! < delay)34
remaining!!35
else36
delay37
if (wait > Duration.ZERO)38
state.loop.sleep(wait)39
scope.job.ensureActive()40
clientRetryRemainingTotal(sequence)41
None42
} catch (error: Throwable) {43
Some(error)44
}45
finally {46
state.lock.withLock {47
var index = 0L48
while (index < state.retryWaits.size) {49
if (state.retryWaits[index] === scope.job) {50
state.retryWaits.removeAt(index);51
break52
}53
index += 1L54
}55
}56
wakeClient(state)57
}58
}59
} catch (error: CancellationException) {60
caller.ensureActive()61
if (state.lock.withLock { state.closing })62
throw HttpClientClosedException()63
throw error64
}65
caller.ensureActive()66
if (state.lock.withLock { state.closing })67
throw HttpClientClosedException()68
if (clientPresent(failure))69
throw failure!!70
}72
private fun clientRetryRemainingTotal(sequence: ClientRequestSequence): Duration? {73
val limit = sequence.timeouts.total ?: return None74
val elapsed = MonotonicTimeSource.markNow() - sequence.started!!75
if (elapsed >= limit)76
throw HttpTimeoutException(77
HttpTimeoutPhase.Total,78
limit,79
elapsed,80
sequence.requestBodyBytes,81
sequence.encodedResponseBodyBytes,82
sequence.responseBodyBytes83
)84
return Some(limit - elapsed)85
}