-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
csp.clj
436 lines (378 loc) · 13.8 KB
/
csp.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
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) Andrey Antukh <niwi@niwi.nz>
(ns promesa.exec.csp
"A core.async analogous implementation of channels that uses promises
instead of callbacks for all operations and are intended to be used
as-is (using blocking operations) in go-blocks backed by virtual
threads.
There are no macro transformations, go blocks are just alias for the
`promesa.core/vthread` macro that launches an virtual thread.
This code is based on the same ideas as core.async but the
implementation is written from scratch, for make it more
simplier (and smaller, because it does not intend to solve all the
corner cases that core.async does right now).
This code is implemented in CLJS for make available the channel
abstraction to the CLJS, but the main use case for this ns is
targeted to the JVM, where you will be able to take advantage of
virtual threads and seamless blocking operations on channels.
**EXPERIMENTAL API**"
(:refer-clojure :exclude [take])
(:require
[promesa.core :as p]
[promesa.exec :as px]
[promesa.exec.csp.buffers :as buffers]
[promesa.exec.csp.channel :as channel]
[promesa.protocols :as pt]
[promesa.util :as pu]))
(set! *warn-on-reflection* true)
(defmacro go
"Schedules the body to be executed asychronously, potentially using
virtual thread if available (a normal thread will be used in other
case). Returns a promise instance that resolves with the return
value when the asynchronous block finishes.
Forwards dynamic bindings."
[& body]
`(->> (px/wrap-bindings (fn [] ~@body))
(p/thread-call channel/*executor*)))
(defmacro go-loop
"A convencience helper macro that combines go + loop."
[bindings & body]
`(go (loop ~bindings ~@body)))
(declare offer!)
(declare close!)
(declare chan)
(defmacro go-chan
"A convencience go macro version that returns a channel instead
of a promise instance."
[& body]
`(let [c# (chan 1)]
(->> (go ~@body)
(p/fnly (fn [v# e#]
(offer! c# (or v# e#))
(close! c#))))
c#))
(defn chan
"Creates a new channel instance, it optionally accepts buffer,
transducer and error handler. If buffer is an integer, it will be
used as initial capacity for the expanding buffer."
([] (chan nil nil nil))
([buf] (chan buf nil nil))
([buf xf] (chan buf xf nil))
([buf xf exh]
(let [buf (if (number? buf)
(buffers/expanding buf)
buf)]
(channel/chan buf xf exh))))
(defn put
"Schedules a put operation on the channel. Returns a promise
instance that will resolve to: false if channel is closed, true if
put is succeed. If channel has buffer, it will return immediatelly
with resolved promise.
Optionally accepts a timeout-duration and timeout-value. The
`timeout-duration` can be a long or Duration instance measured in
milliseconds."
([port val]
(let [d (p/deferred)]
(pt/-put! port val (channel/promise->handler d))
d))
([port val timeout-duration]
(put port val timeout-duration nil))
([port val timeout-duration timeout-value]
(let [d (p/deferred)
h (channel/promise->handler d)
t (px/schedule! timeout-duration
#(when-let [f (channel/commit! h)]
(f timeout-value)))]
(pt/-put! port val h)
(p/finally d (fn [_ _] (p/cancel! t))))))
(defn put!
"A blocking version of `put`."
([port val]
(p/await! (put port val)))
([port val timeout-duration]
(p/await! (put port val timeout-duration nil)))
([port val timeout-duration timeout-value]
(p/await! (put port val timeout-duration timeout-value))))
(defn >!
"A convenience alias for `put!`."
([port val]
(p/await! (put port val)))
([port val timeout-duration]
(p/await! (put port val timeout-duration nil)))
([port val timeout-duration timeout-value]
(p/await! (put port val timeout-duration timeout-value))))
(defn take
"Schedules a take operation on the channel. Returns a promise instance
that will resolve to: nil if channel is closed, obj if value is
found. If channel has non-empty buffer the take operation will
succeed immediatelly with resolved promise.
Optionally accepts a timeout-duration and timeout-value. The
`timeout-duration` can be a long or Duration instance measured in
milliseconds."
([port]
(let [d (p/deferred)]
(pt/-take! port (channel/promise->handler d))
d))
([port timeout-duration]
(take port timeout-duration nil))
([port timeout-duration timeout-value]
(let [d (p/deferred)
h (channel/promise->handler d)
t (px/schedule! timeout-duration
#(when-let [f (channel/commit! h)]
(f timeout-value)))]
(pt/-take! port h)
(p/finally d (fn [_ _] (p/cancel! t))))))
(defn take!
"Blocking version of `take`."
([port]
(p/await! (take port)))
([port timeout-duration]
(p/await! (take port timeout-duration nil)))
([port timeout-duration timeout-value]
(p/await! (take port timeout-duration timeout-value))))
(defn <!
"A blocking version of `take!`"
([port]
(p/await! (take port)))
([port timeout-duration]
(p/await! (take port timeout-duration nil)))
([port timeout-duration timeout-value]
(p/await! (take port timeout-duration timeout-value))))
(defn- alts*
[ports {:keys [priority]}]
(let [ret (p/deferred)
lock (channel/promise->handler ret)
ports (if priority ports (shuffle ports))
handler (fn [port]
(reify
pt/ILock
(-lock! [_] (pt/-lock! lock))
(-unlock! [_] (pt/-unlock! lock))
pt/IHandler
(-active? [_] (pt/-active? lock))
(-blockable? [_] (pt/-blockable? lock))
(-commit! [_]
(when-let [f (pt/-commit! lock)]
(fn [val]
(f [val port]))))))]
(loop [ports (seq ports)]
(when-let [port (first ports)]
(if (vector? port)
(let [[port val] port]
(pt/-put! port val (handler port)))
(pt/-take! port (handler port)))
(recur (rest ports))))
ret))
(defn alts
"Completes at most one of several operations on channel. Receives a
vector of operations and optional keyword options.
A channel operation is defined as a vector of 2 elements for take,
and 3 elements for put. Unless the :priority option is true and if
more than one channel operation is ready, a non-deterministic choice
will be made.
Returns a promise instance that will be resolved when a single
operation is ready to a vector [val channel] where val is return
value of the operation and channel identifies the channel where the
the operation is succeeded."
[ports & {:as opts}]
(alts* ports opts))
(defn alts!
"A blocking variant of `alts`."
[ports & {:as opts}]
(p/await! (alts* ports opts)))
(defn close!
"Close the channel."
[port]
(pt/-close! port)
nil)
(defn closed?
"Returns true if channel is closed."
[port]
(pt/-closed? port))
(defn chan?
"Returns true if `o` is instance of Channel or satisfies IChannel protocol."
[o]
(channel/chan? o))
(defn timeout-chan
"Returns a channel that will be closed in the specified timeout. The
default scheduler will be used. You can provide your own as optional
first argument."
([ms]
(let [ch (chan)]
(px/schedule! ms #(pt/-close! ch))
ch))
([scheduler ms]
(let [ch (chan)]
(px/schedule! scheduler ms #(pt/-close! ch))
ch)))
(defn timeout
"Returns a promise that will be resolved in the specified timeout. The
default scheduler will be used."
[ms]
(go (Thread/sleep (int ms))))
(defn sliding-buffer
"Create a sliding buffer instance."
[n]
(buffers/sliding n))
(defn dropping-buffer
"Create a dropping buffer instance."
[n]
(buffers/dropping n))
(defn fixed-buffer
"Create a fixed size buffer instance."
[n]
(buffers/fixed n))
(defn once-buffer
"Create a once buffer instance."
[]
(buffers/once))
(defn expanding-buffer
"Create a fixed size (but expanding) buffer instance.
This buffer is used by default if you pass an integer as buffer on
channel constructor."
[n]
(buffers/expanding n))
(defn offer!
"Puts a val into channel if it's possible to do so immediately.
Returns a resolved promise with `true` if the operation
succeeded. Never blocks."
[port val]
(let [o (volatile! nil)]
(pt/-put! port val (channel/volatile->handler o))
@o))
(defn poll!
"Takes a val from port if it's possible to do so
immediatelly. Returns a resolved promise with the value if
succeeded, `nil` otherwise."
[port]
(let [o (volatile! nil)]
(pt/-take! port (channel/volatile->handler o))
@o))
(defn pipe
"Takes elements from the from channel and supplies them to the to
channel. By default, the to channel will be closed when the from
channel closes, but can be determined by the close? parameter. Will
stop consuming the from channel if the to channel closes.
Do not creates vthreads (or threads).
"
([from to] (pipe from to true))
([from to close?]
(p/loop []
(->> (take from)
(p/mcat (fn [v]
(if (nil? v)
(do
(when close? (pt/-close! to))
(p/resolved nil))
(->> (put to v)
(p/map (fn [res]
(when res
(p/recur))))))))))
to))
(defn onto-chan!
"Puts the contents of coll into the supplied channel.
By default the channel will be closed after the items are copied,
but can be determined by the close? parameter. Returns a promise
that will be resolved with `nil` once the items are copied.
Do not creates vthreads (or threads)."
([ch coll] (onto-chan! ch coll true))
([ch coll close?]
(p/loop [items (seq coll)]
(if items
(->> (put ch (first items))
(p/map (fn [res]
(if res
(p/recur (next items))
(p/recur nil)))))
(when close?
(pt/-close! ch))))))
(defn mult*
"Create a multiplexer with an externally provided channel. From now,
you can use the external channel or the multiplexer instace to put
values in because multiplexer implements the IWriteChannel protocol.
Optionally accepts `close?` argument, that determines if the channel will
be closed when `close!` is called on multiplexer o not."
([ch] (mult* ch false))
([ch close?]
(let [state (atom {})
mx (reify
pt/IChannelMultiplexer
(-tap! [_ ch close?]
(swap! state assoc ch close?))
(-untap! [_ ch]
(swap! state dissoc ch))
pt/ICloseable
(-close! [_]
(when close? (pt/-close! ch))
(->> @state
(filter (comp true? peek))
(run! (comp pt/-close! key))))
pt/IWriteChannel
(-put! [_ val handler]
(pt/-put! ch val handler)))]
;; (p/loop []
;; (->> (take ch)
;; (p/mcat (fn [v]
;; (if v
;; (let [chs (-> @state keys vec)
;; res (if (seq chs)
;; (let [dff (p/deferred)
;; cnt (atom (count chs))]
;; (doseq [ch chs]
;; (->> (put ch v)
;; (p/fnly (fn [v _]
;; (when (nil? v) (pt/-untap! mx ch))
;; (let [n (swap! cnt dec)]
;; (when (zero? n)
;; (p/resolve! dff nil)))))))
;; dff)
;; (p/resolved nil))]
;; (p/map (fn [_] (p/recur)) res))
;; (p/resolved nil))))))
;;
;; mx)))
(go-loop []
(if-let [v (<! ch)]
(do
(pu/wait-all! (for [ch (-> @state keys vec)]
(->> (put! ch v)
(p/fnly (fn [v _]
(when (nil? v)
(pt/-untap! mx ch)))))))
(recur))
(pt/-close! mx)))
mx)))
(defn mult
"Creates an instance of multiplexer.
A multiplexer instance acts like a write-only channel what enables a
broadcast-like (instead of a queue-like) behavior. Channels
containing copies of this multiplexer can be attached using `tap!`
and dettached with `untap!`.
Each item is forwarded to all attached channels in parallel and
synchronously; use buffers to prevent slow taps from holding up the
multiplexer.
If there are no taps, all received items will be dropped. Closed
channels will be automatically removed from multiplexer."
([] (mult nil nil nil))
([buf] (mult buf nil nil))
([buf xform] (mult buf xform nil))
([buf xform exh]
(let [ch (chan buf xform exh)]
(mult* ch true))))
(defn tap!
"Copies the multiplexer source onto the provided channel."
([mult ch]
(pt/-tap! mult ch true)
ch)
([mult ch close?]
(pt/-tap! mult ch close?)
ch))
(defn untap!
"Disconnects a channel from the multiplexer."
[mult ch]
(pt/-untap! mult ch)
ch)