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 (fibers internal)
36 #:use-module (8sync inbox)
37 #:use-module (8sync rmeta-slot)
39 #:export (;; utilities... ought to go in their own module
41 big-random-number-string
47 ;;; Commenting out the <address> type for now;
48 ;;; it may be back when we have better serializers
51 address-actor-id address-hive-id
58 actor-init! actor-cleanup!
67 with-actor-nonblocking-ports
71 ;; ;; There are more methods for the hive, but there's
72 ;; ;; no reason for the outside world to look at them maybe?
74 create-actor create-actor*
79 message-to message-action message-from
80 message-id message-body message-in-reply-to
88 (set! *random-state* (random-state-from-platform))
90 ;; Same size as a uuid4 I think...
91 (define random-number-size (expt 2 128))
93 (define (big-random-number)
94 (random random-number-size))
96 ;; Would be great to get this base64 encoded instead.
97 (define (big-random-number-string)
98 ;; @@: This is slow. Using format here is wasteful.
99 (format #f "~x" (big-random-number)))
101 ;; @@: This is slow-ish. A mere ~275k / second on my (old) machine.
102 ;; The main cost seems to be in number->string.
103 (define (simple-message-id-generator)
104 ;; Prepending this cookie makes message ids unique per hive
105 (let ((prefix (format #f "~x:" (big-random-number)))
108 (set! counter (1+ counter))
109 (string-append prefix (number->string counter)))))
116 (define-record-type <message>
117 (make-message-intern id to from action
118 body in-reply-to wants-reply)
120 ;; @@: message-ids are removed. They could be re-enabled
121 ;; if we had thread-safe promises...
122 (id message-id) ; id of this message
123 (to message-to) ; actor id this is going to
124 (from message-from) ; actor id of sender
125 (action message-action) ; action (a symbol) to be handled
126 (body message-body) ; argument list "body" of message
127 (in-reply-to message-in-reply-to) ; message id this is in reply to, if any
128 (wants-reply message-wants-reply)) ; whether caller is waiting for reply
131 (define* (make-message id to from action body
132 #:key in-reply-to wants-reply)
133 (make-message-intern id to from action body
134 in-reply-to wants-reply))
136 (define (kwarg-list-to-alist args)
137 (let loop ((remaining args)
140 (((? keyword? key) val rest ...)
142 (cons (cons (keyword->symbol key) val)
145 (_ (throw 'invalid-kwarg-list
146 "Invalid keyword argument list"
150 ;;; See: https://web.archive.org/web/20081223021934/http://mumble.net/~jar/articles/oo-moon-weinreb.html
151 ;;; (also worth seeing: http://mumble.net/~jar/articles/oo.html )
153 ;; This is the internal, generalized message sending method.
154 ;; Users shouldn't use it! Use the <-foo forms instead.
156 (define-inlinable (%<- wants-reply from-actor to action args message-id in-reply-to)
157 ;; Okay, we need to deal with message ids.
158 ;; Could we get rid of them? :\
159 ;; It seems if we can use eq? and have messages be immutable then
160 ;; it should be possible to identify follow-up replies.
161 ;; If we need to track replies across hive boundaries we could
162 ;; register unique ids across the ambassador barrier.
164 (#(_ _ (? channel? channel) dead?)
165 (let ((message (make-message message-id to
166 (and from-actor (actor-id from-actor))
168 #:wants-reply wants-reply
169 #:in-reply-to in-reply-to)))
172 (put-operation channel message)
173 (wait-operation dead?)))))
174 ;; TODO: put remote addresses here.
175 (#(actor-id hive-id #f #f)
176 ;; Here we'd make a call to our hive...
178 ;; A message sent to nobody goes nowhere.
179 ;; TODO: Should we display a warning here, probably?
182 (define (<- to action . args)
183 (define from-actor (*current-actor*))
184 (%<- #f from-actor to action args
186 ((actor-msg-id-generator from-actor)))
187 (big-random-number-string))
190 ;; TODO: this should abort to the prompt, then check for errors
193 (define (<-wait to action . args)
194 (define prompt (*actor-prompt*))
196 (error "Tried to <-wait without being in an actor's context..."))
198 (let ((reply (abort-to-prompt prompt '<-wait to action args)))
199 (cond ((eq? action '*error*)
200 (throw 'hive-unresumable-coroutine
201 "Won't resume coroutine; got an *error* as a reply"
203 (else (apply values (message-body reply))))))
206 ;;; Main actor implementation
207 ;;; =========================
209 (define (actor-inheritable-message-handler actor message)
210 (define action (message-action message))
212 (class-rmeta-ref (class-of actor) 'actions action
213 #:equals? eq? #:cache-set! hashq-set!
214 #:cache-ref hashq-ref))
216 (throw 'action-not-found
217 "No appropriate action handler found for actor"
221 (apply method actor message (message-body message)))
223 (define-syntax-rule (wrap-apply body)
224 "Wrap possibly multi-value function in a procedure, applies all arguments"
228 (define-syntax-rule (build-actions (symbol method) ...)
229 "Construct an alist of (symbol . method), where the method is wrapped
230 with wrap-apply to facilitate live hacking and allow the method definition
231 to come after class definition."
233 (list (cons (quote symbol)
234 (wrap-apply method)) ...)))
236 (define-class <actor> ()
237 ;; An address object... a vector of #(actor-id hive-id inbox-channel dead?)
238 ;; - inbox-channel is the receiving channel (as opposed to actor-inbox-deq)
239 ;; - dead? is a fibers condition variable which is set once this actor
241 (id #:init-keyword #:address
244 ;; Our queue to send/receive messages on
245 (inbox-deq #:init-thunk make-channel
246 #:accessor actor-inbox-deq)
248 (msg-id-generator #:init-thunk simple-message-id-generator
249 #:getter actor-msg-id-generator)
251 ;; How we receive and process new messages
252 (message-handler #:init-value actor-inheritable-message-handler
253 ;; @@: There's no reason not to use #:class instead of
254 ;; #:each-subclass anywhere in this file, except for
255 ;; Guile bug #25211 (#:class is broken in Guile 2.2)
256 #:allocation #:each-subclass
257 #:getter actor-message-handler)
260 ;; - #t as in, send the init message, but don't wait (default)
261 ;; - 'wait, as in wait on the init message
262 ;; - #f as in don't bother to init
263 (should-init #:init-value #t
264 #:getter actor-should-init
265 #:allocation #:each-subclass)
267 ;; This is the default, "simple" way to inherit and process messages.
268 (actions #:init-thunk (build-actions)
269 #:allocation #:each-subclass))
271 ;;; Actors may specify an "init" action that occurs before the actor
272 ;;; actually begins to run.
273 ;;; During actor-init!, an actor may send a message to itself or others
274 ;;; via <- but *may not* use <-wait.
275 (define-method (actor-init! (actor <actor>))
278 (define-method (actor-cleanup! (actor <actor>))
281 ;;; Addresses are vectors where the first part is the actor-id and
282 ;;; the second part is the hive-id. This works well enough... they
283 ;;; look decent being pretty-printed.
285 (define (make-address actor-id hive-id channel dead?)
286 (vector actor-id hive-id channel dead?))
288 (define (address-actor-id address)
289 (vector-ref address 0))
291 (define (address-hive-id address)
292 (vector-ref address 1))
294 (define (address-channel address)
295 (vector-ref address 2))
297 (define (address-dead? address)
298 (vector-ref address 3))
300 (define (address->string address)
301 (string-append (address-actor-id address) "@"
302 (address-hive-id address)))
304 (define (address-equal? address1 address2)
305 "Check whether or not the two addresses are equal.
307 This compares the actor-id and hive-id but ignores the channel and
310 (#(actor-id-1 hive-id-1 _ _)
312 (#(actor-id-2 hive-id-2)
313 (and (equal? actor-id-1 actor-id-2)
314 (and (equal? hive-id-1 hive-id-2))))
318 (define (actor-id-actor actor)
319 "Get the actor id component of the actor-id"
320 (address-actor-id (actor-id actor)))
322 (define (actor-id-hive actor)
323 "Get the hive id component of the actor-id"
324 (address-hive-id (actor-id actor)))
326 (define (actor-id-string actor)
327 "Render the full actor id as a human-readable string"
328 (address->string (actor-id actor)))
330 (define (actor-inbox-enq actor)
331 (address-channel (actor-id actor)))
333 (define *current-actor*
336 (define *actor-prompt*
339 (define *resume-io-channel*
342 (define (actor-main-loop actor)
343 "Main loop of the actor. Loops around, pulling messages off its queue
345 ;; @@: Maybe establish some sort of garbage collection routine for these...
348 (define message-handler
349 (actor-message-handler actor))
351 (address-dead? (actor-id actor)))
352 (define prompt (make-prompt-tag (actor-id-actor actor)))
353 ;; Not always used, only if with-actor-nonblocking-ports is used
354 (define resume-io-channel
357 (define (handle-message message)
362 (message-handler actor message))
364 ;; Return reply if necessary
365 (when (message-wants-reply message)
366 (when (message-wants-reply message)
367 (%<- #f actor (message-from message) '*reply*
368 vals ((actor-msg-id-generator actor))
369 (message-id message)))))))
371 (let ((err (current-error-port)))
374 (let ((stack (make-stack #t 4)))
375 (format err "Uncaught exception when handling message ~a:\n"
377 (display-backtrace stack err)
378 (print-exception err (stack-ref stack 0)
381 ;; If the other actor is waiting on a reply, let's let them
382 ;; know there was an error...
383 (when (message-wants-reply message)
384 (%<- #f actor (message-from message) '*error*
385 (list key) ((actor-msg-id-generator actor))
386 (message-id message)))))))))
388 (define (resume-handler message)
389 (define in-reply-to (message-in-reply-to message))
391 ((hash-ref waiting in-reply-to) =>
393 (hash-remove! waiting in-reply-to)
396 (format (current-error-port)
397 "Tried to resume nonexistant message: ~a\n"
398 (message-id message)))))
400 (define (call-with-actor-prompt thunk)
401 (call-with-prompt prompt
403 ;; Here's where we abort to if we're doing <-wait
404 ;; @@: maybe use match-lambda if we're going to end up
405 ;; handling multiple ~commands
407 ((kont '<-wait to action message-args)
409 ((actor-msg-id-generator actor)))
410 (hash-set! waiting message-id kont)
411 (%<- #t actor to action message-args message-id #f))
415 (define halt-or-handle-message
416 ;; It would be nice if we could give priorities to certain operations.
417 ;; halt should always win over getting a message...
419 (wrap-operation (wait-operation dead?)
420 (const #f)) ; halt and return
421 (wrap-operation (get-operation (actor-inbox-deq actor))
423 (call-with-actor-prompt
425 (if (message-in-reply-to message)
426 ;; resume a continuation which was waiting on a reply
427 (resume-handler message)
428 ;; start handling a new message
429 (handle-message message))))
431 (wrap-operation (get-operation resume-io-channel)
433 (call-with-actor-prompt
438 ;; Mutate the parameter; this should be fine since each fiber
439 ;; runs in its own dynamic state with with-dynamic-state.
440 ;; See with-dynamic-state discussion in
441 ;; https://wingolog.org/archives/2017/06/27/growing-fibers
442 (*current-actor* actor)
443 (*resume-io-channel* resume-io-channel)
445 ;; We temporarily set the *actor-prompt* to #f to make sure that
446 ;; actor-init! doesn't try to do a <-wait message (and not accidentally use
447 ;; the parent fiber's *actor-prompt* either.)
450 (*actor-prompt* prompt)
453 (and (perform-operation halt-or-handle-message)
457 ;; @@: So in order for this to work, we're going to have to add
458 ;; another channel to actors, which is resumable i/o. We'll have to
459 ;; spawn a fiber that wakes up a thunk on the actor when its port is
460 ;; available. Funky...
462 (define (%suspend-io-to-actor resume-method get-wait-fd-method)
464 (define prompt (*actor-prompt*))
465 (define resume-channel (*resume-io-channel*))
466 (define (run-at-prompt k)
469 (suspend-current-fiber
471 (resume-on-readable-fd (port-read-wait-fd port) fiber)))
472 ;; okay, we're awake again, tell the actor to resume this
474 (put-message resume-channel k))
477 (error "Attempt to abort to actor prompt outside of actor"))
478 (abort-to-prompt (*actor-prompt*)
479 'run-me run-at-prompt)))
481 (define suspend-read-to-actor
482 (%suspend-io-to-actor resume-on-readable-fd port-read-wait-fd))
484 (define suspend-write-to-actor
485 (%suspend-io-to-actor resume-on-writable-fd port-write-wait-fd))
487 (define (with-actor-nonblocking-ports thunk)
488 "Runs THUNK in dynamic context in which attempting to read/write
489 from a port that would otherwise block an actor's correspondence with
490 other actors (note that reading from a nonblocking port should never
491 block other fibers) will instead permit reading other messages while
492 I/O is waiting to complete.
494 Note that currently "
495 (parameterize ((current-read-waiter suspend-read-to-actor)
496 (current-write-waiter suspend-write-to-actor))
499 (define (actor-spawn-fiber thunk . args)
500 "Spawn a fiber from an actor but unset actor-machinery-specific
505 (*resume-io-channel* #f)
515 (define-syntax-rule (define-actor class inherits
518 (define-class class inherits
519 (actions #:init-thunk (build-actions action ...)
520 #:allocation #:each-subclass)
526 ;;; Every actor has a hive, which keeps track of other actors, manages
527 ;;; cleanup, and performs inter-hive communication.
529 ;; TODO: Make this a srfi-9 record type
530 (define-class <hive> ()
531 (id #:init-keyword #:id
533 (actor-registry #:init-thunk make-hash-table
534 #:getter hive-actor-registry)
535 ;; TODO: Rename "ambassadors" to "relays"
536 ;; Ambassadors are used (or will be) for inter-hive communication.
537 ;; These are special actors that know how to route messages to other
539 (ambassadors #:init-thunk make-weak-key-hash-table
540 #:getter hive-ambassadors)
541 (channel #:init-thunk make-channel
542 #:getter hive-channel)
543 (halt? #:init-thunk make-condition
544 #:getter hive-halt?))
546 (define* (make-hive #:key hive-id)
547 (make <hive> #:id (or hive-id
548 (big-random-number-string))))
550 (define (gen-actor-id cookie)
552 (string-append cookie ":" (big-random-number-string))
553 (big-random-number-string)))
555 (define (hive-main-loop hive)
556 "The main loop of the hive. This listens for messages on the hive-channel
557 for certain actions to perform.
559 `messages' here is not the same as a <message> object; these are a list of
560 values, the first value being a symbol"
561 (define channel (hive-channel hive))
562 (define halt? (hive-halt? hive))
563 (define registry (hive-actor-registry hive))
565 ;; not the same as a <message> ;P
566 (define handle-message
568 (('register-actor actor-id address actor)
569 (hash-set! registry actor-id (vector address actor)))
570 ;; Remove the actor from hive
571 (('remove-actor actor-id)
572 (hash-remove! (hive-actor-registry hive) actor-id))
573 (('register-ambassador hive-id ambassador-actor-id)
575 (('unregister-ambassador hive-id ambassador-actor-id)
577 (('forward-message from-actor-id message)
580 (define halt-or-handle
582 (wrap-operation (get-operation channel)
586 (wrap-operation (wait-operation halt?)
590 (and (perform-operation halt-or-handle)
593 (define *hive-id* (make-parameter #f))
594 (define *hive-channel* (make-parameter #f))
596 ;; @@: Should we halt the hive either at the end of spawn-hive or run-hive?
597 (define* (spawn-hive proc #:key (hive (make-hive)))
598 "Spawn a hive and run PROC, passing it the fresh hive and establishing
599 a dynamic context surrounding the hive."
600 (spawn-fiber (lambda () (hive-main-loop hive)))
601 (parameterize ((*hive-id* (hive-id hive))
602 (*hive-channel* (hive-channel hive)))
605 (define (run-hive proc . args)
606 "Spawn a hive and run it in run-fibers. Takes a PROC as would be passed
607 to spawn-hive... all remaining arguments passed to run-fibers."
613 (define (%create-actor actor-class init-args id-cookie send-init?)
614 (let* ((hive-channel (*hive-channel*))
615 (hive-id (*hive-id*))
616 (actor-id (gen-actor-id id-cookie))
617 (dead? (make-condition))
618 (inbox-enq (make-channel))
619 (address (make-address actor-id hive-id
621 (actor (apply make actor-class
624 (should-init (actor-should-init actor)))
626 ;; start the main loop
627 (spawn-fiber (lambda ()
628 ;; start the inbox loop
631 (delivery-agent inbox-enq (actor-inbox-deq actor)
633 ;; this one is decidedly non-parallel, because we want
634 ;; the delivery agent to be in the same thread as its actor
637 (actor-main-loop actor))
640 (put-message hive-channel (list 'register-actor actor-id address actor))
642 ;; return the address
645 (define* (create-actor actor-class #:rest init-args)
646 "Create an instance of actor-class. Return the new actor's id.
648 This is the method actors should call directly (unless they want
649 to supply an id-cookie, in which case they should use
651 (%create-actor actor-class init-args #f #t))
654 (define* (create-actor* actor-class id-cookie #:rest init-args)
655 "Create an instance of actor-class. Return the new actor's id.
657 Like create-actor, but permits supplying an id-cookie."
658 (%create-actor actor-class init-args id-cookie #t))
660 (define* (self-destruct actor #:key (cleanup #t))
661 "Remove an actor from the hive.
663 Unless #:cleanup is set to #f, this will first have the actor handle
664 its '*cleanup* action handler."
665 (signal-condition! (address-dead? (actor-id actor)))
666 (put-message (*hive-channel*) (list 'remove-actor (actor-id-actor actor)))
667 ;; Set *actor-prompt* to nothing to prevent actor-cleanup! from sending
668 ;; a message with <-wait
670 (actor-cleanup! actor))
672 ;; From a patch I sent to Fibers...
673 (define (condition-signalled? cvar)
674 "Return @code{#t} if @var{cvar} has already been signalled.
676 In general you will want to use @code{wait} or @code{wait-operation} to
677 wait on a condition. However, sometimes it is useful to see whether or
678 not a condition has already been signalled without blocking."
679 (atomic-box-ref ((@@ (fibers conditions) condition-signalled?) cvar)))
681 (define (actor-alive? actor)
682 (condition-signalled? (address-dead? (actor-id actor))))