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