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