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