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