-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOkHttpClient.kt
More file actions
305 lines (257 loc) · 10.9 KB
/
OkHttpClient.kt
File metadata and controls
305 lines (257 loc) · 10.9 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package dev.arcade.client.okhttp
import dev.arcade.core.RequestOptions
import dev.arcade.core.Timeout
import dev.arcade.core.http.Headers
import dev.arcade.core.http.HttpClient
import dev.arcade.core.http.HttpMethod
import dev.arcade.core.http.HttpRequest
import dev.arcade.core.http.HttpRequestBody
import dev.arcade.core.http.HttpResponse
import dev.arcade.errors.ArcadeIoException
import java.io.IOException
import java.io.InputStream
import java.net.Proxy
import java.time.Duration
import java.util.concurrent.CancellationException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509TrustManager
import okhttp3.Call
import okhttp3.Callback
import okhttp3.ConnectionPool
import okhttp3.Dispatcher
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import okio.BufferedSink
class OkHttpClient
internal constructor(@JvmSynthetic internal val okHttpClient: okhttp3.OkHttpClient) : HttpClient {
override fun execute(request: HttpRequest, requestOptions: RequestOptions): HttpResponse {
val call = newCall(request, requestOptions)
return try {
call.execute().toResponse()
} catch (e: IOException) {
throw ArcadeIoException("Request failed", e)
} finally {
request.body?.close()
}
}
override fun executeAsync(
request: HttpRequest,
requestOptions: RequestOptions,
): CompletableFuture<HttpResponse> {
val future = CompletableFuture<HttpResponse>()
val call = newCall(request, requestOptions)
call.enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
future.complete(response.toResponse())
}
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(ArcadeIoException("Request failed", e))
}
}
)
future.whenComplete { _, e ->
if (e is CancellationException) {
call.cancel()
}
request.body?.close()
}
return future
}
override fun close() {
okHttpClient.dispatcher.executorService.shutdown()
okHttpClient.connectionPool.evictAll()
okHttpClient.cache?.close()
}
private fun newCall(request: HttpRequest, requestOptions: RequestOptions): Call {
val clientBuilder = okHttpClient.newBuilder()
val logLevel =
when (System.getenv("ARCADE_LOG")?.lowercase()) {
"info" -> HttpLoggingInterceptor.Level.BASIC
"debug" -> HttpLoggingInterceptor.Level.BODY
else -> null
}
if (logLevel != null) {
clientBuilder.addNetworkInterceptor(
HttpLoggingInterceptor().setLevel(logLevel).apply { redactHeader("Authorization") }
)
}
requestOptions.timeout?.let {
clientBuilder
.connectTimeout(it.connect())
.readTimeout(it.read())
.writeTimeout(it.write())
.callTimeout(it.request())
}
val client = clientBuilder.build()
return client.newCall(request.toRequest(client))
}
private fun HttpRequest.toRequest(client: okhttp3.OkHttpClient): Request {
var body: RequestBody? = body?.toRequestBody()
if (body == null && requiresBody(method)) {
body = "".toRequestBody()
}
val builder = Request.Builder().url(toUrl()).method(method.name, body)
headers.names().forEach { name ->
headers.values(name).forEach { builder.addHeader(name, it) }
}
if (
!headers.names().contains("X-Stainless-Read-Timeout") && client.readTimeoutMillis != 0
) {
builder.addHeader(
"X-Stainless-Read-Timeout",
Duration.ofMillis(client.readTimeoutMillis.toLong()).seconds.toString(),
)
}
if (!headers.names().contains("X-Stainless-Timeout") && client.callTimeoutMillis != 0) {
builder.addHeader(
"X-Stainless-Timeout",
Duration.ofMillis(client.callTimeoutMillis.toLong()).seconds.toString(),
)
}
return builder.build()
}
/** `OkHttpClient` always requires a request body for some methods. */
private fun requiresBody(method: HttpMethod): Boolean =
when (method) {
HttpMethod.POST,
HttpMethod.PUT,
HttpMethod.PATCH -> true
else -> false
}
private fun HttpRequest.toUrl(): String {
val builder = baseUrl.toHttpUrl().newBuilder()
pathSegments.forEach(builder::addPathSegment)
queryParams.keys().forEach { key ->
queryParams.values(key).forEach { builder.addQueryParameter(key, it) }
}
return builder.toString()
}
private fun HttpRequestBody.toRequestBody(): RequestBody {
val mediaType = contentType()?.toMediaType()
val length = contentLength()
return object : RequestBody() {
override fun contentType(): MediaType? = mediaType
override fun contentLength(): Long = length
override fun isOneShot(): Boolean = !repeatable()
override fun writeTo(sink: BufferedSink) = writeTo(sink.outputStream())
}
}
private fun Response.toResponse(): HttpResponse {
val headers = headers.toHeaders()
return object : HttpResponse {
override fun statusCode(): Int = code
override fun headers(): Headers = headers
override fun body(): InputStream = body!!.byteStream()
override fun close() = body!!.close()
}
}
private fun okhttp3.Headers.toHeaders(): Headers {
val headersBuilder = Headers.builder()
forEach { (name, value) -> headersBuilder.put(name, value) }
return headersBuilder.build()
}
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder internal constructor() {
private var timeout: Timeout = Timeout.default()
private var proxy: Proxy? = null
private var maxIdleConnections: Int? = null
private var keepAliveDuration: Duration? = null
private var dispatcherExecutorService: ExecutorService? = null
private var sslSocketFactory: SSLSocketFactory? = null
private var trustManager: X509TrustManager? = null
private var hostnameVerifier: HostnameVerifier? = null
fun timeout(timeout: Timeout) = apply { this.timeout = timeout }
fun timeout(timeout: Duration) = timeout(Timeout.builder().request(timeout).build())
fun proxy(proxy: Proxy?) = apply { this.proxy = proxy }
/**
* Sets the maximum number of idle connections kept by the underlying [ConnectionPool].
*
* If this is set, then [keepAliveDuration] must also be set.
*
* If unset, then OkHttp's default is used.
*/
fun maxIdleConnections(maxIdleConnections: Int?) = apply {
this.maxIdleConnections = maxIdleConnections
}
/**
* Sets the keep-alive duration for idle connections in the underlying [ConnectionPool].
*
* If this is set, then [maxIdleConnections] must also be set.
*
* If unset, then OkHttp's default is used.
*/
fun keepAliveDuration(keepAliveDuration: Duration?) = apply {
this.keepAliveDuration = keepAliveDuration
}
fun dispatcherExecutorService(dispatcherExecutorService: ExecutorService?) = apply {
this.dispatcherExecutorService = dispatcherExecutorService
}
fun sslSocketFactory(sslSocketFactory: SSLSocketFactory?) = apply {
this.sslSocketFactory = sslSocketFactory
}
fun trustManager(trustManager: X509TrustManager?) = apply {
this.trustManager = trustManager
}
fun hostnameVerifier(hostnameVerifier: HostnameVerifier?) = apply {
this.hostnameVerifier = hostnameVerifier
}
fun build(): OkHttpClient =
OkHttpClient(
okhttp3.OkHttpClient.Builder()
// `RetryingHttpClient` handles retries if the user enabled them.
.retryOnConnectionFailure(false)
.connectTimeout(timeout.connect())
.readTimeout(timeout.read())
.writeTimeout(timeout.write())
.callTimeout(timeout.request())
.proxy(proxy)
.apply {
dispatcherExecutorService?.let { dispatcher(Dispatcher(it)) }
val maxIdleConnections = maxIdleConnections
val keepAliveDuration = keepAliveDuration
if (maxIdleConnections != null && keepAliveDuration != null) {
connectionPool(
ConnectionPool(
maxIdleConnections,
keepAliveDuration.toNanos(),
TimeUnit.NANOSECONDS,
)
)
} else {
check((maxIdleConnections != null) == (keepAliveDuration != null)) {
"Both or none of `maxIdleConnections` and `keepAliveDuration` must be set, but only one was set"
}
}
val sslSocketFactory = sslSocketFactory
val trustManager = trustManager
if (sslSocketFactory != null && trustManager != null) {
sslSocketFactory(sslSocketFactory, trustManager)
} else {
check((sslSocketFactory != null) == (trustManager != null)) {
"Both or none of `sslSocketFactory` and `trustManager` must be set, but only one was set"
}
}
hostnameVerifier?.let(::hostnameVerifier)
}
.build()
.apply {
// We usually make all our requests to the same host so it makes sense to
// raise the per-host limit to the overall limit.
dispatcher.maxRequestsPerHost = dispatcher.maxRequests
}
)
}
}