/
auspex.clj
217 lines (186 loc) · 6 KB
/
auspex.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
(ns qbits.auspex
"This provides a clj friendly wrapper for CompletableFuture and adds a
few utility functions to mimic manifold features. Shamelessly stole
code/ideas from the awesome manifold library."
(:refer-clojure :exclude [future future? realized? loop recur empty])
(:require [qbits.auspex :as a]
[qbits.auspex.function :as f]
[qbits.auspex.impl :as impl]
[qbits.auspex.protocols :as p])
(:import (java.util.concurrent CompletableFuture)))
(set! *warn-on-reflection* true)
(def error! #'p/-error!)
(def error? #'p/-error?)
(def catch #'p/-catch)
(def finally #'p/-finally)
(def complete! #'p/-complete!)
(def success! #'p/-success!)
(def realized? #'p/-realized?)
(def handle #'p/-handle)
(def then #'p/-then)
(def fmap #'p/-fmap)
(def when-complete #'p/-when-complete)
(def cancel! #'p/-cancel!)
(def canceled? #'p/-canceled?)
(def timeout! #'p/-timeout!)
(def wrap #'p/-wrap)
(def empty #'p/-empty)
(defn future?
[x]
(satisfies? p/Future x))
(defn future
"No arg creates an empty/incomplete future, 1 arg creates a future
that will get the return value of f as realized value on fork-join
common pool, 2 arg creates a future that will be realized on
ExecutorService supplied with return value of f as realized value.
The executor that is set at this stage will continue to be used for
subsequent steps (then/chain etc) if another one is not specified at
another level"
([] (CompletableFuture.))
([f]
(CompletableFuture/supplyAsync (f/supplier f)))
([f executor]
(CompletableFuture/supplyAsync (f/supplier f)
executor)))
(defn success-future
"Returns a new CompletableFuture that is already completed with the
given value."
[x]
(CompletableFuture/completedFuture x))
(defn error-future
"Returns a new CompletableFuture that is already completed
exceptionally with the given exception."
[^Throwable x]
(CompletableFuture/failedFuture x))
(defn chain'
"Like chain but assumes fns return raw values instead of potential
futures"
[x & fns]
(reduce then (wrap x) fns))
(defn chain
"Composes functions starting with x as argument triggering calls to
fns for every step coercing the return values to deferreds if
necessary and returns a deferred with the final result."
[x & fns]
(reduce (fn [fut f]
(fmap fut
(fn [x]
(wrap (f x)))))
(wrap x)
fns))
(defn chain-futures
"Like chain but takes a value and functions that will return futures"
[x & fs]
(reduce fmap (wrap x) fs))
(defn any'
"Like `any` but faster if you know you're only dealing with future args"
[fs]
(CompletableFuture/anyOf (into-array CompletableFuture fs)))
(defn any
"Returns one value from a collection of futures"
[xs]
(any' (map wrap xs)))
(defn one'
"Like `one` but faster if you know you're only dealing with future args"
[& fs]
(any' fs))
(defn one
"Returns one value from a list of futures"
[& xs]
(any' (map wrap xs)))
(defn all'
"Like `all` buf faster if you know you're only dealing with futures
args"
[fs]
(-> (CompletableFuture/allOf (into-array CompletableFuture fs))
(then (fn [_]
(map deref fs)))))
(defn all
"Takes a collection of values, some of which may be futures, and
returns a future that will contain a list of realized values"
[xs]
(all' (map wrap xs)))
(defn zip'
"Like zip but faster if you know you're only dealing with futures
args"
[& fs]
(all' fs))
(defn zip
"Takes a list of values, some of which can be futures and returns a
future that will contains a list of realized values"
[& xs]
(all' (map wrap xs)))
(deftype Recur [args]
clojure.lang.IDeref
(deref [_] args))
(defn recur
"Like recur, but to be used with `qbits.auspex/loop`"
[& args]
(Recur. args))
(defn recur?
[x]
(instance? Recur x))
(defmacro loop
"A version of Clojure's loop which allows for asynchronous loops, via
`qbits.auspex/recur`. `loop` will always return a CompletableFuture
Value, even if the body is synchronous. Note that `loop` does
**not** coerce values to deferreds, actual `qbits.auspex/future`s
must be used.
(loop [i 1e6]
(chain (future i)
#(if (zero? %)
%
(recur (dec %)))))"
[bindings & body]
(let [pairs (partition 2 bindings)
vars (map first pairs)
vals (map second pairs)
var-syms (map (fn [_] (gensym "var")) vars)]
`(let [result# (future)]
((fn fun# [result# ~@var-syms]
(clojure.core/loop [~@(interleave vars var-syms)]
(let [ret# (try
~@body
(catch Throwable t#
(error! result# t#)))]
(cond
(future? ret#)
(handle ret#
(fn [ok# err#]
(cond
err#
(error! result# err#)
(recur? ok#)
(apply fun# result# @ok#)
:else
(success! result# ok#))))
(recur? ret#)
(apply fun# result# @ret#)
:else
(success! result# ret#)))))
result#
~@vals)
result#)))
(defmacro let-flow
"manifold.`let-flow` port"
[steps & body]
(let [steps-pairs (partition 2 steps)]
(reduce (fn [step [x f]]
(case x
:when `(when ~f ~step)
`(chain ~f (fn [~x] ~step))))
`(do ~@body)
(reverse steps-pairs))))
(def ex-unwrap
"Takes input exception and return the original exception cause (if
any). This unwraps `ExecutionException` and `CompletionException`"
impl/ex-unwrap)
(defn unwrap
"Tries to deref a Future, returns a value upon completion or the
original exception that triggered exceptional termination (as
opposed to a wrapped exception)"
[f]
(try
@f
(catch Exception e
(throw (ex-unwrap e)))))