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