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 <-reply <-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 (define (<- from-actor to-id action . message-body-args)
169 "Send a message from an actor to another actor"
170 (let* ((hive (actor-hive from-actor))
171 (message (make-message (hive-gen-message-id hive) to-id
172 (actor-id from-actor) action
174 (8sync (hive-process-message hive message))))
176 (define (<-wait from-actor to-id action . message-body-args)
177 "Send a message from an actor to another, but wait until we get a response"
178 (let* ((hive (actor-hive from-actor))
179 (abort-to (hive-prompt (actor-hive from-actor)))
180 (message (make-message (hive-gen-message-id hive) to-id
181 (actor-id from-actor) action
184 (abort-to-prompt abort-to from-actor message)))
186 ;; TODO: Intelligently ~propagate(ish) errors on -wait functions.
187 ;; We might have `send-message-wait-brazen' to allow callers to
188 ;; not have an exception thrown and instead just have a message with
189 ;; the appropriate '*error* message returned.
191 (define (<-reply from-actor original-message . message-body-args)
193 (set-message-replied! original-message #t)
194 (let* ((hive (actor-hive from-actor))
195 (new-message (make-message (hive-gen-message-id hive)
196 (message-from original-message)
197 (actor-id from-actor) '*reply*
199 #:in-reply-to (message-id original-message))))
200 (8sync (hive-process-message hive new-message))))
202 (define (<-auto-reply from-actor original-message)
203 "Auto-reply to a message. Internal use only!"
204 (set-message-replied! original-message #t)
205 (let* ((hive (actor-hive from-actor))
206 (new-message (make-message (hive-gen-message-id hive)
207 (message-from original-message)
208 (actor-id from-actor) '*auto-reply*
210 #:in-reply-to (message-id original-message))))
211 (8sync (hive-process-message hive new-message))))
213 (define (<-reply-wait from-actor original-message . message-body-args)
214 "Reply to a messsage, but wait until we get a response"
215 (set-message-replied! original-message #t)
216 (let* ((hive (actor-hive from-actor))
217 (abort-to (hive-prompt (actor-hive from-actor)))
218 (new-message (make-message (hive-gen-message-id hive)
219 (message-from original-message)
220 (actor-id from-actor) '*reply*
223 #:in-reply-to (message-id original-message))))
224 (abort-to-prompt abort-to from-actor new-message)))
228 ;;; Main actor implementation
229 ;;; =========================
231 (define (actor-inheritable-message-handler actor message)
232 (define action (message-action message))
233 (define (find-message-handler return)
234 (for-each (lambda (this-class)
236 (or (and (class-slot-definition this-class 'actions)
237 (class-slot-ref this-class 'actions))
239 (for-each (match-lambda
240 ((action-name . method)
241 (when (eq? action-name action)
244 (class-precedence-list (class-of actor)))
245 (throw 'action-not-found
246 "No appropriate action handler found for actor"
251 (call/ec find-message-handler))
252 (apply method actor message (message-body message)))
254 (define-class <actor> ()
256 (id #:init-keyword #:id
258 ;; The hive we're connected to.
259 ;; We need this to be able to send messages.
260 (hive #:init-keyword #:hive
261 #:accessor actor-hive)
262 ;; How we receive and process new messages
263 (message-handler #:init-value actor-inheritable-message-handler
264 ;; @@: There's no reason not to use #:class instead of
265 ;; #:each-subclass anywhere in this file, except for
266 ;; Guile bug #25211 (#:class is broken in Guile 2.2)
267 #:allocation #:each-subclass)
269 ;; This is the default, "simple" way to inherit and process messages.
270 (actions #:init-value '()
271 #:allocation #:each-subclass))
273 (define-method (actor-message-handler (actor <actor>))
274 (slot-ref actor 'message-handler))
276 ;;; So these are the nicer representations of addresses.
277 ;;; However, they don't serialize so easily with scheme read/write, so we're
278 ;;; using the simpler cons cell version below for now.
280 ;; (define-record-type <address>
281 ;; (make-address actor-id hive-id) ; @@: Do we want the trailing -id?
283 ;; (actor-id address-actor-id)
284 ;; (hive-id address-hive-id))
286 ;; (set-record-type-printer!
288 ;; (lambda (record port)
289 ;; (format port "<address: ~s@~s>"
290 ;; (address-actor-id record) (address-hive-id record))))
293 (define (make-address actor-id hive-id)
294 (cons actor-id hive-id))
296 (define (address-actor-id address)
299 (define (address-hive-id address)
302 (define (address->string address)
303 (string-append (address-actor-id address) "@"
304 (address-hive-id address)))
306 (define-method (actor-id-actor (actor <actor>))
307 "Get the actor id component of the actor-id"
308 (address-actor-id (actor-id actor)))
310 (define-method (actor-id-hive (actor <actor>))
311 "Get the hive id component of the actor-id"
312 (address-hive-id (actor-id actor)))
314 (define-method (actor-id-string (actor <actor>))
315 "Render the full actor id as a human-readable string"
316 (address->string (actor-id actor)))
318 (define %current-actor
326 (define-syntax-rule (build-actions (symbol method) ...)
327 "Construct an alist of (symbol . method), where the method is wrapped
328 with wrap-apply to facilitate live hacking and allow the method definition
329 to come after class definition."
332 (wrap-apply method)) ...))
334 (define-syntax-rule (define-simple-actor class action ...)
335 (define-class class (<actor>)
336 (actions #:init-value (build-actions action ...)
337 #:allocation #:each-subclass)))
342 ;;; Every actor has a hive. The hive is a kind of "meta-actor"
343 ;;; which routes all the rest of the actors in a system.
345 (define-generic hive-handle-failed-forward)
347 (define-class <hive> (<actor>)
348 (actor-registry #:init-thunk make-hash-table
349 #:getter hive-actor-registry)
350 (msg-id-generator #:init-thunk simple-message-id-generator
351 #:getter hive-msg-id-generator)
352 ;; Ambassadors are used (or will be) for inter-hive communication.
353 ;; These are special actors that know how to route messages to other hives.
354 (ambassadors #:init-thunk make-weak-key-hash-table
355 #:getter hive-ambassadors)
356 ;; Waiting coroutines
357 ;; This is a map from cons cell of message-id
358 ;; to a cons cell of (actor-id . coroutine)
359 ;; @@: Should we have a <waiting-coroutine> record type?
360 ;; @@: Should there be any way to clear out "old" coroutines?
361 (waiting-coroutines #:init-thunk make-hash-table
362 #:getter hive-waiting-coroutines)
364 ;; When actors send messages to each other they abort to this prompt
365 ;; to send the message, then carry on their way
366 (prompt #:init-thunk make-prompt-tag
367 #:getter hive-prompt)
368 (actions #:allocation #:each-subclass
371 ;; This is in the case of an ambassador failing to forward a
372 ;; message... it reports it back to the hive
373 (*failed-forward* hive-handle-failed-forward))))
375 (define-method (hive-handle-failed-forward (hive <hive>) message)
376 "Handle an ambassador failing to forward a message"
379 (define* (make-hive #:key hive-id)
380 (let ((hive (make <hive>
383 (big-random-number-string))))))
384 ;; Set the hive's actor reference to itself
385 (set! (actor-hive hive) hive)
388 (define-method (hive-id (hive <hive>))
389 (actor-id-hive hive))
391 (define-method (hive-gen-actor-id (hive <hive>) cookie)
392 (make-address (if cookie
393 (string-append cookie "-" (big-random-number-string))
394 (big-random-number-string))
397 (define-method (hive-gen-message-id (hive <hive>))
398 "Generate a message id using HIVE's message id generator"
399 ((hive-msg-id-generator hive)))
401 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
402 (hash-ref (hive-actor-registry hive) actor-address))
404 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
405 (hash-ref (hive-ambassadors hive) ambassador-address))
407 (define-method (make-forward-request (hive <hive>) (ambassador <actor>) message)
408 (make-message (hive-gen-message-id hive) (actor-id ambassador)
409 ;; If we make the hive not an actor, we could either switch this
410 ;; to #f or to the original actor...?
411 ;; Maybe some more thinking should be done on what should
412 ;; happen in case of failure to forward? Handling ambassador failures
413 ;; seems like the primary motivation for the hive remaining an actor.
416 `((original . ,message))))
418 (define-method (hive-reply-with-error (hive <hive>) original-message
419 error-key error-args)
420 ;; We only supply the error-args if the original sender is on the same hive
421 (define (orig-actor-on-same-hive?)
422 (equal? (hive-id hive)
423 (address-hive-id (message-from original-message))))
424 (set-message-replied! original-message #t)
425 (let* ((new-message-body
426 (if (orig-actor-on-same-hive?)
427 `(#:original-message ,original-message
428 #:error-key ,error-key
429 #:error-args ,error-args)
430 `(#:original-message ,original-message
431 #:error-key ,error-key)))
432 (new-message (make-message (hive-gen-message-id hive)
433 (message-from original-message)
434 (actor-id hive) '*error*
436 #:in-reply-to (message-id original-message))))
437 ;; We only return a thunk, rather than run 8sync here, because if
438 ;; we ran 8sync in the middle of a catch we'd end up with an
439 ;; unresumable continuation.
440 (lambda () (hive-process-message hive new-message))))
442 (define-method (hive-process-message (hive <hive>) message)
443 "Handle one message, or forward it via an ambassador"
444 (define (maybe-autoreply actor)
445 ;; Possibly autoreply
446 (if (message-needs-reply? message)
447 (<-auto-reply actor message)))
449 (define (resolve-actor-to)
450 "Get the actor the message was aimed at"
451 (let ((actor (hive-resolve-local-actor hive (message-to message))))
453 (throw 'actor-not-found
454 (format #f "Message ~a from ~a directed to nonexistant actor ~a"
456 (address->string (message-from message))
457 (address->string (message-to message)))
461 (define (call-catching-coroutine thunk)
462 (define queued-error-handling-thunk #f)
463 (define (call-catching-errors)
464 ;; TODO: maybe parameterize (or attach to hive) and use
465 ;; maybe-catch-all from agenda.scm
466 ;; @@: Why not just use with-throw-handler and let the catch
467 ;; happen at the agenda? That's what we used to do, but
468 ;; it ended up with a SIGABRT. See:
469 ;; http://lists.gnu.org/archive/html/bug-guile/2016-05/msg00003.html
472 ;; In the actor model, we don't totally crash on errors.
474 ;; If an error happens, we raise it
476 (if (message-needs-reply? message)
477 ;; If the message is waiting on a reply, let them know
478 ;; something went wrong.
479 ;; However, we have to do it outside of this catch
480 ;; routine, or we'll end up in an unrewindable continuation
482 (set! queued-error-handling-thunk
483 (hive-reply-with-error hive message key args)))
484 ;; print error message
485 (apply print-error-and-continue key args)))
486 ;; @@: This is a kludge. See above for why.
487 (if queued-error-handling-thunk
488 (8sync (queued-error-handling-thunk))))
489 (call-with-prompt (hive-prompt hive)
491 (lambda (kont actor message)
492 ;; Register the coroutine
493 (hash-set! (hive-waiting-coroutines hive)
495 (cons (actor-id actor) kont))
496 ;; Send off the message
497 (8sync (hive-process-message hive message)))))
499 (define (process-local-message)
500 (let ((actor (resolve-actor-to)))
501 (call-catching-coroutine
503 (define message-handler (actor-message-handler actor))
504 ;; @@: Should a more general error handling happen here?
505 (parameterize ((%current-actor actor))
507 (message-handler actor message)))
508 (maybe-autoreply actor)
509 ;; Returning result allows actors to possibly make a run-request
510 ;; at the end of handling a message.
511 ;; ... We do want that, right?
514 (define (resume-waiting-coroutine)
516 ((or (eq? (message-action message) '*reply*)
517 (eq? (message-action message) '*auto-reply*))
518 (call-catching-coroutine
520 (match (hash-remove! (hive-waiting-coroutines hive)
521 (message-in-reply-to message))
522 ((_ . (resume-actor-id . kont))
523 (if (not (equal? (message-to message)
525 (throw 'resuming-to-wrong-actor
526 "Attempted to resume a coroutine to the wrong actor!"
527 #:expected-actor-id (message-to message)
528 #:got-actor-id resume-actor-id
530 (let (;; @@: How should we resolve resuming coroutines to actors who are
532 (actor (resolve-actor-to))
533 (result (kont message)))
534 (maybe-autoreply actor)
536 (#f (throw 'no-waiting-coroutine
537 "message in-reply-to tries to resume nonexistent coroutine"
539 ;; Yikes, we must have gotten an error or something back
541 ;; @@: Not what we want in the long run?
542 ;; What we'd *prefer* to do is to resume this message
543 ;; and throw an error inside the message handler
544 ;; (say, from send-mesage-wait), but that causes a SIGABRT (??!!)
545 (hash-remove! (hive-waiting-coroutines hive)
546 (message-in-reply-to message))
548 (if (eq? (message-action message) '*reply*)
549 "Won't resume coroutine; got an *error* as a reply"
550 "Won't resume coroutine because action is not *reply*")))
551 (throw 'hive-unresumable-coroutine
553 #:message message)))))
555 (define (process-remote-message)
556 ;; Find the ambassador
557 (let* ((remote-hive-id (hive-id (message-to message)))
558 (ambassador (hive-resolve-ambassador remote-hive-id))
559 (message-handler (actor-message-handler ambassador))
560 (forward-request (make-forward-request hive ambassador message)))
561 (message-handler ambassador forward-request)))
563 (let ((to (message-to message)))
564 ;; This seems to be an easy mistake to make, so check that addressing
567 (throw 'missing-addressee
568 "`to' field is missing on message"
570 (if (hive-actor-local? hive to)
571 (if (message-in-reply-to message)
572 (resume-waiting-coroutine)
573 (process-local-message))
574 (process-remote-message))))
576 (define-method (hive-actor-local? (hive <hive>) address)
577 (equal? (hive-id hive) (address-hive-id address)))
579 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
580 (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
582 (define-method (%hive-create-actor (hive <hive>) actor-class
584 "Actual method called by hive-create-actor.
586 Since this is a define-method it can't accept fancy define* arguments,
587 so this gets called from the nicer hive-create-actor interface. See
588 that method for documentation."
589 (let* ((actor-id (hive-gen-actor-id hive id-cookie))
590 (actor (apply make actor-class
594 (hive-register-actor! hive actor)
595 ;; return the actor id
598 (define* (hive-create-actor hive actor-class #:rest init)
599 (%hive-create-actor hive actor-class
602 (define* (hive-create-actor* hive actor-class id-cookie #:rest init)
603 (%hive-create-actor hive actor-class
606 (define (call-with-message message proc)
607 "Applies message body arguments into procedure, with message as first
608 argument. Similar to call-with-values in concept."
609 (apply proc message (message-body message)))
611 ;; (msg-receive (<- bar baz)
615 ;; Emacs: (put 'msg-receive 'scheme-indent-function 2)
617 ;; @@: Or receive-msg or receieve-message or??
618 (define-syntax-rule (msg-receive arglist message body ...)
619 "Call body with arglist (which can accept arguments like lambda*)
620 applied from the message-body of message."
621 (call-with-message message
625 (define (msg-val message)
626 "Retrieve the first value from the message-body of message.
627 Like single value return from a procedure call. Probably the most
628 common case when waiting on a reply from some action invocation."
629 (call-with-message message
630 (lambda (_ val) val)))
633 ;;; Various API methods for actors to interact with the system
634 ;;; ==========================================================
636 ;; TODO: move send-message and friends here...?
638 (define* (create-actor from-actor actor-class #:rest init)
639 "Create an instance of actor-class. Return the new actor's id.
641 This is the method actors should call directly (unless they want
642 to supply an id-cookie, in which case they should use
644 (%hive-create-actor (actor-hive from-actor) actor-class
648 (define* (create-actor* from-actor actor-class id-cookie #:rest init)
649 "Create an instance of actor-class. Return the new actor's id.
651 Like create-actor, but permits supplying an id-cookie."
652 (%hive-create-actor (actor-hive from-actor) actor-class
656 (define (self-destruct actor)
657 "Remove an actor from the hive."
658 (hash-remove! (hive-actor-registry (actor-hive actor))
663 ;;; 8sync bootstrap utilities
664 ;;; =========================
666 (define* (ez-run-hive hive initial-tasks #:key repl-server)
667 "Start up an agenda and run HIVE in it with INITIAL-TASKS.
669 Should we start up a cooperative REPL for live hacking? REPL-SERVER
670 wants to know! You can pass it #t or #f, or if you want to specify a port,
672 (let* ((queue (list->q initial-tasks))
673 (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
676 ;; If repl-server is an integer, we'll use that as the port
677 ((integer? repl-server)
678 (spawn-and-queue-repl-server! agenda repl-server))
680 (spawn-and-queue-repl-server! agenda)))
681 (start-agenda agenda)))
683 (define (bootstrap-message hive to-id action . message-body-args)
685 (apply <- hive to-id action message-body-args)))
689 ;;; Basic readers / writers
690 ;;; =======================
692 (define (serialize-message message)
693 "Serialize a message for read/write"
697 (message-from message)
698 (message-action message)
699 (message-body message)
700 (message-in-reply-to message)
701 (message-wants-reply message)
702 (message-replied message)))
704 (define* (write-message message #:optional (port (current-output-port)))
705 "Write out a message to a port for easy reading later.
707 Note that if a sub-value can't be easily written to something
708 Guile's `read' procedure knows how to read, this doesn't do anything
709 to improve that. You'll need a better serializer for that.."
710 (write (serialize-message message) port))
712 (define (serialize-message-pretty message)
713 "Serialize a message in a way that's easy for humans to read."
715 (id ,(message-id message))
716 (to ,(message-to message))
717 (from ,(message-from message))
718 (action ,(message-action message))
719 (body ,(message-body message))
720 (in-reply-to ,(message-in-reply-to message))
721 (wants-reply ,(message-wants-reply message))
722 (replied ,(message-replied message))))
724 (define (pprint-message message)
725 "Pretty print a message."
726 (pretty-print (serialize-message-pretty message)))
728 (define* (read-message #:optional (port (current-input-port)))
729 "Read a message serialized via serialize-message from PORT"
731 ((id to from action body in-reply-to wants-reply replied)
733 id to from action body
734 in-reply-to wants-reply replied))
736 (throw 'message-read-bad-structure
737 "Could not read message from structure"
740 (define (read-message-from-string message-str)
741 "Read message from MESSAGE-STR"
742 (with-input-from-string message-str
744 (read-message (current-input-port)))))