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 mlambda define-mhandler
56 ;; There are more methods for the hive, but there's
57 ;; no reason for the outside world to look at them maybe?
59 hive-create-actor hive-create-actor*
61 create-actor create-actor*
66 message-to message-action message-from
67 message-id message-body message-in-reply-to
71 send-message send-message-wait
72 reply-message reply-message-wait
74 <- <-wait <-reply <-reply-wait
79 serialize-message write-message
80 serialize-message-pretty pprint-message
81 read-message read-message-from-string))
85 (make-parameter (random-state-from-platform)))
87 ;; Same size as a uuid4 I think...
88 (define random-number-size (expt 2 128))
90 (define (big-random-number)
91 (random random-number-size (%random-state)))
93 ;; Would be great to get this base64 encoded instead.
94 (define (big-random-number-string)
95 ;; @@: This is slow. Using format here is wasteful.
96 (format #f "~x" (big-random-number)))
98 ;; @@: This is slow. A mere ~275k / second on my (old) machine.
99 ;; The main cost seems to be in number->string.
100 (define (simple-message-id-generator)
101 ;; Prepending this cookie makes message ids unique per hive
102 (let ((prefix (format #f "~x:" (big-random-number)))
105 (set! counter (1+ counter))
106 (string-append prefix (number->string counter)))))
114 (define-record-type <message>
115 (make-message-intern id to from action
116 body in-reply-to wants-reply
119 ;; Will we ever find a real use case?
125 (action message-action)
127 (in-reply-to message-in-reply-to)
128 (wants-reply message-wants-reply)
130 ;; See XUDD source for these. Not use yet, maybe eventually will be?
131 ;; XUDD uses them for autoreply.
132 ;; Requiring mutation on message objects is clearly not great,
133 ;; but it may be worth it...? Investigate!
134 (replied message-replied set-message-replied!)
135 (deferred-reply message-deferred-reply set-message-deferred-reply!))
138 (define* (make-message id to from action body
139 #:key in-reply-to wants-reply
140 replied deferred-reply)
141 (make-message-intern id to from action body
142 in-reply-to wants-reply replied
145 ;; Note: the body of messages is currently an alist, but it's created
146 ;; from a keyword based property list (see the following two functions).
147 ;; But, that's an extra conversion step, and maybe totally unnecessary:
148 ;; we already have message-ref, and this could just pull a keyword
149 ;; from a property list.
150 ;; The main ways this might be useful are error checking,
151 ;; serialization across the wire (but even that might require some
152 ;; change), and using existing tooling (though adding new tooling
153 ;; would be negligible in implementation effort.)
155 ;; This cons cell is immutable and unique (for eq? tests)
156 (define %nothing-provided (cons 'nothing 'provided))
158 (define* (message-ref message key #:optional (dflt %nothing-provided))
159 "Extract KEY from body of MESSAGE.
161 Optionally set default with [DFLT]
162 If key not found and DFLT not provided, throw an error."
163 (let ((result (assoc key (message-body message))))
164 (if result (cdr result)
165 (if (eq? dflt %nothing-provided)
166 (throw 'message-missing-key
167 "Message body does not contain key and no default provided"
173 (define (message-needs-reply message)
174 "See if this message needs a reply still"
175 (and (message-wants-reply message)
176 (not (or (message-replied message)
177 (message-deferred-reply message)))))
180 (define (kwarg-list-to-alist args)
181 (let loop ((remaining args)
184 (((? keyword? key) val rest ...)
186 (cons (cons (keyword->symbol key) val)
189 (_ (throw 'invalid-kwarg-list
190 "Invalid keyword argument list"
194 (define (send-message from-actor to-id action . message-body-args)
195 "Send a message from an actor to another actor"
196 (let* ((hive (actor-hive from-actor))
197 (message (make-message (hive-gen-message-id hive) to-id
198 (actor-id from-actor) action
199 (kwarg-list-to-alist message-body-args))))
200 (8sync-nowait (hive-process-message hive message))))
202 (define (send-message-wait from-actor to-id action . message-body-args)
203 "Send a message from an actor to another, but wait until we get a response"
204 (let* ((hive (actor-hive from-actor))
205 (abort-to (hive-prompt (actor-hive from-actor)))
206 (message (make-message (hive-gen-message-id hive) to-id
207 (actor-id from-actor) action
208 (kwarg-list-to-alist message-body-args)
210 (abort-to-prompt abort-to from-actor message)))
212 ;; TODO: Intelligently ~propagate(ish) errors on -wait functions.
213 ;; We might have `send-message-wait-brazen' to allow callers to
214 ;; not have an exception thrown and instead just have a message with
215 ;; the appropriate '*error* message returned.
217 (define (reply-message from-actor original-message
220 (set-message-replied! original-message #t)
221 (let* ((hive (actor-hive from-actor))
222 (new-message (make-message (hive-gen-message-id hive)
223 (message-from original-message)
224 (actor-id from-actor) '*reply*
225 (kwarg-list-to-alist message-body-args)
226 #:in-reply-to (message-id original-message))))
227 (8sync-nowait (hive-process-message hive new-message))))
229 (define (reply-message-wait from-actor original-message
231 "Reply to a messsage, but wait until we get a response"
232 (set-message-replied! original-message #t)
233 (let* ((hive (actor-hive from-actor))
234 (abort-to (hive-prompt (actor-hive from-actor)))
235 (new-message (make-message (hive-gen-message-id hive)
236 (message-from original-message)
237 (actor-id from-actor) '*reply*
238 (kwarg-list-to-alist message-body-args)
240 #:in-reply-to (message-id original-message))))
241 (abort-to-prompt abort-to from-actor new-message)))
245 ;;; See: http://mumble.net/~jar/articles/oo-moon-weinreb.html
246 ;;; (also worth seeing: http://mumble.net/~jar/articles/oo.html )
248 (define <- send-message)
249 (define <-wait send-message-wait)
250 (define <-reply reply-message)
251 (define <-reply-wait reply-message-wait)
255 ;;; Main actor implementation
256 ;;; =========================
258 (define-class <actor> ()
260 (id #:init-keyword #:id
262 ;; The hive we're connected to.
263 ;; We need this to be able to send messages.
264 (hive #:init-keyword #:hive
265 #:accessor actor-hive)
266 ;; How we receive and process new messages
267 (message-handler #:allocation #:each-subclass))
269 (define-method (actor-message-handler (actor <actor>))
270 (slot-ref actor 'message-handler))
272 ;;; So these are the nicer representations of addresses.
273 ;;; However, they don't serialize so easily with scheme read/write, so we're
274 ;;; using the simpler cons cell version below for now.
276 ;; (define-record-type <address>
277 ;; (make-address actor-id hive-id) ; @@: Do we want the trailing -id?
279 ;; (actor-id address-actor-id)
280 ;; (hive-id address-hive-id))
282 ;; (set-record-type-printer!
284 ;; (lambda (record port)
285 ;; (format port "<address: ~s@~s>"
286 ;; (address-actor-id record) (address-hive-id record))))
289 (define (make-address actor-id hive-id)
290 (cons actor-id hive-id))
292 (define (address-actor-id address)
295 (define (address-hive-id address)
298 (define (address->string address)
299 (string-append (address-actor-id address) "@"
300 (address-hive-id address)))
302 (define-method (actor-id-actor (actor <actor>))
303 "Get the actor id component of the actor-id"
304 (address-actor-id (actor-id actor)))
306 (define-method (actor-id-hive (actor <actor>))
307 "Get the hive id component of the actor-id"
308 (address-hive-id (actor-id actor)))
310 (define-method (actor-id-string (actor <actor>))
311 "Render the full actor id as a human-readable string"
312 (address->string (actor-id actor)))
319 (define-syntax mlambda
321 "A lambda for building message handlers.
324 (mlambda (actor message foo)
327 Which is like doing manually:
328 (lambda (actor message)
329 (let ((foo (message-ref message foo)))
331 ((_ (actor message message-arg ...)
333 (lambda (actor message)
334 (let ((message-arg (message-ref message (quote message-arg))) ...)
337 ;; @@: Sadly, docstrings won't work with this...
338 ;; I think we need to bust out syntax-case to make that happen...
339 (define-syntax-rule (define-mhandler (name actor message message-arg ...)
342 (mlambda (actor message message-arg ...)
345 (define (simple-dispatcher action-map)
346 (lambda (actor message)
347 (let* ((action (message-action message))
348 (method (assoc-ref action-map action)))
350 (throw 'action-not-found
351 "No appropriate action handler found for actor"
355 #:available-actions (map car action-map)))
356 (method actor message))))
358 (define-syntax %expand-action-item
360 ((_ ((action-name action-args ...) body ...))
361 (cons (quote action-name)
362 (mlambda (action-args ...)
364 ((_ (action-name handler))
365 (cons (quote action-name) handler))))
367 (define-syntax make-action-dispatch
369 "Expand a list of action names and actions into an alist
371 You can use this like the following:
372 (make-action-dispatch
374 (lambda (actor message)
375 (display \"I love cookies!\n\")))
377 (lambda (actor message)
378 (display \"Life of the party!\"))))
380 Alternately, if you'd like to skip the lambda, you could use the slightly
381 more compact following syntax:
382 (make-action-dispatch
383 ((cookies actor message)
384 (display \"I love cookies!\n\"))
385 ((party actor message)
386 (display \"Life of the party!\")))"
387 ((make-action-dispatch action-item ...)
389 (list (%expand-action-item action-item) ...)))))
391 (define-syntax-rule (define-simple-actor class actions ...)
392 (define-class class (<actor>)
394 #:init-value (make-action-dispatch actions ...)
395 #:allocation #:each-subclass)))
400 ;;; Every actor has a hive. The hive is a kind of "meta-actor"
401 ;;; which routes all the rest of the actors in a system.
403 (define-generic hive-handle-failed-forward)
405 (define-class <hive> (<actor>)
406 (actor-registry #:init-thunk make-hash-table
407 #:getter hive-actor-registry)
408 (msg-id-generator #:init-thunk simple-message-id-generator
409 #:getter hive-msg-id-generator)
410 ;; Ambassadors are used (or will be) for inter-hive communication.
411 ;; These are special actors that know how to route messages to other hives.
412 (ambassadors #:init-thunk make-weak-key-hash-table
413 #:getter hive-ambassadors)
414 ;; Waiting coroutines
415 ;; This is a map from cons cell of message-id
416 ;; to a cons cell of (actor-id . coroutine)
417 ;; @@: Should we have a <waiting-coroutine> record type?
418 ;; @@: Should there be any way to clear out "old" coroutines?
419 (waiting-coroutines #:init-thunk make-hash-table
420 #:getter hive-waiting-coroutines)
422 ;; When actors send messages to each other they abort to this prompt
423 ;; to send the message, then carry on their way
424 (prompt #:init-thunk make-prompt-tag
425 #:getter hive-prompt)
428 (make-action-dispatch
429 ;; This is in the case of an ambassador failing to forward a message...
430 ;; it reports it back to the hive
431 (*failed-forward* hive-handle-failed-forward))))
433 (define-method (hive-handle-failed-forward (hive <hive>) message)
434 "Handle an ambassador failing to forward a message"
437 (define* (make-hive #:key hive-id)
438 (let ((hive (make <hive>
441 (big-random-number-string))))))
442 ;; Set the hive's actor reference to itself
443 (set! (actor-hive hive) hive)
446 (define-method (hive-id (hive <hive>))
447 (actor-id-hive hive))
449 (define-method (hive-gen-actor-id (hive <hive>) cookie)
450 (make-address (if cookie
451 (string-append cookie "-" (big-random-number-string))
452 (big-random-number-string))
455 (define-method (hive-gen-message-id (hive <hive>))
456 "Generate a message id using HIVE's message id generator"
457 ((hive-msg-id-generator hive)))
459 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
460 (hash-ref (hive-actor-registry hive) actor-address))
462 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
463 (hash-ref (hive-ambassadors hive) ambassador-address))
465 (define-method (make-forward-request (hive <hive>) (ambassador <actor>) message)
466 (make-message (hive-gen-message-id hive) (actor-id ambassador)
467 ;; If we make the hive not an actor, we could either switch this
468 ;; to #f or to the original actor...?
469 ;; Maybe some more thinking should be done on what should
470 ;; happen in case of failure to forward? Handling ambassador failures
471 ;; seems like the primary motivation for the hive remaining an actor.
474 `((original . ,message))))
476 (define-method (hive-reply-with-error (hive <hive>) original-message
477 error-key error-args)
478 ;; We only supply the error-args if the original sender is on the same hive
479 (define (orig-actor-on-same-hive?)
480 (equal? (hive-id hive)
481 (address-hive-id (message-from original-message))))
482 (set-message-replied! original-message #t)
483 (let* ((new-message-body
484 (if (orig-actor-on-same-hive?)
485 `((original-message . ,original-message)
486 (error-key . ,error-key)
487 (error-args . ,error-args))
488 `((original-message . ,original-message)
489 (error-key . ,error-key))))
490 (new-message (make-message (hive-gen-message-id hive)
491 (message-from original-message)
492 (actor-id hive) '*error*
494 #:in-reply-to (message-id original-message))))
495 (8sync-nowait (hive-process-message hive new-message))))
497 (define-method (hive-process-message (hive <hive>) message)
498 "Handle one message, or forward it via an ambassador"
499 (define (maybe-autoreply actor)
500 ;; Possibly autoreply
501 (if (message-needs-reply message)
502 ;; @@: Should we give *autoreply* as the action instead of *reply*?
503 (reply-message actor message
506 (define (resolve-actor-to)
507 "Get the actor the message was aimed at"
508 (let ((actor (hive-resolve-local-actor hive (message-to message))))
510 (throw 'actor-not-found
511 (format #f "Message ~a from ~a directed to nonexistant actor ~a"
513 (address->string (message-from message))
514 (address->string (message-to message)))
518 (define (call-catching-coroutine thunk)
519 (define (call-catching-errors)
523 (if (message-needs-reply message)
524 ;; If the message is waiting on a reply, let them know
525 ;; something went wrong.
526 (hive-reply-with-error hive message key args)))))
527 (call-with-prompt (hive-prompt hive)
529 (lambda (kont actor message)
530 ;; Register the coroutine
531 (hash-set! (hive-waiting-coroutines hive)
533 (cons (actor-id actor) kont))
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?
544 (message-handler actor message)))
545 (maybe-autoreply actor)
546 ;; Returning result allows actors to possibly make a run-request
547 ;; at the end of handling a message.
548 ;; ... We do want that, right?
551 (define (resume-waiting-coroutine)
553 ((eq? (message-action message) '*reply*)
554 (call-catching-coroutine
556 (match (hash-remove! (hive-waiting-coroutines hive)
557 (message-in-reply-to message))
558 ((_ . (resume-actor-id . kont))
559 (if (not (equal? (message-to message)
561 (throw 'resuming-to-wrong-actor
562 "Attempted to resume a coroutine to the wrong actor!"
563 #:expected-actor-id (message-to message)
564 #:got-actor-id resume-actor-id
566 (let (;; @@: How should we resolve resuming coroutines to actors who are
568 (actor (resolve-actor-to))
569 (result (kont message)))
570 (maybe-autoreply actor)
572 (#f (throw 'no-waiting-coroutine
573 "message in-reply-to tries to resume nonexistent coroutine"
575 ;; Yikes, we must have gotten an error or something back
577 ;; @@: Not what we want in the long run?
578 ;; What we'd *prefer* to do is to resume this message
579 ;; and throw an error inside the message handler
580 ;; (say, from send-mesage-wait), but that causes a SIGABRT (??!!)
581 (hash-remove! (hive-waiting-coroutines hive)
582 (message-in-reply-to message))
584 (if (eq? (message-action message) '*reply*)
585 "Won't resume coroutine; got an *error* as a reply"
586 "Won't resume coroutine because action is not *reply*")))
587 (throw 'hive-unresumable-coroutine
589 #:message message)))))
591 (define (process-remote-message)
592 ;; Find the ambassador
593 (let* ((remote-hive-id (hive-id (message-to message)))
594 (ambassador (hive-resolve-ambassador remote-hive-id))
595 (message-handler (actor-message-handler ambassador))
596 (forward-request (make-forward-request hive ambassador message)))
597 (message-handler ambassador forward-request)))
599 (let ((to (message-to message)))
600 ;; This seems to be an easy mistake to make, so check that addressing
603 (throw 'missing-addressee
604 "`to' field is missing on message"
606 (if (hive-actor-local? hive to)
607 (if (message-in-reply-to message)
608 (resume-waiting-coroutine)
609 (process-local-message))
610 (process-remote-message))))
612 (define-method (hive-actor-local? (hive <hive>) address)
613 (hash-ref (hive-actor-registry hive) address))
615 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
616 (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
618 (define-method (%hive-create-actor (hive <hive>) actor-class
620 "Actual method called by hive-create-actor.
622 Since this is a define-method it can't accept fancy define* arguments,
623 so this gets called from the nicer hive-create-actor interface. See
624 that method for documentation."
625 (let* ((actor-id (hive-gen-actor-id hive id-cookie))
626 (actor (apply make actor-class
630 (hive-register-actor! hive actor)
631 ;; return the actor id
634 (define* (hive-create-actor hive actor-class #:rest init)
635 (%hive-create-actor hive actor-class
638 (define* (hive-create-actor* hive actor-class id-cookie #:rest init)
639 (%hive-create-actor hive actor-class
644 ;;; Various API methods for actors to interact with the system
645 ;;; ==========================================================
647 ;; TODO: move send-message and friends here...?
649 (define* (create-actor from-actor actor-class #:rest init)
650 "Create an instance of actor-class. Return the new actor's id.
652 This is the method actors should call directly (unless they want
653 to supply an id-cookie, in which case they should use
655 (8sync (%hive-create-actor (actor-hive from-actor) actor-class
659 (define* (create-actor* from-actor actor-class id-cookie #:rest init)
660 "Create an instance of actor-class. Return the new actor's id.
662 Like create-actor, but permits supplying an id-cookie."
663 (8sync (%hive-create-actor (actor-hive from-actor) actor-class
667 (define (self-destruct actor)
668 "Remove an actor from the hive."
669 (hash-remove! (hive-actor-registry (actor-hive actor))
674 ;;; 8sync bootstrap utilities
675 ;;; =========================
677 (define* (ez-run-hive hive initial-tasks #:key repl-server)
678 "Start up an agenda and run HIVE in it with INITIAL-TASKS.
680 Should we start up a cooperative REPL for live hacking? REPL-SERVER
681 wants to know! You can pass it #t or #f, or if you want to specify a port,
683 (let* ((queue (list->q initial-tasks))
684 (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
687 ;; If repl-server is an integer, we'll use that as the port
688 ((integer? repl-server)
689 (spawn-and-queue-repl-server! agenda repl-server))
691 (spawn-and-queue-repl-server! agenda)))
692 (start-agenda agenda)))
694 (define (bootstrap-message hive to-id action . message-body-args)
696 (apply send-message hive to-id action message-body-args)))
700 ;;; Basic readers / writers
701 ;;; =======================
703 (define (serialize-message message)
704 "Serialize a message for read/write"
708 (message-from message)
709 (message-action message)
710 (message-body message)
711 (message-in-reply-to message)
712 (message-wants-reply message)
713 (message-replied message)
714 (message-deferred-reply message)))
716 (define* (write-message message #:optional (port (current-output-port)))
717 "Write out a message to a port for easy reading later.
719 Note that if a sub-value can't be easily written to something
720 Guile's `read' procedure knows how to read, this doesn't do anything
721 to improve that. You'll need a better serializer for that.."
722 (write (serialize-message message) port))
724 (define (serialize-message-pretty message)
725 "Serialize a message in a way that's easy for humans to read."
727 (id ,(message-id message))
728 (to ,(message-to message))
729 (from ,(message-from message))
730 (action ,(message-action message))
731 (body ,(message-body message))
732 (in-reply-to ,(message-in-reply-to message))
733 (wants-reply ,(message-wants-reply message))
734 (replied ,(message-replied message))
735 (deferred-reply ,(message-deferred-reply message))))
737 (define (pprint-message message)
738 "Pretty print a message."
739 (pretty-print (serialize-message-pretty message)))
741 (define* (read-message #:optional (port (current-input-port)))
742 "Read a message serialized via serialize-message from PORT"
744 ((id to from action body in-reply-to wants-reply replied deferred-reply)
746 id to from action body
747 in-reply-to wants-reply replied deferred-reply))
749 (throw 'message-read-bad-structure
750 "Could not read message from structure"
753 (define (read-message-from-string message-str)
754 "Read message from MESSAGE-STR"
755 (with-input-from-string message-str
757 (read-message (current-input-port)))))