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