0
# Engine Configuration and Management
1
2
HTTP engine abstraction providing platform-specific implementations and configuration options for connection management, timeouts, and networking behavior across different platforms.
3
4
## Capabilities
5
6
### HttpClientEngine Interface
7
8
Core engine interface providing platform-specific HTTP implementations.
9
10
```kotlin { .api }
11
/**
12
* HTTP client engine interface for platform-specific implementations
13
*/
14
interface HttpClientEngine : CoroutineScope, Closeable {
15
/** Engine configuration */
16
val config: HttpClientEngineConfig
17
18
/** Coroutine dispatcher for engine operations */
19
val dispatcher: CoroutineDispatcher
20
21
/** Set of capabilities supported by this engine */
22
val supportedCapabilities: Set<HttpClientEngineCapability<*>>
23
24
/** Execute HTTP request and return response data */
25
suspend fun execute(data: HttpRequestData): HttpResponseData
26
27
/** Install engine into HTTP client */
28
fun install(client: HttpClient)
29
30
/** Close engine and release resources */
31
override fun close()
32
}
33
```
34
35
### HttpClientEngineConfig
36
37
Base configuration class for HTTP client engines.
38
39
```kotlin { .api }
40
/**
41
* Base configuration for HTTP client engines
42
*/
43
open class HttpClientEngineConfig {
44
/** Custom coroutine dispatcher for engine operations */
45
var dispatcher: CoroutineDispatcher? = null
46
47
/** Enable HTTP pipelining (where supported) */
48
var pipelining: Boolean = false
49
50
/** Proxy configuration */
51
var proxy: ProxyConfig? = null
52
53
/** Local address to bind connections */
54
var localAddress: SocketAddress? = null
55
56
/** Configure proxy from URL string */
57
fun proxy(url: String) {
58
proxy = ProxyConfig.parseUrl(url)
59
}
60
}
61
```
62
63
### Engine Factory Interface
64
65
Interface for creating HTTP client engines.
66
67
```kotlin { .api }
68
/**
69
* Factory interface for creating HTTP client engines
70
* @param T Engine configuration type
71
*/
72
interface HttpClientEngineFactory<out T : HttpClientEngineConfig> {
73
/** Create engine instance with configuration */
74
fun create(block: T.() -> Unit = {}): HttpClientEngine
75
}
76
```
77
78
### Engine Capabilities
79
80
System for declaring and checking engine capabilities.
81
82
```kotlin { .api }
83
/**
84
* Marker for HTTP client engine capabilities
85
* @param T Capability configuration type
86
*/
87
class HttpClientEngineCapability<T : Any>(private val key: String) {
88
override fun toString(): String = "Capability[$key]"
89
}
90
91
/** Check if client supports specific capability */
92
fun HttpClient.isSupported(capability: HttpClientEngineCapability<*>): Boolean
93
```
94
95
## Built-in Engine Types
96
97
### Proxy Configuration
98
99
```kotlin { .api }
100
/**
101
* Proxy configuration for HTTP requests
102
*/
103
class ProxyConfig(
104
/** Proxy type (HTTP or SOCKS) */
105
val type: ProxyType,
106
/** Proxy server address */
107
val address: SocketAddress
108
) {
109
companion object {
110
/** Parse proxy configuration from URL */
111
fun parseUrl(url: String): ProxyConfig
112
}
113
}
114
115
/**
116
* Proxy protocol types
117
*/
118
enum class ProxyType {
119
/** HTTP proxy */
120
HTTP,
121
/** SOCKS proxy */
122
SOCKS
123
}
124
```
125
126
**Usage Examples:**
127
128
```kotlin
129
import io.ktor.client.*
130
import io.ktor.client.engine.*
131
132
// HTTP proxy configuration
133
val httpClient = HttpClient {
134
engine {
135
proxy = ProxyConfig(
136
type = ProxyType.HTTP,
137
address = InetSocketAddress("proxy.example.com", 8080)
138
)
139
}
140
}
141
142
// Proxy from URL string
143
val proxyClient = HttpClient {
144
engine {
145
proxy("http://proxy.example.com:8080")
146
}
147
}
148
149
// SOCKS proxy
150
val socksClient = HttpClient {
151
engine {
152
proxy = ProxyConfig(
153
type = ProxyType.SOCKS,
154
address = InetSocketAddress("socks.example.com", 1080)
155
)
156
}
157
}
158
```
159
160
### Engine Configuration Examples
161
162
**Usage Examples:**
163
164
```kotlin
165
import io.ktor.client.*
166
import io.ktor.client.engine.cio.*
167
import kotlinx.coroutines.Dispatchers
168
169
// Basic engine configuration
170
val client = HttpClient(CIO) {
171
engine {
172
// Enable HTTP pipelining
173
pipelining = true
174
175
// Use custom dispatcher
176
dispatcher = Dispatchers.IO
177
178
// Set local address
179
localAddress = InetSocketAddress("192.168.1.100", 0)
180
181
// Configure proxy
182
proxy("http://proxy.company.com:8080")
183
}
184
}
185
186
// Platform-specific configuration
187
val platformClient = HttpClient {
188
engine {
189
// Configure based on platform capabilities
190
if (isJvmPlatform()) {
191
// JVM-specific settings
192
pipelining = true
193
} else if (isNativePlatform()) {
194
// Native-specific settings
195
dispatcher = Dispatchers.Default
196
}
197
}
198
}
199
200
// Check engine capabilities
201
if (client.isSupported(HttpTimeout)) {
202
println("Engine supports timeout configuration")
203
}
204
205
if (client.isSupported(WebSocketCapability)) {
206
println("Engine supports WebSockets")
207
}
208
```
209
210
## Platform-Specific Engines
211
212
### Common Engine Types
213
214
Different platforms provide different HTTP engine implementations:
215
216
**JVM Engines:**
217
- **Apache**: Apache HttpClient-based engine
218
- **OkHttp**: OkHttp-based engine
219
- **Jetty**: Jetty HttpClient-based engine
220
- **CIO**: Coroutines I/O engine (pure Kotlin)
221
- **Java**: Java 11+ HttpClient engine
222
223
**Native Engines:**
224
- **CIO**: Coroutines I/O engine for Native
225
- **Darwin**: Native macOS/iOS engine using NSURLSession
226
- **WinHttp**: Windows HTTP API engine
227
- **Curl**: libcurl-based engine
228
229
**JavaScript Engine:**
230
- **Js**: JavaScript fetch API or XMLHttpRequest
231
232
```kotlin { .api }
233
/**
234
* Platform-specific engine creation examples
235
*/
236
237
// JVM - Apache engine
238
val apacheClient = HttpClient(Apache) {
239
engine {
240
socketTimeout = 10_000
241
connectTimeout = 10_000
242
connectionRequestTimeout = 20_000
243
}
244
}
245
246
// JVM - OkHttp engine
247
val okHttpClient = HttpClient(OkHttp) {
248
engine {
249
config {
250
retryOnConnectionFailure(true)
251
connectTimeout(10, TimeUnit.SECONDS)
252
}
253
}
254
}
255
256
// Native - CIO engine
257
val nativeClient = HttpClient(CIO) {
258
engine {
259
maxConnectionsCount = 1000
260
endpoint {
261
maxConnectionsPerRoute = 100
262
pipelineMaxSize = 20
263
keepAliveTime = 5000
264
}
265
}
266
}
267
268
// JavaScript - default engine
269
val jsClient = HttpClient(Js) {
270
engine {
271
// JS-specific configuration
272
}
273
}
274
```
275
276
## Advanced Engine Configuration
277
278
### Connection Management
279
280
```kotlin { .api }
281
/**
282
* Advanced connection configuration options
283
*/
284
class EngineConnectionConfig {
285
/** Maximum number of connections */
286
var maxConnectionsCount: Int = 1000
287
288
/** Maximum connections per route */
289
var maxConnectionsPerRoute: Int = 100
290
291
/** Connection keep-alive time */
292
var keepAliveTime: Long = 5000
293
294
/** Connection idle timeout */
295
var idleTimeout: Long = 30000
296
297
/** Enable connection pooling */
298
var connectionPooling: Boolean = true
299
}
300
```
301
302
### SSL/TLS Configuration
303
304
```kotlin { .api }
305
/**
306
* SSL/TLS configuration for secure connections
307
*/
308
class SSLConfig {
309
/** Trust all certificates (development only) */
310
var trustAllCertificates: Boolean = false
311
312
/** Custom certificate validation */
313
var certificateValidator: ((X509Certificate) -> Boolean)? = null
314
315
/** SSL context configuration */
316
var sslContext: SSLContext? = null
317
318
/** Hostname verification */
319
var hostnameVerifier: HostnameVerifier? = null
320
}
321
```
322
323
**Usage Examples:**
324
325
```kotlin
326
import io.ktor.client.*
327
import io.ktor.client.engine.cio.*
328
329
// Advanced connection configuration
330
val advancedClient = HttpClient(CIO) {
331
engine {
332
maxConnectionsCount = 1000
333
334
endpoint {
335
maxConnectionsPerRoute = 100
336
pipelineMaxSize = 20
337
keepAliveTime = 5000
338
connectTimeout = 10000
339
connectAttempts = 3
340
}
341
342
https {
343
// SSL configuration
344
serverName = "api.example.com"
345
cipherSuites = CIOCipherSuites.SupportedSuites
346
trustManager = customTrustManager
347
}
348
}
349
}
350
351
// Development SSL configuration (trust all certificates)
352
val devClient = HttpClient(CIO) {
353
engine {
354
https {
355
trustManager = X509TrustManager.createTrustAllManager()
356
}
357
}
358
}
359
```
360
361
## Types
362
363
### Engine Types
364
365
```kotlin { .api }
366
interface HttpClientEngineCapability<T : Any>
367
368
class ClientEngineClosedException(
369
cause: Throwable? = null
370
) : IllegalStateException("Client engine is already closed.", cause)
371
372
data class HttpRequestData(
373
val url: Url,
374
val method: HttpMethod,
375
val headers: Headers,
376
val body: OutgoingContent,
377
val executionContext: Job,
378
val attributes: Attributes
379
)
380
381
data class HttpResponseData(
382
val statusCode: HttpStatusCode,
383
val requestTime: GMTDate,
384
val headers: Headers,
385
val version: HttpProtocolVersion,
386
val body: Any,
387
val callContext: CoroutineContext
388
)
389
```
390
391
### Network Types
392
393
```kotlin { .api }
394
data class SocketAddress(
395
val hostname: String,
396
val port: Int
397
)
398
399
class InetSocketAddress(
400
hostname: String,
401
port: Int
402
) : SocketAddress(hostname, port) {
403
constructor(port: Int) : this("0.0.0.0", port)
404
}
405
406
class ConnectTimeoutException(
407
message: String,
408
cause: Throwable? = null
409
) : IOException(message, cause)
410
411
class SocketTimeoutException(
412
message: String,
413
cause: Throwable? = null
414
) : IOException(message, cause)
415
```