-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathcsp.cljc
578 lines (498 loc) · 18 KB
/
csp.cljc
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
;; 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 <[email protected]>
(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]))
#?(:clj (set! *warn-on-reflection* true))
(def ^{:dynamic true
:doc "A defalt executor for channel callback dispatching"}
*executor* :vthread)
(defmacro go
"Schedules the body to be executed asychronously, potentially using
virtual thread if available (a normal thread will be used in other
case, determined by *executor* dynamic var). Returns a promise
instance that resolves with the return value when the asynchronous
block finishes.
Forwards dynamic bindings."
[& body]
(when (:ns &env)
(throw (UnsupportedOperationException. "cljs not supported")))
`(->> (px/wrap-bindings (fn [] ~@body))
(p/thread-call *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, has the same semantics as `go` macro."
[& body]
`(let [c# (chan :buf 1)
f# (px/wrap-bindings (^{:once true} fn* [] ~@body))]
(->> (p/thread-call *executor* f#)
(p/fnly (fn [v# e#]
(if e#
(close! c# e#)
(offer! c# v#)))))
c#))
(defmacro thread-chan
"A convencience thread macro version that returns a channel instead of
a promise instance."
[& body]
`(let [c# (chan :buf 1)
f# (px/wrap-bindings (^{:once true} fn* [] ~@body))]
(->> (p/thread-call :thread f#)
(p/fnly (fn [v# e#]
(if e#
(close! c# e#)
(offer! c# v#)))))
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."
[& {:keys [buf xf exh exc] :or {exh channel/close-with-exception}}]
(assert (or (nil? buf)
(and (int? buf) (pos? buf))
(satisfies? pt/IBuffer buf))
"`buf` can be nil, positive int or IBuffer instance")
(assert (or (nil? xf) (and (fn? xf) (some? buf)))
"xf can be nil or fn (if fn, buf should be present")
(let [buf (if (number? buf)
(buffers/expanding buf)
buf)
exc (px/resolve-executor (or exc *executor*))]
(channel/chan buf xf exh exc)))
(defn close-with-exception
"A channel exception handler that closes the channel with the cause
if an exception is raised in the transducer."
[ch cause] (channel/close-with-exception ch cause))
(defn throw-uncaught
"A channel exception handler that throws the exception to the default
uncaught exception handler."
[ch cause] (channel/throw-uncaught ch cause))
(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]
(channel/put port val))
([port val timeout-duration]
(channel/put port val timeout-duration nil))
([port val timeout-duration timeout-value]
(channel/put port val timeout-duration timeout-value)))
#?(:clj
(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)))))
#?(:clj
(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]
(channel/take port))
([port timeout-duration]
(channel/take port timeout-duration nil))
([port timeout-duration timeout-value]
(channel/take port timeout-duration timeout-value)))
#?(:clj
(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)))))
#?(:clj
(defn <!
"A convenience alias for `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]))
([val cause]
(if cause
(f nil cause)
(f [val port] nil))))))))]
(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))
#?(:clj
(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)
([port cause]
(pt/-close! port cause)
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]
(p/delay ms nil :default))
(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))
(first @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))
(let [[v c] (deref o)]
(if c
(throw c)
v))))
(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."
([from to] (pipe from to true))
([from to close?]
#?(:clj
(go-loop []
(let [v (take! from)]
(if (nil? v)
(if close? (pt/-close! to))
(if (put! to v)
(recur)))))
:cljs
(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."
([ch coll] (onto-chan! ch coll true))
([ch coll close?]
#?(:clj
(go-loop [coll (seq coll)]
(if (and coll (put! ch (first coll)))
(recur (next coll))
(when close?
(close! ch))))
:cljs
(->> (p/loop [items (seq coll)]
(when items
(->> (put ch (first items))
(p/fmap (fn [res]
(if res
(p/recur (next items))
(p/recur nil)))))))
(p/fnly (fn [_ _]
(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)))]
#?(:clj
(go-loop []
(let [v (take! ch)]
(if (nil? v)
(pt/-close! mx)
(do
(p/await!
(p/wait-all* (for [ch (keys @state)]
(->> (put ch v)
(p/fnly (fn [v _]
(when (nil? v)
(pt/-untap! mx ch))))))))
(recur)))))
:cljs
(p/loop []
(->> (take ch)
(p/mcat (fn [v]
(if (nil? v)
(do
(pt/-close! mx)
(p/resolved nil))
(->> (p/wait-all* (for [ch (-> @state keys vec)]
(->> (put ch v)
(p/fnly (fn [v _]
(when (nil? v)
(pt/-untap! mx ch)))))))
(p/fmap (fn [_] (p/recur))))))))))
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.
Do not creates vthreads (or threads)."
[& {:as opts}]
(let [ch (chan opts)]
(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)
#?(:clj
(defn pipeline
"Create a processing pipeline with the ability to specify the process
function `proc-fn`, the type of concurrency primitive to
use (`:thread` or `:vthread`) and the parallelism.
The `proc-fn` should be a function that takes the value and the
result channel; the result channel should be closed once the
processing unit is finished.
By default the output channel is closed when pipeline is terminated,
but it can be specified by user using the `:close?` parameter.
Returns a promise which will be resolved once the pipeline is
terminated.
Example:
(def inp (sp/chan))
(def out (sp/chan (map inc)))
(sp/pipeline :typ :vthread
:close? true
:n 10
:in inp
:out out
:f proc-fn)
(sp/go
(loop []
(when-let [val (sp/<! out)]
(prn \"RES:\" val)
(recur)))
(prn \"RES: END\"))
(p/await! (sp/onto-chan! inp [\"1\" \"2\" \"3\" \"4\"] true))
Internally, uses 2 vthreads for pipeline internals processing.
EXPERIMENTAL: API subject to be changed or removed in future
releases."
[& {:keys [typ in out f close? n exh] :or {typ :thread close? true}}]
(assert (pos? n) "the worker number should be positive number")
(assert (chan? in) "`in` parameter is required")
(assert (chan? out) "`outpu` parameter is required")
(assert (fn? f) "`f` parameter is required")
(assert (#{:thread :vthread} typ) "invalid value on `typ` parameter")
(let [jch (chan :buf n)
rch (chan :buf n)
xfm (comp
(map (fn [i]
#(try
(loop []
(when-let [[val rch] (<! jch)]
(f val rch)
(recur)))
(catch Throwable cause
(close! jch)
(close! rch)
(let [exh (or exh close-with-exception)]
(exh out cause)
(when (and close? (not (closed? out)))
(close! out)))))))
(map (fn [f]
(p/thread-call typ f))))]
(go-loop []
(if-let [val (<! in)]
(let [res-ch (chan)]
(if (>! jch [val res-ch])
(if (>! rch res-ch)
(recur)
(close! jch))
(close! rch)))
(do
(close! rch)
(close! jch))))
(go-loop []
(if-let [rch' (<! rch)]
(do
(loop []
(when-let [val (<! rch')]
(if (>! out val)
(recur)
(do
(close! jch)
(close! rch)))))
(recur))
(when close?
(close! out))))
(-> (into #{} xfm (range n))
(p/wait-all*)))))