aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/concurrency/actor.lux
blob: f9ab10327bd38332e79b265296b384a4fc8dd715 (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
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
(.module: {#.doc "The actor model of concurrency."}
  [lux #*
   [abstract
    monad]
   [control
    [pipe (#+ case>)]
    ["." function]
    ["." try (#+ Try)]
    ["." exception (#+ exception:)]
    ["." io (#+ IO io)]
    ["<>" parser
     ["<c>" code (#+ Parser)]]]
   [data
    ["." product]
    [number
     ["n" nat]]
    [text
     ["%" format (#+ format)]]
    [collection
     ["." list ("#\." monoid monad fold)]]]
   [macro
    ["." code]
    [syntax (#+ syntax:)
     ["cs" common
      ["csr" reader]
      ["csw" writer]]]]
   ["." meta (#+ with-gensyms monad)
    ["." annotation]]
   [type (#+ :share)
    ["." abstract (#+ abstract: :representation :abstraction)]]]
  [//
   ["." atom (#+ Atom atom)]
   ["." promise (#+ Promise Resolver) ("#\." monad)]
   ["." frp (#+ Channel)]])

(exception: #export poisoned)
(exception: #export dead)

(with-expansions
  [<Mail> (as-is (-> s (Actor s) (Promise (Try s))))
   <Obituary> (as-is [Text s (List <Mail>)])
   <Mailbox> (as-is (Rec Mailbox
                      [(Promise [<Mail> Mailbox])
                       (Resolver [<Mail> Mailbox])]))]

  (def: (pending [read write])
    (All [a]
      (-> (Rec Mailbox
            [(Promise [a Mailbox])
             (Resolver [a Mailbox])])
          (IO (List a))))
    (do {! io.monad}
      [current (promise.poll read)]
      (case current
        (#.Some [head tail])
        (\ ! map (|>> (#.Cons head))
           (pending tail))
        
        #.None
        (wrap #.Nil))))
  
  (abstract: #export (Actor s)
    {#obituary [(Promise <Obituary>)
                (Resolver <Obituary>)]
     #mailbox (Atom <Mailbox>)}

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

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

    (type: #export (Behavior o s)
      {#.doc "An actor's behavior when mail is received and when a fatal error occurs."}
      {#on-init (-> o s)
       #on-mail (-> (Mail s) s (Actor s) (Promise (Try s)))
       #on-stop (-> Text s (Promise Any))})

    (def: #export (spawn! behavior init)
      {#.doc "Given a behavior and initial state, spawns an actor and returns it."}
      (All [o s] (-> (Behavior o s) o (IO (Actor s))))
      (io (let [[on-init on-mail on-stop] behavior
                self (:share [o s]
                             {(Behavior o s)
                              behavior}
                             {(Actor s)
                              (:abstraction {#obituary (promise.promise [])
                                             #mailbox (atom (promise.promise []))})})
                process (loop [state (on-init init)
                               [|mailbox| _] (io.run (atom.read (get@ #mailbox (:representation self))))]
                          (do {! promise.monad}
                            [[head tail] |mailbox|
                             ?state' (on-mail head state self)]
                            (case ?state'
                              (#try.Failure error)
                              (do !
                                [_ (on-stop error state)]
                                (let [[_ resolve] (get@ #obituary (:representation self))]
                                  (exec (io.run
                                         (do io.monad
                                           [pending (..pending tail)]
                                           (resolve [error state (#.Cons head pending)])))
                                    (wrap []))))

                              (#try.Success state')
                              (recur state' tail))))]
            self)))

    (def: #export (alive? actor)
      (All [s] (-> (Actor s) (IO Bit)))
      (let [[obituary _] (get@ #obituary (:representation actor))]
        (|> obituary
            promise.poll
            (\ io.functor map
               (|>> (case> #.None
                           yes

                           _
                           no))))))

    (def: #export (obituary actor)
      (All [s] (-> (Actor s) (IO (Maybe (Obituary s)))))
      (let [[obituary _] (get@ #obituary (:representation actor))]
        (promise.poll obituary)))

    (def: #export await
      (All [s] (-> (Actor s) (Promise (Obituary s))))
      (|>> :representation
           (get@ #obituary)
           product.left))

    (def: #export (mail! mail actor)
      {#.doc "Send mail to an actor.."}
      (All [s] (-> (Mail s) (Actor s) (IO (Try Any))))
      (do {! io.monad}
        [alive? (..alive? actor)]
        (if alive?
          (let [entry [mail (promise.promise [])]]
            (do !
              [|mailbox|&resolve (atom.read (get@ #mailbox (:representation actor)))]
              (loop [[|mailbox| resolve] |mailbox|&resolve]
                (do !
                  [|mailbox| (promise.poll |mailbox|)]
                  (case |mailbox|
                    #.None
                    (do !
                      [resolved? (resolve entry)]
                      (if resolved?
                        (do !
                          [_ (atom.write (product.right entry) (get@ #mailbox (:representation actor)))]
                          (wrap (exception.return [])))
                        (recur |mailbox|&resolve)))
                    
                    (#.Some [_ |mailbox|'])
                    (recur |mailbox|'))))))
          (wrap (exception.throw ..dead [])))))

    (type: #export (Message s o)
      (-> s (Actor s) (Promise (Try [s o]))))

    (def: (mail message)
      (All [s o] (-> (Message s o) [(Promise (Try o)) (Mail s)]))
      (let [[promise resolve] (:share [s o]
                                      {(Message s o)
                                       message}
                                      {[(Promise (Try o))
                                        (Resolver (Try o))]
                                       (promise.promise [])})]
        [promise
         (function (_ state self)
           (do {! promise.monad}
             [outcome (message state self)]
             (case outcome
               (#try.Success [state' return])
               (exec (io.run (resolve (#try.Success return)))
                 (promise.resolved (#try.Success state')))
               
               (#try.Failure error)
               (exec (io.run (resolve (#try.Failure error)))
                 (promise.resolved (#try.Failure error))))))]))

    (def: #export (tell! message actor)
      {#.doc "Communicate with an actor through message passing."}
      (All [s o] (-> (Message s o) (Actor s) (Promise (Try o))))
      (let [[promise mail] (..mail message)]
        (do promise.monad
          [outcome (promise.future (..mail! mail actor))]
          (case outcome
            (#try.Success)
            promise
            
            (#try.Failure error)
            (wrap (#try.Failure error))))))
    )
  )

(def: (default-on-mail mail state self)
  (All [s] (-> (Mail s) s (Actor s) (Promise (Try s))))
  (mail state self))

(def: (default-on-stop cause state)
  (All [s] (-> Text s (Promise Any)))
  (promise\wrap []))

(def: #export default
  (All [s] (Behavior s s))
  {#on-init function.identity
   #on-mail ..default-on-mail
   #on-stop ..default-on-stop})

(def: #export (poison! actor)
  {#.doc (doc "Kills the actor by sending mail that will kill it upon processing,"
              "but allows the actor to handle previous mail.")}
  (All [s] (-> (Actor s) (IO (Try Any))))
  (..mail! (function (_ state self)
             (promise.resolved (exception.throw ..poisoned [])))
           actor))

(def: actor-decl^
  (Parser [Text (List Text)])
  (<>.either (<c>.form (<>.and <c>.local-identifier (<>.some <c>.local-identifier)))
             (<>.and <c>.local-identifier (\ <>.monad wrap (list)))))

(type: On-MailC
  [[Text Text Text] Code])

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

(type: BehaviorC
  [(Maybe On-MailC) (Maybe On-StopC) (List Code)])

(def: argument
  (Parser Text)
  <c>.local-identifier)

(def: behavior^
  (Parser BehaviorC)
  (let [on-mail-args ($_ <>.and ..argument ..argument ..argument)
        on-stop-args ($_ <>.and ..argument ..argument)]
    ($_ <>.and
        (<>.maybe (<c>.form (<>.and (<c>.form (<>.after (<c>.this! (' on-mail)) on-mail-args))
                                    <c>.any)))
        (<>.maybe (<c>.form (<>.and (<c>.form (<>.after (<c>.this! (' on-stop)) on-stop-args))
                                    <c>.any)))
        (<>.some <c>.any))))

(def: (on-mail g!_ ?on-mail)
  (-> Code (Maybe On-MailC) Code)
  (case ?on-mail
    #.None
    (` (~! ..default-on-mail))

    (#.Some [[mailN stateN selfN] bodyC])
    (` (function ((~ g!_)
                  (~ (code.local-identifier mailN))
                  (~ (code.local-identifier stateN))
                  (~ (code.local-identifier selfN)))
         (~ bodyC)))))

(def: (on-stop g!_ ?on-stop)
  (-> Code (Maybe On-StopC) Code)
  (case ?on-stop
    #.None
    (` (~! ..default-on-stop))

    (#.Some [[causeN stateN] bodyC])
    (` (function ((~ g!_)
                  (~ (code.local-identifier causeN))
                  (~ (code.local-identifier stateN)))
         (~ bodyC)))))

(with-expansions [<examples> (as-is (actor: #export (Stack a)
                                      (List a)

                                      ((on-mail mail state self)
                                       (do (try.with promise.monad)
                                         [#let [_ (log! "BEFORE")]
                                          output (mail state self)
                                          #let [_ (log! "AFTER")]]
                                         (wrap output)))

                                      (message: #export (push {value a} state self (List a))
                                        (let [state' (#.Cons value state)]
                                          (promise.resolved (#try.Success [state' state'])))))

                                    (actor: #export Counter
                                      Nat

                                      ((on-stop cause state)
                                       (\ promise.monad wrap
                                          (log! (if (exception.match? ..poisoned cause)
                                                  (format "Counter was poisoned: " (%.nat state))
                                                  cause))))

                                      (message: #export (count! {increment Nat} state self Any)
                                        (let [state' (n.+ increment state)]
                                          (promise.resolved (#try.Success [state' state']))))

                                      (message: #export (read! state self Nat)
                                        (promise.resolved (#try.Success [state state])))))]
  (syntax: #export (actor:
                     {export csr.export}
                     {[name vars] actor-decl^}
                     {annotations (<>.default cs.empty-annotations csr.annotations)}
                     state-type
                     {[?on-mail ?on-stop messages] behavior^})
    {#.doc (doc "Defines an actor, with its behavior and internal state."
                "Messages for the actor must be defined after the on-mail and on-stop handlers."
                <examples>)}
    (with-gensyms [g!_]
      (do meta.monad
        [g!type (meta.gensym (format name "-abstract-type"))
         #let [g!actor (code.local-identifier name)
               g!vars (list\map code.local-identifier vars)]]
        (wrap (list (` ((~! abstract:) (~+ (csw.export export)) ((~ g!type) (~+ g!vars))
                        (~ state-type)

                        (def: (~+ (csw.export export)) (~ g!actor)
                          (All [(~+ g!vars)]
                            (..Behavior (~ state-type) ((~ g!type) (~+ g!vars))))
                          {#..on-init (|>> ((~! abstract.:abstraction) (~ g!type)))
                           #..on-mail (~ (..on-mail g!_ ?on-mail))
                           #..on-stop (~ (..on-stop g!_ ?on-stop))})

                        (~+ messages))))))))

  (syntax: #export (actor {[state-type init] (<c>.record (<>.and <c>.any <c>.any))}
                          {[?on-mail ?on-stop messages] behavior^})
    (with-gensyms [g!_]
      (wrap (list (` (: ((~! io.IO) (..Actor (~ state-type)))
                        (..spawn! (: (..Behavior (~ state-type) (~ state-type))
                                     {#..on-init (|>>)
                                      #..on-mail (~ (..on-mail g!_ ?on-mail))
                                      #..on-stop (~ (..on-stop g!_ ?on-stop))})
                                  (: (~ state-type)
                                     (~ init)))))))))

  (type: Signature
    {#vars (List Text)
     #name Text
     #inputs (List cs.Typed-Input)
     #state Text
     #self Text
     #output Code})

  (def: signature^
    (Parser Signature)
    (<c>.form ($_ <>.and
                  (<>.default (list) (<c>.tuple (<>.some <c>.local-identifier)))
                  <c>.local-identifier
                  (<>.some csr.typed-input)
                  <c>.local-identifier
                  <c>.local-identifier
                  <c>.any)))

  (def: reference^
    (Parser [Name (List Text)])
    (<>.either (<c>.form (<>.and <c>.identifier (<>.some <c>.local-identifier)))
               (<>.and <c>.identifier (\ <>.monad wrap (list)))))

  (syntax: #export (message:
                     {export csr.export}
                     {signature signature^}
                     {annotations (<>.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 promise 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)."

                <examples>)}
    (with-gensyms [g!_ g!return]
      (do meta.monad
        [actor-scope abstract.current
         #let [g!type (code.local-identifier (get@ #abstract.name actor-scope))
               g!message (code.local-identifier (get@ #name signature))
               g!actor-vars (get@ #abstract.type-vars actor-scope)
               g!all-vars (|> (get@ #vars signature) (list\map code.local-identifier) (list\compose g!actor-vars))
               g!inputsC (|> (get@ #inputs signature) (list\map product.left))
               g!inputsT (|> (get@ #inputs signature) (list\map product.right))
               g!state (|> signature (get@ #state) code.local-identifier)
               g!self (|> signature (get@ #self) code.local-identifier)]]
        (wrap (list (` (def: (~+ (csw.export export)) ((~ g!message) (~+ g!inputsC))
                         (~ (csw.annotations annotations))
                         (All [(~+ g!all-vars)]
                           (-> (~+ g!inputsT)
                               (..Message (~ (get@ #abstract.abstraction actor-scope))
                                          (~ (get@ #output signature)))))
                         (function ((~ g!_) (~ g!state) (~ g!self))
                           (let [(~ g!state) (:coerce (~ (get@ #abstract.representation actor-scope))
                                                      (~ g!state))]
                             (|> (~ body)
                                 (: ((~! promise.Promise) ((~! try.Try) [(~ (get@ #abstract.representation actor-scope))
                                                                         (~ (get@ #output signature))])))
                                 (:coerce ((~! promise.Promise) ((~! try.Try) [(~ (get@ #abstract.abstraction actor-scope))
                                                                               (~ (get@ #output signature))]))))))))
                    ))))))

(type: #export Stop
  (IO Any))

(def: continue! true)
(def: stop! false)

(def: #export (observe action channel actor)
  (All [e s] (-> (-> e Stop (Mail s)) (Channel e) (Actor s) (IO Any)))
  (let [signal (: (Atom Bit)
                  (atom.atom ..continue!))
        stop (: Stop
                (atom.write ..stop! signal))]
    (frp.subscribe (function (_ event)
                     (do {! io.monad}
                       [continue? (atom.read signal)]
                       (if continue?
                         (do !
                           [outcome (..mail! (action event stop) actor)]
                           (wrap (try.to-maybe outcome)))
                         (wrap #.None))))
                   channel)))