aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/concurrency/actor.lux
blob: dd34a7ae8a9bfc4c045c2600d19d473606854e7e (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
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
(;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 Monad<Lux>]
       (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."}
  {#handle (-> (Message s) s (Actor s) (T;Task s))
   #end (-> Text s (P;Promise Unit))})

## [Values]
(def: #export (default-handle message state self)
  (All [s] (-> (Message s) s (Actor s) (T;Task s)))
  (message state self))

(def: #export (default-end cause state)
  (All [s] (-> Text s (P;Promise Unit)))
  (P/wrap []))

(def: #export (spawn behavior init)
  {#;doc "Given a behavior and initial state, spawns an actor and returns it."}
  (All [s] (-> (Behavior s) s (IO (Actor s))))
  (io (let [[handle end] behavior
            self (: (Actor ($ +0))
                    {#mailbox (stm;var (:! (Message ($ +0)) []))
                     #kill-switch (P;promise Unit)
                     #obituary (P;promise (Obituary ($ +0)))})
            mailbox-channel (io;run (stm;follow (get@ #mailbox self)))
            |mailbox| (stm;var mailbox-channel)
            _ (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-channel]
                      (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' (handle 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]
(do-template [<with> <resolve> <tag> <desc>]
  [(def: (<with> name)
     (-> Ident cs;Annotations cs;Annotations)
     (|>. (#;Cons [(ident-for <tag>)
                   (code;tag name)])))
   
   (def: (<resolve> name)
     (-> Ident (Lux Ident))
     (do Monad<Lux>
       [name (macro;normalize name)
        [_ annotations _] (macro;find-def name)]
       (case (macro;get-ident-ann (ident-for <tag>) annotations)
         (#;Some actor-name)
         (wrap actor-name)

         _
         (macro;fail (format "Definition is not " <desc> ".")))))]

  [with-actor   resolve-actor   #;;actor   "an actor"]
  [with-message resolve-message #;;message "a message"]
  )

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

(do-template [<name> <desc>]
  [(def: <name>
     (-> Text Text)
     (|>. (format <desc> "@")))]

  [state-name    "State"]
  [behavior-name "Behavior"]
  [new-name      "new"]
  )

(type: HandleC
  [[Text Text Text] Code])

(type: StopC
  [[Text Text] Code])

(type: BehaviorC
  [(Maybe HandleC) (Maybe StopC)])

(def: behavior^
  (s;Syntax BehaviorC)
  (let [handle-args ($_ p;seq s;local-symbol s;local-symbol s;local-symbol)
        stop-args ($_ p;seq s;local-symbol s;local-symbol)]
    (p;seq (p;opt (s;form (p;seq (s;form (p;after (s;this (' handle)) handle-args))
                                 s;any)))
           (p;opt (s;form (p;seq (s;form (p;after (s;this (' stop)) stop-args))
                                 s;any))))))

(syntax: #export (actor: [export csr;export]
                   [[_name _vars] actor-decl^]
                   [annotations (p;default cs;empty-annotations csr;annotations)]
                   state-type
                   [[?handle ?stop] behavior^])
  {#;doc (doc "Defines an actor, with its behavior and internal state."
              (actor: #export Counter
                Nat
                
                ((stop cause state)
                 (:: P;Monad<Promise> wrap
                     (log! (if (ex;match? ;;Killed cause)
                             (format "Counter was killed: " (%n state))
                             cause)))))

              (actor: #export (Stack a)
                (List a)
                
                ((handle message state self)
                 (do T;Monad<Task>
                   [#let [_ (log! "BEFORE")]
                    output (message state self)
                    #let [_ (log! "AFTER")]]
                   (wrap output)))))}
  (with-gensyms [g!message g!self g!state g!init g!error g!return g!output]
    (do @
      [module macro;current-module-name
       #let [g!type (code;local-symbol (state-name _name))
             g!behavior (code;local-symbol (behavior-name _name))
             g!actor (code;local-symbol _name)
             g!new (code;local-symbol (new-name _name))
             g!vars (L/map code;local-symbol _vars)]]
      (wrap (list (` (type: (~@ (csw;export export)) ((~ g!type) (~@ g!vars))
                       (~ state-type)))
                  (` (type: (~@ (csw;export export)) ((~ g!actor) (~@ g!vars))
                       (~ (|> annotations
                              (with-actor [module _name])
                              csw;annotations))
                       (;;Actor ((~ g!type) (~@ g!vars)))))
                  (` (def: (~@ (csw;export export)) (~ g!behavior)
                       (All [(~@ g!vars)]
                         (;;Behavior ((~ g!type) (~@ g!vars))))
                       {#;;handle (~ (case ?handle
                                       #;None
                                       (` ;;default-handle)

                                       (#;Some [[messageN stateN selfN] bodyC])
                                       (` (function [(~ (code;local-symbol messageN))
                                                     (~ (code;local-symbol stateN))
                                                     (~ (code;local-symbol selfN))]
                                            (do T;Monad<Task>
                                              []
                                              (~ bodyC))))))
                        #;;end (~ (case ?stop
                                    #;None
                                    (` ;;default-handle)

                                    (#;Some [[causeN stateN] bodyC])
                                    (` (function [(~ (code;local-symbol causeN))
                                                  (~ (code;local-symbol stateN))]
                                         (do P;Monad<Promise>
                                           []
                                           (~ bodyC))))))}))
                  (` (def: (~@ (csw;export export)) ((~ g!new) (~ g!init))
                       (All [(~@ g!vars)]
                         (-> ((~ g!type) (~@ g!vars)) (io;IO ((~ g!actor) (~@ g!vars)))))
                       (;;spawn (~ g!behavior) (~ g!init))))))
      )))

(type: Signature
  {#vars (List Text)
   #name Text
   #inputs (List [Text Code])
   #state Text
   #self Text
   #output Code})

(def: signature^
  (s;Syntax Signature)
  (s;form ($_ p;seq
              (p;default (list) (s;tuple (p;some s;local-symbol)))
              s;local-symbol
              (p;some csr;typed-input)
              s;local-symbol
              s;local-symbol
              s;any)))

(def: reference^
  (s;Syntax [Ident (List Text)])
  (p;either (s;form (p;seq s;symbol (p;some s;local-symbol)))
            (p;seq s;symbol (:: p;Monad<Parser> wrap (list)))))

(syntax: #export (message: [export csr;export] [[actor-name actor-vars] reference^]
                   [signature signature^]
                   [annotations (p;default cs;empty-annotations csr;annotations)]
                   body)
  {#;doc (doc "A message can access the actor's state through the state parameter."
              "A message can also access the actor itself through the self parameter."
              "A message's output must be a task containing a 2-tuple with the updated state and a return value."
              "A message may succeed or fail (in case of failure, the actor dies)."

              (message: #export Counter
                (count! [increment Nat] state self Nat)
                (let [state' (n.+ increment state)]
                  (T;return [state' state'])))

              (message: #export (Stack a)
                (push [value a] state self (List a))
                (let [state' (#;Cons value state)]
                  (T;return [state' state']))))}
  (with-gensyms [g!return g!error g!task]
    (do @
      [actor-name (resolve-actor actor-name)
       #let [g!type (code;symbol (product;both id state-name actor-name))
             g!message (code;local-symbol (get@ #name signature))
             g!refs (: (List Code)
                       (if (list;empty? actor-vars)
                         (list)
                         (|> actor-vars list;size n.dec
                             (list;n.range +0) (L/map (|>. code;nat (~) ($) (`))))))
             g!actor (code;symbol actor-name)
             g!tvars (|> (get@ #vars signature) (L/append actor-vars) (L/map code;local-symbol))
             g!inputsC (|> (get@ #inputs signature) (L/map (|>. product;left code;local-symbol)))
             g!inputsT (|> (get@ #inputs signature) (L/map product;right))
             g!outputT (get@ #output signature)
             g!state (|> signature (get@ #state) code;local-symbol)
             g!self (|> signature (get@ #self) code;local-symbol)]]
      (wrap (list (` (def: (~@ (csw;export export)) ((~ g!message) (~@ g!inputsC) (~ g!self))
                       (~ (|> annotations
                              (with-message actor-name)
                              csw;annotations))
                       (All [(~@ g!tvars)] (-> (~@ g!inputsT) (~ g!actor) (T;Task (~ g!outputT))))
                       (let [(~ g!task) (T;task (~ g!outputT))]
                         (exec (;;send (function [(~ g!state) (~ g!self)]
                                         (do P;Monad<Promise>
                                           [(~ g!return) (: (T;Task [((~ g!type) (~@ g!refs))
                                                                     (~ g!outputT)])
                                                            (do T;Monad<Task>
                                                              []
                                                              (~ body)))]
                                           (case (~ g!return)
                                             (#;Right [(~ g!state) (~ g!return)])
                                             (exec (io;run (P;resolve (#;Right (~ g!return)) (~ g!task)))
                                               (T;return (~ g!state)))
                                             
                                             (#;Left (~ g!error))
                                             (exec (io;run (P;resolve (#;Left (~ g!error)) (~ g!task)))
                                               (T;fail (~ g!error))))
                                           ))
                                       (~ g!self))
                           (~ g!task)))))
                  ))
      )))