-
Notifications
You must be signed in to change notification settings - Fork 407
/
core.clj
633 lines (589 loc) · 28.8 KB
/
core.clj
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
(ns clj-http.core
"Core HTTP request/response implementation. Rewrite for Apache 5.0"
(:require [clj-http.conn-mgr :as conn-mgr]
[clj-http.headers :as headers]
[clj-http.multipart :as mp]
[clj-http.util :as util :refer [opt]]
clojure.pprint
[clojure.string :as str])
(:import [java.io ByteArrayOutputStream FilterInputStream InputStream]
[java.net InetAddress ProxySelector URI URL]
java.nio.charset.StandardCharsets
java.util.concurrent.TimeUnit
[org.apache.hc.client5.http.async.methods SimpleHttpRequest SimpleHttpResponse]
[org.apache.hc.client5.http.auth AuthScope NTCredentials UsernamePasswordCredentials]
org.apache.hc.client5.http.cache.HttpCacheContext
[org.apache.hc.client5.http.classic.methods HttpUriRequest HttpUriRequestBase]
org.apache.hc.client5.http.config.RequestConfig
[org.apache.hc.client5.http.cookie CookieSpecFactory StandardCookieSpec]
[org.apache.hc.client5.http.impl.async CloseableHttpAsyncClient HttpAsyncClientBuilder HttpAsyncClients]
org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider
[org.apache.hc.client5.http.impl.cache CacheConfig CachingHttpClientBuilder]
[org.apache.hc.client5.http.impl.classic CloseableHttpClient CloseableHttpResponse HttpClientBuilder HttpClients]
org.apache.hc.client5.http.impl.DefaultRedirectStrategy
[org.apache.hc.client5.http.impl.routing DefaultProxyRoutePlanner SystemDefaultRoutePlanner]
org.apache.hc.client5.http.io.HttpClientConnectionManager
[org.apache.hc.client5.http.protocol HttpClientContext RedirectStrategy]
org.apache.hc.client5.http.routing.HttpRoutePlanner
org.apache.hc.client5.http.utils.URIUtils
[org.apache.hc.core5.http ClassicHttpResponse ContentType HttpEntity HttpHost HttpRequest HttpRequestInterceptor HttpResponse HttpResponseInterceptor ProtocolException]
org.apache.hc.core5.http.config.RegistryBuilder
[org.apache.hc.core5.http.io.entity ByteArrayEntity StringEntity]
org.apache.hc.core5.http.protocol.HttpContext
org.apache.hc.core5.util.TimeValue))
(def CUSTOM_COOKIE_POLICY "_custom")
(defn parse-headers
"Takes a HeaderIterator and returns a map of names to values.
If a name appears more than once (like `set-cookie`) then the value
will be a vector containing the values in the order they appeared
in the headers."
[headers & [use-header-maps-in-response?]]
(if-not use-header-maps-in-response?
(->> (headers/header-iterator-seq headers)
(map (fn [[k v]]
[(.toLowerCase ^String k) v]))
(reduce (fn [hs [k v]]
(headers/assoc-join hs k v))
{}))
(->> (headers/header-iterator-seq headers)
(reduce (fn [hs [k v]]
(headers/assoc-join hs k v))
(headers/header-map)))))
(defn graceful-redirect-strategy
"Similar to the default redirect strategy, however, does not throw an error
when the maximum number of redirects has been reached. Still supports
validating that the new redirect host is not empty."
[req]
(let [validate? (opt req :validate-redirects)]
(reify RedirectStrategy
(^URI getLocationURI [this ^HttpRequest request ^HttpResponse response ^HttpContext context]
(let [uri (.getLocationURI DefaultRedirectStrategy/INSTANCE request response context)]
(when (or validate? (nil? validate?))
(let [new-host (URIUtils/extractHost uri)]
(when (nil? new-host)
(throw
(ProtocolException.
(str "Redirect URI does not specify a valid host name: "
uri))))))
uri))
(isRedirected [this request response context]
(let [^HttpClientContext typed-context context
max-redirects (-> (.getRequestConfig typed-context)
.getMaxRedirects)
num-redirects (.size (.getRedirectLocations typed-context))]
(if (<= max-redirects num-redirects)
false
(.isRedirected DefaultRedirectStrategy/INSTANCE
request response typed-context)))))))
;; TODO: rename this function to match docstring, and make module private
(defn default-redirect-strategy
"Proxies calls to whatever original redirect strategy is passed in, however,
if :validate-redirects is set in the request, checks that the redirected host
is not empty."
[^RedirectStrategy original req]
(let [validate? (opt req :validate-redirects)]
(reify RedirectStrategy
(^URI getLocationURI [this ^HttpRequest request ^HttpResponse response ^HttpContext context]
(let [uri (.getLocationURI DefaultRedirectStrategy/INSTANCE request response context)]
(when (or validate? (nil? validate?))
(let [new-host (URIUtils/extractHost uri)]
(when (nil? new-host)
(throw
(ProtocolException.
(str "Redirect URI does not specify a valid host name: "
uri))))))
uri))
(isRedirected [this request response context]
(.isRedirected original request response context)))))
(defn get-redirect-strategy [{:keys [redirect-strategy] :as req}]
(if (instance? RedirectStrategy redirect-strategy)
redirect-strategy
(case redirect-strategy
:none (reify RedirectStrategy
(getLocationURI [this request response context] nil)
(isRedirected [this request response context] false))
;; Like default, but does not throw exceptions when max redirects is
;; reached.
:graceful (default-redirect-strategy (graceful-redirect-strategy req) req)
:default (default-redirect-strategy DefaultRedirectStrategy/INSTANCE req)
nil (default-redirect-strategy DefaultRedirectStrategy/INSTANCE req)
;; use default
(default-redirect-strategy DefaultRedirectStrategy/INSTANCE req))))
;; TODO: reimplement for with add-retry-strategy
#_(defn ^HttpClientBuilder add-retry-handler [^HttpClientBuilder builder handler]
(when handler
(.setRetryHandler
builder
(proxy [HttpRequestRetryHandler] []
(retryRequest [e cnt context]
(handler e cnt context)))))
builder)
(defn create-custom-cookie-policy-registry
"Given a function that will take an HttpContext and return a CookieSpec,
create a new Registry for the cookie policy under the CUSTOM_COOKIE_POLICY
string."
[cookie-spec-fn]
(-> (RegistryBuilder/create)
(.register CUSTOM_COOKIE_POLICY
(proxy [CookieSpecFactory] []
(create [context]
(cookie-spec-fn context))))
(.build)))
(defmulti get-cookie-policy
"Method to retrieve the cookie policy that should be used for the request.
This is a multimethod that may be extended to return your own cookie policy.
Dispatches based on the `:cookie-policy` key in the request map."
(fn get-cookie-dispatch [request] (:cookie-policy request)))
(defmethod get-cookie-policy :none none-cookie-policy
[_] StandardCookieSpec/IGNORE)
(defmethod get-cookie-policy :default default-cookie-policy
[_] StandardCookieSpec/RELAXED)
(defmethod get-cookie-policy nil nil-cookie-policy
[_] StandardCookieSpec/RELAXED)
(defmethod get-cookie-policy :ignore netscape-cookie-policy
[_] StandardCookieSpec/IGNORE)
(defmethod get-cookie-policy :standard standard-cookie-policy
[_] StandardCookieSpec/RELAXED)
(defmethod get-cookie-policy :stardard-strict standard-strict-cookie-policy
[_] StandardCookieSpec/STRICT)
(defn request-config [{:keys [connection-timeout
connection-request-timeout
max-redirects
cookie-spec]
:as req}]
(let [config (-> (RequestConfig/custom)
(.setRedirectsEnabled true)
(.setCircularRedirectsAllowed
(boolean (opt req :allow-circular-redirects))))]
(and connection-timeout
(.setConnectTimeout
config connection-timeout TimeUnit/MILLISECONDS))
(and connection-request-timeout
(.setConnectionRequestTimeout
config connection-request-timeout TimeUnit/MILLISECONDS))
(if cookie-spec
(.setCookieSpec config CUSTOM_COOKIE_POLICY)
(.setCookieSpec config (get-cookie-policy req)))
(when max-redirects (.setMaxRedirects config max-redirects))
(.build config)))
(defmulti ^:private construct-http-host (fn [proxy-host proxy-port]
(class proxy-host)))
(defmethod construct-http-host String
[^String proxy-host ^Long proxy-port]
(if proxy-port
(HttpHost. proxy-host proxy-port)
(HttpHost. proxy-host)))
(defmethod construct-http-host java.net.InetAddress
[^InetAddress proxy-host ^Long proxy-port]
(if proxy-port
(HttpHost. proxy-host proxy-port)
(HttpHost. proxy-host)))
(defn ^HttpRoutePlanner get-route-planner
"Return an HttpRoutePlanner that either use the supplied proxy settings
if any, or the JVM/system proxy settings otherwise"
[^String proxy-host ^Long proxy-port proxy-ignore-hosts http-url]
(let [ignore-proxy? (and http-url
(contains? (set proxy-ignore-hosts)
(.getHost (URL. http-url))))]
(if (and proxy-host (not ignore-proxy?))
(DefaultProxyRoutePlanner. (construct-http-host proxy-host proxy-port))
(SystemDefaultRoutePlanner. (ProxySelector/getDefault)))))
(defn build-cache-config
"Given a request with :cache-config as a map or a CacheConfig object, return a
CacheConfig object, or nil if no cache config is found. If :cache-config is a
map, it checks for the following options:
- :allow-303-caching
- :asynchronous-workers
- :heuristic-caching-enabled
- :heuristic-coefficient
- :heuristic-default-lifetime
- :max-cache-entries
- :max-object-size
- :max-update-retries
- :never-cache-http10-responses-with-query-string
- :shared-cache
- :weak-etag-on-put-delete-allowed"
[request]
(when-let [cc (:cache-config request)]
(if (instance? CacheConfig cc)
cc
(let [config (CacheConfig/custom)
{:keys [allow-303-caching
asynchronous-workers
heuristic-caching-enabled
heuristic-coefficient
heuristic-default-lifetime
max-cache-entries
max-object-size
max-update-retries
never-cache-http10-responses-with-query-string
shared-cache
weak-etag-on-put-delete-allowed]} cc]
(when (instance? Boolean allow-303-caching)
(.setAllow303Caching config allow-303-caching))
(when asynchronous-workers
(.setAsynchronousWorkers config asynchronous-workers))
(when (instance? Boolean heuristic-caching-enabled)
(.setHeuristicCachingEnabled config heuristic-caching-enabled))
(when heuristic-coefficient
(.setHeuristicCoefficient config heuristic-coefficient))
(when heuristic-default-lifetime
(.setHeuristicDefaultLifetime config (TimeValue/ofMilliseconds heuristic-default-lifetime)))
(when max-cache-entries
(.setMaxCacheEntries config max-cache-entries))
(when max-object-size
(.setMaxObjectSize config max-object-size))
(when max-update-retries
(.setMaxUpdateRetries config max-update-retries))
(when (instance? Boolean never-cache-http10-responses-with-query-string)
(.setNeverCacheHTTP10ResponsesWithQueryString
config never-cache-http10-responses-with-query-string))
(when (instance? Boolean shared-cache)
(.setSharedCache config shared-cache))
(when (instance? Boolean weak-etag-on-put-delete-allowed)
(.setWeakETagOnPutDeleteAllowed config weak-etag-on-put-delete-allowed))
(.build config)))))
(defn build-http-client
"Builds an Apache `HttpClient` from a clj-http request map. Optional arguments
`http-url` and `proxy-ignore-hosts` are used to specify the host and a list of
hostnames to ignore for any proxy settings. They can be safely ignored if not
using proxies."
[{:keys [retry-handler request-interceptor
response-interceptor proxy-host proxy-port
http-builder-fns cookie-spec
cookie-policy-registry ntlm-auth
^HttpClientBuilder http-client-builder]
:as req}
caching?
^HttpClientConnectionManager conn-mgr
& [http-url proxy-ignore-hosts]]
;; have to let first, otherwise we get a reflection warning on (.build)
(let [cache? (opt req :cache)
^HttpClientBuilder builder (cond
http-client-builder
http-client-builder
caching?
(-> (CachingHttpClientBuilder/create)
(.setCacheConfig (build-cache-config req)))
:else
(HttpClients/custom))
builder (-> builder
(.setConnectionManager conn-mgr)
(.setRedirectStrategy
(get-redirect-strategy req))
#_(add-retry-handler retry-handler)
;; prefer using clj-http.client/wrap-decompression
;; for consistency between sync/async client options
(.disableContentCompression)
;; By default, get the proxy settings
;; from the jvm or system properties
(.setRoutePlanner
(get-route-planner
proxy-host proxy-port
proxy-ignore-hosts http-url)))]
(when-let [[user password host domain] ntlm-auth]
(.setDefaultCredentialsProvider
builder
(doto (BasicCredentialsProvider.)
(.setCredentials (AuthScope. nil -1 nil)
(NTCredentials. user password host domain)))))
(when (or cookie-policy-registry cookie-spec)
(if cookie-policy-registry
;; They have a custom registry they'd like to re-use, so use that
(.setDefaultCookieSpecRegistry builder cookie-policy-registry)
;; They have only a one-time function for cookie spec, so use that
(.setDefaultCookieSpecRegistry
builder (create-custom-cookie-policy-registry cookie-spec))))
(when request-interceptor
(.addRequestInterceptorLast
builder (reify HttpRequestInterceptor
(process [_ req entity-details ctx]
(request-interceptor
req entity-details ctx)))))
(when response-interceptor
(.addResponseInterceptorLast
builder (reify HttpResponseInterceptor
(process [_ resp entity-details ctx]
(response-interceptor
resp entity-details ctx)))))
(doseq [http-builder-fn http-builder-fns]
(http-builder-fn builder req))
(.build builder)))
(defn build-async-http-client
"Builds an Apache `HttpAsyncClient` from a clj-http request map. Optional
arguments `http-url` and `proxy-ignore-hosts` are used to specify the host
and a list of hostnames to ignore for any proxy settings. They can be safely
ignored if not using proxies."
[{:keys [request-interceptor response-interceptor
proxy-host proxy-port async-http-builder-fns]
:as req}
conn-mgr & [http-url proxy-ignore-hosts]]
;; have to let first, otherwise we get a reflection warning on (.build)
(let [^HttpAsyncClientBuilder builder (-> (HttpAsyncClients/custom)
(.setConnectionManager conn-mgr)
(.setRedirectStrategy
(get-redirect-strategy req))
;; By default, get the proxy
;; settings from the jvm or system
;; properties
(.setRoutePlanner
(get-route-planner
proxy-host proxy-port
proxy-ignore-hosts http-url)))]
(.setIOReactorConfig builder (conn-mgr/ioreactor-config req))
(.setConnectionManagerShared builder true)
(when request-interceptor
(.addRequestInterceptorLast
builder (proxy [HttpRequestInterceptor] []
(process [req entity ctx]
(request-interceptor req entity ctx)))))
(when response-interceptor
(.addResponseInterceptorLast
builder (proxy [HttpResponseInterceptor] []
(process [resp entity ctx]
(response-interceptor
resp entity ctx)))))
(doseq [async-http-builder-fn async-http-builder-fns]
(async-http-builder-fn builder req))
(.build builder)))
(def ^:dynamic *cookie-store* nil)
(defn ^HttpClientContext http-context [caching? request-config http-client-context]
(let [^HttpClientContext typed-context (or http-client-context
(if caching?
(HttpCacheContext/create)
(HttpClientContext/create)))]
(doto typed-context
(.setRequestConfig request-config))))
(defn ^BasicCredentialsProvider credentials-provider []
(BasicCredentialsProvider.))
(defn- coerce-body-entity
"Coerce the http-entity from an HttpResponse to a stream that closes itself
and the connection manager when closed."
[^HttpEntity http-entity conn-mgr ^CloseableHttpResponse response conn-mgr-reusable?]
(if http-entity
(proxy [FilterInputStream]
[^InputStream (.getContent http-entity)]
(close []
(try
;; Eliminate the reflection warning from proxy-super
(let [^InputStream this this]
(proxy-super close))
(finally
(when (instance? CloseableHttpResponse response)
(.close response))
(when-not conn-mgr-reusable?
(conn-mgr/shutdown-manager conn-mgr))))))
(when-not conn-mgr-reusable?
(conn-mgr/shutdown-manager conn-mgr))))
(defn- print-debug!
"Print out debugging information to *out* for a given request."
[{:keys [debug-body body] :as req} http-req]
(println
(with-out-str
(println "Request:" (type body))
(clojure.pprint/pprint
(assoc req
:body (if (opt req :debug-body)
(cond
(isa? (type body) String)
body
(isa? (type body) HttpEntity)
(let [baos (ByteArrayOutputStream.)]
(.writeTo ^HttpEntity body baos)
(.toString baos "UTF-8"))
:else nil)
(if (isa? (type body) String)
(format "... %s bytes ..."
(count body))
(and body (bean body))))
:body-type (type body)))
(println "HttpRequest:")
(clojure.pprint/pprint (bean http-req)))))
(defn- build-response-map
[^HttpResponse response req ^HttpUriRequest http-req http-url
conn-mgr ^HttpClientContext context ^CloseableHttpClient client conn-mgr-reusable?]
(let [^HttpEntity entity (cond
;; blocking http client
(instance? ClassicHttpResponse response)
(.getEntity ^ClassicHttpResponse response)
;; async http client
(instance? SimpleHttpResponse response)
(ByteArrayEntity.
(.getBodyBytes ^SimpleHttpResponse response)
(.getContentType ^SimpleHttpResponse response)))
status (.getCode response)
protocol-version (.getVersion response)
body (:body req)
response
{:body (coerce-body-entity entity conn-mgr response conn-mgr-reusable?)
:http-client client
:headers (parse-headers
(.headerIterator response)
(opt req :use-header-maps-in-response))
:length (if (nil? entity) 0 (.getContentLength entity))
:chunked? (if (nil? entity) false (.isChunked entity))
:repeatable? (if (nil? entity) false (.isRepeatable entity))
:streaming? (if (nil? entity) false (.isStreaming entity))
:status status
:protocol-version {:name (.getProtocol protocol-version)
:major (.getMajor protocol-version)
:minor (.getMinor protocol-version)}
:reason-phrase (.getReasonPhrase response)
:cached (when (instance? HttpCacheContext context)
(when-let [cache-resp (.getCacheResponseStatus ^HttpCacheContext context)]
(-> cache-resp str keyword)))
:trace-redirects (->> (.getRedirectLocations context)
(.getAll)
(mapv str))}]
(if (opt req :save-request)
(-> response
(assoc :request req)
(assoc-in [:request :body-type] (type body))
(assoc-in [:request :http-url] http-url)
(update-in [:request]
#(if (opt req :debug-body)
(assoc % :body-content
(cond
(isa? (type (:body %)) String)
(:body %)
(isa? (type (:body %)) HttpEntity)
(let [baos (ByteArrayOutputStream.)]
(.writeTo ^HttpEntity (:body %) baos)
(.toString baos "UTF-8"))
:else nil))
%))
(assoc-in [:request :http-req] http-req))
response)))
(defn- get-conn-mgr
[async? req]
(if async?
(or conn-mgr/*async-connection-manager*
(conn-mgr/make-async-conn-manager req))
(or conn-mgr/*connection-manager*
(conn-mgr/make-conn-manager req))))
(defn request
([req] (request req nil nil))
([{:keys [body connection-timeout connection-request-timeout connection-manager
cookie-store cookie-policy headers multipart
query-string redirect-strategy max-redirects
retry-handler request-method scheme server-name server-port
socket-timeout uri response-interceptor proxy-host proxy-port
http-client-context http-request-config http-client
proxy-ignore-hosts proxy-user proxy-pass digest-auth ntlm-auth
multipart-mode multipart-charset mime-subtype]
:as req} respond raise]
(let [async? (opt req :async)
cache? (opt req :cache)
scheme (name scheme)
http-url (str scheme "://" server-name
(when server-port (str ":" server-port))
uri
(when query-string (str "?" query-string)))
;; Has an async connection manager binded *or* specified explicitly?
conn-mgr (or connection-manager
(get-conn-mgr async? req))
conn-mgr-reusable? (boolean (or connection-manager
(if async?
(= conn-mgr conn-mgr/*async-connection-manager*)
(= conn-mgr conn-mgr/*connection-manager*))))
proxy-ignore-hosts (or proxy-ignore-hosts
#{"localhost" "127.0.0.1"})
^RequestConfig request-config (or http-request-config
(request-config req))
^HttpClientContext context
(http-context cache? request-config http-client-context)
^HttpUriRequest http-req (HttpUriRequestBase.
(str/upper-case (name request-method))
(URI/create http-url))]
;; Either it's not async and not reusable, or it's regular and not reusable
(when-not conn-mgr-reusable?
(.addHeader http-req "Connection" "close"))
(when-let [cookie-jar (or cookie-store *cookie-store*)]
(.setCookieStore context cookie-jar))
(when-let [[user pass] digest-auth]
(.setCredentialsProvider
context
(doto (credentials-provider)
(.setCredentials (AuthScope. nil -1 nil)
(UsernamePasswordCredentials. user pass)))))
(when (and proxy-user proxy-pass)
(let [authscope (AuthScope. proxy-host proxy-port)
creds (UsernamePasswordCredentials. proxy-user proxy-pass)]
(.setCredentialsProvider
context
(doto (credentials-provider)
(.setCredentials authscope creds)))))
(if multipart
(.setEntity http-req
(mp/create-multipart-entity multipart req))
(if (instance? HttpEntity body)
(.setEntity http-req body)
(when body
(.setEntity http-req
(if (string? body)
(StringEntity. ^String body StandardCharsets/UTF_8)
(ByteArrayEntity. body ContentType/WILDCARD))))))
(doseq [[header-n header-v] headers]
(if (coll? header-v)
(doseq [header-vth header-v]
(.addHeader http-req header-n header-vth))
(.addHeader http-req header-n (str header-v))))
(when (opt req :debug) (print-debug! req http-req))
(if-not async?
;; Synchronous version
(let [^CloseableHttpClient client
(or http-client
(build-http-client req cache?
conn-mgr http-url proxy-ignore-hosts))]
(try
(build-response-map (.execute client http-req context)
req http-req http-url conn-mgr context client
conn-mgr-reusable?)
(catch Throwable t
(when-not conn-mgr-reusable?
(conn-mgr/shutdown-manager conn-mgr))
(throw t))))
;; Async version
(let [^CloseableHttpAsyncClient client
(build-async-http-client req conn-mgr http-url proxy-ignore-hosts)
original-thread-bindings (clojure.lang.Var/getThreadBindingFrame)
async-http-request (SimpleHttpRequest/copy http-req)]
;; TODO: this is not a nio/reactive friendly approach nio-friendly solution
(when-let [entity (.getEntity http-req)]
(let [bytes (util/force-byte-array (.getContent entity))
content-type (ContentType/parse (.getContentType entity))]
(.setBody async-http-request bytes content-type)))
(when cache?
(throw (IllegalArgumentException.
"caching is not yet supported for async clients")))
(.start client)
(.execute ^CloseableHttpAsyncClient client async-http-request ^HttpContext context
(reify org.apache.hc.core5.concurrent.FutureCallback
(failed [this ex]
(clojure.lang.Var/resetThreadBindingFrame original-thread-bindings)
(when-not conn-mgr-reusable?
(conn-mgr/shutdown-manager conn-mgr))
(if (opt req :ignore-unknown-host)
((:unknown-host-respond req) nil)
(raise ex)))
(completed [this resp]
(clojure.lang.Var/resetThreadBindingFrame original-thread-bindings)
(try
(respond (build-response-map
resp req http-req http-url
conn-mgr context client
conn-mgr-reusable?
))
(catch Throwable t
(when-not conn-mgr-reusable?
(conn-mgr/shutdown-manager conn-mgr))
(raise t))))
(cancelled [this]
(clojure.lang.Var/resetThreadBindingFrame original-thread-bindings)
;; Run the :oncancel function if available
(when-let [oncancel (:oncancel req)]
(oncancel))
;; Attempt to abort the execution of the request
(.abort http-req)
(when-not conn-mgr-reusable?
(conn-mgr/shutdown-manager conn-mgr))))))))))