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