1 ;;; 8sync --- Asynchronous programming for Guile
2 ;;; Copyright (C) 2016 Christopher Allan Webber <cwebber@dustycloud.org>
4 ;;; This file is part of 8sync.
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.
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.
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/>.
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
30 big-random-number-string
31 simple-message-id-generator
39 ;;; Commenting out the <address> type for now;
40 ;;; it may be back when we have better serializers
43 address-actor-id address-hive-id
58 ;; There are more methods for the hive, but there's
59 ;; no reason for the outside world to look at them maybe?
61 hive-create-actor hive-create-actor*
63 create-actor create-actor*
68 message-to message-action message-from
69 message-id message-body message-in-reply-to
74 <- <-wait <-wait* <-reply <-reply-wait <-reply-wait*
76 call-with-message msg-receive msg-val
81 serialize-message write-message
82 serialize-message-pretty pprint-message
83 read-message read-message-from-string))
87 (make-parameter (random-state-from-platform)))
89 ;; Same size as a uuid4 I think...
90 (define random-number-size (expt 2 128))
92 (define (big-random-number)
93 (random random-number-size (%random-state)))
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)))
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)))
107 (set! counter (1+ counter))
108 (string-append prefix (number->string counter)))))
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.
121 (define-record-type <message>
122 (make-message-intern id to from action
123 body in-reply-to wants-reply
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!))
137 (define* (make-message id to from action body
138 #:key in-reply-to wants-reply
140 (make-message-intern id to from action body
141 in-reply-to wants-reply replied))
143 (define (message-auto-reply? message)
144 (eq? (message-action message) '*auto-reply*))
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))))
152 (define (kwarg-list-to-alist args)
153 (let loop ((remaining args)
156 (((? keyword? key) val rest ...)
158 (cons (cons (keyword->symbol key) val)
161 (_ (throw 'invalid-kwarg-list
162 "Invalid keyword argument list"
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 )
169 ;; This is the internal, generalized message sending method.
170 ;; Users shouldn't use it! Use the <-foo forms instead.
172 ;; @@: Could we get rid of some of the conditional checks through
175 (define-inlinable (send-message send-options from-actor to-id action
176 replying-to-message wants-reply?
178 (if replying-to-message
179 (set-message-replied! replying-to-message #t))
180 (let* ((hive (actor-hive from-actor))
182 (make-message (hive-gen-message-id hive) to-id
183 (actor-id from-actor) action
185 #:wants-reply wants-reply?
187 (if replying-to-message
188 (message-id replying-to-message)
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
197 (8sync (hive-process-message hive new-message)))))
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))
205 (define (<-wait* send-options from-actor to-id action . message-body-args)
206 "Like <-wait, but allows extra parameters, for example whether to
208 (apply wait-maybe-handle-errors
209 (send-message send-options from-actor to-id action
210 #f #t message-body-args)
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))
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.
222 (define (<-reply from-actor original-message . message-body-args)
224 (send-message '() from-actor (message-from original-message) '*reply*
225 original-message #f message-body-args))
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 '()))
232 (define (<-reply-wait* send-options from-actor original-message
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)
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))
245 (define* (wait-maybe-handle-errors message
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*)
253 (throw 'hive-unresumable-coroutine
254 "Won't resume coroutine; got an *error* as a reply"
260 ;;; Main actor implementation
261 ;;; =========================
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)
268 (or (and (class-slot-definition this-class 'actions)
269 (class-slot-ref this-class 'actions))
271 (for-each (match-lambda
272 ((action-name . method)
273 (when (eq? action-name action)
276 (class-precedence-list (class-of actor)))
277 (throw 'action-not-found
278 "No appropriate action handler found for actor"
283 (call/ec find-message-handler))
284 (apply method actor message (message-body message)))
286 (define-class <actor> ()
288 (id #:init-keyword #:id
290 ;; The hive we're connected to.
291 ;; We need this to be able to send messages.
292 (hive #:init-keyword #:hive
293 #:accessor actor-hive)
294 ;; How we receive and process new messages
295 (message-handler #:init-value actor-inheritable-message-handler
296 ;; @@: There's no reason not to use #:class instead of
297 ;; #:each-subclass anywhere in this file, except for
298 ;; Guile bug #25211 (#:class is broken in Guile 2.2)
299 #:allocation #:each-subclass
300 #:getter actor-message-handler)
302 ;; This is the default, "simple" way to inherit and process messages.
303 (actions #:init-value '()
304 #:allocation #:each-subclass))
306 ;;; So these are the nicer representations of addresses.
307 ;;; However, they don't serialize so easily with scheme read/write, so we're
308 ;;; using the simpler cons cell version below for now.
310 ;; (define-record-type <address>
311 ;; (make-address actor-id hive-id) ; @@: Do we want the trailing -id?
313 ;; (actor-id address-actor-id)
314 ;; (hive-id address-hive-id))
316 ;; (set-record-type-printer!
318 ;; (lambda (record port)
319 ;; (format port "<address: ~s@~s>"
320 ;; (address-actor-id record) (address-hive-id record))))
323 (define (make-address actor-id hive-id)
324 (vector actor-id hive-id))
326 (define (address-actor-id address)
327 (vector-ref address 0))
329 (define (address-hive-id address)
330 (vector-ref address 1))
332 (define (address->string address)
333 (string-append (address-actor-id address) "@"
334 (address-hive-id address)))
336 (define-method (actor-id-actor (actor <actor>))
337 "Get the actor id component of the actor-id"
338 (address-actor-id (actor-id actor)))
340 (define-method (actor-id-hive (actor <actor>))
341 "Get the hive id component of the actor-id"
342 (address-hive-id (actor-id actor)))
344 (define-method (actor-id-string (actor <actor>))
345 "Render the full actor id as a human-readable string"
346 (address->string (actor-id actor)))
348 (define %current-actor
351 (define (actor-am-i-alive? actor)
352 (hive-resolve-local-actor (actor-hive actor) (actor-id actor)))
359 (define-syntax-rule (build-actions (symbol method) ...)
360 "Construct an alist of (symbol . method), where the method is wrapped
361 with wrap-apply to facilitate live hacking and allow the method definition
362 to come after class definition."
365 (wrap-apply method)) ...))
367 (define-syntax-rule (define-simple-actor class action ...)
368 (define-class class (<actor>)
369 (actions #:init-value (build-actions action ...)
370 #:allocation #:each-subclass)))
375 ;;; Every actor has a hive. The hive is a kind of "meta-actor"
376 ;;; which routes all the rest of the actors in a system.
378 (define-generic hive-handle-failed-forward)
380 (define-class <hive> (<actor>)
381 (actor-registry #:init-thunk make-hash-table
382 #:getter hive-actor-registry)
383 (msg-id-generator #:init-thunk simple-message-id-generator
384 #:getter hive-msg-id-generator)
385 ;; Ambassadors are used (or will be) for inter-hive communication.
386 ;; These are special actors that know how to route messages to other hives.
387 (ambassadors #:init-thunk make-weak-key-hash-table
388 #:getter hive-ambassadors)
389 ;; Waiting coroutines
390 ;; This is a map from cons cell of message-id
391 ;; to a cons cell of (actor-id . coroutine)
392 ;; @@: Should we have a <waiting-coroutine> record type?
393 ;; @@: Should there be any way to clear out "old" coroutines?
394 (waiting-coroutines #:init-thunk make-hash-table
395 #:getter hive-waiting-coroutines)
397 ;; When actors send messages to each other they abort to this prompt
398 ;; to send the message, then carry on their way
399 (prompt #:init-thunk make-prompt-tag
400 #:getter hive-prompt)
401 (actions #:allocation #:each-subclass
404 ;; This is in the case of an ambassador failing to forward a
405 ;; message... it reports it back to the hive
406 (*failed-forward* hive-handle-failed-forward))))
408 (define-method (hive-handle-failed-forward (hive <hive>) message)
409 "Handle an ambassador failing to forward a message"
412 (define* (make-hive #:key hive-id)
413 (let ((hive (make <hive>
416 (big-random-number-string))))))
417 ;; Set the hive's actor reference to itself
418 (set! (actor-hive hive) hive)
421 (define-method (hive-id (hive <hive>))
422 (actor-id-hive hive))
424 (define-method (hive-gen-actor-id (hive <hive>) cookie)
425 (make-address (if cookie
426 (string-append cookie "-" (big-random-number-string))
427 (big-random-number-string))
430 (define-method (hive-gen-message-id (hive <hive>))
431 "Generate a message id using HIVE's message id generator"
432 ((hive-msg-id-generator hive)))
434 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
435 (hash-ref (hive-actor-registry hive) actor-address))
437 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
438 (hash-ref (hive-ambassadors hive) ambassador-address))
440 (define-method (make-forward-request (hive <hive>) (ambassador <actor>) message)
441 (make-message (hive-gen-message-id hive) (actor-id ambassador)
442 ;; If we make the hive not an actor, we could either switch this
443 ;; to #f or to the original actor...?
444 ;; Maybe some more thinking should be done on what should
445 ;; happen in case of failure to forward? Handling ambassador failures
446 ;; seems like the primary motivation for the hive remaining an actor.
449 `((original . ,message))))
451 (define-method (hive-reply-with-error (hive <hive>) original-message
452 error-key error-args)
453 ;; We only supply the error-args if the original sender is on the same hive
454 (define (orig-actor-on-same-hive?)
455 (equal? (hive-id hive)
456 (address-hive-id (message-from original-message))))
457 (set-message-replied! original-message #t)
458 (let* ((new-message-body
459 (if (orig-actor-on-same-hive?)
460 `(#:original-message ,original-message
461 #:error-key ,error-key
462 #:error-args ,error-args)
463 `(#:original-message ,original-message
464 #:error-key ,error-key)))
465 (new-message (make-message (hive-gen-message-id hive)
466 (message-from original-message)
467 (actor-id hive) '*error*
469 #:in-reply-to (message-id original-message))))
470 ;; We only return a thunk, rather than run 8sync here, because if
471 ;; we ran 8sync in the middle of a catch we'd end up with an
472 ;; unresumable continuation.
473 (lambda () (hive-process-message hive new-message))))
475 (define-record-type <waiting-on-reply>
476 (make-waiting-on-reply actor-id kont send-options)
478 (actor-id waiting-on-reply-actor-id)
479 (kont waiting-on-reply-kont)
480 (send-options waiting-on-reply-send-options))
483 (define-method (hive-process-message (hive <hive>) message)
484 "Handle one message, or forward it via an ambassador"
485 (define (maybe-autoreply actor)
486 ;; Possibly autoreply
487 (if (message-needs-reply? message)
488 (<-auto-reply actor message)))
490 (define (resolve-actor-to)
491 "Get the actor the message was aimed at"
492 (let ((actor (hive-resolve-local-actor hive (message-to message))))
494 (throw 'actor-not-found
495 (format #f "Message ~a from ~a directed to nonexistant actor ~a"
497 (address->string (message-from message))
498 (address->string (message-to message)))
502 (define (call-catching-coroutine thunk)
503 (define queued-error-handling-thunk #f)
504 (define (call-catching-errors)
505 ;; TODO: maybe parameterize (or attach to hive) and use
506 ;; maybe-catch-all from agenda.scm
507 ;; @@: Why not just use with-throw-handler and let the catch
508 ;; happen at the agenda? That's what we used to do, but
509 ;; it ended up with a SIGABRT. See:
510 ;; http://lists.gnu.org/archive/html/bug-guile/2016-05/msg00003.html
513 ;; In the actor model, we don't totally crash on errors.
515 ;; If an error happens, we raise it
517 (if (message-needs-reply? message)
518 ;; If the message is waiting on a reply, let them know
519 ;; something went wrong.
520 ;; However, we have to do it outside of this catch
521 ;; routine, or we'll end up in an unrewindable continuation
523 (set! queued-error-handling-thunk
524 (hive-reply-with-error hive message key args)))
525 ;; print error message
526 (apply print-error-and-continue key args)))
527 ;; @@: This is a kludge. See above for why.
528 (if queued-error-handling-thunk
529 (8sync (queued-error-handling-thunk))))
530 (call-with-prompt (hive-prompt hive)
532 (lambda (kont actor message send-options)
533 ;; Register the coroutine
534 (hash-set! (hive-waiting-coroutines hive)
536 (make-waiting-on-reply
537 (actor-id actor) kont send-options))
538 ;; Send off the message
539 (8sync (hive-process-message hive message)))))
541 (define (process-local-message)
542 (let ((actor (resolve-actor-to)))
543 (call-catching-coroutine
545 (define message-handler (actor-message-handler actor))
546 ;; @@: Should a more general error handling happen here?
547 (parameterize ((%current-actor actor))
549 (message-handler actor message)))
550 (maybe-autoreply actor)
551 ;; Returning result allows actors to possibly make a run-request
552 ;; at the end of handling a message.
553 ;; ... We do want that, right?
556 (define (resume-waiting-coroutine)
557 (case (message-action message)
558 ;; standard reply / auto-reply
559 ((*reply* *auto-reply* *error*)
560 (call-catching-coroutine
562 (match (hash-remove! (hive-waiting-coroutines hive)
563 (message-in-reply-to message))
565 (if (not (equal? (message-to message)
566 (waiting-on-reply-actor-id waiting)))
567 (throw 'resuming-to-wrong-actor
568 "Attempted to resume a coroutine to the wrong actor!"
569 #:expected-actor-id (message-to message)
570 #:got-actor-id (waiting-on-reply-actor-id waiting)
572 (let* (;; @@: How should we resolve resuming coroutines to actors who are
574 (actor (resolve-actor-to))
575 (kont (waiting-on-reply-kont waiting))
576 (result (kont message)))
577 (maybe-autoreply actor)
579 (#f (throw 'no-waiting-coroutine
580 "message in-reply-to tries to resume nonexistent coroutine"
582 ;; Unhandled action for a reply!
584 (throw 'hive-unresumable-coroutine
585 "Won't resume coroutine, nonsense action on reply message"
586 #:action (message-action message)
587 #:message message))))
589 (define (process-remote-message)
590 ;; Find the ambassador
591 (let* ((remote-hive-id (hive-id (message-to message)))
592 (ambassador (hive-resolve-ambassador remote-hive-id))
593 (message-handler (actor-message-handler ambassador))
594 (forward-request (make-forward-request hive ambassador message)))
595 (message-handler ambassador forward-request)))
597 (let ((to (message-to message)))
598 ;; This seems to be an easy mistake to make, so check that addressing
601 (throw 'missing-addressee
602 "`to' field is missing on message"
604 (if (hive-actor-local? hive to)
605 (if (message-in-reply-to message)
606 (resume-waiting-coroutine)
607 (process-local-message))
608 (process-remote-message))))
610 (define-method (hive-actor-local? (hive <hive>) address)
611 (equal? (hive-id hive) (address-hive-id address)))
613 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
614 (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
616 (define-method (%hive-create-actor (hive <hive>) actor-class
618 "Actual method called by hive-create-actor.
620 Since this is a define-method it can't accept fancy define* arguments,
621 so this gets called from the nicer hive-create-actor interface. See
622 that method for documentation."
623 (let* ((actor-id (hive-gen-actor-id hive id-cookie))
624 (actor (apply make actor-class
628 (hive-register-actor! hive actor)
629 ;; return the actor id
632 (define* (hive-create-actor hive actor-class #:rest init)
633 (%hive-create-actor hive actor-class
636 (define* (hive-create-actor* hive actor-class id-cookie #:rest init)
637 "Create an actor, but also add a 'cookie' to the name for debugging"
638 (%hive-create-actor hive actor-class
641 (define (call-with-message message proc)
642 "Applies message body arguments into procedure, with message as first
643 argument. Similar to call-with-values in concept."
644 (apply proc message (message-body message)))
646 ;; (msg-receive (<- bar baz)
650 ;; Emacs: (put 'msg-receive 'scheme-indent-function 2)
652 ;; @@: Or receive-msg or receieve-message or??
653 (define-syntax-rule (msg-receive arglist message body ...)
654 "Call body with arglist (which can accept arguments like lambda*)
655 applied from the message-body of message."
656 (call-with-message message
660 (define (msg-val message)
661 "Retrieve the first value from the message-body of message.
662 Like single value return from a procedure call. Probably the most
663 common case when waiting on a reply from some action invocation."
664 (call-with-message message
665 (lambda (_ val) val)))
668 ;;; Various API methods for actors to interact with the system
669 ;;; ==========================================================
671 ;; TODO: move send-message and friends here...?
673 (define* (create-actor from-actor actor-class #:rest init)
674 "Create an instance of actor-class. Return the new actor's id.
676 This is the method actors should call directly (unless they want
677 to supply an id-cookie, in which case they should use
679 (%hive-create-actor (actor-hive from-actor) actor-class
683 (define* (create-actor* from-actor actor-class id-cookie #:rest init)
684 "Create an instance of actor-class. Return the new actor's id.
686 Like create-actor, but permits supplying an id-cookie."
687 (%hive-create-actor (actor-hive from-actor) actor-class
691 (define (self-destruct actor)
692 "Remove an actor from the hive."
693 (hash-remove! (hive-actor-registry (actor-hive actor))
698 ;;; 8sync bootstrap utilities
699 ;;; =========================
701 (define* (ez-run-hive hive initial-tasks)
702 "Start up an agenda and run HIVE in it with INITIAL-TASKS."
703 (let* ((queue (list->q initial-tasks))
704 (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
706 (start-agenda agenda)))
708 (define (bootstrap-message hive to-id action . message-body-args)
710 (apply <- hive to-id action message-body-args)))
714 ;;; Basic readers / writers
715 ;;; =======================
717 (define (serialize-message message)
718 "Serialize a message for read/write"
722 (message-from message)
723 (message-action message)
724 (message-body message)
725 (message-in-reply-to message)
726 (message-wants-reply message)
727 (message-replied message)))
729 (define* (write-message message #:optional (port (current-output-port)))
730 "Write out a message to a port for easy reading later.
732 Note that if a sub-value can't be easily written to something
733 Guile's `read' procedure knows how to read, this doesn't do anything
734 to improve that. You'll need a better serializer for that.."
735 (write (serialize-message message) port))
737 (define (serialize-message-pretty message)
738 "Serialize a message in a way that's easy for humans to read."
740 (id ,(message-id message))
741 (to ,(message-to message))
742 (from ,(message-from message))
743 (action ,(message-action message))
744 (body ,(message-body message))
745 (in-reply-to ,(message-in-reply-to message))
746 (wants-reply ,(message-wants-reply message))
747 (replied ,(message-replied message))))
749 (define (pprint-message message)
750 "Pretty print a message."
751 (pretty-print (serialize-message-pretty message)))
753 (define* (read-message #:optional (port (current-input-port)))
754 "Read a message serialized via serialize-message from PORT"
756 ((id to from action body in-reply-to wants-reply replied)
758 id to from action body
759 in-reply-to wants-reply replied))
761 (throw 'message-read-bad-structure
762 "Could not read message from structure"
765 (define (read-message-from-string message-str)
766 "Read message from MESSAGE-STR"
767 (with-input-from-string message-str
769 (read-message (current-input-port)))))