Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add :async-future as an option for async request processing #516

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion README.org
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
- [[#post][POST]]
- [[#delete][DELETE]]
- [[#async-http-request][Async HTTP Request]]
- [[#async-futures][Async Futures]]
- [[#cancelling-requests][Cancelling Requests]]
- [[#coercions][Coercions]]
- [[#input-coercion][Input coercion]]
Expand Down Expand Up @@ -429,12 +430,22 @@ start an async request is easy, for example:

All exceptions thrown during the request will be passed to the raise callback.

*** Async Futures
Alternatively, if you prefer working with Futures, you can get the async response in the shape of a Future:

#+begin_src clojure
(def fut (client/get "http://example.com" {:async-future? true}))
@fut
#+end_src

Deref-ing the future will return the response map or throw a [[https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutionException.html][ExecutionException]] on error.

*** Cancelling Requests
:PROPERTIES:
:CUSTOM_ID: cancelling-requests
:END:

Calls to the http methods with =:async true= return an Apache [[https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/concurrent/BasicFuture.html][BasicFuture]] that you can call =.get=
Calls to the http methods with =:async true or :async-future true= return an Apache [[https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/concurrent/BasicFuture.html][BasicFuture]] that you can call =.get=
or =.cancel= on. See the Javadocs for =BasicFuture= [[https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/concurrent/BasicFuture.html][here]]. For instance:

#+BEGIN_SRC clojure
Expand Down
18 changes: 16 additions & 2 deletions src/clj_http/client.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1168,12 +1168,26 @@
(throw (IllegalArgumentException. "Host URL cannot be nil"))))

(defn- request*
[req [respond raise]]
(if (opt req :async)
[req & [respond raise]]
{:pre [(not (and (:async req) (:async-future req)))]}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should use (opt req :async) and (opt req :async-future) so they support the optional ? suffix

(cond
(opt req :async)
(if (some nil? [respond raise])
(throw (IllegalArgumentException.
"If :async? is true, you must pass respond and raise"))
(request (dissoc req :respond :raise) respond raise))

(opt req :async-future)
(let [basic-future (org.apache.http.concurrent.BasicFuture. nil)]
(request (-> req
(dissoc :async-future)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In order to avoid having multiple options I think this should be:

Suggested change
(dissoc :async-future)
(dissoc :async :async? :async-future :async-future?)

(assoc :async true
:oncancel #(.cancel basic-future)))
#(.completed basic-future %)
#(.failed basic-future %))
basic-future)

:default
(request req)))

(defn get
Expand Down
51 changes: 49 additions & 2 deletions test/clj_http/test/client_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@

(defn request
([req]
(client/request (merge base-req req)))
(#'client/request* (merge base-req req)))
([req respond raise]
(client/request (merge base-req req) respond raise)))
(#'client/request* (merge base-req req) respond raise)))

(defn parse-form-params [s]
(->> (str/split (form-decode-str s) #"&")
Expand Down Expand Up @@ -90,6 +90,14 @@
(is (= "get" (:body @resp)))
(is (not (realized? exception))))

;; roundrtrip with error handling
(let [resp (promise)
exception (promise)
_ (request {:uri "/error" :method :get
:scheme "http"
:async? true} resp exception)]
(is (instance? Exception @exception)))

(let [params {:a "1" :b "2"}]
(doseq [[content-type read-fn]
[[nil (comp parse-form-params slurp)]
Expand All @@ -111,6 +119,45 @@
(is (= params (read-fn (:body @resp))))
(is (not (realized? exception)))))))

(deftest ^:integration roundtrip-async-future
(run-server)
;; roundtrip with scheme as a keyword
(let [resp (request {:uri "/get" :method :get
:async-future? true})]
(is (= 200 (:status @resp)))
(is (= "close" (get-in @resp [:headers "connection"])))
(is (= "get" (:body @resp))))
;; roundtrip with scheme as a string
(let [resp (request {:uri "/get" :method :get
:scheme "http"
:async-future? true})]
(is (= 200 (:status @resp)))
(is (= "close" (get-in @resp [:headers "connection"])))
(is (= "get" (:body @resp))))
;; error handling
(let [resp (request {:uri "/error" :method :get
:async-future? true})]
(is (thrown? java.util.concurrent.ExecutionException
@resp)))

(let [params {:a "1" :b "2"}]
(doseq [[content-type read-fn]
[[nil (comp parse-form-params slurp)]
[:x-www-form-urlencoded (comp parse-form-params slurp)]
[:edn (comp read-string slurp)]
[:transit+json #(client/parse-transit % :json)]
[:transit+msgpack #(client/parse-transit % :msgpack)]]]
(let [resp (request {:uri "/post"
:as :stream
:method :post
:content-type content-type
:flatten-nested-keys []
:form-params params
:async-future? true})]
(is (= 200 (:status @resp)))
(is (= "close" (get-in @resp [:headers "connection"])))
(is (= params (read-fn (:body @resp))))))))

(def ^:dynamic *test-dynamic-var* nil)

(deftest ^:integration async-preserves-dynamic-variable-bindings
Expand Down