-
Notifications
You must be signed in to change notification settings - Fork 1k
/
CIOEngine.kt
145 lines (116 loc) · 4.2 KB
/
CIOEngine.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.cio
import io.ktor.client.engine.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.websocket.*
import io.ktor.client.request.*
import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.network.selector.*
import io.ktor.util.*
import io.ktor.util.collections.*
import io.ktor.util.network.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.coroutines.*
@OptIn(InternalAPI::class, DelicateCoroutinesApi::class)
internal class CIOEngine(
override val config: CIOEngineConfig
) : HttpClientEngineBase("ktor-cio") {
override val dispatcher: CoroutineDispatcher by lazy {
Dispatchers.clientDispatcher(config.threadsCount, "ktor-cio-dispatcher")
}
override val supportedCapabilities = setOf(HttpTimeout, WebSocketCapability, WebSocketExtensionsCapability)
private val endpoints = ConcurrentMap<String, Endpoint>()
private val selectorManager: SelectorManager by lazy { SelectorManager(dispatcher) }
private val connectionFactory = ConnectionFactory(
selectorManager,
config.maxConnectionsCount,
config.endpoint.maxConnectionsPerRoute
)
private val requestsJob: CoroutineContext
override val coroutineContext: CoroutineContext
private val proxy: ProxyConfig? = when (val type = config.proxy?.type) {
ProxyType.SOCKS,
null -> null
ProxyType.HTTP -> config.proxy
else -> throw IllegalStateException("CIO engine does not currently support $type proxies.")
}
init {
val parentContext = super.coroutineContext
val parent = parentContext[Job]!!
requestsJob = SilentSupervisor(parent)
val requestField = requestsJob
coroutineContext = parentContext + requestField
val requestJob = requestField[Job]!!
val selector = selectorManager
@OptIn(ExperimentalCoroutinesApi::class)
GlobalScope.launch(parentContext, start = CoroutineStart.ATOMIC) {
try {
requestJob.join()
} finally {
selector.close()
selector.coroutineContext[Job]!!.join()
}
}
}
override suspend fun execute(data: HttpRequestData): HttpResponseData {
val callContext = callContext()
while (coroutineContext.isActive) {
val endpoint = selectEndpoint(data.url, proxy)
try {
return endpoint.execute(data, callContext)
} catch (cause: ClosedSendChannelException) {
continue
} finally {
if (!coroutineContext.isActive) {
endpoint.close()
}
}
}
throw ClientEngineClosedException()
}
override fun close() {
super.close()
endpoints.forEach { (_, endpoint) ->
endpoint.close()
}
(requestsJob[Job] as CompletableJob).complete()
}
private fun selectEndpoint(url: Url, proxy: ProxyConfig?): Endpoint {
val host: String
val port: Int
val protocol: URLProtocol = url.protocol
if (proxy != null) {
val proxyAddress = proxy.resolveAddress()
host = proxyAddress.hostname
port = proxyAddress.port
} else {
host = url.host
port = url.port
}
val endpointId = "$host:$port:$protocol"
return endpoints.computeIfAbsent(endpointId) {
val secure = (protocol.isSecure())
Endpoint(
host,
port,
proxy,
secure,
config,
connectionFactory,
coroutineContext,
onDone = { endpoints.remove(endpointId) }
)
}
}
}
@Suppress("KDocMissingDocumentation")
@Deprecated(
"Use ClientEngineClosedException instead",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("ClientEngineClosedException")
)
public class ClientClosedException(cause: Throwable? = null) : IllegalStateException("Client already closed", cause)