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