-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.clj
81 lines (67 loc) · 2.23 KB
/
example.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
(ns clj-amp.example
(:require [clj-amp.command :as command]
[clj-amp.core :refer [client simple-server make-responder]]
[clj-amp.argument :as a]
[manifold.deferred :as d]
[manifold.time :as dt]
[slingshot.slingshot :refer [try+ throw+]]))
(command/defcommand sum
{:a {:type ::a/integer}
:b {:type ::a/integer}}
{:total {:type ::a/integer}}
:command-name "Sum")
(command/defcommand divide
{:numerator {:type ::a/integer}
:denominator {:type ::a/integer}}
{:result {:type ::a/float}}
:errors {::zero-division "ZERO_DIVISION"}
:command-name "Divide")
(defn -example-client
[& args]
@(d/chain
(client "localhost" 1234 (make-responder {}))
(fn [[call-remote close!]]
(d/chain
(call-remote sum {:a 13 :b 81})
(fn [r]
(println "Sum:" r)
(call-remote divide {:numerator 1234 :denominator 2}))
(fn [r]
(println "Quotient:" r)
(close!))))))
(defn -example-client-concurrent
[& args]
@(d/chain
(client "localhost" 1234 (make-responder {}))
(fn [[call-remote close!]]
(d/let-flow
[{sum-result :total} (call-remote sum {:a 13 :b 81})
quotient (d/catch
(d/chain
(call-remote divide {:numerator 1234 :denominator 0})
:result)
clojure.lang.ExceptionInfo
(fn [e]
(if (= ::zero-division (-> e ex-data :type))
(do (println "Divided by zero: returning INF")
1e1000)
(throw+ e))))]
(println "Done with math:" [sum-result quotient])
(close!)))))
(defn- sum'
[{:keys [a b]}]
(let [total (+ a b)]
(println "Did a sum:" a "+" b "=" total)
(dt/in 2000 #(identity {:total total}))))
(defn- divide'
[{:keys [numerator denominator]}]
(try+
(let [result (double (/ numerator denominator))]
(println "Divided:" numerator "/" denominator "=" result)
{:result result})
(catch ArithmeticException _
(throw+ {:type ::zero-division}))))
(defn -example-server
[& args]
(let [responder (make-responder {sum sum' divide divide'})]
(simple-server responder 1234)))