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