Export *current-actor*.
[8sync.git] / 8sync / actors.scm
1 ;;; 8sync --- Asynchronous programming for Guile
2 ;;; Copyright © 2016, 2017 Christopher Allan Webber <cwebber@dustycloud.org>
3 ;;;
4 ;;; This file is part of 8sync.
5 ;;;
6 ;;; 8sync is free software: you can redistribute it and/or modify it
7 ;;; under the terms of the GNU Lesser General Public License as
8 ;;; published by the Free Software Foundation, either version 3 of the
9 ;;; License, or (at your option) any later version.
10 ;;;
11 ;;; 8sync is distributed in the hope that it will be useful,
12 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ;;; GNU Lesser General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU Lesser General Public
17 ;;; License along with 8sync.  If not, see <http://www.gnu.org/licenses/>.
18
19 (define-module (8sync actors)
20   #:use-module (oop goops)
21   #:use-module (srfi srfi-9)
22   #:use-module (ice-9 control)
23   #:use-module (ice-9 format)
24   #:use-module (ice-9 match)
25   #:use-module (ice-9 atomic)
26   #:use-module ((ice-9 ports internal)
27                 #:select (port-read-wait-fd port-write-wait-fd))
28   #:use-module (ice-9 pretty-print)
29   #:use-module (ice-9 receive)
30   #:use-module (ice-9 suspendable-ports)
31   #:use-module (fibers)
32   #:use-module (fibers channels)
33   #:use-module (fibers conditions)
34   #:use-module (fibers operations)
35   #:use-module (8sync inbox)
36   #:use-module (8sync rmeta-slot)
37
38   #:export (;; utilities... ought to go in their own module
39             big-random-number
40             big-random-number-string
41
42             <actor>
43             actor-id
44             actor-message-handler
45
46             *current-actor*
47
48             ;;; Commenting out the <address> type for now;
49             ;;; it may be back when we have better serializers
50             ;; <address>
51             make-address
52             address-actor-id address-hive-id
53
54             address->string
55             actor-id-actor
56             actor-id-hive
57             actor-id-string
58
59             actor-init! actor-cleanup!
60
61             actor-alive?
62
63             build-actions
64
65             define-actor
66
67             actor-spawn-fiber
68             with-actor-nonblocking-ports
69
70             ;; <hive>
71             ;; make-hive
72             ;; ;; There are more methods for the hive, but there's
73             ;; ;; no reason for the outside world to look at them maybe?
74             ;; hive-id
75             create-actor create-actor*
76             self-destruct
77
78             <message>
79             make-message message?
80             message-to message-action message-from
81             message-id message-body message-in-reply-to
82             message-wants-reply
83
84             <- <-wait
85
86             spawn-hive run-hive
87
88             ;; Maybe the wrong place for this, or for it to be exported.
89             ;; But it's used in websockets' server implementation at least...
90             live-wrap))
91
92 ;; For ids
93 (set! *random-state* (random-state-from-platform))
94
95 ;; Same size as a uuid4 I think...
96 (define random-number-size (expt 2 128))
97
98 (define (big-random-number)
99   (random random-number-size))
100
101 ;; Would be great to get this base64 encoded instead.
102 (define (big-random-number-string)
103   ;; @@: This is slow.  Using format here is wasteful.
104   (format #f "~x" (big-random-number)))
105
106 ;; @@: This is slow-ish.  A mere ~275k / second on my (old) machine.
107 ;;   The main cost seems to be in number->string.
108 (define (simple-message-id-generator)
109   ;; Prepending this cookie makes message ids unique per hive
110   (let ((prefix (format #f "~x:" (big-random-number)))
111         (counter 0))
112     (lambda ()
113       (set! counter (1+ counter))
114       (string-append prefix (number->string counter)))))
115
116
117 \f
118 ;;; Messages
119 ;;; ========
120
121 (define-record-type <message>
122   (make-message-intern id to from action
123                        body in-reply-to wants-reply)
124   message?
125   ;; @@: message-ids are removed.  They could be re-enabled
126   ;;   if we had thread-safe promises...
127   (id message-id)                    ; id of this message
128   (to message-to)                    ; actor id this is going to
129   (from message-from)                ; actor id of sender
130   (action message-action)            ; action (a symbol) to be handled
131   (body message-body)                ; argument list "body" of message
132   (in-reply-to message-in-reply-to)  ; message id this is in reply to, if any
133   (wants-reply message-wants-reply)) ; whether caller is waiting for reply
134
135
136 (define* (make-message id to from action body
137                        #:key in-reply-to wants-reply)
138   (make-message-intern id to from action body
139                        in-reply-to wants-reply))
140
141 (define (kwarg-list-to-alist args)
142   (let loop ((remaining args)
143              (result '()))
144     (match remaining
145       (((? keyword? key) val rest ...)
146        (loop rest
147              (cons (cons (keyword->symbol key) val) 
148                    result)))
149       (() result)
150       (_ (throw 'invalid-kwarg-list
151                 "Invalid keyword argument list"
152                 args)))))
153
154
155 ;;; See: https://web.archive.org/web/20081223021934/http://mumble.net/~jar/articles/oo-moon-weinreb.html
156 ;;;   (also worth seeing: http://mumble.net/~jar/articles/oo.html )
157
158 ;; This is the internal, generalized message sending method.
159 ;; Users shouldn't use it!  Use the <-foo forms instead.
160
161 (define-inlinable (%<- wants-reply from-actor to action args message-id in-reply-to)
162   ;; Okay, we need to deal with message ids.
163   ;; Could we get rid of them? :\
164   ;; It seems if we can use eq? and have messages be immutable then
165   ;; it should be possible to identify follow-up replies.
166   ;; If we need to track replies across hive boundaries we could
167   ;; register unique ids across the ambassador barrier.
168   (match to
169     (#(_ _ (? channel? channel) dead?)
170      (let ((message (make-message message-id to
171                                   (and from-actor (actor-id from-actor))
172                                   action args
173                                   #:wants-reply wants-reply
174                                   #:in-reply-to in-reply-to)))
175        (perform-operation
176         (choice-operation
177          (put-operation channel message)
178          (wait-operation dead?)))))
179     ;; TODO: put remote addresses here.
180     (#(actor-id hive-id #f #f)
181      ;; Here we'd make a call to our hive...
182      'TODO)
183     ;; A message sent to nobody goes nowhere.
184     ;; TODO: Should we display a warning here, probably?
185     (#f #f)))
186
187 (define (<- to action . args)
188   (define from-actor (*current-actor*))
189   (%<- #f from-actor to action args
190        (or (and from-actor
191                 ((actor-msg-id-generator from-actor)))
192            (big-random-number-string))
193        #f))
194
195 ;; TODO: this should abort to the prompt, then check for errors
196 ;;   when resuming.
197
198 (define (<-wait to action . args)
199   (define prompt (*actor-prompt*))
200   (when (not prompt)
201     (error "Tried to <-wait without being in an actor's context..."))
202
203   (let ((reply (abort-to-prompt prompt '<-wait to action args)))
204     (cond ((eq? action '*error*)
205            (throw 'hive-unresumable-coroutine
206                   "Won't resume coroutine; got an *error* as a reply"
207                   #:message reply))
208           (else (apply values (message-body reply))))))
209
210 \f
211 ;;; Main actor implementation
212 ;;; =========================
213
214 (define (actor-inheritable-message-handler actor message)
215   (define action (message-action message))
216   (define method
217     (class-rmeta-ref (class-of actor) 'actions action
218                      #:equals? eq? #:cache-set! hashq-set!
219                      #:cache-ref hashq-ref))
220   (unless method
221     (throw 'action-not-found
222            "No appropriate action handler found for actor"
223            #:action action
224            #:actor actor
225            #:message message))
226   (apply method actor message (message-body message)))
227
228 (define-syntax-rule (live-wrap body)
229   "Wrap possibly multi-value function in a procedure, applies all arguments"
230   (lambda args
231     (apply body args)))
232
233 (define-syntax-rule (build-actions (symbol method) ...)
234   "Construct an alist of (symbol . method), where the method is wrapped
235 with `live-wrap' to facilitate live hacking and allow the method definition
236 to come after class definition."
237   (build-rmeta-slot
238    (list (cons (quote symbol)
239                (live-wrap method)) ...)))
240
241 (define-class <actor> ()
242   ;; An address object... a vector of #(actor-id hive-id inbox-channel dead?)
243   ;;  - inbox-channel is the receiving channel (as opposed to actor-inbox-deq)
244   ;;  - dead? is a fibers condition variable which is set once this actor
245   ;;    kicks the bucket
246   (id #:init-keyword #:address
247       #:getter actor-id)
248
249   ;; Our queue to send/receive messages on
250   (inbox-deq #:init-thunk make-channel
251              #:accessor actor-inbox-deq)
252
253   (msg-id-generator #:init-thunk simple-message-id-generator
254                     #:getter actor-msg-id-generator)
255
256   ;; How we receive and process new messages
257   (message-handler #:init-value actor-inheritable-message-handler
258                    ;; @@: There's no reason not to use #:class instead of
259                    ;;   #:each-subclass anywhere in this file, except for
260                    ;;   Guile bug #25211 (#:class is broken in Guile 2.2)
261                    #:allocation #:each-subclass
262                    #:getter actor-message-handler)
263
264   ;; valid values are:
265   ;;  - #t as in, send the init message, but don't wait (default)
266   ;;  - 'wait, as in wait on the init message
267   ;;  - #f as in don't bother to init
268   (should-init #:init-value #t
269                #:getter actor-should-init
270                #:allocation #:each-subclass)
271
272   ;; This is the default, "simple" way to inherit and process messages.
273   (actions #:init-thunk (build-actions)
274            #:allocation #:each-subclass))
275
276 ;;; Actors may specify an "init" action that occurs before the actor
277 ;;; actually begins to run.
278 ;;; During actor-init!, an actor may send a message to itself or others
279 ;;; via <- but *may not* use <-wait.
280 (define-method (actor-init! (actor <actor>))
281   'no-op)
282
283 (define-method (actor-cleanup! (actor <actor>))
284   'no-op)
285
286 ;;; Addresses are vectors where the first part is the actor-id and
287 ;;; the second part is the hive-id.  This works well enough... they
288 ;;; look decent being pretty-printed.
289
290 (define (make-address actor-id hive-id channel dead?)
291   (vector actor-id hive-id channel dead?))
292
293 (define (address-actor-id address)
294   (vector-ref address 0))
295
296 (define (address-hive-id address)
297   (vector-ref address 1))
298
299 (define (address-channel address)
300   (vector-ref address 2))
301
302 (define (address-dead? address)
303   (vector-ref address 3))
304
305 (define (address->string address)
306   (string-append (address-actor-id address) "@"
307                  (address-hive-id address)))
308
309 (define (address-equal? address1 address2)
310   "Check whether or not the two addresses are equal.
311
312 This compares the actor-id and hive-id but ignores the channel and
313 dead? condition."
314   (match address1
315     (#(actor-id-1 hive-id-1 _ _)
316      (match address2
317        (#(actor-id-2 hive-id-2)
318         (and (equal? actor-id-1 actor-id-2)
319              (and (equal? hive-id-1 hive-id-2))))
320        (_ #f)))
321     (_ #f)))
322
323 (define (actor-id-actor actor)
324   "Get the actor id component of the actor-id"
325   (address-actor-id (actor-id actor)))
326
327 (define (actor-id-hive actor)
328   "Get the hive id component of the actor-id"
329   (address-hive-id (actor-id actor)))
330
331 (define (actor-id-string actor)
332   "Render the full actor id as a human-readable string"
333   (address->string (actor-id actor)))
334
335 (define (actor-inbox-enq actor)
336   (address-channel (actor-id actor)))
337
338 (define *current-actor*
339   (make-parameter #f))
340
341 (define *actor-prompt*
342   (make-parameter #f))
343
344 (define *resume-io-channel*
345   (make-parameter #f))
346
347 (define (actor-main-loop actor)
348   "Main loop of the actor.  Loops around, pulling messages off its queue
349 and handling them."
350   ;; @@: Maybe establish some sort of garbage collection routine for these...
351   (define waiting
352     (make-hash-table))
353   (define message-handler
354     (actor-message-handler actor))
355   (define dead?
356     (address-dead? (actor-id actor)))
357   (define prompt (make-prompt-tag (actor-id-actor actor)))
358   ;; Not always used, only if with-actor-nonblocking-ports is used
359   (define resume-io-channel
360     (make-channel))
361
362   (define (handle-message message)
363     (catch #t
364       (lambda ()
365         (call-with-values
366             (lambda ()
367               (message-handler actor message))
368           (lambda vals
369             ;; Return reply if necessary
370             (when (message-wants-reply message)
371               (when (message-wants-reply message)
372                 (%<- #f actor (message-from message) '*reply*
373                      vals ((actor-msg-id-generator actor))
374                      (message-id message)))))))
375       (const #t)
376       (let ((err (current-error-port)))
377         (lambda (key . args)
378           (false-if-exception
379            (let ((stack (make-stack #t 4)))
380              (format err "Uncaught exception when handling message ~a:\n"
381                      message)
382              (display-backtrace stack err)
383              (print-exception err (stack-ref stack 0)
384                               key args)
385              (newline err)
386              ;; If the other actor is waiting on a reply, let's let them
387              ;; know there was an error...
388              (when (message-wants-reply message)
389                (%<- #f actor (message-from message) '*error*
390                     (list key) ((actor-msg-id-generator actor))
391                     (message-id message)))))))))
392   
393   (define (resume-handler message)
394     (define in-reply-to (message-in-reply-to message))
395     (cond
396      ((hash-ref waiting in-reply-to) =>
397       (lambda (kont)
398         (hash-remove! waiting in-reply-to)
399         (kont message)))
400      (else
401       (format (current-error-port)
402               "Tried to resume nonexistant message: ~a\n"
403               (message-id message)))))
404
405   (define (call-with-actor-prompt thunk)
406     (call-with-prompt prompt
407       thunk
408       ;; Here's where we abort to if we're doing <-wait
409       ;; @@: maybe use match-lambda if we're going to end up
410       ;;   handling multiple ~commands
411       (match-lambda*
412         ((kont '<-wait to action message-args)
413          (define message-id
414            ((actor-msg-id-generator actor)))
415          (hash-set! waiting message-id kont)
416          (%<- #t actor to action message-args message-id #f))
417         ((kont 'run-me proc)
418          (proc kont)))))
419
420   (define halt-or-handle-message
421     ;; It would be nice if we could give priorities to certain operations.
422     ;; halt should always win over getting a message...
423     (choice-operation
424      (wrap-operation (wait-operation dead?)
425                      (const #f))  ; halt and return
426      (wrap-operation (get-operation (actor-inbox-deq actor))
427                      (lambda (message)
428                        (call-with-actor-prompt
429                         (lambda ()
430                           (if (message-in-reply-to message)
431                               ;; resume a continuation which was waiting on a reply
432                               (resume-handler message)
433                               ;; start handling a new message
434                               (handle-message message))))
435                        #t))   ; loop again
436      (wrap-operation (get-operation resume-io-channel)
437                      (lambda (thunk)
438                        (call-with-actor-prompt
439                         (lambda ()
440                           (thunk)))
441                        #t))))
442
443   ;; Mutate the parameter; this should be fine since each fiber
444   ;; runs in its own dynamic state with with-dynamic-state.
445   ;; See with-dynamic-state discussion in
446   ;;   https://wingolog.org/archives/2017/06/27/growing-fibers
447   (*current-actor* actor)
448   (*resume-io-channel* resume-io-channel)
449
450   ;; We temporarily set the *actor-prompt* to #f to make sure that
451   ;; actor-init! doesn't try to do a <-wait message (and not accidentally use
452   ;; the parent fiber's *actor-prompt* either.)
453   (*actor-prompt* #f)
454   (actor-init! actor)
455   (*actor-prompt* prompt)
456
457   (let loop ()
458     (and (perform-operation halt-or-handle-message)
459          (loop))))
460
461
462 ;; @@: So in order for this to work, we're going to have to add
463 ;; another channel to actors, which is resumable i/o.  We'll have to
464 ;; spawn a fiber that wakes up a thunk on the actor when its port is
465 ;; available.  Funky...
466
467 (define (%suspend-io-to-actor wait-for-read/write)
468   (lambda (port)
469     (define prompt (*actor-prompt*))
470     (define resume-channel (*resume-io-channel*))
471     (define (run-at-prompt k)
472       (spawn-fiber
473        (lambda ()
474          (wait-for-read/write port)
475          ;; okay, we're awake again, tell the actor to resume this
476          ;; continuation
477          (put-message resume-channel k))
478        #:parallel? #f))
479     (when (not prompt)
480       (error "Attempt to abort to actor prompt outside of actor"))
481     (abort-to-prompt (*actor-prompt*)
482                      'run-me run-at-prompt)))
483
484 (define suspend-read-to-actor
485   (%suspend-io-to-actor (@@ (fibers) wait-for-readable)))
486
487 (define suspend-write-to-actor
488   (%suspend-io-to-actor (@@ (fibers) wait-for-writable)))
489
490 (define (with-actor-nonblocking-ports thunk)
491   "Runs THUNK in dynamic context in which attempting to read/write
492 from a port that would otherwise block an actor's correspondence with
493 other actors (note that reading from a nonblocking port should never
494 block other fibers) will instead permit reading other messages while
495 I/O is waiting to complete.
496
497 Note that currently "
498   (parameterize ((current-read-waiter suspend-read-to-actor)
499                  (current-write-waiter suspend-write-to-actor))
500     (thunk)))
501
502 (define (actor-spawn-fiber thunk . args)
503   "Spawn a fiber from an actor but unset actor-machinery-specific
504 dynamic context."
505   (apply spawn-fiber
506          (lambda ()
507            (*current-actor* #f)
508            (*resume-io-channel* #f)
509            (*actor-prompt* #f)
510            (thunk))
511          args))
512
513
514 \f
515 ;;; Actor utilities
516 ;;; ===============
517
518 (define-syntax-rule (define-actor class inherits
519                       (action ...)
520                       slots ...)
521   (define-class class inherits
522     (actions #:init-thunk (build-actions action ...)
523              #:allocation #:each-subclass)
524     slots ...))
525
526 \f
527 ;;; The Hive
528 ;;; ========
529 ;;;   Every actor has a hive, which keeps track of other actors, manages
530 ;;;   cleanup, and performs inter-hive communication.
531
532 ;; TODO: Make this a srfi-9 record type
533 (define-class <hive> ()
534   (id #:init-keyword #:id
535       #:getter hive-id)
536   (actor-registry #:init-thunk make-hash-table
537                   #:getter hive-actor-registry)
538   ;; TODO: Rename "ambassadors" to "relays"
539   ;; Ambassadors are used (or will be) for inter-hive communication.
540   ;; These are special actors that know how to route messages to other
541   ;; hives.
542   (ambassadors #:init-thunk make-weak-key-hash-table
543                #:getter hive-ambassadors)
544   (channel #:init-thunk make-channel
545            #:getter hive-channel)
546   (halt? #:init-thunk make-condition
547          #:getter hive-halt?))
548
549 (define* (make-hive #:key hive-id)
550   (make <hive> #:id (or hive-id
551                         (big-random-number-string))))
552
553 (define (gen-actor-id cookie)
554   (if cookie
555       (string-append cookie ":" (big-random-number-string))
556       (big-random-number-string)))
557
558 (define (hive-main-loop hive)
559   "The main loop of the hive.  This listens for messages on the hive-channel
560 for certain actions to perform.
561
562 `messages' here is not the same as a <message> object; these are a list of
563 values, the first value being a symbol"
564   (define channel (hive-channel hive))
565   (define halt? (hive-halt? hive))
566   (define registry (hive-actor-registry hive))
567
568   ;; not the same as a <message> ;P
569   (define handle-message
570     (match-lambda
571       (('register-actor actor-id address actor)
572        (hash-set! registry actor-id (vector address actor)))
573       ;; Remove the actor from hive
574       (('remove-actor actor-id)
575        (hash-remove! (hive-actor-registry hive) actor-id))
576       (('register-ambassador hive-id ambassador-actor-id)
577        'TODO)
578       (('unregister-ambassador hive-id ambassador-actor-id)
579        'TODO)
580       (('forward-message from-actor-id message)
581        'TODO)))
582
583   (define halt-or-handle
584     (choice-operation
585      (wrap-operation (get-operation channel)
586                      (lambda (msg)
587                        (handle-message msg)
588                        #t))
589      (wrap-operation (wait-operation halt?)
590                      (const #f))))
591
592   (let lp ()
593     (and (perform-operation halt-or-handle)
594          (lp))))
595
596 (define *hive-id* (make-parameter #f))
597 (define *hive-channel* (make-parameter #f))
598
599 ;; @@: Should we halt the hive either at the end of spawn-hive or run-hive?
600 (define* (spawn-hive proc #:key (hive (make-hive)))
601   "Spawn a hive and run PROC, passing it the fresh hive and establishing
602 a dynamic context surrounding the hive."
603   (spawn-fiber (lambda () (hive-main-loop hive)))
604   (parameterize ((*hive-id* (hive-id hive))
605                  (*hive-channel* (hive-channel hive)))
606     (proc hive)))
607
608 (define (run-hive proc . args)
609   "Spawn a hive and run it in run-fibers.  Takes a PROC as would be passed
610 to spawn-hive... all remaining arguments passed to run-fibers."
611   (apply run-fibers
612          (lambda ()
613            (spawn-hive proc))
614          args))
615
616 (define (%create-actor actor-class init-args id-cookie send-init?)
617   (let* ((hive-channel (*hive-channel*))
618          (hive-id (*hive-id*))
619          (actor-id (gen-actor-id id-cookie))
620          (dead? (make-condition))
621          (inbox-enq (make-channel))
622          (address (make-address actor-id hive-id
623                                 inbox-enq dead?))
624          (actor (apply make actor-class
625                        #:address address
626                        init-args))
627          (should-init (actor-should-init actor)))
628
629     ;; start the main loop
630     (spawn-fiber (lambda ()
631                    ;; start the inbox loop
632                    (spawn-fiber
633                     (lambda ()
634                       (delivery-agent inbox-enq (actor-inbox-deq actor)
635                                       dead?))
636                     ;; this one is decidedly non-parallel, because we want
637                     ;; the delivery agent to be in the same thread as its actor
638                     #:parallel? #f)
639
640                    (actor-main-loop actor))
641                  #:parallel? #t)
642
643     (put-message hive-channel (list 'register-actor actor-id address actor))
644     
645     ;; return the address
646     address))
647
648 (define* (create-actor actor-class #:rest init-args)
649   "Create an instance of actor-class.  Return the new actor's id.
650
651 This is the method actors should call directly (unless they want
652 to supply an id-cookie, in which case they should use
653 create-actor*)."
654   (%create-actor actor-class init-args #f #t))
655
656
657 (define* (create-actor* actor-class id-cookie #:rest init-args)
658   "Create an instance of actor-class.  Return the new actor's id.
659
660 Like create-actor, but permits supplying an id-cookie."
661   (%create-actor actor-class init-args id-cookie #t))
662
663 (define* (self-destruct actor #:key (cleanup #t))
664   "Remove an actor from the hive.
665
666 Unless #:cleanup is set to #f, this will first have the actor handle
667 its '*cleanup* action handler."
668   (signal-condition! (address-dead? (actor-id actor)))
669   (put-message (*hive-channel*) (list 'remove-actor (actor-id-actor actor)))
670   ;; Set *actor-prompt* to nothing to prevent actor-cleanup! from sending
671   ;; a message with <-wait
672   (*actor-prompt* #f)
673   (actor-cleanup! actor))
674
675 ;; From a patch I sent to Fibers...
676 (define (condition-signalled? cvar)
677   "Return @code{#t} if @var{cvar} has already been signalled.
678
679 In general you will want to use @code{wait} or @code{wait-operation} to
680 wait on a condition.  However, sometimes it is useful to see whether or
681 not a condition has already been signalled without blocking."
682   (atomic-box-ref ((@@ (fibers conditions) condition-signalled?) cvar)))
683
684 (define (actor-alive? actor)
685   (condition-signalled? (address-dead? (actor-id actor))))