Scoop API

scoop:scoop.http.client:0.1.0

src/authentication/bearer/select.scoop

Selected production source · src/authentication/bearer/select.scoop

1package scoop.http.client
3internal suspend fun awaitClientBearer(call: ClientCall, session: ClientAuthenticationSession,
4 provider: ClientBearerAuthentication): ClientBearerValue {
5 while (true) {
6 requireClientCall(call)
7 val decision = selectClientBearer(call, session, provider)
8 when (decision) {
9 case Ready(val value) -> return value
10 case Start(val flight) -> return waitClientBearer(call, flight, true)
11 case Join(val flight) -> return waitClientBearer(call, flight, false)
12 case Settle(val flight) -> awaitClientBearerSettlement(flight)
13 }
14 }
17private fun selectClientBearer(call: ClientCall, session: ClientAuthenticationSession,
18 provider: ClientBearerAuthentication): ClientBearerDecision = call.client.lock.withLock {
19 val state = call.client
20 if (state.closing) throw HttpClientClosedException()
21 var selected: ClientBearerEntry? = None
22 for (entry in state.bearerEntries) {
23 if (entry.authenticator === session.authenticator && sameClientAuthenticationScope(entry.scope, session.scope)) { selected = Some(entry); break }
24 }
25 if (!clientPresent(selected)) {
26 val entry = ClientBearerEntry(session.scope, session.authenticator, provider)
27 state.bearerEntries.add(entry)
28 selected = Some(entry)
29 }
30 val entry = selected!!
31 val active = entry.flight
32 if (clientPresent(active)) return@withLock if (active!!.stopping)
33 ClientBearerDecision.Settle(active!!) else ClientBearerDecision.Join(active!!)
34 val current = entry.value
35 val rejected = session.rejectedBearer
36 if (clientPresent(current) && (!clientPresent(rejected) ||
37 current!!.tokens.accessToken != rejected!!.tokens.accessToken))
38 return@withLock ClientBearerDecision.Ready(current!!)
39 val request = session.scope.request(call, session.challenge)
40 val flight = ClientBearerFlight(state, entry, state.scope!!, request, current)
41 entry.flight = Some(flight)
42 ClientBearerDecision.Start(flight)
45private suspend fun awaitClientBearerSettlement(flight: ClientBearerFlight) {
46 suspendCancellableCoroutine<Unit> { continuation ->
47 val finished = flight.client.lock.withLock {
48 if (clientPresent(flight.outcome)) true else { flight.settled.add(continuation); false }
49 }
50 if (finished) continuation.tryResume(Unit)
51 else continuation.invokeOnCancellation { _ ->
52 flight.client.lock.withLock {
53 var index = 0L
54 while (index < flight.settled.size) {
55 if (flight.settled[index] === continuation) { flight.settled.removeAt(index); break }
56 index += 1L
57 }
58 }
59 }
60 Unit
61 }