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