1 ;;; 8sync --- Asynchronous programming for Guile
2 ;;; Copyright © 2016, 2017 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 (ice-9 control)
23 #:use-module (ice-9 format)
24 #:use-module (ice-9 match)
25 #:use-module (ice-9 atomic)
26 #:use-module ((ice-9 ports internal)
27 #:select (port-read-wait-fd port-write-wait-fd))
28 #:use-module (ice-9 pretty-print)
29 #:use-module (ice-9 receive)
30 #:use-module (ice-9 suspendable-ports)
32 #:use-module (fibers channels)
33 #:use-module (fibers conditions)
34 #:use-module (fibers operations)
35 #:use-module (8sync inbox)
36 #:use-module (8sync rmeta-slot)
38 #:export (;; utilities... ought to go in their own module
40 big-random-number-string
48 ;;; Commenting out the <address> type for now;
49 ;;; it may be back when we have better serializers
52 address-actor-id address-hive-id
59 actor-init! actor-cleanup!
66 with-actor-nonblocking-ports
70 ;; ;; There are more methods for the hive, but there's
71 ;; ;; no reason for the outside world to look at them maybe?
73 create-actor create-actor*
78 message-to message-action message-from
79 message-id message-body message-in-reply-to
86 ;; Maybe the wrong place for this, or for it to be exported.
87 ;; But it's used in websockets' server implementation at least...
91 (set! *random-state* (random-state-from-platform))
93 ;; Same size as a uuid4 I think...
94 (define random-number-size (expt 2 128))
96 (define (big-random-number)
97 (random random-number-size))
99 ;; Would be great to get this base64 encoded instead.
100 (define (big-random-number-string)
101 ;; @@: This is slow. Using format here is wasteful.
102 (format #f "~x" (big-random-number)))
104 ;; @@: This is slow-ish. A mere ~275k / second on my (old) machine.
105 ;; The main cost seems to be in number->string.
106 (define (simple-message-id-generator)
107 ;; Prepending this cookie makes message ids unique per hive
108 (let ((prefix (format #f "~x:" (big-random-number)))
111 (set! counter (1+ counter))
112 (string-append prefix (number->string counter)))))
119 (define-record-type <message>
120 (make-message-intern id to from action
121 body in-reply-to wants-reply)
123 ;; @@: message-ids are removed. They could be re-enabled
124 ;; if we had thread-safe promises...
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
134 (define* (make-message id to from action body
135 #:key in-reply-to wants-reply)
136 (make-message-intern id to from action body
137 in-reply-to wants-reply))
139 (define (kwarg-list-to-alist args)
140 (let loop ((remaining args)
143 (((? keyword? key) val rest ...)
145 (cons (cons (keyword->symbol key) val)
148 (_ (throw 'invalid-kwarg-list
149 "Invalid keyword argument list"
153 ;;; See: https://web.archive.org/web/20081223021934/http://mumble.net/~jar/articles/oo-moon-weinreb.html
154 ;;; (also worth seeing: http://mumble.net/~jar/articles/oo.html )
156 ;; This is the internal, generalized message sending method.
157 ;; Users shouldn't use it! Use the <-foo forms instead.
159 (define (%<- wants-reply from-actor to action args message-id in-reply-to)
160 ;; Okay, we need to deal with message ids.
161 ;; Could we get rid of them? :\
162 ;; It seems if we can use eq? and have messages be immutable then
163 ;; it should be possible to identify follow-up replies.
164 ;; If we need to track replies across hive boundaries we could
165 ;; register unique ids across the ambassador barrier.
167 (#(_ _ (? channel? channel) dead?)
168 (let ((message (make-message message-id to
169 (and from-actor (actor-id from-actor))
171 #:wants-reply wants-reply
172 #:in-reply-to in-reply-to)))
175 (put-operation channel message)
176 (wait-operation dead?)))))
177 ;; TODO: put remote addresses here.
178 (#(actor-id hive-id #f #f)
179 ;; Here we'd make a call to our hive...
181 ;; A message sent to nobody goes nowhere.
182 ;; TODO: Should we display a warning here, probably?
184 ;; We shouldn't technically be passing in actors but rather their
185 ;; addresses, but often actors want to message themselves and
186 ;; this makes that slightly easier.
187 ((? (lambda (x) (is-a? x <actor>)) actor)
188 (%<- wants-reply from-actor (actor-id actor) action
189 args message-id in-reply-to))))
191 (define (<- to action . args)
192 (define from-actor (*current-actor*))
193 (%<- #f from-actor to action args
195 ((actor-msg-id-generator from-actor)))
196 (big-random-number-string))
199 ;; TODO: this should abort to the prompt, then check for errors
202 (define (<-wait to action . args)
203 (define prompt (*actor-prompt*))
205 (error "Tried to <-wait without being in an actor's context..."))
207 (let ((reply (abort-to-prompt prompt '<-wait to action args)))
208 (cond ((eq? action '*error*)
209 (throw 'hive-unresumable-coroutine
210 "Won't resume coroutine; got an *error* as a reply"
212 (else (apply values (message-body reply))))))
215 ;;; Main actor implementation
216 ;;; =========================
218 (define (actor-inheritable-message-handler actor message)
219 (define action (message-action message))
221 (class-rmeta-ref (class-of actor) 'actions action
222 #:equals? eq? #:cache-set! hashq-set!
223 #:cache-ref hashq-ref))
225 (throw 'action-not-found
226 "No appropriate action handler found for actor"
230 (apply method actor message (message-body message)))
232 (define-syntax-rule (live-wrap body)
233 "Wrap possibly multi-value function in a procedure, applies all arguments"
237 (define-syntax-rule (build-actions (symbol method) ...)
238 "Construct an alist of (symbol . method), where the method is wrapped
239 with `live-wrap' to facilitate live hacking and allow the method definition
240 to come after class definition."
242 (list (cons (quote symbol)
243 (live-wrap method)) ...)))
245 (define-class <actor> ()
246 ;; An address object... a vector of #(actor-id hive-id inbox-channel dead?)
247 ;; - inbox-channel is the receiving channel (as opposed to actor-inbox-deq)
248 ;; - dead? is a fibers condition variable which is set once this actor
250 (id #:init-keyword #:address
253 ;; Our queue to send/receive messages on
254 (inbox-deq #:init-thunk make-channel
255 #:accessor actor-inbox-deq)
257 (msg-id-generator #:init-thunk simple-message-id-generator
258 #:getter actor-msg-id-generator)
260 ;; How we receive and process new messages
261 (message-handler #:init-value actor-inheritable-message-handler
262 ;; @@: There's no reason not to use #:class instead of
263 ;; #:each-subclass anywhere in this file, except for
264 ;; Guile bug #25211 (#:class is broken in Guile 2.2)
265 #:allocation #:each-subclass
266 #:getter actor-message-handler)
269 ;; - #t as in, send the init message, but don't wait (default)
270 ;; - 'wait, as in wait on the init message
271 ;; - #f as in don't bother to init
272 (should-init #:init-value #t
273 #:getter actor-should-init
274 #:allocation #:each-subclass)
276 ;; This is the default, "simple" way to inherit and process messages.
277 (actions #:init-thunk (build-actions)
278 #:allocation #:each-subclass))
280 ;;; Actors may specify an "init" action that occurs before the actor
281 ;;; actually begins to run.
282 ;;; During actor-init!, an actor may send a message to itself or others
283 ;;; via <- but *may not* use <-wait.
284 (define-method (actor-init! (actor <actor>))
287 (define-method (actor-cleanup! (actor <actor>))
290 ;;; Addresses are vectors where the first part is the actor-id and
291 ;;; the second part is the hive-id. This works well enough... they
292 ;;; look decent being pretty-printed.
294 (define (make-address actor-id hive-id channel dead?)
295 (vector actor-id hive-id channel dead?))
297 (define (address-actor-id address)
298 (vector-ref address 0))
300 (define (address-hive-id address)
301 (vector-ref address 1))
303 (define (address-channel address)
304 (vector-ref address 2))
306 (define (address-dead? address)
307 (vector-ref address 3))
309 (define (address->string address)
310 (string-append (address-actor-id address) "@"
311 (address-hive-id address)))
313 (define (address-equal? address1 address2)
314 "Check whether or not the two addresses are equal.
316 This compares the actor-id and hive-id but ignores the channel and
319 (#(actor-id-1 hive-id-1 _ _)
321 (#(actor-id-2 hive-id-2)
322 (and (equal? actor-id-1 actor-id-2)
323 (and (equal? hive-id-1 hive-id-2))))
327 (define (actor-id-actor actor)
328 "Get the actor id component of the actor-id"
329 (address-actor-id (actor-id actor)))
331 (define (actor-id-hive actor)
332 "Get the hive id component of the actor-id"
333 (address-hive-id (actor-id actor)))
335 (define (actor-id-string actor)
336 "Render the full actor id as a human-readable string"
337 (address->string (actor-id actor)))
339 (define (actor-inbox-enq actor)
340 (address-channel (actor-id actor)))
342 (define *current-actor*
345 (define *actor-prompt*
348 (define *resume-io-channel*
351 (define (actor-main-loop actor)
352 "Main loop of the actor. Loops around, pulling messages off its queue
354 ;; @@: Maybe establish some sort of garbage collection routine for these...
357 (define message-handler
358 (actor-message-handler actor))
360 (address-dead? (actor-id actor)))
361 (define prompt (make-prompt-tag (actor-id-actor actor)))
362 ;; Not always used, only if with-actor-nonblocking-ports is used
363 (define resume-io-channel
366 (define (handle-message message)
371 (message-handler actor message))
373 ;; Return reply if necessary
374 (when (message-wants-reply message)
375 (%<- #f actor (message-from message) '*reply*
376 vals ((actor-msg-id-generator actor))
377 (message-id message))))))
379 (let ((err (current-error-port)))
382 (let ((stack (make-stack #t 4)))
383 (format err "Uncaught exception when handling message ~a:\n"
385 (display-backtrace stack err)
386 (print-exception err (stack-ref stack 0)
389 ;; If the other actor is waiting on a reply, let's let them
390 ;; know there was an error...
391 (when (message-wants-reply message)
392 (%<- #f actor (message-from message) '*error*
393 (list key) ((actor-msg-id-generator actor))
394 (message-id message)))))))))
396 (define (resume-handler message)
397 (define in-reply-to (message-in-reply-to message))
399 ((hash-ref waiting in-reply-to) =>
401 (hash-remove! waiting in-reply-to)
404 (format (current-error-port)
405 "Tried to resume nonexistant message: ~a\n"
406 (message-id message)))))
408 (define (call-with-actor-prompt thunk)
409 (call-with-prompt prompt
411 ;; Here's where we abort to if we're doing <-wait
412 ;; @@: maybe use match-lambda if we're going to end up
413 ;; handling multiple ~commands
415 ((kont '<-wait to action message-args)
417 ((actor-msg-id-generator actor)))
418 (hash-set! waiting message-id kont)
419 (%<- #t actor to action message-args message-id #f))
423 (define halt-or-handle-message
424 ;; It would be nice if we could give priorities to certain operations.
425 ;; halt should always win over getting a message...
427 (wrap-operation (wait-operation dead?)
428 (const #f)) ; halt and return
429 (wrap-operation (get-operation (actor-inbox-deq actor))
431 (call-with-actor-prompt
433 (if (message-in-reply-to message)
434 ;; resume a continuation which was waiting on a reply
435 (resume-handler message)
436 ;; start handling a new message
437 (handle-message message))))
439 (wrap-operation (get-operation resume-io-channel)
441 (call-with-actor-prompt
446 ;; Mutate the parameter; this should be fine since each fiber
447 ;; runs in its own dynamic state with with-dynamic-state.
448 ;; See with-dynamic-state discussion in
449 ;; https://wingolog.org/archives/2017/06/27/growing-fibers
450 (*current-actor* actor)
451 (*resume-io-channel* resume-io-channel)
453 ;; We temporarily set the *actor-prompt* to #f to make sure that
454 ;; actor-init! doesn't try to do a <-wait message (and not accidentally use
455 ;; the parent fiber's *actor-prompt* either.)
458 (*actor-prompt* prompt)
461 (and (perform-operation halt-or-handle-message)
465 ;; @@: So in order for this to work, we're going to have to add
466 ;; another channel to actors, which is resumable i/o. We'll have to
467 ;; spawn a fiber that wakes up a thunk on the actor when its port is
468 ;; available. Funky...
470 (define (%suspend-io-to-actor wait-for-read/write)
472 (define prompt (*actor-prompt*))
473 (define resume-channel (*resume-io-channel*))
474 (define (run-at-prompt k)
477 (wait-for-read/write port)
478 ;; okay, we're awake again, tell the actor to resume this
480 (put-message resume-channel k))
483 (error "Attempt to abort to actor prompt outside of actor"))
484 (abort-to-prompt (*actor-prompt*)
485 'run-me run-at-prompt)))
487 (define suspend-read-to-actor
488 (%suspend-io-to-actor (@@ (fibers) wait-for-readable)))
490 (define suspend-write-to-actor
491 (%suspend-io-to-actor (@@ (fibers) wait-for-writable)))
493 (define (with-actor-nonblocking-ports thunk)
494 "Runs THUNK in dynamic context in which attempting to read/write
495 from a port that would otherwise block an actor's correspondence with
496 other actors (note that reading from a nonblocking port should never
497 block other fibers) will instead permit reading other messages while
498 I/O is waiting to complete.
500 Note that currently "
501 (parameterize ((current-read-waiter suspend-read-to-actor)
502 (current-write-waiter suspend-write-to-actor))
505 (define (actor-spawn-fiber thunk . args)
506 "Spawn a fiber from an actor but unset actor-machinery-specific
511 (*resume-io-channel* #f)
521 (define-syntax-rule (define-actor class inherits
524 (define-class class inherits
525 (actions #:init-thunk (build-actions action ...)
526 #:allocation #:each-subclass)
532 ;;; Every actor has a hive, which keeps track of other actors, manages
533 ;;; cleanup, and performs inter-hive communication.
535 ;; TODO: Make this a srfi-9 record type
536 (define-class <hive> ()
537 (id #:init-keyword #:id
539 (actor-registry #:init-thunk make-hash-table
540 #:getter hive-actor-registry)
541 ;; TODO: Rename "ambassadors" to "relays"
542 ;; Ambassadors are used (or will be) for inter-hive communication.
543 ;; These are special actors that know how to route messages to other
545 (ambassadors #:init-thunk make-weak-key-hash-table
546 #:getter hive-ambassadors)
547 (channel #:init-thunk make-channel
548 #:getter hive-channel)
549 (halt? #:init-thunk make-condition
550 #:getter hive-halt?))
552 (define* (make-hive #:key hive-id)
553 (make <hive> #:id (or hive-id
554 (big-random-number-string))))
556 (define (gen-actor-id cookie)
558 (string-append cookie ":" (big-random-number-string))
559 (big-random-number-string)))
561 (define (hive-main-loop hive)
562 "The main loop of the hive. This listens for messages on the hive-channel
563 for certain actions to perform.
565 `messages' here is not the same as a <message> object; these are a list of
566 values, the first value being a symbol"
567 (define channel (hive-channel hive))
568 (define halt? (hive-halt? hive))
569 (define registry (hive-actor-registry hive))
571 ;; not the same as a <message> ;P
572 (define handle-message
574 (('register-actor actor-id address actor)
575 (hash-set! registry actor-id (vector address actor)))
576 ;; Remove the actor from hive
577 (('remove-actor actor-id)
578 (hash-remove! (hive-actor-registry hive) actor-id))
579 (('register-ambassador hive-id ambassador-actor-id)
581 (('unregister-ambassador hive-id ambassador-actor-id)
583 (('forward-message from-actor-id message)
586 (define halt-or-handle
588 (wrap-operation (get-operation channel)
592 (wrap-operation (wait-operation halt?)
596 (and (perform-operation halt-or-handle)
599 (define *hive-id* (make-parameter #f))
600 (define *hive-channel* (make-parameter #f))
602 ;; @@: Should we halt the hive either at the end of spawn-hive or run-hive?
603 (define* (spawn-hive proc #:key (hive (make-hive)))
604 "Spawn a hive and run PROC, passing it the fresh hive and establishing
605 a dynamic context surrounding the hive."
606 (spawn-fiber (lambda () (hive-main-loop hive)))
607 (parameterize ((*hive-id* (hive-id hive))
608 (*hive-channel* (hive-channel hive)))
611 (define (run-hive proc . args)
612 "Spawn a hive and run it in run-fibers. Takes a PROC as would be passed
613 to spawn-hive... all remaining arguments passed to run-fibers."
619 (define (%create-actor actor-class init-args id-cookie send-init?)
620 (let* ((hive-channel (*hive-channel*))
621 (hive-id (*hive-id*))
622 (actor-id (gen-actor-id id-cookie))
623 (dead? (make-condition))
624 (inbox-enq (make-channel))
625 (address (make-address actor-id hive-id
627 (actor (apply make actor-class
630 (should-init (actor-should-init actor)))
632 ;; start the main loop
633 (spawn-fiber (lambda ()
634 ;; start the inbox loop
637 (delivery-agent inbox-enq (actor-inbox-deq actor)
639 ;; this one is decidedly non-parallel, because we want
640 ;; the delivery agent to be in the same thread as its actor
643 (actor-main-loop actor))
646 (put-message hive-channel (list 'register-actor actor-id address actor))
648 ;; return the address
651 (define* (create-actor actor-class #:rest init-args)
652 "Create an instance of actor-class. Return the new actor's id.
654 This is the method actors should call directly (unless they want
655 to supply an id-cookie, in which case they should use
657 (%create-actor actor-class init-args #f #t))
660 (define* (create-actor* actor-class id-cookie #:rest init-args)
661 "Create an instance of actor-class. Return the new actor's id.
663 Like create-actor, but permits supplying an id-cookie."
664 (%create-actor actor-class init-args id-cookie #t))
666 (define* (self-destruct actor #:key (cleanup #t))
667 "Remove an actor from the hive.
669 Unless #:cleanup is set to #f, this will first have the actor handle
670 its '*cleanup* action handler."
671 (signal-condition! (address-dead? (actor-id actor)))
672 (put-message (*hive-channel*) (list 'remove-actor (actor-id-actor actor)))
673 ;; Set *actor-prompt* to nothing to prevent actor-cleanup! from sending
674 ;; a message with <-wait
676 (actor-cleanup! actor))