aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/concurrency/actor.lux
blob: 0b9c1032f92eb94b85e678cac832affa89b47f5e (plain)
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
(;module: {#;doc "The actor model of concurrency."}
  lux
  (lux (control monad
                ["p" parser]
                ["ex" exception #+ exception:])
       [io #- run "io/" Monad<IO>]
       (data text/format
             (coll [list "L/" Monoid<List> Monad<List>])
             [product])
       [macro #+ with-gensyms]
       (macro [code]
              ["s" syntax #+ syntax: Syntax]
              (syntax ["cs" common]
                      (common ["csr" reader]
                              ["csw" writer])))
       [type])
  (.. ["A" atom]
      ["P" promise "P/" Monad<Promise>]
      ["T" task]
      [stm #+ Monad<STM>]
      [frp]))

(exception: #export Poisoned)
(exception: #export Killed)

## [Types]
(with-expansions
  [<Message> (as-is (-> s (Actor s) (T;Task s)))
   <Obituary> (as-is [Text s (List <Message>)])]
  (type: #export (Actor s)
    {#;doc "An actor, defined as all the necessities it requires."}
    {#mailbox (stm;Var <Message>)
     #kill-switch (P;Promise Unit)
     #obituary (P;Promise <Obituary>)})

  (type: #export (Message s)
    <Message>)

  (type: #export (Obituary s)
    <Obituary>))

(type: #export (Behavior s)
  {#;doc "An actor's behavior when messages are received."}
  {#step (-> (Message s) s (Actor s) (T;Task s))
   #end (-> Text s (P;Promise Unit))})

## [Values]
(def: #export (spawn init behavior)
  {#;doc "Given a behavior and initial state, spawns an actor and returns it."}
  (All [s] (-> s (Behavior s) (IO (Actor s))))
  (io (let [[step end] behavior
            self (: (Actor ($ +0))
                    {#mailbox (stm;var (:! (Message ($ +0)) []))
                     #kill-switch (P;promise Unit)
                     #obituary (P;promise (Obituary ($ +0)))})
            mailbox-chan (io;run (stm;follow (get@ #mailbox self)))
            |mailbox| (stm;var mailbox-chan)
            _ (P/map (function [_]
                       (io;run (do Monad<IO>
                                 [mb (stm;read! |mailbox|)]
                                 (frp;close mb))))
                     (get@ #kill-switch self))
            process (loop [state init
                           messages mailbox-chan]
                      (do P;Monad<Promise>
                        [?messages+ messages]
                        (case ?messages+
                          ## No kill-switch so far, so I may proceed...
                          (#;Some [message messages'])
                          (do P;Monad<Promise>
                            [#let [_ (io;run (stm;write! messages' |mailbox|))]
                             ?state' (step message state self)]
                            (case ?state'
                              (#;Left error)
                              (do @
                                [#let [_ (io;run (P;resolve [] (get@ #kill-switch self)))
                                       _ (io;run (frp;close messages'))]
                                 _ (end error state)
                                 remaining-messages (frp;consume messages')]
                                (wrap [error state (#;Cons message remaining-messages)]))

                              (#;Right state')
                              (recur state' messages')))

                          ## Otherwise, clean-up and return current state.
                          #;None
                          (do P;Monad<Promise>
                            [#let [_ (io;run (frp;close messages))
                                   death-message (Killed "")]
                             _ (end death-message state)]
                            (wrap [death-message state (list)])))))]
        self)))

(def: #export (alive? actor)
  (All [s] (-> (Actor s) Bool))
  (case [(P;poll (get@ #kill-switch actor))
         (P;poll (get@ #obituary actor))]
    [#;None #;None]
    true

    _
    false))

(def: #export (send message actor)
  {#;doc "Communicate with an actor through message passing."}
  (All [s] (-> (Message s) (Actor s) (IO Bool)))
  (if (alive? actor)
    (exec (io;run (stm;write! message (get@ #mailbox actor)))
      (io/wrap true))
    (io/wrap false)))

(def: #export (kill actor)
  {#;doc "Immediately kills the given actor (if it is not already dead)."}
  (All [s] (-> (Actor s) (io;IO Bool)))
  (if (alive? actor)
    (|> actor (get@ #kill-switch) (P;resolve []))
    (io/wrap false)))

(def: #export (poison actor)
  {#;doc "Kills the actor by sending a message that will kill it upon processing,
          but allows the actor to handle previous messages."}
  (All [s] (-> (Actor s) (IO Bool)))
  (send (function [state self]
          (T;throw Poisoned ""))
        actor))

## [Syntax]
(type: Method
  {#name Text
   #vars (List Text)
   #args (List [Text Code])
   #state Text
   #self Text
   #return Code
   #body Code})

(def: method^
  (Syntax Method)
  (s;form (do p;Monad<Parser>
            [vars (p;default (list) (s;tuple (p;some s;local-symbol)))
             [name args state self] (s;form ($_ p;seq
                                                s;local-symbol
                                                (p;some csr;typed-input)
                                                s;local-symbol
                                                s;local-symbol
                                                ))
             return s;any
             body s;any]
            (wrap {#name name
                   #vars vars
                   #args args
                   #state state
                   #self self
                   #return return
                   #body body}))))

(def: stop^
  (Syntax [[Text Text] Code])
  (s;form (p;seq (s;tuple (p;seq s;local-symbol
                                 s;local-symbol))
                 s;any)))

(def: actor-decl^
  (Syntax [(List Text) Text (List [Text Code])])
  (p;seq (p;default (list) (s;tuple (p;some s;local-symbol)))
         (p;either (s;form (p;seq s;local-symbol (p;many csr;typed-input)))
                   (p;seq s;local-symbol (:: p;Monad<Parser> wrap (list))))))

(syntax: #export (actor: [export csr;export]
                   [[_vars _name _args] actor-decl^]
                   state-type
                   [methods (p;some method^)]
                   [?stop (p;opt stop^)])
  {#;doc (doc "Defines an actor, with internal state and methods that can be called on it."
              "A method can access the actor's state through the state parameter."
              "A method can also access the actor itself through the self parameter."
              "A method may succeed or fail (in case of failure, the actor dies). This is handled through the Either type."
              "A method's output must be a promise containing a 2-tuple with the updated state and a return value."
              "All methods are run implicitly within the Promise monad."

              (actor: #export Counter
                Int
                
                ((count! [increment Int] state self)
                 [Int Int]
                 (if (i.>= 0 increment)
                   (let [state' (i.+ increment state)]
                     (T;return [state' [state state']]))
                   (T;fail "Cannot add negative numbers!")))

                ([cause state]
                 (:: P;Monad<Promise> wrap
                     (log! (if (ex;match? ;;Killed cause)
                             (format "Counter was killed: " (%i state))
                             cause))))
                ))}
  (with-gensyms [g!message g!self g!state g!init g!error g!return g!output]
    (let [g!state-type (code;symbol ["" (format _name "//Actor:State")])
          g!behavior (code;symbol ["" (format _name "//Actor:Behavior")])
          g!actor (code;symbol ["" _name])
          g!methods (L/map (: (-> Method Code)
                              (function [(^slots [#name #vars #args #state #self #return #body])]
                                (let [g!method (code;symbol ["" name])
                                      g!vars (L/map (|>. [""] code;symbol) vars)
                                      g!var-refs (: (List Code)
                                                    (if (list;empty? vars)
                                                      (list)
                                                      (|> vars list;size n.dec
                                                          (list;n.range +0) (L/map (|>. code;nat (~) ($) (`))))))
                                      g!args-names (L/map (|>. product;left [""] code;symbol) args)
                                      g!arg-types (L/map product;right args)
                                      g!state (code;symbol ["" state])
                                      g!self (code;symbol ["" self])]
                                  (` (def: (~@ (csw;export export)) ((~ g!method) (~@ g!args-names) (~ g!self))
                                       (All [(~@ g!vars)]
                                         (-> (~@ g!arg-types) (~ g!actor) (T;Task (~ return))))
                                       (let [(~ g!output) (T;task (~ return))]
                                         (exec (;;send (function [(~ g!state) (~ g!self)]
                                                         (do P;Monad<Promise>
                                                           [(~ g!return) (: (T;Task [((~ g!state-type) (~@ g!var-refs))
                                                                                     (~ return)])
                                                                            (~ body))]
                                                           (case (~ g!return)
                                                             (#;Right [(~ g!state) (~ g!return)])
                                                             (exec (io;run (P;resolve (#;Right (~ g!return)) (~ g!output)))
                                                               (T;return (~ g!state)))
                                                             
                                                             (#;Left (~ g!error))
                                                             (exec (io;run (P;resolve (#;Left (~ g!error)) (~ g!output)))
                                                               (T;fail (~ g!error))))))
                                                       (~ g!self))
                                           (~ g!output))))))))
                           methods)
          g!new (code;symbol ["" (format "new-" _name)])
          g!vars (L/map (|>. [""] code;symbol) _vars)]
      (wrap (list& (` (type: (~@ (csw;export export)) ((~ g!state-type) (~@ g!vars))
                        (~ state-type)))
                   (` (type: (~@ (csw;export export)) ((~ g!actor) (~@ g!vars))
                        (;;Actor ((~ g!state-type) (~@ g!vars)))))
                   (` (def: (~@ (csw;export export)) (~ g!behavior)
                        (All [(~@ g!vars)]
                          (Behavior ((~ g!state-type) (~@ g!vars))))
                        {#step (function [(~' message) (~' state) (~' self)]
                                 ((~' message) (~' state) (~' self)))
                         #end (~ (case ?stop
                                   (#;Some [[cause state] body])
                                   (let [g!cause (code;symbol ["" cause])
                                         g!state (code;symbol ["" state])]
                                     (` (function [(~ g!cause) (~ g!state)]
                                          (do P;Monad<Promise>
                                            []
                                            (~ body)))))

                                   #;None
                                   (` (:: P;Monad<Promise> (~' wrap) []))))}))
                   (` (def: (~@ (csw;export export)) ((~ g!new) (~ g!init))
                        (All [(~@ g!vars)]
                          (-> ((~ g!state-type) (~@ g!vars)) (io;IO ((~ g!actor) (~@ g!vars)))))
                        (;;spawn (~ g!init) (~ g!behavior))))
                   g!methods))
      )))