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