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 #:use-module (8sync repl)
29 #:export (;; utilities... ought to go in their own module
31 big-random-number-string
32 simple-message-id-generator
40 ;;; Commenting out the <address> type for now;
41 ;;; it may be back when we have better serializers
44 address-actor-id address-hive-id
57 ;; There are more methods for the hive, but there's
58 ;; no reason for the outside world to look at them maybe?
60 hive-create-actor hive-create-actor*
62 create-actor create-actor*
67 message-to message-action message-from
68 message-id message-body message-in-reply-to
73 <- <-wait <-wait* <-reply <-reply-wait <-reply-wait*
75 call-with-message msg-receive msg-val
80 serialize-message write-message
81 serialize-message-pretty pprint-message
82 read-message read-message-from-string))
86 (make-parameter (random-state-from-platform)))
88 ;; Same size as a uuid4 I think...
89 (define random-number-size (expt 2 128))
91 (define (big-random-number)
92 (random random-number-size (%random-state)))
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)))
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)))
106 (set! counter (1+ counter))
107 (string-append prefix (number->string counter)))))
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.
120 (define-record-type <message>
121 (make-message-intern id to from action
122 body in-reply-to wants-reply
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!))
136 (define* (make-message id to from action body
137 #:key in-reply-to wants-reply
139 (make-message-intern id to from action body
140 in-reply-to wants-reply replied))
142 (define (message-auto-reply? message)
143 (eq? (message-action message) '*auto-reply*))
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))))
151 (define (kwarg-list-to-alist args)
152 (let loop ((remaining args)
155 (((? keyword? key) val rest ...)
157 (cons (cons (keyword->symbol key) val)
160 (_ (throw 'invalid-kwarg-list
161 "Invalid keyword argument list"
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 )
168 ;; This is the internal, generalized message sending method.
169 ;; Users shouldn't use it! Use the <-foo forms instead.
171 ;; @@: Could we get rid of some of the conditional checks through
174 (define-inlinable (send-message send-options from-actor to-id action
175 replying-to-message wants-reply?
177 (if replying-to-message
178 (set-message-replied! replying-to-message #t))
179 (let* ((hive (actor-hive from-actor))
181 (make-message (hive-gen-message-id hive) to-id
182 (actor-id from-actor) action
184 #:wants-reply wants-reply?
186 (if replying-to-message
187 (message-id replying-to-message)
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
196 (8sync (hive-process-message hive new-message)))))
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))
204 (define (<-wait* send-options from-actor to-id action . message-body-args)
205 "Like <-wait, but allows extra parameters, for example whether to
207 (apply wait-maybe-handle-errors
208 (send-message send-options from-actor to-id action
209 #f #t message-body-args)
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))
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.
221 (define (<-reply from-actor original-message . message-body-args)
223 (send-message '() from-actor (message-from original-message) '*reply*
224 original-message #f message-body-args))
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 '()))
231 (define (<-reply-wait* send-options from-actor original-message
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)
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))
244 (define* (wait-maybe-handle-errors message
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*)
252 (throw 'hive-unresumable-coroutine
253 "Won't resume coroutine; got an *error* as a reply"
259 ;;; Main actor implementation
260 ;;; =========================
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)
267 (or (and (class-slot-definition this-class 'actions)
268 (class-slot-ref this-class 'actions))
270 (for-each (match-lambda
271 ((action-name . method)
272 (when (eq? action-name action)
275 (class-precedence-list (class-of actor)))
276 (throw 'action-not-found
277 "No appropriate action handler found for actor"
282 (call/ec find-message-handler))
283 (apply method actor message (message-body message)))
285 (define-class <actor> ()
287 (id #:init-keyword #: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)
301 ;; This is the default, "simple" way to inherit and process messages.
302 (actions #:init-value '()
303 #:allocation #:each-subclass))
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.
309 ;; (define-record-type <address>
310 ;; (make-address actor-id hive-id) ; @@: Do we want the trailing -id?
312 ;; (actor-id address-actor-id)
313 ;; (hive-id address-hive-id))
315 ;; (set-record-type-printer!
317 ;; (lambda (record port)
318 ;; (format port "<address: ~s@~s>"
319 ;; (address-actor-id record) (address-hive-id record))))
322 (define (make-address actor-id hive-id)
323 (vector actor-id hive-id))
325 (define (address-actor-id address)
326 (vector-ref address 0))
328 (define (address-hive-id address)
329 (vector-ref address 1))
331 (define (address->string address)
332 (string-append (address-actor-id address) "@"
333 (address-hive-id address)))
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)))
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)))
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)))
347 (define %current-actor
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."
361 (wrap-apply method)) ...))
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)))
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.
374 (define-generic hive-handle-failed-forward)
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)
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
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))))
404 (define-method (hive-handle-failed-forward (hive <hive>) message)
405 "Handle an ambassador failing to forward a message"
408 (define* (make-hive #:key hive-id)
409 (let ((hive (make <hive>
412 (big-random-number-string))))))
413 ;; Set the hive's actor reference to itself
414 (set! (actor-hive hive) hive)
417 (define-method (hive-id (hive <hive>))
418 (actor-id-hive hive))
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))
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)))
430 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
431 (hash-ref (hive-actor-registry hive) actor-address))
433 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
434 (hash-ref (hive-ambassadors hive) ambassador-address))
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.
445 `((original . ,message))))
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*
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))))
471 (define-record-type <waiting-on-reply>
472 (make-waiting-on-reply actor-id kont send-options)
474 (actor-id waiting-on-reply-actor-id)
475 (kont waiting-on-reply-kont)
476 (send-options waiting-on-reply-send-options))
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)))
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))))
490 (throw 'actor-not-found
491 (format #f "Message ~a from ~a directed to nonexistant actor ~a"
493 (address->string (message-from message))
494 (address->string (message-to message)))
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
509 ;; In the actor model, we don't totally crash on errors.
511 ;; If an error happens, we raise it
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
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)
528 (lambda (kont actor message send-options)
529 ;; Register the coroutine
530 (hash-set! (hive-waiting-coroutines hive)
532 (make-waiting-on-reply
533 (actor-id actor) kont send-options))
534 ;; Send off the message
535 (8sync (hive-process-message hive message)))))
537 (define (process-local-message)
538 (let ((actor (resolve-actor-to)))
539 (call-catching-coroutine
541 (define message-handler (actor-message-handler actor))
542 ;; @@: Should a more general error handling happen here?
543 (parameterize ((%current-actor actor))
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?
552 (define (resume-waiting-coroutine)
553 (case (message-action message)
554 ;; standard reply / auto-reply
555 ((*reply* *auto-reply* *error*)
556 (call-catching-coroutine
558 (match (hash-remove! (hive-waiting-coroutines hive)
559 (message-in-reply-to message))
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)
568 (let* (;; @@: How should we resolve resuming coroutines to actors who are
570 (actor (resolve-actor-to))
571 (kont (waiting-on-reply-kont waiting))
572 (result (kont message)))
573 (maybe-autoreply actor)
575 (#f (throw 'no-waiting-coroutine
576 "message in-reply-to tries to resume nonexistent coroutine"
578 ;; Unhandled action for a reply!
580 (throw 'hive-unresumable-coroutine
581 "Won't resume coroutine, nonsense action on reply message"
582 #:action (message-action message)
583 #:message message))))
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)))
593 (let ((to (message-to message)))
594 ;; This seems to be an easy mistake to make, so check that addressing
597 (throw 'missing-addressee
598 "`to' field is missing on 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))))
606 (define-method (hive-actor-local? (hive <hive>) address)
607 (equal? (hive-id hive) (address-hive-id address)))
609 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
610 (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
612 (define-method (%hive-create-actor (hive <hive>) actor-class
614 "Actual method called by hive-create-actor.
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
624 (hive-register-actor! hive actor)
625 ;; return the actor id
628 (define* (hive-create-actor hive actor-class #:rest init)
629 (%hive-create-actor hive actor-class
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
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)))
642 ;; (msg-receive (<- bar baz)
646 ;; Emacs: (put 'msg-receive 'scheme-indent-function 2)
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
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)))
664 ;;; Various API methods for actors to interact with the system
665 ;;; ==========================================================
667 ;; TODO: move send-message and friends here...?
669 (define* (create-actor from-actor actor-class #:rest init)
670 "Create an instance of actor-class. Return the new actor's id.
672 This is the method actors should call directly (unless they want
673 to supply an id-cookie, in which case they should use
675 (%hive-create-actor (actor-hive from-actor) actor-class
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.
682 Like create-actor, but permits supplying an id-cookie."
683 (%hive-create-actor (actor-hive from-actor) actor-class
687 (define (self-destruct actor)
688 "Remove an actor from the hive."
689 (hash-remove! (hive-actor-registry (actor-hive actor))
694 ;;; 8sync bootstrap utilities
695 ;;; =========================
697 (define* (ez-run-hive hive initial-tasks #:key repl-server)
698 "Start up an agenda and run HIVE in it with INITIAL-TASKS.
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,
703 (let* ((queue (list->q initial-tasks))
704 (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
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))
711 (spawn-and-queue-repl-server! agenda)))
712 (start-agenda agenda)))
714 (define (bootstrap-message hive to-id action . message-body-args)
716 (apply <- hive to-id action message-body-args)))
720 ;;; Basic readers / writers
721 ;;; =======================
723 (define (serialize-message message)
724 "Serialize a message for read/write"
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)))
735 (define* (write-message message #:optional (port (current-output-port)))
736 "Write out a message to a port for easy reading later.
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))
743 (define (serialize-message-pretty message)
744 "Serialize a message in a way that's easy for humans to read."
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))))
755 (define (pprint-message message)
756 "Pretty print a message."
757 (pretty-print (serialize-message-pretty message)))
759 (define* (read-message #:optional (port (current-input-port)))
760 "Read a message serialized via serialize-message from PORT"
762 ((id to from action body in-reply-to wants-reply replied)
764 id to from action body
765 in-reply-to wants-reply replied))
767 (throw 'message-read-bad-structure
768 "Could not read message from structure"
771 (define (read-message-from-string message-str)
772 "Read message from MESSAGE-STR"
773 (with-input-from-string message-str
775 (read-message (current-input-port)))))