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