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
41 ;;; Commenting out the <address> type for now;
42 ;;; it may be back when we have better serializers
45 address-actor-id address-hive-id
57 ;; There are more methods for the hive, but there's
58 ;; no reason for the outside world to look at them maybe?
60 hive-create-actor hive-create-actor*
64 message-to message-action message-from
65 message-id message-body message-in-reply-to
69 send-message send-message-wait
70 reply-message reply-message-wait
73 hive-bootstrap-message
75 serialize-message write-message
76 serialize-message-pretty pprint-message
77 read-message read-message-from-string))
81 (make-parameter (random-state-from-platform)))
83 ;; Probably bigger than necessary
84 (define random-number-size (expt 10 50))
86 (define (big-random-number)
87 (random random-number-size (%random-state)))
89 ;; Would be great to get this base64 encoded instead.
90 (define (big-random-number-string)
91 ;; @@: This is slow. Using format here is wasteful.
92 (format #f "~x" (big-random-number)))
94 ;; @@: This is slow. A mere ~275k / second on my (old) machine.
95 ;; The main cost seems to be in number->string.
96 (define (simple-message-id-generator)
97 ;; Prepending this cookie makes message ids unique per hive
98 (let ((prefix (format #f "~x:" (big-random-number)))
101 (set! counter (1+ counter))
102 (string-append prefix (number->string counter)))))
104 (define (require-slot slot-name)
105 "Generate something for #:init-thunk to complain about unfilled slot"
107 (throw 'required-slot
108 (format #f "Slot ~s not filled" slot-name)
117 (define-record-type <message>
118 (make-message-intern id to from action
119 body in-reply-to wants-reply ; do we need hive-proxy?
120 ;; Are these still needed?
121 replied deferred-reply)
126 (action message-action)
128 (in-reply-to message-in-reply-to)
129 (wants-reply message-wants-reply)
131 ;; See XUDD source for these. Not use yet, maybe eventually will be?
132 ;; XUDD uses them for autoreply.
133 ;; Requiring mutation on message objects is clearly not great,
134 ;; but it may be worth it...? Investigate!
135 (replied message-replied set-message-replied!)
136 (deferred-reply message-deferred-reply set-message-deferred-reply!))
139 (define* (make-message id to from action body
140 #:key in-reply-to wants-reply
141 replied deferred-reply)
142 (make-message-intern id to from action body
143 in-reply-to wants-reply replied
146 ;; Note: the body of messages is currently an alist, but it's created
147 ;; from a keyword based property list (see the following two functions).
148 ;; But, that's an extra conversion step, and maybe totally unnecessary:
149 ;; we already have message-ref, and this could just pull a keyword
150 ;; from a property list.
151 ;; The main ways this might be useful are error checking,
152 ;; serialization across the wire (but even that might require some
153 ;; change), and using existing tooling (though adding new tooling
154 ;; would be negligible in implementation effort.)
156 ;; This cons cell is immutable and unique (for eq? tests)
157 (define %nothing-provided (cons 'nothing 'provided))
159 (define* (message-ref message key #:optional (dflt %nothing-provided))
160 "Extract KEY from body of MESSAGE.
162 Optionally set default with [DFLT]
163 If key not found and DFLT not provided, throw an error."
164 (let ((result (assoc key (message-body message))))
165 (if result (cdr result)
166 (if (eq? dflt %nothing-provided)
167 (throw 'message-missing-key
168 "Message body does not contain key and no default provided"
174 (define (kwarg-list-to-alist args)
175 (let loop ((remaining args)
178 (((? keyword? key) val rest ...)
180 (cons (cons (keyword->symbol key) val)
183 (_ (throw 'invalid-kwarg-list
184 "Invalid keyword argument list"
188 (define (send-message from-actor to-id action . message-body-args)
189 "Send a message from an actor to another actor"
190 (let* ((hive (actor-hive from-actor))
191 (message (make-message (hive-gen-message-id hive) to-id
192 (actor-id from-actor) action
193 (kwarg-list-to-alist message-body-args))))
194 (8sync (hive-process-message hive message))))
196 (define (send-message-wait from-actor to-id action . message-body-args)
197 "Send a message from an actor to another, but wait until we get a response"
198 (let* ((hive (actor-hive from-actor))
199 (agenda-prompt (hive-prompt (actor-hive from-actor)))
200 (message (make-message (hive-gen-message-id hive) to-id
201 (actor-id from-actor) action
202 (kwarg-list-to-alist message-body-args)
204 (abort-to-prompt agenda-prompt from-actor message)))
206 ;; TODO: Intelligently ~propagate(ish) errors on -wait functions.
207 ;; We might have `send-message-wait-brazen' to allow callers to
208 ;; not have an exception thrown and instead just have a message with
209 ;; the appropriate '*error* message returned.
211 (define (reply-message from-actor original-message
214 (set-message-replied! original-message #t)
215 (let* ((hive (actor-hive from-actor))
216 (new-message (make-message (hive-gen-message-id hive)
217 (message-from original-message)
218 (actor-id from-actor) '*reply*
219 (kwarg-list-to-alist message-body-args)
220 #:in-reply-to (message-id original-message))))
221 (8sync (hive-process-message hive new-message))))
223 (define (reply-message-wait from-actor original-message
225 "Reply to a messsage, but wait until we get a response"
226 (set-message-replied! original-message #t)
227 (let* ((hive (actor-hive from-actor))
228 (agenda-prompt (hive-prompt (actor-hive from-actor)))
229 (new-message (make-message (hive-gen-message-id hive)
230 (message-from original-message)
231 (actor-id from-actor) '*reply*
232 (kwarg-list-to-alist message-body-args)
234 #:in-reply-to (message-id original-message))))
235 (abort-to-prompt agenda-prompt from-actor new-message)))
239 ;;; Main actor implementation
240 ;;; =========================
242 (define-class <actor> ()
244 (id #:init-thunk (require-slot "id")
247 ;; The hive we're connected to.
248 ;; We need this to be able to send messages.
249 (hive #:init-thunk (require-slot "hive")
250 #:init-keyword #:hive
251 #:accessor actor-hive)
252 ;; How we receive and process new messages
253 (message-handler #:init-thunk (require-slot "message-handler")
254 #:allocation #:each-subclass))
256 (define-method (actor-message-handler (actor <actor>))
257 (slot-ref actor 'message-handler))
259 ;;; So these are the nicer representations of addresses.
260 ;;; However, they don't serialize so easily with scheme read/write, so we're
261 ;;; using the simpler cons cell version below for now.
263 ;; (define-record-type <address>
264 ;; (make-address actor-id hive-id) ; @@: Do we want the trailing -id?
266 ;; (actor-id address-actor-id)
267 ;; (hive-id address-hive-id))
269 ;; (set-record-type-printer!
271 ;; (lambda (record port)
272 ;; (format port "<address: ~s@~s>"
273 ;; (address-actor-id record) (address-hive-id record))))
276 (define (make-address actor-id hive-id)
277 (cons actor-id hive-id))
279 (define (address-actor-id address)
282 (define (address-hive-id address)
285 (define (address->string address)
286 (string-append (address-actor-id address) "@"
287 (address-hive-id address)))
289 (define-method (actor-id-actor (actor <actor>))
290 "Get the actor id component of the actor-id"
291 (address-actor-id (actor-id actor)))
293 (define-method (actor-id-hive (actor <actor>))
294 "Get the hive id component of the actor-id"
295 (address-hive-id (actor-id actor)))
297 (define-method (actor-id-string (actor <actor>))
298 "Render the full actor id as a human-readable string"
299 (address->string (actor-id actor)))
306 (define (simple-dispatcher action-map)
307 (lambda (actor message)
308 (let* ((action (message-action message))
309 (method (assoc-ref action-map action)))
311 (throw 'action-not-found
312 "No appropriate action handler found for actor"
316 #:available-actions (map car action-map)))
317 (method actor message))))
319 (define-syntax %expand-action-item
321 ((_ ((action-name action-args ...) body ...))
322 (cons (quote action-name)
323 (lambda (action-args ...)
325 ((_ (action-name handler))
326 (cons (quote action-name) handler))))
328 (define-syntax make-action-dispatch
330 "Expand a list of action names and actions into an alist
332 You can use this like the following:
333 (make-action-dispatch
335 (lambda (actor message)
336 (display \"I love cookies!\n\")))
338 (lambda (actor message)
339 (display \"Life of the party!\"))))
341 Alternately, if you'd like to skip the lambda, you could use the slightly
342 more compact following syntax:
343 (make-action-dispatch
344 ((cookies actor message)
345 (display \"I love cookies!\n\"))
346 ((party actor message)
347 (display \"Life of the party!\")))"
348 ((make-action-dispatch action-item ...)
350 (list (%expand-action-item action-item) ...)))))
352 (define-syntax-rule (define-simple-actor class actions ...)
353 (define-class class (<actor>)
355 #:init-value (make-action-dispatch actions ...)
356 #:allocation #:each-subclass)))
361 ;;; Every actor has a hive. The hive is a kind of "meta-actor"
362 ;;; which routes all the rest of the actors in a system.
364 (define-generic hive-handle-failed-forward)
366 (define-class <hive> (<actor>)
367 ;; This gets set to itself immediately after being created
368 (hive #:init-value #f)
369 (actor-registry #:init-thunk make-hash-table
370 #:getter hive-actor-registry)
371 (msg-id-generator #:init-thunk simple-message-id-generator
372 #:getter hive-msg-id-generator)
373 ;; Ambassadors are used (or will be) for inter-hive communication.
374 ;; These are special actors that know how to route messages to other hives.
375 (ambassadors #:init-thunk make-weak-key-hash-table
376 #:getter hive-ambassadors)
377 ;; Waiting coroutines
378 ;; This is a map from cons cell of message-id
379 ;; to a cons cell of (actor-id . coroutine)
380 ;; @@: Should we have a <waiting-coroutine> record type?
381 (waiting-coroutines #:init-thunk make-hash-table
382 #:getter hive-waiting-coroutines)
384 ;; When actors send messages to each other they abort to this prompt
385 ;; to send the message, then carry on their way
386 (prompt #:init-thunk make-prompt-tag
387 #:getter hive-prompt)
390 (make-action-dispatch
391 ;; This is in the case of an ambassador failing to forward a message...
392 ;; it reports it back to the hive
393 (*failed-forward* hive-handle-failed-forward))))
395 (define-method (hive-handle-failed-forward (hive <hive>) message)
396 "Handle an ambassador failing to forward a message"
399 (define* (make-hive #:key hive-id)
400 (let ((hive (make <hive>
403 (big-random-number-string))))))
404 ;; Set the hive's actor reference to itself
405 (set! (actor-hive hive) hive)
408 (define-method (hive-id (hive <hive>))
409 (actor-id-hive hive))
411 (define-method (hive-gen-actor-id (hive <hive>) cookie)
412 (make-address (if cookie
413 (string-append cookie "-" (big-random-number-string))
414 (big-random-number-string))
417 (define-method (hive-gen-message-id (hive <hive>))
418 "Generate a message id using HIVE's message id generator"
419 ((hive-msg-id-generator hive)))
421 (define-method (hive-resolve-local-actor (hive <hive>) actor-address)
422 (hash-ref (hive-actor-registry hive) actor-address))
424 (define-method (hive-resolve-ambassador (hive <hive>) ambassador-address)
425 (hash-ref (hive-ambassadors hive) ambassador-address))
427 (define-method (make-forward-request (hive <hive>) (ambassador <actor>) message)
428 (make-message (hive-gen-message-id hive) (actor-id ambassador)
429 ;; If we make the hive not an actor, we could either switch this
430 ;; to #f or to the original actor...?
431 ;; Maybe some more thinking should be done on what should
432 ;; happen in case of failure to forward? Handling ambassador failures
433 ;; seems like the primary motivation for the hive remaining an actor.
436 `((original . ,message))))
438 (define-method (hive-process-message (hive <hive>) message)
439 "Handle one message, or forward it via an ambassador"
440 (define (process-local-message)
441 (let ((actor (hive-resolve-local-actor hive (message-to message))))
443 (throw 'actor-not-found
444 (format #f "Message ~a from ~a directed to nonexistant actor ~a"
446 (address->string (message-from message))
447 (address->string (message-to message)))
449 (call-with-prompt (hive-prompt hive)
451 (define message-handler (actor-message-handler actor))
452 ;; @@: Should a more general error handling happen here?
453 (message-handler actor message))
455 (lambda (kont actor message)
456 (let ((hive (actor-hive actor)))
457 ;; Register the coroutine
458 (hash-set! (hive-waiting-coroutines hive)
460 (cons (actor-id actor) kont))
461 ;; Send off the message
462 (8sync (hive-process-message hive message)))))))
464 (define (resume-waiting-coroutine)
465 (match (hash-remove! (hive-waiting-coroutines hive)
466 (message-in-reply-to message))
467 ((_ . (resume-actor-id . kont))
468 (if (not (equal? (message-to message)
470 (throw 'resuming-to-wrong-actor
471 "Attempted to resume a coroutine to the wrong actor!"
472 #:expected-actor-id (message-to message)
473 #:got-actor-id resume-actor-id
476 (#f (throw 'no-waiting-coroutine
477 "message in-reply-to tries to resume nonexistent coroutine"
480 (define (process-remote-message)
481 ;; Find the ambassador
482 (let* ((remote-hive-id (hive-id (message-to message)))
483 (ambassador (hive-resolve-ambassador remote-hive-id))
484 (message-handler (actor-message-handler ambassador))
485 (forward-request (make-forward-request hive ambassador message)))
486 (message-handler ambassador forward-request)))
488 (let ((to (message-to message)))
489 ;; This seems to be an easy mistake to make, so check that addressing
492 (throw 'missing-addressee
493 "`to' field is missing on message"
495 (if (hive-actor-local? hive to)
496 (if (message-in-reply-to message)
497 (resume-waiting-coroutine)
498 (process-local-message))
499 (process-remote-message))))
501 (define-method (hive-actor-local? (hive <hive>) address)
502 (hash-ref (hive-actor-registry hive) address))
504 (define-method (hive-register-actor! (hive <hive>) (actor <actor>))
505 (hash-set! (hive-actor-registry hive) (actor-id actor) actor))
507 (define-method (%hive-create-actor (hive <hive>) actor-class
509 "Actual method called by hive-create-actor.
511 Since this is a define-method it can't accept fancy define* arguments,
512 so this gets called from the nicer hive-create-actor interface. See
513 that method for documentation."
514 (let* ((actor-id (hive-gen-actor-id hive id-cookie))
515 (actor (apply make actor-class
516 ;; @@: If we switch to a hive-proxy, do it here
520 (hive-register-actor! hive actor)
521 ;; return the actor id
524 (define* (hive-create-actor hive actor-class
528 (%hive-create-actor hive actor-class
531 (define-syntax hive-create-actor*
533 "Create an instance of actor-class attached to this hive.
534 Return the new actor's id.
536 Used internally, and used for bootstrapping a fresh hive.
538 Note that actors should generally not call this method directly.
539 Instead, actors should call create-actor."
540 ((_ args ... (init-args ...))
541 (hive-create-actor args ...
542 #:init (list init-args ...)))))
545 ;; TODO: Give actors this instead of the actual hive reference
546 (define-class <hive-proxy> ()
547 (send-message #:getter proxy-send-message
548 #:init-keyword #:send-message)
549 (create-actor #:getter proxy-create-actor
550 #:init-keyword #:create-actor))
552 ;; Live the hive proxy, but has access to the hive itself...
553 (define-class <debug-hive-proxy> (<hive-proxy>)
554 (hive #:init-keyword #:hive))
558 ;;; 8sync bootstrap utilities
559 ;;; =========================
561 (define* (ez-run-hive hive initial-tasks #:key repl-server)
562 "Start up an agenda and run HIVE in it with INITIAL-TASKS.
564 Should we start up a cooperative REPL for live hacking? REPL-SERVER
565 wants to know! You can pass it #t or #f, or if you want to specify a port,
567 (let* ((queue (list->q initial-tasks))
568 (agenda (make-agenda #:pre-unwind-handler print-error-and-continue
571 ;; If repl-server is an integer, we'll use that as the port
572 ((integer? repl-server)
573 (spawn-and-queue-repl-server! agenda repl-server))
575 (spawn-and-queue-repl-server! agenda)))
576 (start-agenda agenda)))
578 (define (hive-bootstrap-message hive to-id action . message-body-args)
580 (apply send-message hive to-id action message-body-args)))
584 ;;; Basic readers / writers
585 ;;; =======================
587 (define (serialize-message message)
588 "Serialize a message for read/write"
592 (message-from message)
593 (message-action message)
594 (message-body message)
595 (message-in-reply-to message)
596 (message-wants-reply message)
597 (message-replied message)
598 (message-deferred-reply message)))
600 (define* (write-message message #:optional (port (current-output-port)))
601 "Write out a message to a port for easy reading later.
603 Note that if a sub-value can't be easily written to something
604 Guile's `read' procedure knows how to read, this doesn't do anything
605 to improve that. You'll need a better serializer for that.."
606 (write (serialize-message message) port))
608 (define (serialize-message-pretty message)
609 "Serialize a message in a way that's easy for humans to read."
611 (id ,(message-id message))
612 (to ,(message-to message))
613 (from ,(message-from message))
614 (action ,(message-action message))
615 (body ,(message-body message))
616 (in-reply-to ,(message-in-reply-to message))
617 (wants-reply ,(message-wants-reply message))
618 (replied ,(message-replied message))
619 (deferred-reply ,(message-deferred-reply message))))
621 (define (pprint-message message)
622 "Pretty print a message."
623 (pretty-print (serialize-message-pretty message)))
625 (define* (read-message #:optional (port (current-input-port)))
626 "Read a message serialized via serialize-message from PORT"
628 ((id to from action body in-reply-to wants-reply replied deferred-reply)
630 id to from action body
631 in-reply-to wants-reply replied deferred-reply))
633 (throw 'message-read-bad-structure
634 "Could not read message from structure"
637 (define (read-message-from-string message-str)
638 "Read message from MESSAGE-STR"
639 (with-input-from-string message-str
641 (read-message (current-input-port)))))