Skip to content

Commit

Permalink
feat: Add antq.util.async/fn-with-timeout
Browse files Browse the repository at this point in the history
cf. #158
  • Loading branch information
liquidz committed Jun 20, 2022
1 parent 4104cd8 commit 0844604
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/antq/util/async.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
(ns antq.util.async
(:require
[clojure.core.async :as async]))

(defn fn-with-timeout
[f timeout-ms]
(fn [& args]
(let [ch (async/chan)]
(async/go
(let [ret (try
(apply f args)
(catch Throwable ex
[::exception ex]))]
(async/>! ch ret)))
(let [ret (-> [ch
(async/timeout timeout-ms)]
(async/alts!!)
(first))]

(if (and (vector? ret) (= ::exception (first ret)))
(throw (second ret))
ret)))))
28 changes: 28 additions & 0 deletions test/antq/util/async_test.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
(ns antq.util.async-test
(:require
[antq.util.async :as sut]
[clojure.core.async :as async]
[clojure.test :as t]))

(def ^:private test-async-fn
(sut/fn-with-timeout
(fn [x]
(cond
(= ::error x)
(throw (Exception. "test error"))

(= ::timeout x)
(do (async/<!! (async/timeout 500))
x)

:else
x))
100))

(t/deftest fn-with-timeout-test
(t/is (= 10 (test-async-fn 10)))
(t/is (nil? (test-async-fn ::timeout)))
(t/is (thrown-with-msg? Exception #"^test error$"
(test-async-fn ::error))))


0 comments on commit 0844604

Please sign in to comment.