scoop:scoop.http.client:0.1.0
src/pool/drive.scoop
Selected production source · src/pool/drive.scoop
1
package scoop.http.client3
import scoop.asyncio.IoClosedException4
import scoop.time.Duration6
internal suspend fun driveClientPool(state: ClientState, scope: CoroutineScope) {7
var timer: Job? = None8
try {9
while (true) {10
if (clientPresent(timer)) { timer!!.cancel(); timer = None }11
val plan = planClientPool(state)12
for (action in plan.actions) {13
when (action) {14
case Dial(val call, val entry) -> { stopClientDeadline(call.poolDeadline); startClientDial(state, call, entry) }15
case Upgrade(val work) -> startClientUpgrade(work)16
case Reject(val call, val error) -> failClientCall(call, error)17
case Deliver(val call, val entry, val waiter) -> {18
stopClientDeadline(call.poolDeadline)19
val error = call.lock.withLock {20
if (call.ending) Some(call.failure ?: IoClosedException()) else None21
}22
if (clientPresent(error)) waiter.resumeWithException(error!!) else waiter.resume(ClientConnectResult.Connected(entry.connection!!))23
}24
case Close(val entry) -> closeClientPoolEntry(state, entry, entry.connection!!)25
}26
}27
if (plan.done) return28
if (plan.actions.size != 0L) continue29
if (clientPresent(plan.delay) && !state.lock.withLock { state.closing }) {30
val delay = plan.delay!!31
timer = Some(scope.launch suspend {32
try {33
if (delay > Duration.ZERO) state.loop.sleep(delay)34
wakeClient(state)35
} catch (_: CancellationException) {36
} catch (error: Throwable) {37
state.lock.withLock { state.closeFailure = Some(clientCombined(state.closeFailure, error)) }38
stopClient(state)39
}40
})41
}42
suspendCoroutine<Unit> { continuation ->43
val immediate = state.lock.withLock {44
if (state.dirty) true else { state.wake = Some(continuation); false }45
}46
if (immediate) continuation.resume(Unit)47
}48
}49
} finally { if (clientPresent(timer)) timer!!.cancel() }50
}52
private suspend fun closeClientPoolEntry(state: ClientState, entry: ClientPoolEntry, connection: ClientConnection) {53
try { closeClientConnection(connection) }54
catch (error: Throwable) {55
state.lock.withLock { state.closeFailure = Some(clientCombined(state.closeFailure, error)) }56
} finally { removeClientPoolEntry(state, entry) }57
}