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 ;; XUDD inspired actor system
21 (define-module (8sync systems actors)
22 #:use-module (oop goops)
23 #:use-module (srfi srfi-9)
24 #:use-module (srfi srfi-9 gnu)
25 #:use-module (ice-9 format)
26 #:use-module (ice-9 match)
27 #:use-module (ice-9 pretty-print)
28 #:use-module (8sync agenda)
29 #:use-module (8sync repl)
30 #:export (;; utilities... ought to go in their own module
32 big-random-number-string
33 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
50 simple-dispatcher build-actions make-action-dispatch
55 ;; There are more methods for the hive, but there's
56 ;; no reason for the outside world to look at them maybe?
58 hive-create-actor hive-create-actor*
60 create-actor create-actor*
65 message-to message-action message-from
66 message-id message-body message-in-reply-to
71 <- <-wait <-reply <-reply-wait
73 call-with-message msg-receive
78 serialize-message write-message
79 serialize-message-pretty pprint-message
80 read-message read-message-from-string))
84 (make-parameter (random-state-from-platform)))
86 ;; Same size as a uuid4 I think...
87 (define random-number-size (expt 2 128))
89 (define (big-random-number)
90 (random random-number-size (%random-state)))
92 ;; Would be great to get this base64 encoded instead.
93 (define (big-random-number-string)
94 ;; @@: This is slow. Using format here is wasteful.
95 (format #f "~x" (big-random-number)))
97 ;; @@: This is slow. A mere ~275k / second on my (old) machine.
98 ;; The main cost seems to be in number->string.
99 (define (simple-message-id-generator)
100 ;; Prepending this cookie makes message ids unique per hive
101 (let ((prefix (format #f "~x:" (big-random-number)))
104 (set! counter (1+ counter))
105 (string-append prefix (number->string counter)))))
113 ;; @@: We may want to add a deferred-reply to the below, similar to
114 ;; what we had in XUDD, for actors which do their own response
115 ;; queueing.... ie, that might receive messages but need to shelve
116 ;; them to be acted upon after something else is taken care of.
118 (define-record-type <message>
119 (make-message-intern id to from action
120 body in-reply-to wants-reply
126 (action message-action)
128 (in-reply-to message-in-reply-to)
129 (wants-reply message-wants-reply)
130 (replied message-replied set-message-replied!))
133 (define* (make-message id to from action body
134 #:key in-reply-to wants-reply
136 (make-message-intern id to from action body
137 in-reply-to wants-reply replied))
139 (define (message-auto-reply? message)
140 (eq? (message-action message) '*auto-reply*))
142 (define (message-needs-reply? message)
143 "See if this message needs a reply still"
144 (and (message-wants-reply message)
145 (not (message-replied message))))
148 (define (kwarg-list-to-alist args)
149 (let loop ((remaining args)
152 (((? keyword? key) val rest ...)
154 (cons (cons (keyword->symbol key) val)
157 (_ (throw 'invalid-kwarg-list
158 "Invalid keyword argument list"
162 ;;; See: https://web.archive.org/web/20081223021934/http://mumble.net/~jar/articles/oo-moon-weinreb.html
163 ;;; (also worth seeing: http://mumble.net/~jar/articles/oo.html )
165 (define (<- from-actor to-id action . message-body-args)
166 "Send a message from an actor to another actor"
167 (let* ((hive (actor-hive from-actor))
168 (message (make-message (hive-gen-message-id hive) to-id
169 (actor-id from-actor) action
171 (8sync (hive-process-message hive message))))
173 (define (<-wait from-actor to-id action . message-body-args)
174 "Send a message from an actor to another, but wait until we get a response"
175 (let* ((hive (actor-hive from-actor))
176 (abort-to (hive-prompt (actor-hive from-actor)))
177 (message (make-message (hive-gen-message-id hive) to-id
178 (actor-id from-actor) action
181 (abort-to-prompt abort-to from-actor message)))
183 ;; TODO: Intelligently ~propagate(ish) errors on -wait functions.
184 ;; We might have `send-message-wait-brazen' to allow callers to
185 ;; not have an exception thrown and instead just have a message with
186 ;; the appropriate '*error* message returned.
188 (define (<-reply from-actor original-message . message-body-args)
190 (set-message-replied! original-message #t)
191 (let* ((hive (actor-hive from-actor))
192 (new-message (make-message (hive-gen-message-id hive)
193 (message-from original-message)
194 (actor-id from-actor) '*reply*
196 #:in-reply-to (message-id original-message))))
197 (8sync (hive-process-message hive new-message))))
199 (define (<-auto-reply from-actor original-message)
200 "Auto-reply to a message. Internal use only!"
201 (set-message-replied! original-message #t)
202 (let* ((hive (actor-hive from-actor))
203 (new-message (make-message (hive-gen-message-id hive)
204 (message-from original-message)
205 (actor-id from-actor) '*auto-reply*
207 #:in-reply-to (message-id original-message))))
208 (8sync (hive-process-message hive new-message))))
210 (define (<-reply-wait from-actor original-message . message-body-args)
211 "Reply to a messsage, but wait until we get a response"
212 (set-message-replied! original-message #t)
213 (let* ((hive (actor-hive from-actor))
214 (abort-to (hive-prompt (actor-hive from-actor)))
215 (new-message (make-message (hive-gen-message-id hive)
216 (message-from original-message)
217 (actor-id from-actor) '*reply*
220 #:in-reply-to (message-id original-message))))
221 (abort-to-prompt abort-to from-actor new-message)))
225 ;;; Main actor implementation
226 ;;; =========================
228 (define-class <actor> ()
230 (id #:init-keyword #:id
232 ;; The hive we're connected to.
233 ;; We need this to be able to send messages.
234 (hive #:init-keyword #:hive
235 #:accessor actor-hive)
236 ;; How we receive and process new messages
237 (message-handler #:allocation #:each-subclass))
239 (define-method (actor-message-handler (actor <actor>))
240 (slot-ref actor 'message-handler))
242 ;;; So these are the nicer representations of addresses.
243 ;;; However, they don't serialize so easily with scheme read/write, so we're
244 ;;; using the simpler cons cell version below for now.
246 ;; (define-record-type <address>
247 ;; (make-address actor-id hive-id) ; @@: Do we want the trailing -id?
249 ;; (actor-id address-actor-id)
250 ;; (hive-id address-hive-id))
252 ;; (set-record-type-printer!
254 ;; (lambda (record port)
255 ;; (format port "<address: ~s@~s>"
256 ;; (address-actor-id record) (address-hive-id record))))
259 (define (make-address actor-id hive-id)
260 (cons actor-id hive-id))
262 (define (address-actor-id address)
265 (define (address-hive-id address)
268 (define (address->string address)
269 (string-append (address-actor-id address) "@"
270 (address-hive-id address)))
272 (define-method (actor-id-actor (actor <actor>))
273 "Get the actor id component of the actor-id"
274 (address-actor-id (actor-id actor)))
276 (define-method (actor-id-hive (actor <actor>))
277 "Get the hive id component of the actor-id"
278 (address-hive-id (actor-id actor)))
280 (define-method (actor-id-string (actor <actor>))
281 "Render the full actor id as a human-readable string"
282 (address->string (actor-id actor)))
289 (define (simple-dispatcher action-map)
290 (lambda (actor message)
291 (let* ((action (message-action message))
292 (method (assoc-ref action-map action)))
294 ;; @@: There's every possibility this should be handled in
295 ;; hive-process-message instead.
296 (throw 'action-not-found
297 "No appropriate action handler found for actor"
301 #:available-actions (map car action-map)))
302 (apply method actor message (message-body message)))))
304 (define-syntax %expand-action-item
306 ((_ (action-name handler))
307 (cons (quote action-name) handler))))
309 (define-syntax-rule (build-actions action-item ...)
310 "Build a mapping of actions. Same syntax as make-action-dispatch
311 but this doesn't build the dispatcher for you (you probably want to
312 pass it to simple-dispatcher).
314 The advantage here is that since this simply builds an alist, you can
315 compose it with other action maps."
316 (list (%expand-action-item action-item) ...))
318 (define-syntax make-action-dispatch
320 "Expand a list of action names and actions into an alist
322 You can use this like the following:
323 (make-action-dispatch
325 (lambda (actor message)
326 (display \"I love cookies!\n\")))
328 (lambda (actor message)
329 (display \"Life of the party!\"))))
331 Alternately, if you'd like to skip the lambda, you could use the slightly
332 more compact following syntax:
333 (make-action-dispatch
334 ((cookies actor message)
335 (display \"I love cookies!\n\"))
336 ((party actor message)
337 (display \"Life of the party!\")))"
338 ((make-action-dispatch action-item ...)
339 (simple-dispatcher (build-actions action-item ...)))))
341 (define-syntax-rule (define-simple-actor class actions ...)
342 (define-class class (<actor>)
344 #:init-value (make-action-dispatch actions ...)
345 #:allocation #:each-subclass)))
350 ;;; Every actor has a hive. The hive is a kind of "meta-actor"
351 ;;; which routes all the rest of the actors in a system.
353 (define-generic hive-handle-failed-forward)
355 (define-class <hive> (<actor>)
356 (actor-registry #:init-thunk make-hash-table
357 #:getter hive-actor-registry)
358 (msg-id-generator #:init-thunk simple-message-id-generator
359 #:getter hive-msg-id-generator)
360 ;; Ambassadors are used (or will be) for inter-hive communication.
361 ;; These are special actors that know how to route messages to other hives.
362 (ambassadors #:init-thunk make-weak-key-hash-table
363 #:getter hive-ambassadors)
364 ;; Waiting coroutines
365 ;; This is a map from cons cell of message-id
366 ;; to a cons cell of (actor-id . coroutine)
367 ;; @@: Should we have a <waiting-coroutine> record type?
368 ;; @@: Should there be any way to clear out "old" coroutines?
369 (waiting-coroutines #:init-thunk make-hash-table
370 #:getter hive-waiting-coroutines)
372 ;; When actors send messages to each other they abort to this prompt
373 ;; to send the message, then carry on their way
374 (prompt #:init-thunk make-prompt-tag
375 #:getter hive-prompt)
378 (make-action-dispatch
379 ;; This is in the case of an ambassador failing to forward a message...
380 ;; it reports it back to the hive
381 (*failed-forward* hive-handle-failed-forward))))
383 (define-method (hive-handle-failed-forward (hive <hive>) message)
384 "Handle an ambassador failing to forward a message"
387 (define* (make-hive #:key hive-id)
388 (let ((hive (make <hive>
391 (big-random-number-string))))))
392 ;; Set the hive's actor reference to itself
393 (set! (actor-hive hive) hive)
396 (define-method (hive-id (hive <hive>))
397 (actor-id-hive hive))
399 (define-method (hive-gen-actor-id (hive <hive>) cookie)
400 (make-address (if cookie
401 (string-append cookie "-" (big-random-number-string))
402 (big-random-number-string))
405 (define-method (hive-gen-message-id (hive <hive>))
406 "Generate a message id using HIVE's message id generator"
407 ((hive-msg-id-generator hive)))
409 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
410 (hash-ref (hive-actor-registry hive) actor-address))
412 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
413 (hash-ref (hive-ambassadors hive) ambassador-address))
415 (define-method (make-forward-request (hive <hive>) (ambassador <actor>) message)
416 (make-message (hive-gen-message-id hive) (actor-id ambassador)
417 ;; If we make the hive not an actor, we could either switch this
418 ;; to #f or to the original actor...?
419 ;; Maybe some more thinking should be done on what should
420 ;; happen in case of failure to forward? Handling ambassador failures
421 ;; seems like the primary motivation for the hive remaining an actor.
424 `((original . ,message))))
426 (define-method (hive-reply-with-error (hive <hive>) original-message
427 error-key error-args)
428 ;; We only supply the error-args if the original sender is on the same hive
429 (define (orig-actor-on-same-hive?)
430 (equal? (hive-id hive)
431 (address-hive-id (message-from original-message))))
432 (set-message-replied! original-message #t)
433 (let* ((new-message-body
434 (if (orig-actor-on-same-hive?)
435 `(#:original-message ,original-message
436 #:error-key ,error-key
437 #:error-args ,error-args)
438 `(#:original-message ,original-message
439 #:error-key ,error-key)))
440 (new-message (make-message (hive-gen-message-id hive)
441 (message-from original-message)
442 (actor-id hive) '*error*
444 #:in-reply-to (message-id original-message))))
445 ;; We only return a thunk, rather than run 8sync here, because if
446 ;; we ran 8sync in the middle of a catch we'd end up with an
447 ;; unresumable continuation.
448 (lambda () (hive-process-message hive new-message))))
450 (define-method (hive-process-message (hive <hive>) message)
451 "Handle one message, or forward it via an ambassador"
452 (define (maybe-autoreply actor)
453 ;; Possibly autoreply
454 (if (message-needs-reply? message)
455 (<-auto-reply actor message)))
457 (define (resolve-actor-to)
458 "Get the actor the message was aimed at"
459 (let ((actor (hive-resolve-local-actor hive (message-to message))))
461 (throw 'actor-not-found
462 (format #f "Message ~a from ~a directed to nonexistant actor ~a"
464 (address->string (message-from message))
465 (address->string (message-to message)))
469 (define (call-catching-coroutine thunk)
470 (define queued-error-handling-thunk #f)
471 (define (call-catching-errors)
472 ;; TODO: maybe parameterize (or attach to hive) and use
473 ;; maybe-catch-all from agenda.scm
474 ;; @@: Why not just use with-throw-handler and let the catch
475 ;; happen at the agenda? That's what we used to do, but
476 ;; it ended up with a SIGABRT. See:
477 ;; http://lists.gnu.org/archive/html/bug-guile/2016-05/msg00003.html
480 ;; In the actor model, we don't totally crash on errors.
482 ;; If an error happens, we raise it
484 (if (message-needs-reply? message)
485 ;; If the message is waiting on a reply, let them know
486 ;; something went wrong.
487 ;; However, we have to do it outside of this catch
488 ;; routine, or we'll end up in an unrewindable continuation
490 (set! queued-error-handling-thunk
491 (hive-reply-with-error hive message key args)))
492 ;; print error message
493 (apply print-error-and-continue key args)))
494 ;; @@: This is a kludge. See above for why.
495 (if queued-error-handling-thunk
496 (8sync (queued-error-handling-thunk))))
497 (call-with-prompt (hive-prompt hive)
499 (lambda (kont actor message)
500 ;; Register the coroutine
501 (hash-set! (hive-waiting-coroutines hive)
503 (cons (actor-id actor) kont))
504 ;; Send off the message
505 (8sync (hive-process-message hive message)))))
507 (define (process-local-message)
508 (let ((actor (resolve-actor-to)))
509 (call-catching-coroutine
511 (define message-handler (actor-message-handler actor))
512 ;; @@: Should a more general error handling happen here?
514 (message-handler actor message)))
515 (maybe-autoreply actor)
516 ;; Returning result allows actors to possibly make a run-request
517 ;; at the end of handling a message.
518 ;; ... We do want that, right?
521 (define (resume-waiting-coroutine)
523 ((or (eq? (message-action message) '*reply*)
524 (eq? (message-action message) '*auto-reply*))
525 (call-catching-coroutine
527 (match (hash-remove! (hive-waiting-coroutines hive)
528 (message-in-reply-to message))
529 ((_ . (resume-actor-id . kont))
530 (if (not (equal? (message-to message)
532 (throw 'resuming-to-wrong-actor
533 "Attempted to resume a coroutine to the wrong actor!"
534 #:expected-actor-id (message-to message)
535 #:got-actor-id resume-actor-id
537 (let (;; @@: How should we resolve resuming coroutines to actors who are
539 (actor (resolve-actor-to))
540 (result (kont message)))
541 (maybe-autoreply actor)
543 (#f (throw 'no-waiting-coroutine
544 "message in-reply-to tries to resume nonexistent coroutine"
546 ;; Yikes, we must have gotten an error or something back
548 ;; @@: Not what we want in the long run?
549 ;; What we'd *prefer* to do is to resume this message
550 ;; and throw an error inside the message handler
551 ;; (say, from send-mesage-wait), but that causes a SIGABRT (??!!)
552 (hash-remove! (hive-waiting-coroutines hive)
553 (message-in-reply-to message))
555 (if (eq? (message-action message) '*reply*)
556 "Won't resume coroutine; got an *error* as a reply"
557 "Won't resume coroutine because action is not *reply*")))
558 (throw 'hive-unresumable-coroutine
560 #:message message)))))
562 (define (process-remote-message)
563 ;; Find the ambassador
564 (let* ((remote-hive-id (hive-id (message-to message)))
565 (ambassador (hive-resolve-ambassador remote-hive-id))
566 (message-handler (actor-message-handler ambassador))
567 (forward-request (make-forward-request hive ambassador message)))
568 (message-handler ambassador forward-request)))
570 (let ((to (message-to message)))
571 ;; This seems to be an easy mistake to make, so check that addressing
574 (throw 'missing-addressee
575 "`to' field is missing on message"
577 (if (hive-actor-local? hive to)
578 (if (message-in-reply-to message)
579 (resume-waiting-coroutine)
580 (process-local-message))
581 (process-remote-message))))
583 (define-method (hive-actor-local? (hive <hive>) address)
584 (equal? (hive-id hive) (address-hive-id address)))
586 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
587 (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
589 (define-method (%hive-create-actor (hive <hive>) actor-class
591 "Actual method called by hive-create-actor.
593 Since this is a define-method it can't accept fancy define* arguments,
594 so this gets called from the nicer hive-create-actor interface. See
595 that method for documentation."
596 (let* ((actor-id (hive-gen-actor-id hive id-cookie))
597 (actor (apply make actor-class
601 (hive-register-actor! hive actor)
602 ;; return the actor id
605 (define* (hive-create-actor hive actor-class #:rest init)
606 (%hive-create-actor hive actor-class
609 (define* (hive-create-actor* hive actor-class id-cookie #:rest init)
610 (%hive-create-actor hive actor-class
613 (define (call-with-message message proc)
614 "Applies message body arguments into procedure, with message as first
615 argument. Similar to call-with-values in concept."
616 (apply proc message (message-body message)))
618 ;; (msg-receive (<- bar baz)
622 ;; Emacs: (put 'msg-receive 'scheme-indent-function 2)
624 ;; @@: Or receive-msg or receieve-message or??
625 (define-syntax-rule (msg-receive arglist the-message body ...)
626 (call-with-message the-message
631 ;;; Various API methods for actors to interact with the system
632 ;;; ==========================================================
634 ;; TODO: move send-message and friends here...?
636 (define* (create-actor from-actor actor-class #:rest init)
637 "Create an instance of actor-class. Return the new actor's id.
639 This is the method actors should call directly (unless they want
640 to supply an id-cookie, in which case they should use
642 (%hive-create-actor (actor-hive from-actor) actor-class
646 (define* (create-actor* from-actor actor-class id-cookie #:rest init)
647 "Create an instance of actor-class. Return the new actor's id.
649 Like create-actor, but permits supplying an id-cookie."
650 (%hive-create-actor (actor-hive from-actor) actor-class
654 (define (self-destruct actor)
655 "Remove an actor from the hive."
656 (hash-remove! (hive-actor-registry (actor-hive actor))
661 ;;; 8sync bootstrap utilities
662 ;;; =========================
664 (define* (ez-run-hive hive initial-tasks #:key repl-server)
665 "Start up an agenda and run HIVE in it with INITIAL-TASKS.
667 Should we start up a cooperative REPL for live hacking? REPL-SERVER
668 wants to know! You can pass it #t or #f, or if you want to specify a port,
670 (let* ((queue (list->q initial-tasks))
671 (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
674 ;; If repl-server is an integer, we'll use that as the port
675 ((integer? repl-server)
676 (spawn-and-queue-repl-server! agenda repl-server))
678 (spawn-and-queue-repl-server! agenda)))
679 (start-agenda agenda)))
681 (define (bootstrap-message hive to-id action . message-body-args)
683 (apply <- hive to-id action message-body-args)))
687 ;;; Basic readers / writers
688 ;;; =======================
690 (define (serialize-message message)
691 "Serialize a message for read/write"
695 (message-from message)
696 (message-action message)
697 (message-body message)
698 (message-in-reply-to message)
699 (message-wants-reply message)
700 (message-replied message)))
702 (define* (write-message message #:optional (port (current-output-port)))
703 "Write out a message to a port for easy reading later.
705 Note that if a sub-value can't be easily written to something
706 Guile's `read' procedure knows how to read, this doesn't do anything
707 to improve that. You'll need a better serializer for that.."
708 (write (serialize-message message) port))
710 (define (serialize-message-pretty message)
711 "Serialize a message in a way that's easy for humans to read."
713 (id ,(message-id message))
714 (to ,(message-to message))
715 (from ,(message-from message))
716 (action ,(message-action message))
717 (body ,(message-body message))
718 (in-reply-to ,(message-in-reply-to message))
719 (wants-reply ,(message-wants-reply message))
720 (replied ,(message-replied message))))
722 (define (pprint-message message)
723 "Pretty print a message."
724 (pretty-print (serialize-message-pretty message)))
726 (define* (read-message #:optional (port (current-input-port)))
727 "Read a message serialized via serialize-message from PORT"
729 ((id to from action body in-reply-to wants-reply replied)
731 id to from action body
732 in-reply-to wants-reply replied))
734 (throw 'message-read-bad-structure
735 "Could not read message from structure"
738 (define (read-message-from-string message-str)
739 "Read message from MESSAGE-STR"
740 (with-input-from-string message-str
742 (read-message (current-input-port)))))