forked from ktorio/ktor
/
DarwinLegacySession.kt
65 lines (55 loc) · 2.02 KB
/
DarwinLegacySession.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
package io.ktor.client.engine.darwin.internal
import io.ktor.client.engine.darwin.*
import io.ktor.client.request.*
import io.ktor.util.*
import io.ktor.utils.io.core.*
import kotlinx.atomicfu.*
import kotlinx.cinterop.*
import kotlinx.coroutines.*
import platform.Foundation.*
import kotlin.coroutines.*
@OptIn(UnsafeNumber::class)
internal class DarwinLegacySession(
private val config: DarwinLegacyClientEngineConfig,
private val requestQueue: NSOperationQueue?
) : Closeable {
private val closed = atomic(false)
private val sessionAndDelegate = config.sessionAndDelegate ?: createSession(config, requestQueue)
private val session = sessionAndDelegate.first
private val delegate = sessionAndDelegate.second
@OptIn(InternalAPI::class)
internal suspend fun execute(request: HttpRequestData, callContext: CoroutineContext): HttpResponseData {
val nativeRequest = request.toNSUrlRequest()
.apply(config.requestConfig)
val task = session.dataTaskWithRequest(nativeRequest)
val response = delegate.read(request, callContext, task)
task.resume()
try {
return response.await()
} catch (cause: Throwable) {
if (task.state == NSURLSessionTaskStateRunning) task.cancel()
throw cause
}
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
session.finishTasksAndInvalidate()
}
}
@OptIn(UnsafeNumber::class)
internal fun createSession(
config: DarwinLegacyClientEngineConfig,
requestQueue: NSOperationQueue?
): Pair<NSURLSession, KtorLegacyNSURLSessionDelegate> {
val configuration = NSURLSessionConfiguration.defaultSessionConfiguration().apply {
setupProxy(config)
setHTTPCookieStorage(null)
config.sessionConfig(this)
}
val delegate = KtorLegacyNSURLSessionDelegate(config.challengeHandler)
return NSURLSession.sessionWithConfiguration(
configuration,
delegate,
delegateQueue = requestQueue
) to delegate
}