Scoop API

scoop:scoop.http.client:0.1.0

src/retry/wait.scoop

Selected production source · src/retry/wait.scoop

1package scoop.http.client
3import scoop.platform.time.MonotonicTimeSource
4import scoop.time.Duration
6internal suspend fun awaitClientRetry(
7 state: ClientState,
8 caller: Job,
9 sequence: ClientRequestSequence,
10 delay: Duration
11) {
12 caller.ensureActive()
13 val failure =
14 try {
15 coroutineScope<Throwable?> {
16 val scope = this
18 val registered =
19 state.lock.withLock {
20 if (state.closing)
21 false
22 else {
23 state.retryWaits.add(scope.job);
24 true
25 }
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 else
36 delay
37 if (wait > Duration.ZERO)
38 state.loop.sleep(wait)
39 scope.job.ensureActive()
40 clientRetryRemainingTotal(sequence)
41 None
42 } catch (error: Throwable) {
43 Some(error)
44 }
45 finally {
46 state.lock.withLock {
47 var index = 0L
48 while (index < state.retryWaits.size) {
49 if (state.retryWaits[index] === scope.job) {
50 state.retryWaits.removeAt(index);
51 break
52 }
53 index += 1L
54 }
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 error
64 }
65 caller.ensureActive()
66 if (state.lock.withLock { state.closing })
67 throw HttpClientClosedException()
68 if (clientPresent(failure))
69 throw failure!!
72private fun clientRetryRemainingTotal(sequence: ClientRequestSequence): Duration? {
73 val limit = sequence.timeouts.total ?: return None
74 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.responseBodyBytes
83 )
84 return Some(limit - elapsed)