├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── project.clj ├── src ├── naiad.clj └── naiad │ ├── backends │ ├── csp.clj │ └── graphviz.clj │ ├── db.clj │ ├── error_handlers.clj │ ├── graph.clj │ ├── metrics.clj │ ├── nodes.clj │ ├── passes.clj │ ├── passes │ ├── fuse_transducer_nodes.clj │ ├── insert_duplicators.clj │ ├── non_channel_edges_to_nodes.clj │ └── remove_distributes.clj │ ├── reducer_functions.clj │ ├── transducers.clj │ └── transducers │ └── ioc.clj └── test └── naiad ├── core_test.clj ├── error_handlers_test.clj ├── metrics_test.clj ├── reducer_functions_test.clj └── transducers_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | .hgignore 11 | .hg/ 12 | /.idea* 13 | autodoc/** -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # naiad 2 | 3 | A library for building declarative data flow graphs via a fluent api and core.async. 4 | 5 | ## Rationale 6 | ### Premise 7 | Core.async is simple but not easy. That is to say, it is possible to write simple maintainable using core.async but it 8 | is not a easy task. Often users want to deal with core.async channels in a way that mirrors lazy seqs but are somewhat 9 | hindered by the congitive overhead of using abstractions just as `async/mult` and `async/pub`. Naiad attempts to abstract 10 | the construction of data flow graphs in a declarative way. You specify the operations you want to apply to a set of channels, 11 | and then let Naiad work out how to wire it all up. 12 | 13 | ### Tenets 14 | The goals of Naiad are as follows: 15 | * Represent dataflow graphs as data, that can be manipulated via post-processing optimizers 16 | * Provide a fluent API that works well with threading macros: `(-> (range 3) (take 2) (map inc))` 17 | * Provide a keyword argument API that works well when needing to connect graphs `(-> (range 3) (take 2 :out o :in))` 18 | * Provide a map based API that works well with programatic data transformers `(->take {:in (range 3) :n 2 :out o})` 19 | * Do *not* introduce a large number of new macros. Should prefer functions over DSLs 20 | * Performance hints (such as parallel pipelining) should not require restructuring of code, it should be as simple as 21 | wrapping a block of code in a macro or function call. 22 | 23 | 24 | 25 | ### Example 1: 26 | Let's say you (for some strange reason) wanted to take a sequence of integers, square them, 27 | split them into odds and evens, then decrement the odds and increment the evens, sending the first 100 results into a 28 | output channel. The code may look something like this in core.async 29 | 30 | ```clojure 31 | 32 | (let [in-c (chan (map (fn [x] (* x x)))) 33 | m (mult c) 34 | odds (chan (comp (filter odd?) 35 | (map dec))) 36 | evens (chan (comp (filter even?) 37 | (map inc))) 38 | final-chan (chan (take 100))] 39 | (tap m odds) 40 | (tap m evens) 41 | (onto-chan in-c (range 1000)) 42 | (pipe (merge odds evens) final-chan) 43 | (pipe final-chan output-chan)) 44 | 45 | ``` 46 | 47 | While the core.async code here is not complex, it is rather hard to read and comprehend, the flow of data does not match 48 | the normal human way of reading lisp code. In addition, some constructs like `merge` are ill suited to situations were we 49 | have a pre-existing output channel. 50 | 51 | This same code written in Naiad would look something like this: 52 | 53 | ```clojure 54 | 55 | (require '[naiad :as n]) 56 | 57 | (n/flow 58 | (let [in-c (->> (n/range 1000) 59 | (n/map (fn [x] (* x x)))) 60 | 61 | odds (->> in-c 62 | (n/filter odd?) 63 | (n/map dec)) 64 | 65 | evens (->> in-c 66 | (n/filter even?) 67 | (n/map inc))] 68 | (->> (n/merge odds evens) 69 | (n/->take :n 100 :out output-chan :in)))) 70 | 71 | ``` 72 | 73 | The `flow` macro is not a complex deep-walking macro, but is simply a easy way of setting up some bindings and post-processing 74 | the resulting graph created by the other functions in the body of this snippet. The rest of the code is macro-free (except 75 | for `let` of course), this means that normal clojure constructs like `apply` and `map` will continue to work as expected, 76 | *there is no black magic here*. 77 | 78 | ## License 79 | 80 | Copyright © 2016 Timothy Baldridge 81 | 82 | Distributed under the Eclipse Public License either version 1.0 or (at 83 | your option) any later version. 84 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject naiad "0.1.0-SNAPSHOT" 2 | :description "FIXME: write description" 3 | :url "http://example.com/FIXME" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.8.0"] 7 | [org.clojure/core.async "0.2.374"]] 8 | :plugins [[lein-codox "0.9.4"]]) 9 | -------------------------------------------------------------------------------- /src/naiad.clj: -------------------------------------------------------------------------------- 1 | (ns naiad 2 | (:refer-clojure :exclude [map take filter partition-all merge]) 3 | (:require [clojure.core :as clj] 4 | [clojure.core.async :as async] 5 | [naiad.graph :refer [add-node! add-node gen-id id? *graph* ports 6 | INode ->GraphSource annotate-link add-port! annotate-link!] 7 | :as graph] 8 | [naiad.backends.csp :as csp] 9 | [naiad.nodes :refer :all] 10 | [naiad.graph :as graph] 11 | [naiad.metrics] 12 | [naiad.passes :as passes])) 13 | 14 | (def ^:dynamic *io* false) 15 | 16 | (defmacro with-annotations [ann & body] 17 | `(binding [graph/*default-annotations* ~ann] 18 | ~@body)) 19 | 20 | 21 | 22 | (comment (defn destructurable [id] 23 | (reify 24 | clojure.lang.ILookup 25 | (valAt [this val] 26 | (let [result (gen-id)] 27 | (set! *graph* (assoc-in *graph* [id :outputs val] result)) 28 | result)))) 29 | 30 | (defrecord Duplicate [id inputs outputs] 31 | INode 32 | (transducer? [this] false) 33 | (validate [this] 34 | (assert (= (keys inputs) [:in]) "Duplicate takes only one input") 35 | (assert (> (count outputs) 0) "Must have at least one output"))) 36 | 37 | (defn splitter [pred input] 38 | (let [id (gen-id) 39 | out (destructurable id)] 40 | (add-node! {:op ::split 41 | :pred pred 42 | :id id 43 | :inputs {:in input}}) 44 | out)) 45 | 46 | ) 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | (defmacro flow 56 | "Creates a graph and executes it using standard optimizations." 57 | [& body] 58 | `(binding [*graph* {}] 59 | ~@body 60 | (csp/construct-graph (passes/run-passes *graph*)))) 61 | 62 | (defmacro graph [& body] 63 | `(binding [*graph* {}] 64 | ~@body 65 | (passes/run-passes *graph*))) 66 | 67 | (comment (let [p (promise)] 68 | (flow 69 | (nodes/promise-accumulator p (nodes/map inc [1 2 3 4]))) 70 | @p) 71 | 72 | (let [p (promise)] 73 | (binding [*graph* {}] 74 | 75 | (nodes/promise-accumulator p (nodes/map inc [1 2 3 4])) 76 | *graph* 77 | (csp/construct-graph (non-channel-edges-to-nodes *graph*))) 78 | @p)) 79 | 80 | 81 | 82 | ;; Node Constructors 83 | 84 | 85 | 86 | 87 | (defn ->map 88 | ([mp] 89 | (-> mp 90 | (map-keys :in [:inputs 0]) 91 | (map-keys :out [:outputs :out]) 92 | (assoc :type ::map) 93 | add-node!)) 94 | ([h & r] 95 | (let [opts (apply hash-map h r)] 96 | (->map opts)))) 97 | 98 | (defn map 99 | "Constructs a mapping node that applies a function to values taken from one or more channels. 100 | Multiple inputs are supported. Values are applied to f in lockstep, so that (map f a b) will first 101 | call f with [a0 b0] then with [a1 b1], etc. " 102 | [f & ins] 103 | (let [out (gen-id)] 104 | (->map 105 | :id (gen-id) 106 | :f f 107 | :out out 108 | :inputs (zipmap (range) ins)) 109 | out)) 110 | 111 | 112 | (defn merge [& ins] 113 | (let [out (gen-id)] 114 | (add-node! 115 | {:type ::merge 116 | :inputs (zipmap (range) ins) 117 | :outputs{:out out}}) 118 | out)) 119 | 120 | (defn no-close [in] 121 | (let [out (gen-id)] 122 | (add-node! 123 | {:type ::no-close 124 | :inputs {:in in} 125 | :outputs {:out out}}) 126 | out)) 127 | 128 | (defn multiplexer [selector inputs] 129 | (let [out (gen-id)] 130 | (add-node! 131 | {:type ::multiplexer 132 | :input-count (count inputs) 133 | :inputs (assoc (zipmap (range) inputs) 134 | :selector selector) 135 | :outputs {:out out}}) 136 | out)) 137 | 138 | (defn demultiplexer [num-outputs input] 139 | (let [selector (gen-id) 140 | outputs (repeatedly num-outputs gen-id)] 141 | (add-node! 142 | {:type ::demultiplexer 143 | :output-count num-outputs 144 | :inputs {:in input} 145 | :outputs (assoc (zipmap (range) outputs) 146 | :selector selector)}) 147 | {:selector selector 148 | :outputs outputs})) 149 | 150 | (defn promise-accumulator [p input] 151 | (add-node! {:type ::promise-accumulator 152 | :promise p 153 | :inputs {:in input}}) 154 | nil) 155 | 156 | 157 | (def ^{:doc "Creates a node that will take the first X items from the input port before closing both the 158 | input and output ports. 159 | 160 | Usage: 161 | (take n input) 162 | n - The number of items to take from input 163 | input - Input node to take n items from 164 | 165 | Returns: 166 | A link that will receive n items taken from input"} 167 | take 168 | (gen-transducer-node clj/take)) 169 | 170 | (def ^{:doc "Creates a node that will take the first X items from the input port before closing both the 171 | input and output ports. 172 | 173 | Usage: 174 | (take :n x :in input :out output) 175 | n - (required) The number of items to take from in 176 | input - (required) Input node to take n items from 177 | output - output node to put items taken form in 178 | 179 | Returns: 180 | :out, will construct a link if one is not given"} 181 | ->take 182 | (gen-verbose-transducer-node clojure.core/take [:n])) 183 | 184 | (def filter (gen-transducer-node clj/filter)) 185 | (def partition-all (gen-transducer-node clj/partition-all)) 186 | 187 | (defn distribute [in] 188 | (let [node-id (gen-id)] 189 | (add-node! {:type ::distribute 190 | :id node-id 191 | :inputs {:in in} 192 | :outputs {}}) 193 | (clj/map 194 | (fn [idx] 195 | (let [id (gen-id)] 196 | (set! *graph* (assoc-in *graph* [node-id :outputs idx] id)) 197 | id)) 198 | (range)))) 199 | 200 | 201 | (defn subscribe [topic-fn in] 202 | (let [node-id (gen-id)] 203 | (add-node! {:type ::subscribe 204 | :topic-fn topic-fn 205 | :id node-id 206 | :inputs {:in in} 207 | :outputs {}}) 208 | (reify 209 | clojure.lang.ILookup 210 | (valAt [this val] 211 | (add-port! node-id :outputs val)) 212 | (valAt [this val _] 213 | (.valAt this val))))) 214 | 215 | 216 | 217 | 218 | (defn parallel* [{:keys [threads ordered?]} f in] 219 | (if ordered? 220 | (let [{:keys [selector outputs]} (demultiplexer threads in)] 221 | (multiplexer selector (clj/map f outputs))) 222 | 223 | (let [outs (mapv f 224 | (clj/take threads (distribute in)))] 225 | (apply merge outs)))) 226 | 227 | (defmacro parallel->> [opts & body] 228 | `(parallel* ~opts 229 | (fn [in#] 230 | (->> in# ~@(butlast body))) 231 | ~(last body))) 232 | 233 | (defmacro flow-result [& expr] 234 | `(let [p# (promise)] 235 | (flow 236 | (promise-accumulator p# (do ~@expr))) 237 | @p#)) 238 | 239 | (defn mapcat-async [f & ins] 240 | (let [out (gen-id)] 241 | (add-node! 242 | {:type ::mapcat-async 243 | :f f 244 | :inputs (zipmap (range) ins) 245 | :outputs {:out out}}) 246 | out)) 247 | 248 | 249 | #_(naiad.backends.graphviz/output-dotfile (let [p (promise)] 250 | (graph 251 | (let [v (take 3 [1 2 3 4]) 252 | result (map vector (map inc v) 253 | (map dec v))] 254 | (promise-accumulator p result)))) 255 | "test.dot") 256 | 257 | 258 | (defn annotate 259 | ([link k v & rest] 260 | (annotate link (apply hash-map k v rest))) 261 | ([link meta] 262 | (annotate-link! link meta) 263 | link)) 264 | 265 | (defmacro blocking-io [& body] 266 | (binding [*io* true] 267 | ~@body)) 268 | 269 | 270 | 271 | (comment 272 | 273 | (->> foo 274 | (map inc) 275 | (parallel-> {:threads 3} 276 | (map dec) 277 | (filter pos?)) 278 | (take 3) 279 | ) 280 | 281 | ) -------------------------------------------------------------------------------- /src/naiad/backends/csp.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.backends.csp 2 | (:require [clojure.core.async :as async :refer [close! ! go]] 3 | [clojure.core.async.impl.protocols :as aproto] 4 | [naiad.graph :refer [links]] 5 | [naiad.error-handlers :refer [print-and-continue]] 6 | [naiad.metrics :as metrics])) 7 | 8 | 9 | (defmulti construct! :type) 10 | 11 | (defn xf-pipe [to xf from {:keys [error-fn] :as opts 12 | :or {error-fn print-and-continue}}] 13 | (assert error-fn (println error-fn)) 14 | (go (try (let [a (volatile! []) 15 | rf (xf (fn [_ v] 16 | (vswap! a conj v)))] 17 | (loop [] 18 | (if-some [v (! to h) 23 | (recur t) 24 | :exit)))] 25 | (if (or exit? 26 | (reduced? retval)) 27 | (do (close! to) 28 | (close! from)) 29 | (do (vreset! a []) 30 | (recur)))) 31 | 32 | 33 | (let [_ (xf nil)] 34 | (doseq [v @a] 35 | (>! to v)) 36 | (close! to))))) 37 | (catch Throwable t 38 | (condp = (MetricsWrappedBuffer b metrics) 84 | b)] 85 | (async/chan b)))) 86 | 87 | 88 | 89 | (defn construct-graph [graph] 90 | (let [link-ids (links graph) 91 | chans (zipmap link-ids 92 | (->> link-ids 93 | ;; Get any options for the links 94 | (map graph) 95 | (map construct-channel)))] 96 | (reduce-kv 97 | (fn [acc k {:keys [type] :as node}] 98 | (if (= type :naiad/link-annotation) 99 | (assoc acc k node) 100 | (let [{:keys [inputs outputs closes]} node 101 | new-node (assoc node 102 | :inputs (inject-channels chans inputs) 103 | :outputs (inject-channels chans outputs) 104 | :closes (inject-channels chans closes))] 105 | (construct! new-node) 106 | (assoc acc k new-node)))) 107 | graph 108 | graph))) 109 | -------------------------------------------------------------------------------- /src/naiad/backends/graphviz.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.backends.graphviz 2 | (:require [naiad.graph :as graph] 3 | [clojure.java.io :refer [writer]])) 4 | 5 | (defn output-dotfile [graph file] 6 | (let [edges (graph/edges graph)] 7 | (with-open [wtr (writer file)] 8 | (binding [*out* wtr] 9 | (println "digraph G {") 10 | (doseq [{:keys [link in out]} edges] 11 | (println (pr-str (str (:node in))) "->" (pr-str (str (:node out))) 12 | "[ headlabel= " (pr-str (str (:port out))) 13 | "taillabel=" (pr-str (str (:port in))) "];")) 14 | (doseq [[id node] graph] 15 | (let [without-meta (dissoc node :inputs :outputs :closes :id :type)] 16 | (print (pr-str (str id)) "[label= ") 17 | 18 | (print (pr-str (apply str (:type node) \newline 19 | (interpose \newline (map 20 | (fn [[k v]] 21 | (str k " = " v)) 22 | without-meta))))) 23 | 24 | (println "]"))) 25 | (println "}")))) 26 | 27 | ) 28 | -------------------------------------------------------------------------------- /src/naiad/db.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.db 2 | (:require [clojure.set :as set])) 3 | 4 | ;; The original prototype of this library just stored the database in a hashmap of nodes, 5 | ;; but that got both complex and slow fairly quickly. So this namespace now defines a fairly fast 6 | ;; and efficient graph database 7 | 8 | (defrecord Link [node port class link]) 9 | (defrecord Node [id structure]) 10 | 11 | 12 | (defrecord DB [nodes links]) 13 | 14 | (def conj-set (fnil conj #{})) 15 | 16 | (defn add-link [db link] 17 | (conj db link)) 18 | 19 | (defn add-node [db {:keys [id] :as node}] 20 | {:pre [id]} 21 | (let [db (reduce 22 | (fn [db klass] 23 | (reduce-kv 24 | (fn [db k v] 25 | (add-link db (->Link id k klass v))) 26 | db 27 | (klass node))) 28 | db 29 | #{:inputs :outputs :closes})] 30 | (conj db (->Node id node)))) 31 | 32 | 33 | (defn query [{:keys [links]} & {:as kvs}] 34 | (filter 35 | (fn [link] 36 | (reduce-kv 37 | (fn [_ k v] 38 | (or 39 | (= (get link k) v) 40 | (reduced false))) 41 | true 42 | kvs)) 43 | links)) 44 | 45 | (defn combine-db [& dbs] 46 | (apply set/union dbs)) 47 | 48 | (-> #{} 49 | (add-node {:id 42 :inputs {4 3}})) 50 | 51 | 52 | (defmacro FlowVar [link-id db]) 53 | 54 | (defn merge-flow-vars [& vars] 55 | (let [merged-db (apply set/union (map :db vars))] 56 | (mapv #(assoc % :db merged-db)))) -------------------------------------------------------------------------------- /src/naiad/error_handlers.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.error-handlers 2 | (:require [clojure.core.async :as async] 3 | [clojure.stacktrace :as stacktrace])) 4 | 5 | (defn ignore [^Throwable t] 6 | (async/go :error/continue)) 7 | 8 | (defn log-to-chan [c] 9 | (fn [^Throwable t] 10 | (async/go 11 | (async/>! c t) 12 | :error/continue))) 13 | 14 | (defn print-and-continue [^Throwable t] 15 | (async/thread 16 | (stacktrace/print-stack-trace t) 17 | :error/continue)) 18 | 19 | (defn abort [^Throwable t] 20 | (async/go :error/abort)) -------------------------------------------------------------------------------- /src/naiad/graph.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.graph) 2 | 3 | (def ^:dynamic *graph*) 4 | 5 | (def ^:dynamic *default-annotations* nil) 6 | 7 | (defprotocol INode 8 | (transducer? [this] "Returns true if this node can be a transducer") 9 | (as-transducer [this] "Create a transducer by supplying a reducer function") 10 | (validate [this]) 11 | (construct [this])) 12 | 13 | 14 | 15 | 16 | (deftype Id [] 17 | Object 18 | (hashCode [this] 19 | (System/identityHashCode this)) 20 | (toString [this] 21 | (str "ID<" (System/identityHashCode this) ">"))) 22 | 23 | 24 | (def id? (partial instance? Id)) 25 | 26 | (defn annotate-link [graph id data] 27 | (update-in graph [id] merge {:type :naiad/link-annotation 28 | :id id} data)) 29 | 30 | (defn annotate-link! [id data] 31 | (set! *graph* (annotate-link *graph* id data))) 32 | 33 | (defn gen-id [] 34 | (let [id (->Id)] 35 | (when *default-annotations* 36 | (annotate-link! id *default-annotations*)) 37 | id)) 38 | 39 | (defmethod print-method Id 40 | [v ^java.io.Writer w] 41 | (.write w (str v))) 42 | 43 | 44 | (defn add-node [graph {:keys [id type] :as node}] 45 | (assert type (str "Node" node " must have a type")) 46 | (let [id (or id (gen-id))] 47 | (assoc graph id (assoc (merge *default-annotations* node) :id id)))) 48 | 49 | 50 | 51 | (defn add-node! [node] 52 | (set! *graph* (add-node *graph* node))) 53 | 54 | (defn add-port! [node-id klass name] 55 | (if-let [port (get-in *graph* [node-id klass name])] 56 | port 57 | (let [id (gen-id)] 58 | (set! *graph* (assoc-in *graph* [node-id klass name] id)) 59 | id))) 60 | 61 | 62 | (defn ports [graph type] 63 | (assert #{:inputs :outputs} type) 64 | (for [[id node] graph 65 | [port-name link] (type node)] 66 | {:node id 67 | :port port-name 68 | :link link})) 69 | 70 | (defn validate-graph [graph] 71 | (doseq [[k node] graph] 72 | (validate node))) 73 | 74 | (defn links-by-class [graph class-kw] 75 | (for [[id node] graph 76 | :let [inputs (class-kw node)] 77 | [name link] inputs] 78 | link)) 79 | 80 | (defn links [graph] 81 | (set (concat (links-by-class graph :inputs) 82 | (links-by-class graph :outputs) 83 | (links-by-class graph :closes)))) 84 | 85 | (defn edges [graph] 86 | (let [outputs (ports graph :inputs) 87 | inputs (group-by :link (ports graph :outputs))] 88 | (for [{:keys [link] :as out} outputs 89 | in (inputs link)] 90 | {:link link 91 | :out out 92 | :in in}))) 93 | 94 | 95 | (defn nodes-by-link [graph type link] 96 | (filter #(= (:link %) link) 97 | (ports graph type))) 98 | 99 | 100 | (defrecord GraphSource [link-id extra-nodes]) -------------------------------------------------------------------------------- /src/naiad/metrics.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.metrics) 2 | 3 | 4 | (defprotocol IMetricsLogger 5 | (counter [t metric-name delta]) 6 | (guage [t metric-name value-fn]) 7 | (histogram [t metric-name value]) 8 | (meter [t metric-name n-events])) 9 | 10 | 11 | (extend-protocol IMetricsLogger 12 | nil 13 | (counter [t metric-name delta] 14 | nil) 15 | (guage [t metric-name value-fn] 16 | nil) 17 | (histogram [t metric-name value] 18 | nil) 19 | (meter [t metric-name n-events] 20 | nil) 21 | 22 | clojure.lang.IFn 23 | (counter [f metric-name delta] 24 | (f :counter metric-name delta)) 25 | (guage [f metric-name value-fn] 26 | (f :guage metric-name value-fn)) 27 | (histogram [f metric-name value] 28 | (f :histogram metric-name value)) 29 | (meter [f metric-name n-events] 30 | (f :meter metric-name n-events))) -------------------------------------------------------------------------------- /src/naiad/nodes.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.nodes 2 | (:require [clojure.core :as clj] 3 | [naiad.graph :refer [add-node! gen-id id? *graph* ports 4 | INode]] 5 | [naiad.backends.csp :as csp] 6 | [clojure.core.async :refer [go ! close! thread] :as async])) 7 | 8 | (defmacro process [{:keys [blocking-io] :as opts} & body] 9 | (if blocking-io 10 | `(thread))) 11 | 12 | 13 | 14 | 15 | (defmethod csp/construct! :naiad/map 16 | [{:keys [inputs outputs f]}] 17 | (go 18 | (let [out (:out outputs)] 19 | (loop [acc []] 20 | (if (< (count acc) (count inputs)) 21 | (if-some [v (! out (apply f acc)) 27 | (recur []) 28 | (doseq [[_ v] inputs] 29 | (close! v)))))))) 30 | 31 | 32 | 33 | 34 | 35 | (defmacro gen-transducer-node [f] 36 | `(fn ~f [& args#] 37 | (let [fargs# (butlast args#) 38 | input# (last args#) 39 | output# (gen-id)] 40 | (add-node! 41 | {:type :generic-transducer 42 | :f (apply ~f fargs#) 43 | :transducer? true 44 | :inputs {:in input#} 45 | :outputs {:out output#}}) 46 | output#))) 47 | 48 | (defmacro gen-verbose-transducer-node [f arg-names] 49 | (let [fname (symbol (str (name f) "-node"))] 50 | `(let [extractor# (apply juxt ~arg-names)] 51 | (fn ~fname 52 | ([first# & rargs#] 53 | (~fname (apply hash-map first# rargs#))) 54 | ([args#] 55 | (let [fargs# (extractor# args#) 56 | input# (or (:in args#) (gen-id)) 57 | output# (or (:out args#) (gen-id))] 58 | (add-node! 59 | {:type :generic-transducer 60 | :f (apply ~f fargs#) 61 | :transducer? true 62 | :inputs {:in input#} 63 | :outputs {:out output#}}) 64 | output#)))))) 65 | 66 | 67 | 68 | (defn map-keys [mp from to] 69 | (if-let [v (get mp from)] 70 | (assoc-in (dissoc mp from) to v) 71 | mp)) 72 | 73 | 74 | 75 | 76 | 77 | (defmethod csp/construct! :naiad/promise-accumulator 78 | [{:keys [inputs promise]}] 79 | (async/take! (async/into [] (:in inputs)) 80 | (partial deliver promise))) 81 | 82 | 83 | (defmethod csp/construct! :naiad/duplicate 84 | [{:keys [inputs outputs]}] 85 | (let [in (:in inputs) 86 | outs (vec (vals outputs))] 87 | (go (loop [] 88 | (if-some [v ( (count remain) 0) 91 | (let [[ret c] (async/alts! (vec remain))] 92 | (if ret 93 | (recur (disj remain [c v])) 94 | (do (doseq [c outs] 95 | (close! c)) 96 | (close! in) 97 | :exit)))))] 98 | (when-not exit? 99 | (recur))) 100 | (doseq [c outs] 101 | (close! c))))))) 102 | 103 | (defmethod csp/construct! :naiad/merge 104 | [{:keys [inputs outputs]}] 105 | (let [ins (vals inputs) 106 | out (:out outputs)] 107 | (go (loop [ins ins] 108 | (when (pos? (count ins)) 109 | (let [[v c] (async/alts! ins)] 110 | (if v 111 | (if (>! out v) 112 | (recur ins) 113 | (do (doseq [in ins] 114 | (close! ins)))) 115 | (do (close! c) 116 | (recur (remove (partial = c) ins))))))) 117 | (close! out)))) 118 | 119 | 120 | (defmethod csp/construct! :naiad/subscribe 121 | [{:keys [topic-fn inputs outputs default-key default-c]}] 122 | (let [default-c (or (and default-key (default-key outputs)) 123 | default-c) 124 | in-c (:in inputs)] 125 | (go 126 | (loop [] 127 | (if-some [v (! out-c v) 133 | (recur) 134 | (do (close! in-c) 135 | (doseq [[k v] outputs] 136 | (close! v)))) 137 | (recur))) 138 | (do (doseq [[k v] outputs] 139 | (close! v)))))))) 140 | 141 | 142 | 143 | 144 | (defmethod csp/construct! :naiad/onto-chan 145 | [{:keys [outputs coll]}] 146 | (clojure.core.async/onto-chan (:out outputs) coll true)) 147 | 148 | (defmethod csp/construct! :naiad/no-close 149 | [{:keys [inputs outputs]}] 150 | (clojure.core.async/pipe (:in inputs) (:out outputs) false)) 151 | 152 | (defn close-all! 153 | ([& chans-seq] 154 | (doseq [chans chans-seq] 155 | (doseq [c (if (map? chans) 156 | (vals chans) 157 | chans)] 158 | (close! c))))) 159 | 160 | (defn index-of [coll itm] 161 | (loop [idx 0 162 | s (seq coll)] 163 | (if s 164 | (if (= (first s) itm) 165 | idx 166 | (recur (inc idx) (next s))) 167 | nil))) 168 | 169 | (defmethod csp/construct! :naiad/multiplexer 170 | [{:keys [inputs outputs]}] 171 | (let [out (:out outputs) 172 | selector (:selector inputs) 173 | closed-c (let [c (async/chan)] 174 | (close! c) 175 | c)] 176 | (go (loop [] 177 | (if-some [idx (! out v) 180 | (recur) 181 | (close-all! inputs outputs)) 182 | (recur)) 183 | (close-all! inputs outputs)))))) 184 | 185 | (defmethod csp/construct! :naiad/demultiplexer 186 | [{:keys [inputs outputs]}] 187 | (let [selector (:selector outputs) 188 | in (:in inputs) 189 | outs (vals (dissoc outputs :selector))] 190 | (go (loop [] 191 | (if-some [v (! selector idx) 196 | (recur) 197 | (close-all! inputs outputs)) 198 | (close-all! inputs outputs))) 199 | (close-all! inputs outputs)))))) 200 | 201 | (defmethod csp/construct! :naiad/mapcat-async 202 | [{:keys [inputs outputs f] :as node}] 203 | (go 204 | (let [out (:out outputs)] 205 | (loop [acc []] 206 | (if (< (count acc) (count inputs)) 207 | (if-some [v (! out v) 215 | (recur) 216 | false) 217 | true)))] 218 | (if continue? 219 | (recur []) 220 | (close-all! inputs outputs)))))))) -------------------------------------------------------------------------------- /src/naiad/passes.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.passes 2 | (:require [naiad.passes.remove-distributes :refer [remove-distributes]] 3 | [naiad.passes.fuse-transducer-nodes :refer [fuse-transducers]] 4 | [naiad.passes.insert-duplicators :refer [insert-duplicators]] 5 | [naiad.passes.non-channel-edges-to-nodes :refer [non-channel-edges-to-nodes]])) 6 | 7 | 8 | (defn run-passes [graph] 9 | (-> graph 10 | non-channel-edges-to-nodes 11 | insert-duplicators 12 | fuse-transducers 13 | remove-distributes)) 14 | -------------------------------------------------------------------------------- /src/naiad/passes/fuse_transducer_nodes.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.passes.fuse-transducer-nodes 2 | (:require [naiad.graph :as graph])) 3 | 4 | (defn fuse-transducer-nodes [graph from to] 5 | (let [f1 (get-in graph [from :f]) 6 | f2 (get-in graph [to :f]) 7 | new-f (comp f1 f2) 8 | _ (assert f1) 9 | _ (assert f2) 10 | new-node {:type ::fused-transducer 11 | :id from 12 | :transducer? true 13 | :f new-f 14 | :inputs (:inputs (graph from)) 15 | :outputs (:outputs (graph to))}] 16 | (-> graph 17 | (dissoc to) 18 | (assoc from new-node)))) 19 | 20 | (defn fuse-transducers [graph] 21 | (let [xducer (->> (for [[id node] graph 22 | :when (and (:transducer? node) 23 | (= 1 (count (:outputs node)))) 24 | :let [onodes (graph/nodes-by-link graph :inputs (fnext (first (:outputs node))))] 25 | :when (= (count onodes) 1) 26 | :let [onode (graph (:node (first onodes)))] 27 | :when (:transducer? onode) 28 | ] 29 | {:from node 30 | :to onode 31 | }) 32 | first)] 33 | (if xducer 34 | (recur (fuse-transducer-nodes graph (:id (:from xducer)) (:id (:to xducer)))) 35 | graph))) 36 | -------------------------------------------------------------------------------- /src/naiad/passes/insert_duplicators.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.passes.insert-duplicators 2 | (:require [naiad.graph :as g])) 3 | 4 | (defn insert-duplicators [graph] 5 | (let [links (->> (g/ports graph :inputs) 6 | (group-by :link) 7 | (filter (fn [[k v]] 8 | (> (count v) 1)))) 9 | new-nodes (for [[link inputs] links 10 | :let [new-ids (repeatedly (count inputs) g/gen-id)]] 11 | {:node {:type :naiad/duplicate 12 | :id (g/gen-id) 13 | :inputs {:in link} 14 | :outputs (zipmap (range) new-ids)} 15 | :links (zipmap new-ids 16 | inputs)}) 17 | graph (reduce 18 | (fn [acc {:keys [node links]}] 19 | (let [acc (assoc acc (:id node) node)] 20 | (reduce 21 | (fn [acc [new-id {:keys [node port link]}]] 22 | (assoc-in acc [node :inputs port] new-id)) 23 | acc 24 | links))) 25 | graph 26 | new-nodes)] 27 | graph)) 28 | -------------------------------------------------------------------------------- /src/naiad/passes/non_channel_edges_to_nodes.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.passes.non-channel-edges-to-nodes 2 | (:require [naiad.graph :as g]) 3 | (:import (java.util IdentityHashMap))) 4 | 5 | (defprotocol IToEdge 6 | (insert-into-graph [this graph] "Insert this non-channel edge as a new node in the graph")) 7 | 8 | 9 | (extend-protocol IToEdge 10 | clojure.lang.PersistentVector 11 | (insert-into-graph [this graph] 12 | (let [id (g/gen-id)] 13 | {:id id 14 | :graph (g/add-node graph {:type :naiad/onto-chan 15 | :id id 16 | :coll this 17 | :outputs {:out id}})})) 18 | 19 | 20 | clojure.core.async.impl.protocols.ReadPort 21 | (insert-into-graph [this graph] 22 | (let [id (g/gen-id)] 23 | {:id id 24 | :graph (g/annotate-link graph id {:existing-channel this})})) 25 | 26 | clojure.core.async.impl.protocols.WritePort 27 | (insert-into-graph [this graph] 28 | (let [id (g/gen-id)] 29 | {:id id 30 | :graph (g/annotate-link graph id {:existing-channel this})})) 31 | 32 | clojure.lang.ISeq 33 | (insert-into-graph [this graph] 34 | (let [id (g/gen-id)] 35 | {:id id 36 | :graph (g/add-node graph {:type :naiad/onto-chan 37 | :id id 38 | :coll this 39 | :outputs {:out id}})}))) 40 | 41 | 42 | (defn non-channel-edges-to-nodes [graph] 43 | (let [seen (IdentityHashMap.) 44 | update-fn 45 | (fn [graph port-key] 46 | (reduce 47 | (fn [graph [node-id node]] 48 | (reduce 49 | (fn [graph [port-id port]] 50 | (if (g/id? port) 51 | graph 52 | (let [{:keys [id graph]} (if (.containsKey seen port) 53 | {:id (.get seen port) 54 | :graph graph} 55 | (insert-into-graph port graph))] 56 | (.put seen port id) 57 | (assoc-in graph [node-id port-key port-id] id)))) 58 | graph 59 | (port-key node))) 60 | graph 61 | graph))] 62 | (reduce update-fn graph [:inputs :outputs :closes]))) -------------------------------------------------------------------------------- /src/naiad/passes/remove_distributes.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.passes.remove-distributes 2 | (:require [naiad.graph :as g])) 3 | 4 | (defn remove-distributes [graph] 5 | (let [id-maps (atom {}) 6 | graph (reduce-kv 7 | (fn [acc id {:keys [type] :as node}] 8 | (if (= :naiad/distribute type) 9 | (do (apply swap! id-maps assoc (interleave 10 | (vals (:outputs node)) 11 | (repeat (:in (:inputs node))))) 12 | acc) 13 | (assoc acc id node))) 14 | {} 15 | graph)] 16 | (reduce 17 | (fn [graph {:keys [node link port]}] 18 | (assoc-in graph [node :inputs port] (@id-maps link))) 19 | graph 20 | (->> (g/ports graph :inputs) 21 | (filter (comp @id-maps :link)))))) -------------------------------------------------------------------------------- /src/naiad/reducer_functions.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.reducer-functions 2 | (:refer-clojure :exclude [first second nfirst])) 3 | 4 | 5 | (defn first 6 | ([] nil) 7 | ([acc] acc) 8 | ([_ i] 9 | (reduced i))) 10 | 11 | 12 | (defn nfirst [n] 13 | (let [idx (volatile! 0)] 14 | (fn 15 | ([] nil) 16 | ([acc] acc) 17 | ([acc i] 18 | (if (= n @idx) 19 | (reduced i) 20 | (do (vswap! idx inc) 21 | acc)))))) 22 | 23 | (def second (nfirst 1)) 24 | (def third (nfirst 2)) 25 | (def forth (nfirst 3)) -------------------------------------------------------------------------------- /src/naiad/transducers.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.transducers 2 | (:require [naiad.transducers.ioc :refer [transducer ingest emit if-value]]) 3 | (:refer-clojure :exclude [first nth last reduce])) 4 | 5 | 6 | 7 | (defn reduce [rf init] 8 | (transducer 9 | (loop [acc init] 10 | (if-value [v (ingest)] 11 | (let [acc (rf acc v)] 12 | (if (reduced? acc) 13 | (emit acc) 14 | (recur acc))) 15 | (emit acc))))) 16 | 17 | (def ^{:doc "A transducer that filters all but the first item in a tansduction"} 18 | first 19 | (take 1)) 20 | 21 | (defn nth 22 | "Creates a transducer that filters all but the nth item of a transduction" 23 | [idx] 24 | (comp (drop idx) 25 | first)) 26 | 27 | (def ^{:doc "A transducer that filters all but the last item in a transduction"} 28 | last 29 | (transducer 30 | (loop [have-item? false 31 | item nil] 32 | (if-value [v (ingest)] 33 | (recur true v) 34 | (when have-item? 35 | (emit item)))))) 36 | -------------------------------------------------------------------------------- /src/naiad/transducers/ioc.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.transducers.ioc 2 | (:refer-clojure :exclude [first second nfirst reduce into transduce]) 3 | (:require [clojure.core.async.impl.ioc-macros :as ioc])) 4 | 5 | 6 | 7 | 8 | (def XF-IDX ioc/USER-START-IDX) 9 | (def ACC-IDX (inc ioc/USER-START-IDX)) 10 | (def STARTED-IDX (+ 2 ioc/USER-START-IDX)) 11 | 12 | (defn ingest [] 13 | (throw (ex-info "Can't call ingest outside of a transducer macro" {}))) 14 | 15 | (defn emit [val] 16 | (throw (ex-info "Can't call emit outside of a transducer macro" {}))) 17 | 18 | (defn -ingest [state blk] 19 | (ioc/aset-object state ioc/STATE-IDX blk) 20 | ::ingest) 21 | 22 | (defn -emit [state blk v] 23 | (ioc/aset-all! state ioc/STATE-IDX blk) 24 | (let [xf (ioc/aget-object state XF-IDX) 25 | acc (ioc/aget-object state ACC-IDX) 26 | result (xf acc v)] 27 | (ioc/aset-all! state ACC-IDX result) 28 | (when-not (reduced? result) 29 | :recur))) 30 | 31 | (defn -return [state val] 32 | (ioc/aset-all! state ACC-IDX (reduced (ioc/aget-object state ACC-IDX)))) 33 | 34 | (def transducer-custom-terminators 35 | {`ingest `-ingest 36 | `emit `-emit 37 | :Return `-return}) 38 | 39 | (defmacro if-value 40 | ([[v test] then] 41 | `(let [~v ~test] 42 | (if (identical? ~v ::end) 43 | nil 44 | ~then))) 45 | ([[v test] then else] 46 | `(let [~v ~test] 47 | (if (identical? ~v ::end) 48 | ~else 49 | ~then)))) 50 | 51 | 52 | (defmacro transducer 53 | [& body] 54 | `(fn [xf#] 55 | (let [f# ~(ioc/state-machine `(do ~@body) 3 (keys &env) transducer-custom-terminators) 56 | state# (-> (f#) 57 | (ioc/aset-all! ioc/BINDINGS-IDX (clojure.lang.Var/getThreadBindingFrame) 58 | STARTED-IDX false))] 59 | (fn 60 | ([] (xf#)) 61 | ([acc#] 62 | (ioc/aset-all! state# ACC-IDX acc# XF-IDX xf# ioc/VALUE-IDX ::end) 63 | (ioc/run-state-machine state#) 64 | (xf# (unreduced (ioc/aget-object state# ACC-IDX)))) 65 | ([acc# itm#] 66 | (ioc/aset-all! state# XF-IDX xf# ACC-IDX acc#) 67 | (when-not (ioc/aget-object state# STARTED-IDX) 68 | (ioc/run-state-machine state#) 69 | (ioc/aset-all! state# STARTED-IDX true)) 70 | (ioc/run-state-machine 71 | (ioc/aset-all! state# ioc/VALUE-IDX itm#)) 72 | (ioc/aget-object state# ACC-IDX)))))) 73 | 74 | 75 | -------------------------------------------------------------------------------- /test/naiad/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.core-test 2 | (:require [clojure.test :refer :all] 3 | [clojure.core.async :as async] 4 | [naiad :as df :refer [flow-result]])) 5 | 6 | 7 | (df/graph 8 | (df/map inc (df/map dec (df/map #(+ % %) [1 2 3])))) 9 | 10 | (df/graph 11 | (let [data [1 2 3]] 12 | (flow-result 13 | (df/filter even? [1 2 3 4])))) 14 | 15 | (deftest map-tests 16 | (testing "basic map usage" 17 | (is (= (flow-result 18 | (df/map inc [1 2 3 4])) 19 | [2 3 4 5]))) 20 | 21 | (testing "map with multiple input" 22 | (is (= (flow-result 23 | (df/map vector [1 2 3 4] [5 6 7 8])) 24 | [[1 5] [2 6] [3 7] [4 8]])) 25 | 26 | (is (= (flow-result 27 | (df/map + [1 2] [1 2] [1 2] [1 2])) 28 | [4 8]))) 29 | 30 | (testing "map chaining" 31 | (is (= (flow-result 32 | (df/map inc (df/map dec (df/map #(+ % %) [1 2 3])))) 33 | [2 4 6])) 34 | 35 | (is (= (flow-result 36 | (let [data [1 2 3]] 37 | (df/map + 38 | (df/map dec data) 39 | (df/map inc data)))) 40 | [2 4 6])))) 41 | 42 | 43 | (deftest basic-tansducer-tests 44 | (testing "filter" 45 | (is (= (flow-result 46 | (df/filter even? [1 2 3 4])) 47 | [2 4]))) 48 | 49 | (testing "take" 50 | (is (= (flow-result 51 | (df/take 3 (df/filter even? [1 2 3 4 5 6 7 8]))) 52 | [2 4 6])) 53 | 54 | (testing "constructor form" 55 | (is (= (flow-result 56 | (df/->take :n 3 :in (df/filter even? (range 8))))) 57 | [2 3 4]))) 58 | 59 | (testing "partition" 60 | (is (= (flow-result 61 | (df/partition-all 2 [1 2 3 4])) 62 | [[1 2] [3 4]])) 63 | 64 | )) 65 | 66 | (deftest multi-use-channels 67 | (testing "data distribution" 68 | (is (= (flow-result 69 | (let [filtered (df/filter pos? [1 2])] 70 | (df/map + 71 | (df/map inc filtered) 72 | (df/map dec filtered)))) 73 | [2 4])))) 74 | 75 | (deftest transducer-fusing 76 | (testing "multiple simple transducers become one" 77 | (let [make-graph (fn [] 78 | (->> [-1 1 2 3 -33] 79 | (df/filter pos?) 80 | (df/filter even?) 81 | (df/filter integer?) 82 | (df/filter number?)))] 83 | (is (= (flow-result 84 | (make-graph)) 85 | [2])) 86 | 87 | (is (= (count (df/graph 88 | (make-graph))) 89 | 2))))) 90 | 91 | (deftest merge-tests 92 | (testing "basic merge usage" 93 | (is (= (set (flow-result 94 | (df/merge [1 2] [3 4] [5 6]))) 95 | #{1 2 3 4 5 6})))) 96 | 97 | 98 | (deftest parallel->>-tests 99 | (testing "basic parallel usage" 100 | (is (= (set (flow-result 101 | (->> [1 2 3 4 5 6 7] 102 | (df/parallel->> {:threads 3} 103 | (df/map inc)) 104 | (df/take 7)))) 105 | #{2 3 4 5 6 7 8}))) 106 | 107 | (testing "supports ordering" 108 | (is (= (flow-result 109 | (->> [1 2 3 4 5 6 7] 110 | (df/parallel->> {:threads 3 111 | :ordered? true} 112 | (df/map inc)) 113 | (df/take 7))) 114 | [2 3 4 5 6 7 8])))) 115 | 116 | 117 | (deftest channel-data-sources 118 | (testing "can use a bare channel as a data source" 119 | (is (= (let [input (async/to-chan [1 2 3])] 120 | (flow-result 121 | (df/map inc input))) 122 | [2 3 4]))) 123 | 124 | (testing "can use a bare channel as a data sink" 125 | (is (= (let [output (async/chan 3)] 126 | (df/flow 127 | (df/->take :n 1 :in (range 10) :out output)) 128 | [(async/map :f inc :in rec :out input) 155 | (df/take 4 out)))) 156 | [10 10 10 10]))) 157 | 158 | 159 | (deftest multiplexer-test 160 | (testing "basic usage" 161 | (is (= (flow-result 162 | (df/multiplexer [2 1 0] [[10] [11] [12]])) 163 | [12 11 10]))) 164 | 165 | (testing "early termination of output" 166 | (is (= (flow-result 167 | (->> (df/multiplexer (cycle [0 1 2]) [(range 10 100) (range 20 100) (range 30 100)]) 168 | (df/take 6))) 169 | [10 20 30 11 21 31]))) 170 | 171 | (testing "early termination of selector input" 172 | (is (= (flow-result 173 | (df/multiplexer (df/take 6 (cycle [0 1 2])) [(range 10 100) (range 20 100) (range 30 100)])) 174 | [10 20 30 11 21 31])))) 175 | 176 | (deftest demultiplexer-test 177 | (testing "basic usage" 178 | (is (= (flow-result 179 | (let [{:keys [selector outputs]} (df/demultiplexer 4 (range 10))] 180 | (df/multiplexer selector outputs))) 181 | (range 10))) 182 | 183 | (is (= (flow-result 184 | (let [{:keys [selector outputs]} (df/demultiplexer 4 (range 10))] 185 | (df/multiplexer selector (map (partial df/map inc) outputs)))) 186 | (range 1 11))))) 187 | 188 | 189 | (deftest mapcat-async-test 190 | (let [inc-dec (fn [c v] 191 | (async/put! c (inc v)) 192 | (async/put! c (dec v)) 193 | (async/close! c))] 194 | (testing "basic usage" 195 | (is (= (flow-result 196 | (df/mapcat-async 197 | inc-dec 198 | (range 2))) 199 | [1 -1 2 0]))) 200 | 201 | (testing "early termination before" 202 | (is (= (flow-result 203 | (df/mapcat-async 204 | inc-dec 205 | (df/take 2 (range 3)))) 206 | [1 -1 2 0]))) 207 | 208 | (testing "early termination after" 209 | (is (= (flow-result 210 | (df/take 3 (df/mapcat-async 211 | inc-dec 212 | (range 3)))) 213 | [1 -1 2]))) 214 | 215 | 216 | (testing "call call flow inside mapcat-async" 217 | (is (= (flow-result 218 | (df/mapcat-async 219 | (fn [c v] 220 | (df/flow 221 | (df/->map :f inc :out c :in (range v (+ v 10))))) 222 | [10 20 30])) 223 | (range 11 41)))))) 224 | 225 | #_(naiad.backends.graphviz/output-dotfile (df/graph 226 | (->> [1 2 3 4 5 6 7] 227 | (df/parallel->> {:threads 3 228 | :ordered? true} 229 | (df/map inc)) 230 | (df/take 7)) 231 | 232 | ) 233 | "test.dot") 234 | -------------------------------------------------------------------------------- /test/naiad/error_handlers_test.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.error-handlers-test 2 | (:require [clojure.test :refer :all] 3 | [clojure.core.async :as async] 4 | [naiad :as n] 5 | [naiad.error-handlers :refer [log-to-chan abort]])) 6 | 7 | (deftest error-log-test 8 | (let [log (async/chan 1000)] 9 | (is (= (n/flow-result 10 | (n/with-annotations {:error-fn (log-to-chan log)} 11 | (n/filter (fn [x] 12 | (assert (odd? x)) 13 | true) 14 | (range 10)))) 15 | (filter odd? (range 10)))))) 16 | 17 | 18 | (deftest abort-test 19 | (is (= (n/flow-result 20 | (n/with-annotations {:error-fn abort} 21 | (n/filter (fn [x] 22 | (assert (odd? x)) 23 | true) 24 | [1 3 5 6 7]))) 25 | [1 3 5]))) 26 | 27 | -------------------------------------------------------------------------------- /test/naiad/metrics_test.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.metrics-test 2 | (:require [clojure.test :refer :all] 3 | [clojure.core.async :as async] 4 | [naiad :as df :refer [flow-result]])) 5 | 6 | 7 | (deftest throughput-metrics 8 | (let [a (atom []) 9 | ml (fn [& args] 10 | (swap! a conj args))] 11 | (is (= (flow-result 12 | (df/annotate (df/map inc (range 2)) 13 | :metrics ml)) 14 | [1 2])) 15 | 16 | (is (= @a [[:histogram :buffer-size 1] 17 | [:histogram :buffer-size 0] 18 | [:histogram :buffer-size 1] 19 | [:histogram :buffer-size 0]]))) 20 | 21 | 22 | 23 | (let [a (atom []) 24 | ml (fn [& args] 25 | (swap! a conj args))] 26 | (is (= (flow-result 27 | (df/with-annotations {:metrics ml} 28 | (df/map inc (range 2)))) 29 | [1 2])) 30 | 31 | (is (= @a [[:histogram :buffer-size 1] 32 | [:histogram :buffer-size 0] 33 | [:histogram :buffer-size 1] 34 | [:histogram :buffer-size 0]])))) 35 | -------------------------------------------------------------------------------- /test/naiad/reducer_functions_test.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.reducer-functions-test 2 | (:require [clojure.test :refer :all] 3 | [naiad.reducer-functions :as rf])) 4 | 5 | (deftest first-test 6 | (is (= (transduce (map inc) rf/first [1 2 3]) 7 | 2)) 8 | (is (= (reduce rf/first nil [1 2 3])))) 9 | 10 | 11 | (deftest nfirst-test 12 | (dotimes [x 10] 13 | (dotimes [y 11] 14 | (is (= (transduce (map identity) (rf/nfirst y) (range x)) 15 | (first (drop y (range x)))))))) 16 | 17 | 18 | 19 | (deftest second-third-forth-tests 20 | (is (= (transduce (map identity) rf/second (range 10)) 21 | 1)) 22 | (is (= (transduce (map identity) rf/third (range 10)) 23 | 2)) 24 | (is (= (transduce (map identity) rf/forth (range 10)) 25 | 3))) -------------------------------------------------------------------------------- /test/naiad/transducers_test.clj: -------------------------------------------------------------------------------- 1 | (ns naiad.transducers-test 2 | (:require [naiad.transducers :as tr] 3 | [clojure.test :refer :all])) 4 | 5 | 6 | (deftest reduce-test 7 | (is (= (into #{} 8 | (tr/reduce conj []) 9 | (range 3)) 10 | #{(vec (range 3))})) 11 | 12 | (is (= (into #{} 13 | (comp (take 5) 14 | (tr/reduce conj [])) 15 | (range 10)) 16 | #{(vec (range 5))})) 17 | 18 | (is (= (into #{} 19 | (comp (take 5) 20 | (tr/reduce conj []) 21 | (take 1)) 22 | (range 10)) 23 | #{(vec (range 5))}))) 24 | 25 | (defn transient-conj 26 | ([] (transient [])) 27 | ([acc] (persistent! acc)) 28 | ([acc itm] (conj acc itm))) 29 | 30 | (deftest first-tests 31 | (is (= (into #{} tr/first (range 10)) 32 | #{0})) 33 | 34 | (is (= (into #{} tr/first []) 35 | #{}))) 36 | 37 | (deftest nth-tests 38 | (is (= (into #{} (tr/nth 2) (range 10)) 39 | #{2})) 40 | (is (= (into #{} (tr/nth 0) (range 10)) 41 | #{0})) 42 | (is (= (into #{} (tr/nth 100) (range 10)) 43 | #{}))) 44 | 45 | (deftest last-tests 46 | (is (= (into #{} tr/last (range 10)) 47 | #{9})) 48 | 49 | (is (= (into #{} tr/last []) 50 | #{})) 51 | 52 | (is (= (into #{} (comp (take 3) tr/last) (range)) 53 | #{2}))) 54 | 55 | #_(deftest transduce-test 56 | (is (= (into #{} 57 | (tr/transduce (map inc) 58 | conj []) 59 | (range 3)) 60 | #{(mapv inc (range 3))})) 61 | 62 | 63 | (is (= (into #{} 64 | (tr/transduce (map inc) 65 | conj) 66 | (range 3)) 67 | #{(mapv inc (range 3))})) 68 | 69 | (is (= (into #{} 70 | (tr/transduce (take 3) 71 | conj) 72 | (range 10)) 73 | #{(vec (range 3))})) 74 | ) 75 | 76 | --------------------------------------------------------------------------------