actors: Use rmeta-slot for actions dispatch.
[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 pretty-print)
27   #:use-module (8sync agenda)
28   #:use-module (8sync rmeta-slot)
29   #:export (;; utilities... ought to go in their own module
30             big-random-number
31             big-random-number-string
32             simple-message-id-generator
33
34             <actor>
35             actor-id
36             actor-message-handler
37
38             %current-actor
39
40             ;;; Commenting out the <address> type for now;
41             ;;; it may be back when we have better serializers
42             ;; <address>
43             make-address address?
44             address-actor-id address-hive-id
45
46             address->string
47             actor-id-actor
48             actor-id-hive
49             actor-id-string
50
51             actor-alive?
52
53             build-actions
54
55             define-actor
56
57             <hive>
58             make-hive
59             ;; There are more methods for the hive, but there's
60             ;; no reason for the outside world to look at them maybe?
61             hive-id
62             bootstrap-actor bootstrap-actor*
63
64             create-actor create-actor*
65             self-destruct
66
67             <message>
68             make-message message?
69             message-to message-action message-from
70             message-id message-body message-in-reply-to
71             message-wants-reply
72
73             message-auto-reply?
74
75             <- <-* <-wait <-wait* <-reply <-reply* <-reply-wait <-reply-wait*
76
77             call-with-message mbody-receive mbody-val
78
79             run-hive
80             bootstrap-message
81
82             serialize-message write-message
83             serialize-message-pretty pprint-message
84             read-message read-message-from-string))
85
86 ;; For ids
87 (define %random-state
88   (make-parameter (random-state-from-platform)))
89
90 ;; Same size as a uuid4 I think...
91 (define random-number-size (expt 2 128))
92
93 (define (big-random-number)
94   (random random-number-size (%random-state)))
95
96 ;; Would be great to get this base64 encoded instead.
97 (define (big-random-number-string)
98   ;; @@: This is slow.  Using format here is wasteful.
99   (format #f "~x" (big-random-number)))
100
101 ;; @@: This is slow.  A mere ~275k / second on my (old) machine.
102 ;;   The main cost seems to be in number->string.
103 (define (simple-message-id-generator)
104   ;; Prepending this cookie makes message ids unique per hive
105   (let ((prefix (format #f "~x:" (big-random-number)))
106         (counter 0))
107     (lambda ()
108       (set! counter (1+ counter))
109       (string-append prefix (number->string counter)))))
110
111
112 \f
113 ;;; Messages
114 ;;; ========
115
116
117 ;; @@: We may want to add a deferred-reply to the below, similar to
118 ;;   what we had in XUDD, for actors which do their own response
119 ;;   queueing.... ie, that might receive messages but need to shelve
120 ;;   them to be acted upon after something else is taken care of.
121
122 (define-record-type <message>
123   (make-message-intern id to from action
124                        body in-reply-to wants-reply
125                        replied)
126   message?
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   (replied message-replied           ; was this message replied to?
135            set-message-replied!))
136
137
138 (define* (make-message id to from action body
139                        #:key in-reply-to wants-reply
140                        replied)
141   (make-message-intern id to from action body
142                        in-reply-to wants-reply replied))
143
144 (define (message-auto-reply? message)
145   (eq? (message-action message) '*auto-reply*))
146
147 (define (message-needs-reply? message)
148   "See if this message needs a reply still"
149   (and (message-wants-reply message)
150        (not (message-replied message))))
151
152
153 (define (kwarg-list-to-alist args)
154   (let loop ((remaining args)
155              (result '()))
156     (match remaining
157       (((? keyword? key) val rest ...)
158        (loop rest
159              (cons (cons (keyword->symbol key) val) 
160                    result)))
161       (() result)
162       (_ (throw 'invalid-kwarg-list
163                 "Invalid keyword argument list"
164                 args)))))
165
166
167 ;;; See: https://web.archive.org/web/20081223021934/http://mumble.net/~jar/articles/oo-moon-weinreb.html
168 ;;;   (also worth seeing: http://mumble.net/~jar/articles/oo.html )
169
170 ;; This is the internal, generalized message sending method.
171 ;; Users shouldn't use it!  Use the <-foo forms instead.
172
173 ;; @@: Could we get rid of some of the conditional checks through
174 ;;   some macro-foo?
175
176 (define-inlinable (send-message send-options from-actor to-id action
177                                 replying-to-message wants-reply?
178                                 message-body-args)
179   (if replying-to-message
180       (set-message-replied! replying-to-message #t))
181   (let* ((hive (actor-hive from-actor))
182          (new-message
183           (make-message (hive-gen-message-id hive) to-id
184                         (actor-id from-actor) action
185                         message-body-args
186                         #:wants-reply wants-reply?
187                         #:in-reply-to
188                         (if replying-to-message
189                             (message-id replying-to-message)
190                             #f))))
191     (if wants-reply?
192         (abort-to-prompt (hive-prompt (actor-hive from-actor))
193                          from-actor new-message send-options)
194         ;; @@: It might be that eventually we pass in send-options
195         ;;   here too.  Since <-wait and <-reply-wait are the only ones
196         ;;   that use it yet, for now it kind of just makes things
197         ;;   confusing.
198         (8sync (hive-process-message hive new-message)))))
199
200 (define (<- to-id action . message-body-args)
201   "Send a message from an actor to another actor"
202   (send-message '() (%current-actor) to-id action
203                 #f #f message-body-args))
204
205 (define (<-* send-options to-id action . message-body-args)
206   "Like <-*, but allows extra parameters via send-options"
207   (define* (really-send #:key (actor (%current-actor))
208                         #:allow-other-keys)
209     (send-message send-options actor to-id action
210                   #f #f message-body-args))
211   (apply really-send send-options))
212
213 (define (<-wait to-id action . message-body-args)
214   "Send a message from an actor to another, but wait until we get a response"
215   (wait-maybe-handle-errors
216    (send-message '() (%current-actor) to-id action
217                  #f #t message-body-args)))
218
219 (define (<-wait* send-options to-id action . message-body-args)
220   "Like <-wait, but allows extra parameters, for example whether to
221 #:accept-errors"
222   (define* (really-send #:key (actor (%current-actor))
223                         #:allow-other-keys)
224     (apply wait-maybe-handle-errors
225            (send-message send-options actor to-id action
226                          #f #t message-body-args)
227            send-options))
228   (apply really-send send-options))
229
230 ;; TODO: Intelligently ~propagate(ish) errors on -wait functions.
231 ;;   We might have `send-message-wait-brazen' to allow callers to
232 ;;   not have an exception thrown and instead just have a message with
233 ;;   the appropriate '*error* message returned.
234
235 (define (<-reply original-message . message-body-args)
236   "Reply to a message"
237   (when (message-needs-reply? original-message)
238     (send-message '() (%current-actor) (message-from original-message) '*reply*
239                   original-message #f message-body-args)))
240
241 (define (<-reply* send-options original-message . message-body-args)
242   "Like <-reply, but allows extra parameters via send-options"
243   (define* (really-send #:key (actor (%current-actor))
244                         #:allow-other-keys)
245     (send-message send-options actor
246                   (message-from original-message) '*reply*
247                   original-message #f message-body-args))
248   (when (message-needs-reply? original-message)
249     (apply really-send send-options)))
250
251 (define (<-auto-reply actor original-message)
252   "Auto-reply to a message.  Internal use only!"
253   (send-message '() actor (message-from original-message) '*auto-reply*
254                 original-message #f '()))
255
256 (define (<-reply-wait original-message . message-body-args)
257   "Reply to a messsage, but wait until we get a response"
258   (if (message-needs-reply? original-message)
259       (wait-maybe-handle-errors
260        (send-message '() (%current-actor)
261                      (message-from original-message) '*reply*
262                      original-message #t message-body-args))
263       #f))
264
265 (define (<-reply-wait* send-options original-message
266                        . message-body-args)
267   "Like <-reply-wait, but allows extra parameters via send-options"
268   (define* (really-send #:key (actor (%current-actor))
269                         #:allow-other-keys)
270     (apply wait-maybe-handle-errors
271            (send-message send-options actor
272                          (message-from original-message) '*reply*
273                          original-message #t message-body-args)
274            send-options))
275   (when (message-needs-reply? original-message)
276     (apply really-send send-options)))
277
278 (define* (wait-maybe-handle-errors message
279                                    #:key accept-errors
280                                    #:allow-other-keys)
281   "Before returning a message to a waiting caller, see if we need to
282 raise an exception if an error."
283   (define action (message-action message))
284   (cond ((and (eq? action '*error*)
285               (not accept-errors))
286          (throw 'hive-unresumable-coroutine
287                 "Won't resume coroutine; got an *error* as a reply"
288                 #:message message))
289         (else message)))
290
291
292 \f
293 ;;; Main actor implementation
294 ;;; =========================
295
296 (define (actor-inheritable-message-handler actor message)
297   (define action (message-action message))
298   (define method
299     (class-rmeta-ref (class-of actor) 'actions action
300                      #:equals? eq? #:cache-set! hashq-set!
301                      #:cache-ref hashq-ref))
302   (unless method
303     (throw 'action-not-found
304            "No appropriate action handler found for actor"
305            #:action action
306            #:actor actor
307            #:message message))
308   (apply method actor message (message-body message)))
309
310 (define-syntax-rule (build-actions (symbol method) ...)
311   "Construct an alist of (symbol . method), where the method is wrapped
312 with wrap-apply to facilitate live hacking and allow the method definition
313 to come after class definition."
314   (make-rmeta-slot
315    (list (cons (quote symbol)
316                (wrap-apply method)) ...)))
317
318 (define-class <actor> ()
319   ;; An address object
320   (id #:init-keyword #:id
321       #:getter actor-id)
322   ;; The hive we're connected to.
323   ;; We need this to be able to send messages.
324   (hive #:init-keyword #:hive
325         #:accessor actor-hive)
326   ;; How we receive and process new messages
327   (message-handler #:init-value actor-inheritable-message-handler
328                    ;; @@: There's no reason not to use #:class instead of
329                    ;;   #:each-subclass anywhere in this file, except for
330                    ;;   Guile bug #25211 (#:class is broken in Guile 2.2)
331                    #:allocation #:each-subclass
332                    #:getter actor-message-handler)
333
334   ;; valid values are:
335   ;;  - #t as in, send the init message, but don't wait (default)
336   ;;  - 'wait, as in wait on the init message
337   ;;  - #f as in don't bother to init
338   (should-init #:init-value #t
339                #:allocation #:each-subclass)
340
341   ;; This is the default, "simple" way to inherit and process messages.
342   (actions #:init-value (build-actions
343                          ;; Default init method is to do nothing.
344                          (*init* (const #f))
345                          ;; Default cleanup method is to do nothing.
346                          (*cleanup* (const #f)))
347            #:allocation #:each-subclass))
348
349 ;;; Addresses are vectors where the first part is the actor-id and
350 ;;; the second part is the hive-id.  This works well enough... they
351 ;;; look decent being pretty-printed.
352
353 (define (make-address actor-id hive-id)
354   (vector actor-id hive-id))
355
356 (define (address-actor-id address)
357   (vector-ref address 0))
358
359 (define (address-hive-id address)
360   (vector-ref address 1))
361
362 (define (address->string address)
363   (string-append (address-actor-id address) "@"
364                  (address-hive-id address)))
365
366 (define-method (actor-id-actor (actor <actor>))
367   "Get the actor id component of the actor-id"
368   (address-actor-id (actor-id actor)))
369
370 (define-method (actor-id-hive (actor <actor>))
371   "Get the hive id component of the actor-id"
372   (address-hive-id (actor-id actor)))
373
374 (define-method (actor-id-string (actor <actor>))
375   "Render the full actor id as a human-readable string"
376   (address->string (actor-id actor)))
377
378 (define %current-actor
379   (make-parameter #f))
380
381 (define (actor-alive? actor)
382   (hive-resolve-local-actor (actor-hive actor) (actor-id actor)))
383
384
385 \f
386 ;;; Actor utilities
387 ;;; ===============
388
389 (define-syntax-rule (define-actor class inherits
390                       (action ...)
391                       slots ...)
392   (define-class class inherits
393     (actions #:init-value (build-actions action ...)
394              #:allocation #:each-subclass)
395     slots ...))
396
397 \f
398 ;;; The Hive
399 ;;; ========
400 ;;;   Every actor has a hive.  The hive is a kind of "meta-actor"
401 ;;;   which routes all the rest of the actors in a system.
402
403 (define-generic hive-handle-failed-forward)
404
405 (define-class <hive> (<actor>)
406   (actor-registry #:init-thunk make-hash-table
407                   #:getter hive-actor-registry)
408   (msg-id-generator #:init-thunk simple-message-id-generator
409                     #:getter hive-msg-id-generator)
410   ;; Ambassadors are used (or will be) for inter-hive communication.
411   ;; These are special actors that know how to route messages to other hives.
412   (ambassadors #:init-thunk make-weak-key-hash-table
413                #:getter hive-ambassadors)
414   ;; Waiting coroutines
415   ;; This is a map from cons cell of message-id
416   ;;   to a cons cell of (actor-id . coroutine)
417   ;; @@: Should we have a <waiting-coroutine> record type?
418   ;; @@: Should there be any way to clear out "old" coroutines?
419   (waiting-coroutines #:init-thunk make-hash-table
420                       #:getter hive-waiting-coroutines)
421   ;; Message prompt
422   ;; When actors send messages to each other they abort to this prompt
423   ;; to send the message, then carry on their way
424   (prompt #:init-thunk make-prompt-tag
425           #:getter hive-prompt)
426   (actions #:allocation #:each-subclass
427            #:init-value
428            (build-actions
429             ;; This is in the case of an ambassador failing to forward a
430             ;; message... it reports it back to the hive
431             (*failed-forward* hive-handle-failed-forward)
432             ;; These are called at start and end of run-hive
433             (*init-all* hive-handle-init-all)
434             (*cleanup-all* hive-handle-cleanup-all))))
435
436 (define-method (hive-handle-init-all (hive <hive>) message)
437   "Run *init* method on all actors in registry"
438   ;; We have to do this hack and run over the list
439   ;; twice, because hash-for-each would result in an unrewindable
440   ;; continuation, and to avoid the hash-map changing during the
441   ;; middle of this.
442   (define actor-ids
443     (hash-map->list (lambda (actor-id actor) actor-id)
444                     (hive-actor-registry hive)))
445   (for-each (lambda (actor-id)
446               (let* ((actor (hash-ref (hive-actor-registry hive)
447                                       actor-id)))
448                 (match (slot-ref actor 'should-init)
449                   (#f #f)
450                   ('wait
451                    (<-wait actor-id '*init*))
452                   (_
453                    (<- actor-id '*init*)))))
454             actor-ids))
455
456 (define-method (hive-handle-failed-forward (hive <hive>) message)
457   "Handle an ambassador failing to forward a message"
458   'TODO)
459
460 (define-method (hive-handle-cleanup-all (hive <hive>) message)
461   "Send a message to all actors in our registry to clean themselves up."
462   ;; We have to do this hack and run over the list
463   ;; twice, because hash-for-each would result in an unrewindable
464   ;; continuation, and to avoid the hash-map changing during the
465   ;; middle of this.
466   (define actor-ids
467     (hash-map->list (lambda (actor-id actor) actor-id)
468                     (hive-actor-registry hive)))
469   (for-each (lambda (actor-id)
470               (<- actor-id '*cleanup*))
471             actor-ids))
472
473 (define* (make-hive #:key hive-id)
474   (let ((hive (make <hive>
475                 #:id (make-address
476                       "hive" (or hive-id
477                                  (big-random-number-string))))))
478     ;; Set the hive's actor reference to itself
479     (set! (actor-hive hive) hive)
480     ;; Register the actor with itself
481     (hive-register-actor! hive hive)
482     hive))
483
484 (define-method (hive-id (hive <hive>))
485   (actor-id-hive hive))
486
487 (define-method (hive-gen-actor-id (hive <hive>) cookie)
488   (make-address (if cookie
489                     (string-append cookie ":" (big-random-number-string))
490                     (big-random-number-string))
491                 (hive-id hive)))
492
493 (define-method (hive-gen-message-id (hive <hive>))
494   "Generate a message id using HIVE's message id generator"
495   ((hive-msg-id-generator hive)))
496
497 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
498   (hash-ref (hive-actor-registry hive) actor-address))
499
500 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
501   (hash-ref (hive-ambassadors hive) ambassador-address))
502
503 (define-method (make-forward-request (hive <hive>) (ambassador <actor>) message)
504   (make-message (hive-gen-message-id hive) (actor-id ambassador)
505                 ;; If we make the hive not an actor, we could either switch this
506                 ;; to #f or to the original actor...?
507                 ;; Maybe some more thinking should be done on what should
508                 ;; happen in case of failure to forward?  Handling ambassador failures
509                 ;; seems like the primary motivation for the hive remaining an actor.
510                 (actor-id hive)
511                 '*forward*
512                 `((original . ,message))))
513
514 (define-method (hive-reply-with-error (hive <hive>) original-message
515                                       error-key error-args)
516   ;; We only supply the error-args if the original sender is on the same hive
517   (define (orig-actor-on-same-hive?)
518     (equal? (hive-id hive)
519             (address-hive-id (message-from original-message))))
520   (set-message-replied! original-message #t)
521   (let* ((new-message-body
522           (if (orig-actor-on-same-hive?)
523               `(#:original-message ,original-message
524                 #:error-key ,error-key
525                 #:error-args ,error-args)
526               `(#:original-message ,original-message
527                 #:error-key ,error-key)))
528          (new-message (make-message (hive-gen-message-id hive)
529                                     (message-from original-message)
530                                     (actor-id hive) '*error*
531                                     new-message-body
532                                     #:in-reply-to (message-id original-message))))
533     ;; We only return a thunk, rather than run 8sync here, because if
534     ;; we ran 8sync in the middle of a catch we'd end up with an
535     ;; unresumable continuation.
536     (lambda () (hive-process-message hive new-message))))
537
538 (define-record-type <waiting-on-reply>
539   (make-waiting-on-reply actor-id kont send-options)
540   waiting-on-reply?
541   (actor-id waiting-on-reply-actor-id)
542   (kont waiting-on-reply-kont)
543   (send-options waiting-on-reply-send-options))
544
545
546 (define-method (hive-process-message (hive <hive>) message)
547   "Handle one message, or forward it via an ambassador"
548   (define (maybe-autoreply actor)
549     ;; Possibly autoreply
550     (if (message-needs-reply? message)
551         (<-auto-reply actor message)))
552
553   (define (resolve-actor-to)
554     "Get the actor the message was aimed at"
555     (let ((actor (hive-resolve-local-actor hive (message-to message))))
556       (if (not actor)
557           (throw 'actor-not-found
558                  (format #f "Message ~a from ~a directed to nonexistant actor ~a"
559                          (message-id message)
560                          (address->string (message-from message))
561                          (address->string (message-to message)))
562                  message))
563       actor))
564
565   (define (call-catching-coroutine thunk)
566     (define queued-error-handling-thunk #f)
567     (define (call-catching-errors)
568       ;; TODO: maybe parameterize (or attach to hive) and use
569       ;;   maybe-catch-all from agenda.scm
570       ;; @@: Why not just use with-throw-handler and let the catch
571       ;;   happen at the agenda?  That's what we used to do, but
572       ;;   it ended up with a SIGABRT.  See:
573       ;;     http://lists.gnu.org/archive/html/bug-guile/2016-05/msg00003.html
574       (catch #t
575         thunk
576         ;; In the actor model, we don't totally crash on errors.
577         (lambda _ #f)
578         ;; If an error happens, we raise it
579         (lambda (key . args)
580           (if (message-needs-reply? message)
581               ;; If the message is waiting on a reply, let them know
582               ;; something went wrong.
583               ;; However, we have to do it outside of this catch
584               ;; routine, or we'll end up in an unrewindable continuation
585               ;; situation.
586               (set! queued-error-handling-thunk
587                     (hive-reply-with-error hive message key args)))
588           ;; print error message
589           (apply print-error-and-continue key args)))
590       ;; @@: This is a kludge.  See above for why.
591       (if queued-error-handling-thunk
592           (8sync (queued-error-handling-thunk))))
593     (call-with-prompt (hive-prompt hive)
594       call-catching-errors
595       (lambda (kont actor message send-options)
596         ;; Register the coroutine
597         (hash-set! (hive-waiting-coroutines hive)
598                    (message-id message)
599                    (make-waiting-on-reply
600                     (actor-id actor) kont send-options))
601         ;; Send off the message
602         (8sync (hive-process-message hive message)))))
603
604   (define (process-local-message)
605     (let ((actor (resolve-actor-to)))
606       (call-catching-coroutine
607        (lambda ()
608          (define message-handler (actor-message-handler actor))
609          ;; @@: Should a more general error handling happen here?
610          (parameterize ((%current-actor actor))
611            (let ((result
612                   (message-handler actor message)))
613              (maybe-autoreply actor)
614              ;; Returning result allows actors to possibly make a run-request
615              ;; at the end of handling a message.
616              ;; ... We do want that, right?
617              result))))))
618
619   (define (resume-waiting-coroutine)
620     (case (message-action message)
621       ;; standard reply / auto-reply
622       ((*reply* *auto-reply* *error*)
623        (call-catching-coroutine
624         (lambda ()
625           (match (hash-remove! (hive-waiting-coroutines hive)
626                                (message-in-reply-to message))
627             ((_ . waiting)
628              (if (not (equal? (message-to message)
629                               (waiting-on-reply-actor-id waiting)))
630                  (throw 'resuming-to-wrong-actor
631                         "Attempted to resume a coroutine to the wrong actor!"
632                         #:expected-actor-id (message-to message)
633                         #:got-actor-id (waiting-on-reply-actor-id waiting)
634                         #:message message))
635              (let* (;; @@: How should we resolve resuming coroutines to actors who are
636                     ;;   now gone?
637                     (actor (resolve-actor-to))
638                     (kont (waiting-on-reply-kont waiting))
639                     (result (kont message)))
640                (maybe-autoreply actor)
641                result))
642             (#f (throw 'no-waiting-coroutine
643                        "message in-reply-to tries to resume nonexistent coroutine"
644                        message))))))
645       ;; Unhandled action for a reply!
646       (else
647        (throw 'hive-unresumable-coroutine
648               "Won't resume coroutine, nonsense action on reply message"
649               #:action (message-action message)
650               #:message message))))
651
652   (define (process-remote-message)
653     ;; Find the ambassador
654     (let* ((remote-hive-id (hive-id (message-to message)))
655            (ambassador (hive-resolve-ambassador remote-hive-id))
656            (message-handler (actor-message-handler ambassador))
657            (forward-request (make-forward-request hive ambassador message)))
658       (message-handler ambassador forward-request)))
659
660   (let ((to (message-to message)))
661     ;; This seems to be an easy mistake to make, so check that addressing
662     ;; is correct here
663     (if (not to)
664         (throw 'missing-addressee
665                "`to' field is missing on message"
666                #:message message))
667     (if (hive-actor-local? hive to)
668         (if (message-in-reply-to message)
669             (resume-waiting-coroutine)
670             (process-local-message))
671         (process-remote-message))))
672
673 (define-method (hive-actor-local? (hive <hive>) address)
674   (equal? (hive-id hive) (address-hive-id address)))
675
676 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
677   (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
678
679 (define-method (%hive-create-actor (hive <hive>) actor-class
680                                    init-args id-cookie send-init?)
681   "Actual method called by bootstrap-actor / create-actor.
682
683 Since this is a define-method it can't accept fancy define* arguments,
684 so this gets called from the nicer bootstrap-actor interface.  See
685 that method for documentation."
686   (let* ((actor-id (hive-gen-actor-id hive id-cookie))
687          (actor (apply make actor-class
688                        #:hive hive
689                        #:id actor-id
690                        init-args))
691          (actor-should-init (slot-ref actor 'should-init)))
692     (hive-register-actor! hive actor)
693     ;; Maybe run actor init method
694     (when (and send-init? actor-should-init)
695       (let ((send-method
696              (if (eq? actor-should-init 'wait)
697                  <-wait <-)))
698         (send-method actor-id '*init*)))
699     ;; return the actor id
700     actor-id))
701
702 (define* (bootstrap-actor hive actor-class #:rest init-args)
703   "Create an actor on HIVE using ACTOR-CLASS passing in INIT-ARGS args"
704   (%hive-create-actor hive actor-class
705                     init-args (symbol->string (class-name actor-class))
706                     #f))
707
708 (define* (bootstrap-actor* hive actor-class id-cookie #:rest init-args)
709   "Create an actor, but also allow customizing a 'cookie' added to the id
710 for debugging"
711   (%hive-create-actor hive actor-class
712                     init-args id-cookie
713                     #f))
714
715 (define (call-with-message message proc)
716   "Applies message body arguments into procedure, with message as first
717 argument.  Similar to call-with-values in concept."
718   (apply proc message (message-body message)))
719
720 ;; (mbody-receive (<- bar baz)
721 ;;     (baz)
722 ;;   basil)
723
724 ;; Emacs: (put 'mbody-receive 'scheme-indent-function 2)
725
726 ;; @@: Or receive-msg or receieve-message or??
727 (define-syntax-rule (mbody-receive arglist message body ...)
728   "Call body with arglist (which can accept arguments like lambda*)
729 applied from the message-body of message."
730   (call-with-message message
731                      (lambda* arglist
732                        body ...)))
733
734 (define (mbody-val message)
735   "Retrieve the first value from the message-body of message.
736 Like single value return from a procedure call.  Probably the most
737 common case when waiting on a reply from some action invocation."
738   (call-with-message message
739                      (lambda (_ val) val)))
740
741 \f
742 ;;; Various API methods for actors to interact with the system
743 ;;; ==========================================================
744
745 ;; TODO: move send-message and friends here...?
746
747 (define* (create-actor from-actor actor-class #:rest init-args)
748   "Create an instance of actor-class.  Return the new actor's id.
749
750 This is the method actors should call directly (unless they want
751 to supply an id-cookie, in which case they should use
752 create-actor*)."
753   (%hive-create-actor (actor-hive from-actor) actor-class
754                       init-args #f #t))
755
756
757 (define* (create-actor* from-actor actor-class id-cookie #:rest init-args)
758   "Create an instance of actor-class.  Return the new actor's id.
759
760 Like create-actor, but permits supplying an id-cookie."
761   (%hive-create-actor (actor-hive from-actor) actor-class
762                       init-args id-cookie #t))
763
764
765 (define* (self-destruct actor #:key (cleanup #t))
766   "Remove an actor from the hive.
767
768 Unless #:cleanup is set to #f, this will first have the actor handle
769 its '*cleanup* action handler."
770   (when cleanup
771     (<-wait (actor-id actor) '*cleanup*))
772   (hash-remove! (hive-actor-registry (actor-hive actor))
773                 (actor-id actor)))
774
775
776 \f
777 ;;; 8sync bootstrap utilities
778 ;;; =========================
779
780 (define* (run-hive hive initial-tasks
781                    #:key (cleanup #t)
782                    (handle-signals (list SIGINT SIGTERM)))
783   "Start up an agenda and run HIVE in it with INITIAL-TASKS.
784
785 Keyword arguments:
786  - #:cleanup: Whether to run *cleanup* on all actors.
787  - #:handle-sigactions: a list of signals to set up interrupt
788    handlers for, so cleanup sill still happen as expected.
789    Defaults to a list of SIGINT and SIGTERM."
790   (dynamic-wind
791     (const #f)
792     (lambda ()
793       (define (run-it escape)
794         (define (handle-signal signum)
795           (restore-signals)
796           (escape signum))
797         (for-each (lambda (signum)
798                     (sigaction signum handle-signal))
799                   handle-signals)
800         (let* ((queue (list->q
801                        (cons (bootstrap-message hive (actor-id hive) '*init-all*)
802                              initial-tasks)))
803                (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
804                                     #:queue queue)))
805           (run-agenda agenda)))
806       (call/ec run-it))
807     ;; Run cleanup
808     (lambda ()
809       (when cleanup
810         (run-hive-cleanup hive)))))
811
812 (define (run-hive-cleanup hive)
813   (let ((queue (list->q (list (bootstrap-message hive (actor-id hive)
814                                                  '*cleanup-all*)))))
815     (run-agenda
816      (make-agenda #:queue queue))))
817
818 (define (bootstrap-message hive to-id action . message-body-args)
819   (wrap
820    (apply <-* `(#:actor ,hive) to-id action message-body-args)))
821
822
823 \f
824 ;;; Basic readers / writers
825 ;;; =======================
826
827 (define (serialize-message message)
828   "Serialize a message for read/write"
829   (list
830    (message-id message)
831    (message-to message)
832    (message-from message)
833    (message-action message)
834    (message-body message)
835    (message-in-reply-to message)
836    (message-wants-reply message)
837    (message-replied message)))
838
839 (define* (write-message message #:optional (port (current-output-port)))
840   "Write out a message to a port for easy reading later.
841
842 Note that if a sub-value can't be easily written to something
843 Guile's `read' procedure knows how to read, this doesn't do anything
844 to improve that.  You'll need a better serializer for that.."
845   (write (serialize-message message) port))
846
847 (define (serialize-message-pretty message)
848   "Serialize a message in a way that's easy for humans to read."
849   `(*message*
850     (id ,(message-id message))
851     (to ,(message-to message))
852     (from ,(message-from message))
853     (action ,(message-action message))
854     (body ,(message-body message))
855     (in-reply-to ,(message-in-reply-to message))
856     (wants-reply ,(message-wants-reply message))
857     (replied ,(message-replied message))))
858
859 (define (pprint-message message)
860   "Pretty print a message."
861   (pretty-print (serialize-message-pretty message)))
862
863 (define* (read-message #:optional (port (current-input-port)))
864   "Read a message serialized via serialize-message from PORT"
865   (match (read port)
866     ((id to from action body in-reply-to wants-reply replied)
867      (make-message-intern
868       id to from action body
869       in-reply-to wants-reply replied))
870     (anything-else
871      (throw 'message-read-bad-structure
872             "Could not read message from structure"
873             anything-else))))
874
875 (define (read-message-from-string message-str)
876   "Read message from MESSAGE-STR"
877   (with-input-from-string message-str
878     (lambda ()
879       (read-message (current-input-port)))))