2ce7e142b16a0cedf8706f21c1ad390d00ed24c6
[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     (case (message-action message)
516       ;; standard reply / auto-reply
517       ((*reply* *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, an error!
540       ((*error*)
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 #:message message)))
553       ;; Unhandled action for a reply!
554       (else
555        (throw 'hive-unresumable-coroutine
556               "Won't resume coroutine, nonsense action on reply message"
557               #:action (message-action message)
558               #:message message))))
559
560   (define (process-remote-message)
561     ;; Find the ambassador
562     (let* ((remote-hive-id (hive-id (message-to message)))
563            (ambassador (hive-resolve-ambassador remote-hive-id))
564            (message-handler (actor-message-handler ambassador))
565            (forward-request (make-forward-request hive ambassador message)))
566       (message-handler ambassador forward-request)))
567
568   (let ((to (message-to message)))
569     ;; This seems to be an easy mistake to make, so check that addressing
570     ;; is correct here
571     (if (not to)
572         (throw 'missing-addressee
573                "`to' field is missing on message"
574                #:message message))
575     (if (hive-actor-local? hive to)
576         (if (message-in-reply-to message)
577             (resume-waiting-coroutine)
578             (process-local-message))
579         (process-remote-message))))
580
581 (define-method (hive-actor-local? (hive <hive>) address)
582   (equal? (hive-id hive) (address-hive-id address)))
583
584 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
585   (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
586
587 (define-method (%hive-create-actor (hive <hive>) actor-class
588                                    init id-cookie)
589   "Actual method called by hive-create-actor.
590
591 Since this is a define-method it can't accept fancy define* arguments,
592 so this gets called from the nicer hive-create-actor interface.  See
593 that method for documentation."
594   (let* ((actor-id (hive-gen-actor-id hive id-cookie))
595          (actor (apply make actor-class
596                        #:hive hive
597                        #:id actor-id
598                        init)))
599     (hive-register-actor! hive actor)
600     ;; return the actor id
601     actor-id))
602
603 (define* (hive-create-actor hive actor-class #:rest init)
604   (%hive-create-actor hive actor-class
605                       init #f))
606
607 (define* (hive-create-actor* hive actor-class id-cookie #:rest init)
608   (%hive-create-actor hive actor-class
609                       init id-cookie))
610
611 (define (call-with-message message proc)
612   "Applies message body arguments into procedure, with message as first
613 argument.  Similar to call-with-values in concept."
614   (apply proc message (message-body message)))
615
616 ;; (msg-receive (<- bar baz)
617 ;;     (baz)
618 ;;   basil)
619
620 ;; Emacs: (put 'msg-receive 'scheme-indent-function 2)
621
622 ;; @@: Or receive-msg or receieve-message or??
623 (define-syntax-rule (msg-receive arglist message body ...)
624   "Call body with arglist (which can accept arguments like lambda*)
625 applied from the message-body of message."
626   (call-with-message message
627                      (lambda* arglist
628                        body ...)))
629
630 (define (msg-val message)
631   "Retrieve the first value from the message-body of message.
632 Like single value return from a procedure call.  Probably the most
633 common case when waiting on a reply from some action invocation."
634   (call-with-message message
635                      (lambda (_ val) val)))
636
637 \f
638 ;;; Various API methods for actors to interact with the system
639 ;;; ==========================================================
640
641 ;; TODO: move send-message and friends here...?
642
643 (define* (create-actor from-actor actor-class #:rest init)
644   "Create an instance of actor-class.  Return the new actor's id.
645
646 This is the method actors should call directly (unless they want
647 to supply an id-cookie, in which case they should use
648 create-actor*)."
649   (%hive-create-actor (actor-hive from-actor) actor-class
650                       init #f))
651
652
653 (define* (create-actor* from-actor actor-class id-cookie #:rest init)
654   "Create an instance of actor-class.  Return the new actor's id.
655
656 Like create-actor, but permits supplying an id-cookie."
657   (%hive-create-actor (actor-hive from-actor) actor-class
658                       init id-cookie))
659
660
661 (define (self-destruct actor)
662   "Remove an actor from the hive."
663   (hash-remove! (hive-actor-registry (actor-hive actor))
664                 (actor-id actor)))
665
666
667 \f
668 ;;; 8sync bootstrap utilities
669 ;;; =========================
670
671 (define* (ez-run-hive hive initial-tasks #:key repl-server)
672   "Start up an agenda and run HIVE in it with INITIAL-TASKS.
673
674 Should we start up a cooperative REPL for live hacking?  REPL-SERVER
675 wants to know!  You can pass it #t or #f, or if you want to specify a port,
676 an integer."
677   (let* ((queue (list->q initial-tasks))
678          (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
679                               #:queue queue)))
680     (cond
681      ;; If repl-server is an integer, we'll use that as the port
682      ((integer? repl-server)
683       (spawn-and-queue-repl-server! agenda repl-server))
684      (repl-server
685       (spawn-and-queue-repl-server! agenda)))
686     (start-agenda agenda)))
687
688 (define (bootstrap-message hive to-id action . message-body-args)
689   (wrap
690    (apply <- hive to-id action message-body-args)))
691
692
693 \f
694 ;;; Basic readers / writers
695 ;;; =======================
696
697 (define (serialize-message message)
698   "Serialize a message for read/write"
699   (list
700    (message-id message)
701    (message-to message)
702    (message-from message)
703    (message-action message)
704    (message-body message)
705    (message-in-reply-to message)
706    (message-wants-reply message)
707    (message-replied message)))
708
709 (define* (write-message message #:optional (port (current-output-port)))
710   "Write out a message to a port for easy reading later.
711
712 Note that if a sub-value can't be easily written to something
713 Guile's `read' procedure knows how to read, this doesn't do anything
714 to improve that.  You'll need a better serializer for that.."
715   (write (serialize-message message) port))
716
717 (define (serialize-message-pretty message)
718   "Serialize a message in a way that's easy for humans to read."
719   `(*message*
720     (id ,(message-id message))
721     (to ,(message-to message))
722     (from ,(message-from message))
723     (action ,(message-action message))
724     (body ,(message-body message))
725     (in-reply-to ,(message-in-reply-to message))
726     (wants-reply ,(message-wants-reply message))
727     (replied ,(message-replied message))))
728
729 (define (pprint-message message)
730   "Pretty print a message."
731   (pretty-print (serialize-message-pretty message)))
732
733 (define* (read-message #:optional (port (current-input-port)))
734   "Read a message serialized via serialize-message from PORT"
735   (match (read port)
736     ((id to from action body in-reply-to wants-reply replied)
737      (make-message-intern
738       id to from action body
739       in-reply-to wants-reply replied))
740     (anything-else
741      (throw 'message-read-bad-structure
742             "Could not read message from structure"
743             anything-else))))
744
745 (define (read-message-from-string message-str)
746   "Read message from MESSAGE-STR"
747   (with-input-from-string message-str
748     (lambda ()
749       (read-message (current-input-port)))))