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 (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 atomic)
27 #:use-module ((ice-9 ports internal)
28 #:select (port-read-wait-fd port-write-wait-fd))
29 #:use-module (ice-9 pretty-print)
30 #:use-module (ice-9 receive)
31 #:use-module (ice-9 suspendable-ports)
33 #:use-module (fibers channels)
34 #:use-module (fibers conditions)
35 #:use-module (fibers operations)
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
49 ;;; Commenting out the <address> type for now;
50 ;;; it may be back when we have better serializers
53 address-actor-id address-hive-id
60 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
87 ;; Maybe the wrong place for this, or for it to be exported.
88 ;; But it's used in websockets' server implementation at least...
92 (set! *random-state* (random-state-from-platform))
94 ;; Same size as a uuid4 I think...
95 (define random-number-size (expt 2 128))
97 (define (big-random-number)
98 (random random-number-size))
100 ;; Would be great to get this base64 encoded instead.
101 (define (big-random-number-string)
102 ;; @@: This is slow. Using format here is wasteful.
103 (format #f "~x" (big-random-number)))
105 ;; @@: This is slow-ish. A mere ~275k / second on my (old) machine.
106 ;; The main cost seems to be in number->string.
107 (define (simple-message-id-generator)
108 ;; Prepending this cookie makes message ids unique per hive
109 (let ((prefix (format #f "~x:" (big-random-number)))
112 (set! counter (1+ counter))
113 (string-append prefix (number->string counter)))))
120 (define-record-type <message>
121 (make-message-intern id to from action
122 body in-reply-to wants-reply)
124 ;; @@: message-ids are removed. They could be re-enabled
125 ;; if we had thread-safe promises...
126 (id message-id) ; id of this message
127 (to message-to) ; actor id this is going to
128 (from message-from) ; actor id of sender
129 (action message-action) ; action (a symbol) to be handled
130 (body message-body) ; argument list "body" of message
131 (in-reply-to message-in-reply-to) ; message id this is in reply to, if any
132 (wants-reply message-wants-reply)) ; whether caller is waiting for reply
135 (define* (make-message id to from action body
136 #:key in-reply-to wants-reply)
137 (make-message-intern id to from action body
138 in-reply-to wants-reply))
140 (define (kwarg-list-to-alist args)
141 (let loop ((remaining args)
144 (((? keyword? key) val rest ...)
146 (cons (cons (keyword->symbol key) val)
149 (_ (throw 'invalid-kwarg-list
150 "Invalid keyword argument list"
154 ;;; See: https://web.archive.org/web/20081223021934/http://mumble.net/~jar/articles/oo-moon-weinreb.html
155 ;;; (also worth seeing: http://mumble.net/~jar/articles/oo.html )
157 ;; This is the internal, generalized message sending method.
158 ;; Users shouldn't use it! Use the <-foo forms instead.
160 (define (%<- wants-reply from-actor to action args message-id in-reply-to)
161 ;; Okay, we need to deal with message ids.
162 ;; Could we get rid of them? :\
163 ;; It seems if we can use eq? and have messages be immutable then
164 ;; it should be possible to identify follow-up replies.
165 ;; If we need to track replies across hive boundaries we could
166 ;; register unique ids across the ambassador barrier.
168 (($ <address> _ _ (? channel? channel) dead?)
169 (let ((message (make-message message-id to
170 (and from-actor (actor-id from-actor))
172 #:wants-reply wants-reply
173 #:in-reply-to in-reply-to)))
176 (put-operation channel message)
177 (wait-operation dead?)))))
178 ;; TODO: put remote addresses here.
179 (($ <address> actor-id hive-id #f #f)
180 ;; Here we'd make a call to our hive...
182 ;; A message sent to nobody goes nowhere.
183 ;; TODO: Should we display a warning here, probably?
185 ;; We shouldn't technically be passing in actors but rather their
186 ;; addresses, but often actors want to message themselves and
187 ;; this makes that slightly easier.
188 ((? (lambda (x) (is-a? x <actor>)) actor)
189 (%<- wants-reply from-actor (actor-id actor) action
190 args message-id in-reply-to))))
192 (define (<- to action . args)
193 (define from-actor (*current-actor*))
194 (%<- #f from-actor to action args
196 ((actor-msg-id-generator from-actor)))
197 (big-random-number-string))
200 (define (<-wait to action . args)
201 (define prompt (*actor-prompt*))
203 (error "Tried to <-wait without being in an actor's context..."))
205 (let ((reply (abort-to-prompt prompt '<-wait to action args)))
206 (cond ((eq? (message-action reply) '*error*)
207 (throw 'hive-unresumable-coroutine
208 "Won't resume coroutine; got an *error* as a reply"
210 (else (apply values (message-body reply))))))
213 ;;; Main actor implementation
214 ;;; =========================
216 (define (actor-inheritable-message-handler actor message)
217 (define action (message-action message))
219 (class-rmeta-ref (class-of actor) 'actions action
220 #:equals? eq? #:cache-set! hashq-set!
221 #:cache-ref hashq-ref))
223 (throw 'action-not-found
224 "No appropriate action handler found for actor"
228 (apply method actor message (message-body message)))
230 (define-syntax-rule (live-wrap body)
231 "Wrap possibly multi-value function in a procedure, applies all arguments"
235 (define-syntax-rule (build-actions (symbol method) ...)
236 "Construct an alist of (symbol . method), where the method is wrapped
237 with `live-wrap' to facilitate live hacking and allow the method definition
238 to come after class definition."
240 (list (cons (quote symbol)
241 (live-wrap method)) ...)))
243 (define-class <actor> ()
244 ;; An <address> object
245 (id #:init-keyword #:address
248 ;; Our queue to send/receive messages on
249 (inbox-deq #:init-thunk make-channel
250 #:accessor actor-inbox-deq)
252 (msg-id-generator #:init-thunk simple-message-id-generator
253 #:getter actor-msg-id-generator)
255 ;; How we receive and process new messages
256 (message-handler #:init-value actor-inheritable-message-handler
257 ;; @@: There's no reason not to use #:class instead of
258 ;; #:each-subclass anywhere in this file, except for
259 ;; Guile bug #25211 (#:class is broken in Guile 2.2)
260 #:allocation #:each-subclass
261 #:getter actor-message-handler)
264 ;; - #t as in, send the init message, but don't wait (default)
265 ;; - 'wait, as in wait on the init message
266 ;; - #f as in don't bother to init
267 (should-init #:init-value #t
268 #:getter actor-should-init
269 #:allocation #:each-subclass)
271 ;; This is the default, "simple" way to inherit and process messages.
272 (actions #:init-thunk (build-actions)
273 #:allocation #:each-subclass))
275 ;;; Actors may specify an "init" action that occurs before the actor
276 ;;; actually begins to run.
277 ;;; During actor-init!, an actor may send a message to itself or others
278 ;;; via <- but *may not* use <-wait.
279 (define-method (actor-init! (actor <actor>))
282 (define-method (actor-cleanup! (actor <actor>))
285 ;;; Every actor has an address, which is how its identified.
286 ;;; We also pack in some routing information.
287 (define-record-type <address>
288 (make-address actor-id hive-id channel dead?)
290 ;; Unique-to-this-actor-on-this-hive part
291 (actor-id address-actor-id)
292 ;; Unique identifier for the hive we're connected to.
293 ;; If we don't have a "direct" link to the other actor through
294 ;; a channel, we'll have to look up if our hive has a way to route
295 ;; to the other hive.
296 (hive-id address-hive-id)
297 ;; The receiving channel (as opposed to actor-inbox-deq)
298 (channel address-channel)
299 ;; A fibers condition variable which is set once this actor kicks
301 (dead? address-dead?))
303 (set-record-type-printer!
305 (lambda (address port)
306 (format port "<address ~a ~a>"
307 (address->string address)
308 (if (address-channel address)
312 ((@@ (fibers conditions) condition-signalled?)
313 (address-dead? address)))
317 (define (address->string address)
318 (string-append (address-actor-id address) "@"
319 (address-hive-id address)))
321 (define (address-equal? address1 address2)
322 "Check whether or not the two addresses are equal.
324 This compares the actor-id and hive-id but ignores the channel and
326 (and (equal? (address-actor-id address1)
327 (address-actor-id address2))
328 (equal? (address-hive-id address1)
329 (address-hive-id address2))))
331 (define (actor-id-actor actor)
332 "Get the actor id component of the actor-id"
333 (address-actor-id (actor-id actor)))
335 (define (actor-id-hive actor)
336 "Get the hive id component of the actor-id"
337 (address-hive-id (actor-id actor)))
339 (define (actor-id-string actor)
340 "Render the full actor id as a human-readable string"
341 (address->string (actor-id actor)))
343 (define (actor-inbox-enq actor)
344 (address-channel (actor-id actor)))
346 (define *current-actor*
349 (define *actor-prompt*
352 (define *resume-io-channel*
355 (define (actor-main-loop actor)
356 "Main loop of the actor. Loops around, pulling messages off its queue
358 ;; @@: Maybe establish some sort of garbage collection routine for these...
361 (define message-handler
362 (actor-message-handler actor))
364 (address-dead? (actor-id actor)))
365 (define prompt (make-prompt-tag (actor-id-actor actor)))
366 ;; Not always used, only if with-actor-nonblocking-ports is used
367 (define resume-io-channel
370 (define (handle-message message)
375 (message-handler actor message))
377 ;; Return reply if necessary
378 (when (message-wants-reply message)
379 (%<- #f actor (message-from message) '*reply*
380 vals ((actor-msg-id-generator actor))
381 (message-id message))))))
383 (let ((err (current-error-port)))
386 (let ((stack (make-stack #t 4)))
387 (format err "Uncaught exception when handling message ~a:\n"
389 (display-backtrace stack err)
390 (print-exception err (stack-ref stack 0)
393 ;; If the other actor is waiting on a reply, let's let them
394 ;; know there was an error...
395 (when (message-wants-reply message)
396 (%<- #f actor (message-from message) '*error*
397 (list key) ((actor-msg-id-generator actor))
398 (message-id message)))))))))
400 (define (resume-handler message)
401 (define in-reply-to (message-in-reply-to message))
403 ((hash-ref waiting in-reply-to) =>
405 (hash-remove! waiting in-reply-to)
408 (format (current-error-port)
409 "Tried to resume nonexistant message: ~a\n"
410 (message-id message)))))
412 (define (call-with-actor-prompt thunk)
413 (call-with-prompt prompt
415 ;; Here's where we abort to if we're doing <-wait
416 ;; @@: maybe use match-lambda if we're going to end up
417 ;; handling multiple ~commands
419 ((kont '<-wait to action message-args)
421 ((actor-msg-id-generator actor)))
422 (hash-set! waiting message-id kont)
423 (%<- #t actor to action message-args message-id #f))
427 (define halt-or-handle-message
428 ;; It would be nice if we could give priorities to certain operations.
429 ;; halt should always win over getting a message...
431 (wrap-operation (wait-operation dead?)
432 (const #f)) ; halt and return
433 (wrap-operation (get-operation (actor-inbox-deq actor))
435 (call-with-actor-prompt
437 (if (message-in-reply-to message)
438 ;; resume a continuation which was waiting on a reply
439 (resume-handler message)
440 ;; start handling a new message
441 (handle-message message))))
443 (wrap-operation (get-operation resume-io-channel)
445 (call-with-actor-prompt
450 ;; Mutate the parameter; this should be fine since each fiber
451 ;; runs in its own dynamic state with with-dynamic-state.
452 ;; See with-dynamic-state discussion in
453 ;; https://wingolog.org/archives/2017/06/27/growing-fibers
454 (*current-actor* actor)
455 (*resume-io-channel* resume-io-channel)
457 ;; We temporarily set the *actor-prompt* to #f to make sure that
458 ;; actor-init! doesn't try to do a <-wait message (and not accidentally use
459 ;; the parent fiber's *actor-prompt* either.)
462 (*actor-prompt* prompt)
465 (and (perform-operation halt-or-handle-message)
469 ;; @@: So in order for this to work, we're going to have to add
470 ;; another channel to actors, which is resumable i/o. We'll have to
471 ;; spawn a fiber that wakes up a thunk on the actor when its port is
472 ;; available. Funky...
474 (define (%suspend-io-to-actor wait-for-read/write)
476 (define prompt (*actor-prompt*))
477 (define resume-channel (*resume-io-channel*))
478 (define (run-at-prompt k)
481 (wait-for-read/write port)
482 ;; okay, we're awake again, tell the actor to resume this
484 (put-message resume-channel k))
487 (error "Attempt to abort to actor prompt outside of actor"))
488 (abort-to-prompt (*actor-prompt*)
489 'run-me run-at-prompt)))
491 (define suspend-read-to-actor
492 (%suspend-io-to-actor (@@ (fibers) wait-for-readable)))
494 (define suspend-write-to-actor
495 (%suspend-io-to-actor (@@ (fibers) wait-for-writable)))
497 (define (with-actor-nonblocking-ports thunk)
498 "Runs THUNK in dynamic context in which attempting to read/write
499 from a port that would otherwise block an actor's correspondence with
500 other actors (note that reading from a nonblocking port should never
501 block other fibers) will instead permit reading other messages while
502 I/O is waiting to complete.
504 Note that currently "
505 (parameterize ((current-read-waiter suspend-read-to-actor)
506 (current-write-waiter suspend-write-to-actor))
509 (define (actor-spawn-fiber thunk . args)
510 "Spawn a fiber from an actor but unset actor-machinery-specific
515 (*resume-io-channel* #f)
525 (define-syntax-rule (define-actor class inherits
528 (define-class class inherits
529 (actions #:init-thunk (build-actions action ...)
530 #:allocation #:each-subclass)
536 ;;; Every actor has a hive, which keeps track of other actors, manages
537 ;;; cleanup, and performs inter-hive communication.
539 ;; TODO: Make this a srfi-9 record type
540 (define-class <hive> ()
541 (id #:init-keyword #:id
543 (actor-registry #:init-thunk make-hash-table
544 #:getter hive-actor-registry)
545 ;; TODO: Rename "ambassadors" to "relays"
546 ;; Ambassadors are used (or will be) for inter-hive communication.
547 ;; These are special actors that know how to route messages to other
549 (ambassadors #:init-thunk make-weak-key-hash-table
550 #:getter hive-ambassadors)
551 (channel #:init-thunk make-channel
552 #:getter hive-channel)
553 (halt? #:init-thunk make-condition
554 #:getter hive-halt?))
556 (define* (make-hive #:key hive-id)
557 (make <hive> #:id (or hive-id
558 (big-random-number-string))))
560 (define (gen-actor-id cookie)
562 (string-append cookie ":" (big-random-number-string))
563 (big-random-number-string)))
565 (define (hive-main-loop hive)
566 "The main loop of the hive. This listens for messages on the hive-channel
567 for certain actions to perform.
569 `messages' here is not the same as a <message> object; these are a list of
570 values, the first value being a symbol"
571 (define channel (hive-channel hive))
572 (define halt? (hive-halt? hive))
573 (define registry (hive-actor-registry hive))
575 ;; not the same as a <message> ;P
576 (define handle-message
578 (('register-actor actor-id address actor)
579 (hash-set! registry actor-id (vector address actor)))
580 ;; Remove the actor from hive
581 (('remove-actor actor-id)
582 (hash-remove! (hive-actor-registry hive) actor-id))
583 (('register-ambassador hive-id ambassador-actor-id)
585 (('unregister-ambassador hive-id ambassador-actor-id)
587 (('forward-message from-actor-id message)
590 (define halt-or-handle
592 (wrap-operation (get-operation channel)
596 (wrap-operation (wait-operation halt?)
600 (and (perform-operation halt-or-handle)
603 (define *hive-id* (make-parameter #f))
604 (define *hive-channel* (make-parameter #f))
606 ;; @@: Should we halt the hive either at the end of spawn-hive or run-hive?
607 (define* (spawn-hive proc #:key (hive (make-hive)))
608 "Spawn a hive and run PROC, passing it the fresh hive and establishing
609 a dynamic context surrounding the hive."
610 (spawn-fiber (lambda () (hive-main-loop hive)))
611 (parameterize ((*hive-id* (hive-id hive))
612 (*hive-channel* (hive-channel hive)))
615 (define (run-hive proc . args)
616 "Spawn a hive and run it in run-fibers. Takes a PROC as would be passed
617 to spawn-hive... all remaining arguments passed to run-fibers."
623 (define (%create-actor actor-class init-args id-cookie send-init?)
624 (let* ((hive-channel (*hive-channel*))
625 (hive-id (*hive-id*))
626 (actor-id (gen-actor-id id-cookie))
627 (dead? (make-condition))
628 (inbox-enq (make-channel))
629 (address (make-address actor-id hive-id
631 (actor (apply make actor-class
634 (should-init (actor-should-init actor)))
636 ;; start the main loop
637 (spawn-fiber (lambda ()
638 ;; start the inbox loop
641 (delivery-agent inbox-enq (actor-inbox-deq actor)
643 ;; this one is decidedly non-parallel, because we want
644 ;; the delivery agent to be in the same thread as its actor
647 (actor-main-loop actor))
650 (put-message hive-channel (list 'register-actor actor-id address actor))
652 ;; return the address
655 (define* (create-actor actor-class #:rest init-args)
656 "Create an instance of actor-class. Return the new actor's id.
658 This is the method actors should call directly (unless they want
659 to supply an id-cookie, in which case they should use
661 (%create-actor actor-class init-args #f #t))
664 (define* (create-actor* actor-class id-cookie #:rest init-args)
665 "Create an instance of actor-class. Return the new actor's id.
667 Like create-actor, but permits supplying an id-cookie."
668 (%create-actor actor-class init-args id-cookie #t))
670 (define* (self-destruct actor #:key (cleanup #t))
671 "Remove an actor from the hive.
673 Unless #:cleanup is set to #f, this will first have the actor handle
674 its '*cleanup* action handler."
675 (signal-condition! (address-dead? (actor-id actor)))
676 (put-message (*hive-channel*) (list 'remove-actor (actor-id-actor actor)))
677 ;; Set *actor-prompt* to nothing to prevent actor-cleanup! from sending
678 ;; a message with <-wait
680 (actor-cleanup! actor))