67eba86d284a1b1fdb855300ae826e4bf9c565d1
[8sync.git] / doc / 8sync.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename 8sync.info
4 @settitle 8sync
5 @c %**end of header
6 @copying
7 Copyright @copyright{} 2015  Christopher Allan Webber @email{cwebber@@dustycloud.org}
8 @end copying
9
10 @quotation
11 Permission is granted to copy, distribute and/or modify this document
12 under the terms of the GNU Free Documentation License, Version 1.3
13 or any later version published by the Free Software Foundation;
14 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
15 A copy of the license is included in the section entitled ``GNU
16 Free Documentation License''.
17
18 A copy of the license is also available from the Free Software
19 Foundation Web site at @url{http://www.gnu.org/licenses/fdl.html}.
20
21 Alternately, this document is also available under the Lesser General
22 Public License, version 3 or later, as published by the Free Software
23 Foundation.
24
25 A copy of the license is also available from the Free Software
26 Foundation Web site at @url{http://www.gnu.org/licenses/lgpl.html}.
27 @end quotation
28
29
30 @titlepage
31 @title 8sync
32 @subtitle 8sync, asynchronous actors for Guile
33 @author Christopher Allan Webber
34 @page
35 @vskip 0pt plus 1filll
36 @insertcopying
37 @end titlepage
38
39 @c Output the table of the contents at the beginning.
40 @contents
41
42 @ifnottex
43 @node Top, Preface, (dir), (dir)
44 @top 8sync
45
46 @insertcopying
47 @end ifnottex
48
49 @c Generate the nodes for this menu with `C-c C-u C-m'.
50
51
52 @c Update all node entries with `C-c C-u C-n'.
53 @c Insert new nodes with `C-c C-c n'.
54
55 @menu
56 * Preface::
57 * Tutorial::
58 * API reference::
59 * Systems reference::
60 * Addendum::
61 * Copying This Manual::
62 * Index::
63 @end menu
64
65 \f
66
67 @node Preface
68 @chapter Preface
69
70 Welcome to 8sync's documentation!
71 8sync is an asynchronous programming environment for GNU Guile.
72 (Get it? 8sync? Async??? Quiet your groans, it's a great name!)
73
74 8sync has some nice properties:
75
76 @itemize
77 @item
78 8sync uses the actor model as its fundamental concurrency
79 synchronization mechanism.
80 Since the actor model is a "shared nothing" asynchronous
81 environment, you don't need to worry about deadlocks or other
82 tricky problems common to other asynchronous models.
83 Actors are modular units of code and state which communicate
84 by sending messages to each other.
85 @item
86 If you've done enough asynchronous programming, you're probably
87 familiar with the dreaded term "callback hell".
88 Getting around callback hell usually involves a tradeoff of other,
89 still rather difficult to wrap your brain around programming
90 patterns.
91 8sync uses some clever tricks involving "delimited continuations"
92 under the hood to make the code you write look familiar and
93 straightforward.
94 When you need to send a request to another actor and get some
95 information back from it without blocking, there's no need
96 to write a separate procedure@dots{} 8sync's scheduler will suspend
97 your procedure and wake it back up when a response is ready.
98 @item
99 Even nonblocking I/O code is straightforward to write.
100 Thanks to the "suspendable ports" code introduced in Guile 2.2,
101 writing asynchronous, nonblocking networked code looks mostly
102 like writing the same synchronous code.
103 8sync's scheduler handles suspending and resuming networked
104 code that would otherwise block.
105 @item
106 8sync aims to be "batteries included".
107 Useful subsystems for IRC bots, HTTP servers, and so on are
108 included out of the box.
109 @item
110 8sync prioritizes live hacking.
111 If using an editor like Emacs with a nice mode like Geiser,
112 an 8sync-using developer can change and fine-tune the behavior
113 of code @emph{while it runs}.
114 This makes both debugging and development much more natural,
115 allowing the right designs to evolve under your fingertips.
116 A productive hacker is a happy hacker, after all!
117 @end itemize
118
119 In the future, 8sync will also provide the ability to spawn and
120 communicate with actors on different threads, processes, and machines,
121 with most code running the same as if actors were running in the same
122 execution environment.
123
124 But as a caution, 8sync is still very young.
125 The API is stabilizing, but not yet stable, and it is not yet well
126 "battle-tested".
127 Hacker beware!
128 But, consider this as much an opportunity as a warning.
129 8sync is in a state where there is much room for feedback and
130 contributions.
131 Your help wanted!
132
133 And now, into the wild, beautiful frontier.
134 Onward!
135
136 @node Tutorial
137 @chapter Tutorial
138
139 @menu
140 * A silly little IRC bot::
141 * Writing our own actors::
142 * Writing our own network-enabled actor::
143 * An intermission on live hacking::
144 @end menu
145
146 \f
147
148 @node A silly little IRC bot
149 @section A silly little IRC bot
150
151 IRC!  Internet Relay Chat!
152 The classic chat protocol of the Internet.
153 And it turns out, one of the best places to learn about networked
154 programming.@footnote{In the 1990s I remember stumbling into some funky IRC chat rooms and
155 being astounded that people there had what they called "bots" hanging
156 around.
157 From then until now, I've always enjoyed encountering bots whose range
158 of functionality has spanned from saying absurd things, to taking
159 messages when their "owners" were offline, to reporting the weather,
160 to logging meetings for participants.
161 And it turns out, IRC bots are a great way to cut your teeth on
162 networked programming; since IRC is a fairly simple line-delineated
163 protocol, it's a great way to learn to interact with sockets.
164 (My first IRC bot helped my team pick a place to go to lunch, previously
165 a source of significant dispute!)
166 At the time of writing, venture capital awash startups are trying to
167 turn chatbots into "big business"@dots{} a strange (and perhaps absurd)
168 thing given chat bots being a fairly mundane novelty amongst hackers
169 and teenagers everywhere a few decades ago.}
170 We ourselves are going to explore chat bots as a basis for getting our
171 feet wet in 8sync.
172
173 First of all, we're going to need to import some modules.  Put this at
174 the top of your file:
175
176 @example
177 (use-modules (8sync)               ; 8sync's agenda and actors
178              (8sync systems irc)   ; the irc bot subsystem
179              (oop goops)           ; 8sync's actors use GOOPS
180              (ice-9 format)        ; basic string formatting
181              (ice-9 match))        ; pattern matching
182 @end example
183
184 Now we need to add our bot.  Initially, it won't do much.
185
186 @example
187 (define-class <my-irc-bot> (<irc-bot>))
188
189 (define-method (handle-line (irc-bot <my-irc-bot>) message
190                             speaker channel line emote?)
191   (if emote?
192       (format #t "~a emoted ~s in channel ~a\n"
193               speaker line channel)
194       (format #t "~a said ~s in channel ~a\n"
195               speaker line channel)))
196 @end example
197
198 We've just defined our own IRC bot!
199 This is an 8sync actor.
200 (8sync uses GOOPS to define actors.)
201 We extended the handle-line generic method, so this is the code that
202 will be called whenever the IRC bot "hears" anything.
203 This method is itself an action handler, hence the second argument
204 for @verb{~message~}, which we can ignore for now.
205 Pleasantly, the message's argument body is passed in as the rest of
206 the arguments.
207
208 For now the code is pretty basic: it just outputs whatever it "hears"
209 from a user in a channel to the current output port.
210 Pretty boring!
211 But it should help us make sure we have things working when we kick
212 things off.
213
214 Speaking of, even though we've defined our actor, it's not running
215 yet.  Time to fix that!
216
217 @example
218 (define* (run-bot #:key (username "examplebot")
219                   (server "irc.freenode.net")
220                   (channels '("##botchat")))
221   (define hive (make-hive))
222   (define irc-bot
223     (bootstrap-actor hive <my-irc-bot>
224                      #:username username
225                      #:server server
226                      #:channels channels))
227   (run-hive hive '()))
228 @end example
229
230 Actors are connected to something called a "hive", which is a
231 special kind of actor that runs and manages all the other actors.
232 Actors can spawn other actors, but before we start the hive we use
233 this special @verb{~bootstrap-actor~} method.
234 It takes the hive as its first argument, the actor class as the second
235 argument, and the rest are initialization arguments to the
236 actor.
237 @verb{~bootstrap-actor~} passes back not the actor itself (we don't
238 get access to that usually) but the @strong{id} of the actor.
239 (More on this later.)
240 Finally we run the hive with run-hive and pass it a list of
241 "bootstrapped" messages.
242 Normally actors send messages to each other (and sometimes themselves),
243 but we need to send a message or messages to start things or else
244 nothing is going to happen.
245
246 We can run it like:
247
248 @example
249 (run-bot #:username "some-bot-name") ; be creative!
250 @end example
251
252 Assuming all the tubes on the internet are properly connected, you
253 should be able to join the "##botchat" channel on irc.freenode.net and
254 see your bot join as well.
255 Now, as you probably guessed, you can't really @emph{do} much yet.
256 If you talk to the bot, it'll send messages to the terminal informing
257 you as such, but it's hardly a chat bot if it's not chatting yet.
258
259 So let's do the most boring (and annoying) thing possible.
260 Let's get it to echo whatever we say back to us.
261 Change handle-line to this:
262
263 @example
264 (define-method (handle-line (irc-bot <my-irc-bot>) message
265                             speaker channel line emote?)
266   (<- (actor-id irc-bot) 'send-line channel
267       (format #f "Bawwwwk! ~a says: ~a" speaker line)))
268 @end example
269
270 This will do exactly what it looks like: repeat back whatever anyone
271 says like an obnoxious parrot.
272 Give it a try, but don't keep it running for too long@dots{} this
273 bot is so annoying it's likely to get banned from whatever channel
274 you put it in.
275
276 This method handler does have the advantage of being simple though.
277 It introduces a new concept simply@dots{} sending a message!
278 Whenever you see "<-", you can think of that as saying "send this
279 message".
280 The arguments to "<-" are as follows: the actor sending the message,
281 the id of the actor the message is being sent to, the "action" we
282 want to invoke (a symbol), and the rest are arguments to the
283 "action handler" which is in this case send-line (with itself takes
284 two arguments: the channel our bot should send a message to, and
285 the line we want it to spit out to the channel).@footnote{8sync's name for sending a message, "<-", comes from older,
286 early lisp object oriented systems which were, as it turned out,
287 inspired by the actor model!
288 Eventually message passing was dropped in favor of something called
289 "generic functions" or "generic methods"
290 (you may observe we made use of such a thing in extending
291 handle-line).
292 Many lispers believe that there is no need for message passing
293 with generic methods and some advanced functional techniques,
294 but in a concurrent environment message passing becomes useful
295 again, especially when the communicating objects / actors are not
296 in the same address space.}
297
298 Normally in the actor model, we don't have direct references to
299 an actor, only an identifier.
300 This is for two reasons: to quasi-enforce the "shared nothing"
301 environment (actors absolutely control their own resources, and
302 "all you can do is send a message" to request that they modify
303 them) and because@dots{} well, you don't even know where that actor is!
304 Actors can be anything, and anywhere.
305 It's possible in 8sync to have an actor on a remote hive, which means
306 the actor could be on a remote process or even remote machine, and
307 in most cases message passing will look exactly the same.
308 (There are some exceptions; it's possible for two actors on the same
309 hive to "hand off" some special types of data that can't be serialized
310 across processes or the network, eg a socket or a closure, perhaps even
311 one with mutable state.
312 This must be done with care, and the actors should be careful both
313 to ensure that they are both local and that the actor handing things
314 off no longer accesses that value to preserve the actor model.
315 But this is an advanced topic, and we are getting ahead of ourselves.)
316 We have to supply the id of the receiving actor, and usually we'd have
317 only the identifier.
318 But since in this case, since the actor we're sending this to is
319 ourselves, we have to pass in our identifier, since the Hive won't
320 deliver to anything other than an address.
321
322 Astute readers may observe, since this is a case where we are just
323 referencing our own object, couldn't we just call "sending a line"
324 as a method of our own object without all the message passing?
325 Indeed, we do have such a method, so we @emph{could} rewrite handle-line
326 like so:
327
328 @example
329 (define-method (handle-line (irc-bot <my-irc-bot>) message
330                             speaker channel line emote?)
331   (irc-bot-send-line irc-bot channel
332                      (format #f "Bawwwwk! ~a says: ~a" speaker line)))
333 @end example
334
335 @dots{} but we want to get you comfortable and familiar with message
336 passing, and we'll be making use of this same message passing shortly
337 so that @emph{other} actors may participate in communicating with IRC
338 through our IRC bot.
339
340 Anyway, our current message handler is simply too annoying.
341 What we would really like to do is have our bot respond to individual
342 "commands" like this:
343
344 @example
345 <foo-user> examplebot: hi!
346 <examplebot> Oh hi foo-user!
347 <foo-user> examplebot: botsnack
348 <examplebot> Yippie! *does a dance!*
349 <foo-user> examplebot: echo I'm a very silly bot
350 <examplebot> I'm a very silly bot
351 @end example
352
353 Whee, that looks like fun!
354 To implement it, we're going to pull out Guile's pattern matcher.
355
356 @example
357 (define-method (handle-line (irc-bot <my-irc-bot>) message
358                             speaker channel line emote?)
359   (define my-name (irc-bot-username irc-bot))
360   (define (looks-like-me? str)
361     (or (equal? str my-name)
362         (equal? str (string-concatenate (list my-name ":")))))
363   (match (string-split line #\space)
364     (((? looks-like-me? _) action action-args ...)
365      (match action
366        ;; The classic botsnack!
367        ("botsnack"
368         (<- (actor-id irc-bot) 'send-line channel
369             "Yippie! *does a dance!*"))
370        ;; Return greeting
371        ((or "hello" "hello!" "hello." "greetings" "greetings." "greetings!"
372             "hei" "hei." "hei!" "hi" "hi!")
373         (<- (actor-id irc-bot) 'send-line channel
374             (format #f "Oh hi ~a!" speaker)))
375        ("echo"
376         (<- (actor-id irc-bot) 'send-line channel
377             (string-join action-args " ")))
378
379        ;; --->  Add yours here <---
380
381        ;; Default
382        (_
383         (<- (actor-id irc-bot) 'send-line channel
384             "*stupid puppy look*"))))))
385 @end example
386
387 Parsing the pattern matcher syntax is left as an exercise for the
388 reader.
389
390 If you're getting the sense that we could make this a bit less wordy,
391 you're right:
392
393 @example
394 (define-method (handle-line (irc-bot <my-irc-bot>) message
395                             speaker channel line emote?)
396   (define my-name (irc-bot-username irc-bot))
397   (define (looks-like-me? str)
398     (or (equal? str my-name)
399         (equal? str (string-concatenate (list my-name ":")))))
400   (define (respond respond-line)
401     (<- (actor-id irc-bot) 'send-line channel
402         respond-line))
403   (match (string-split line #\space)
404     (((? looks-like-me? _) action action-args ...)
405      (match action
406        ;; The classic botsnack!
407        ("botsnack"
408         (respond "Yippie! *does a dance!*"))
409        ;; Return greeting
410        ((or "hello" "hello!" "hello." "greetings" "greetings." "greetings!"
411             "hei" "hei." "hei!" "hi" "hi." "hi!")
412         (respond (format #f "Oh hi ~a!" speaker)))
413        ("echo"
414         (respond (string-join action-args " ")))
415
416        ;; --->  Add yours here <---
417
418        ;; Default
419        (_
420         (respond "*stupid puppy look*"))))))
421 @end example
422
423 Okay, that looks pretty good!
424 Now we have enough information to build an IRC bot that can do a lot
425 of things.
426 Take some time to experiment with extending the bot a bit before
427 moving on to the next section!
428 What cool commands can you add?
429
430 \f
431 @node Writing our own actors
432 @section Writing our own actors
433
434 Let's write the most basic, boring actor possible.
435 How about an actor that start sleeping, and keeps sleeping?
436
437 @example
438 (use-modules (oop goops)
439              (8sync))
440
441 (define-class <sleeper> (<actor>)
442   (actions #:allocation #:each-subclass
443            #:init-thunk (build-actions
444                          (*init* sleeper-loop))))
445
446 (define (sleeper-loop actor message)
447   (while (actor-alive? actor)
448     (display "Zzzzzzzz....\n")
449     ;; Sleep for one second
450     (8sleep (sleeper-sleep-secs actor))))
451
452 (let* ((hive (make-hive))
453        (sleeper (bootstrap-actor hive <sleeper>)))
454   (run-hive hive '()))
455 @end example
456
457 We see some particular things in this example.
458 One thing is that our @verb{~<sleeper>~} actor has an actions slot.
459 This is used to look up what the "action handler" for a message is.
460 We have to set the #:allocation to either @verb{~#:each-subclass~}
461 and use @verb{~#:init-thunk~}.@footnote{@verb{~build-subclass~} returns
462 a thunk to be called later so that each subclass may correctly build
463 its own instance.  This is important because the structure returned
464 contains a cache, which may vary from subclass to subclass based on
465 its inheritance structure.}
466
467 The only action handler we've added is for @verb{~*init*~}, which is called
468 implicitly when the actor first starts up.
469 (This will be true whether we bootstrap the actor before the hive
470 starts or create it during the hive's execution.)
471
472 In our sleeper-loop we also see a call to "8sleep".
473 "8sleep" is like Guile's "sleep" method, except it is non-blocking
474 and will always yield to the scheduler.
475
476 Our while loop also checks "actor-alive?" to see whether or not
477 it is still registered.
478 In general, if you keep a loop in your actor that regularly yields
479 to the scheduler, you should check this.@footnote{Or rather, for now you should call @verb{~actor-alive?~} if your code
480 is looping like this.
481 In the future, after an actor dies, its coroutines will
482 automatically be "canceled".}
483 (An alternate way to handle it would be to not use a while loop at all
484 but simply send a message to ourselves with "<-" to call the
485 sleeper-loop handler again.
486 If the actor was dead, the message simply would not be delivered and
487 thus the loop would stop.)
488
489 It turns out we could have written the class for the actor much more
490 simply:
491
492 @example
493 ;; You could do this instead of the define-class above.
494 (define-actor <sleeper> (<actor>)
495   ((*init* sleeper-loop)))
496 @end example
497
498 This is sugar, and expands into exactly the same thing as the
499 define-class above.
500 The third argument is an argument list, the same as what's passed
501 into build-actions.
502 Everything after that is a slot.
503 So for example, if we had added an optional slot to specify
504 how many seconds to sleep, we could have done it like so:
505
506 @example
507 (define-actor <sleeper> (<actor>)
508   ((*init* sleeper-loop))
509   (sleep-secs #:init-value 1
510               #:getter sleeper-sleep-secs))
511 @end example
512
513 This actor is pretty lazy though.
514 Time to get back to work!
515 Let's build a worker / manager type system.
516
517 @example
518 (use-modules (8sync)
519              (oop goops))
520
521 (define-actor <manager> (<actor>)
522   ((assign-task manager-assign-task))
523   (direct-report #:init-keyword #:direct-report
524                  #:getter manager-direct-report))
525
526 (define (manager-assign-task manager message difficulty)
527   "Delegate a task to our direct report"
528   (display "manager> Work on this task for me!\n")
529   (<- (manager-direct-report manager)
530       'work-on-this difficulty))
531 @end example
532
533 This manager keeps track of a direct report and tells them to start
534 working on a task@dots{} simple delegation.
535 Nothing here is really new, but note that our friend "<-" (which means
536 "send message") is back.
537 There's one difference this time@dots{} the first time we saw "<-" was in
538 the handle-line procedure of the irc-bot, and in that case we explicitly
539 pulled the actor-id after the actor we were sending the message to
540 (ourselves), which we aren't doing here.
541 But that was an unusual case, because the actor was ourself.
542 In this case, and in general, actors don't have direct references to
543 other actors; instead, all they have is access to identifiers which
544 reference other actors.
545
546 @example
547 (define-actor <worker> (<actor>)
548   ((work-on-this worker-work-on-this))
549   (task-left #:init-keyword #:task-left
550              #:accessor worker-task-left))
551
552 (define (worker-work-on-this worker message difficulty)
553   "Work on one task until done."
554   (set! (worker-task-left worker) difficulty)
555   (display "worker> Whatever you say, boss!\n")
556   (while (and (actor-alive? worker)
557               (> (worker-task-left worker) 0))
558     (display "worker> *huff puff*\n")
559     (set! (worker-task-left worker)
560           (- (worker-task-left worker) 1))
561     (8sleep (/ 1 3))))
562 @end example
563
564 The worker also contains familiar code, but we now see that we can
565 call 8sleep with non-integer real numbers.
566
567 Looks like there's nothing left to do but run it.
568
569 @example
570 (let* ((hive (make-hive))
571        (worker (bootstrap-actor hive <worker>))
572        (manager (bootstrap-actor hive <manager>
573                                  #:direct-report worker)))
574   (run-hive hive (list (bootstrap-message hive manager 'assign-task 5))))
575 @end example
576
577 Unlike the @verb{~<sleeper>~}, our @verb{~<manager>~} doesn't have an implicit
578 @verb{~*init*~} method, so we've bootstrapped the calling @verb{~assign-task~} action.
579
580 @example
581 manager> Work on this task for me!
582 worker> Whatever you say, boss!
583 worker> *huff puff*
584 worker> *huff puff*
585 worker> *huff puff*
586 worker> *huff puff*
587 worker> *huff puff*
588 @end example
589
590 "<-" pays no attention to what happens with the messages it has sent
591 off.
592 This is useful in many cases@dots{} we can blast off many messages and
593 continue along without holding anything back.
594
595 But sometimes we want to make sure that something completes before
596 we do something else, or we want to send a message and get some sort
597 of information back.
598 Luckily 8sync comes with an answer to that with "<-wait", which will
599 suspend the caller until the callee gives some sort of response, but
600 which does not block the rest of the program from running.
601 Let's try applying that to our own code by turning our manager
602 into a micromanager.
603
604 @example
605 ;;; Update this method
606 (define (manager-assign-task manager message difficulty)
607   "Delegate a task to our direct report"
608   (display "manager> Work on this task for me!\n")
609   (<- (manager-direct-report manager)
610       'work-on-this difficulty)
611
612   ;; Wait a moment, then call the micromanagement loop
613   (8sleep (/ 1 2))
614   (manager-micromanage-loop manager))
615
616 ;;; And add the following
617 ;;;   (... Note: do not model actual employee management off this)
618 (define (manager-micromanage-loop manager)
619   "Pester direct report until they're done with their task."
620   (display "manager> Are you done yet???\n")
621   (let ((worker-is-done
622          (mbody-val (<-wait (manager-direct-report manager)
623                             'done-yet?))))
624     (if worker-is-done
625         (begin (display "manager> Oh!  I guess you can go home then.\n")
626                (<- (manager-direct-report manager) 'go-home))
627         (begin (display "manager> Harumph!\n")
628                (8sleep (/ 1 2))
629                (when (actor-alive? manager)
630                  (manager-micromanage-loop manager))))))
631 @end example
632
633 We've appended a micromanagement loop here@dots{} but what's going on?
634 "<-wait", as it sounds, waits for a reply, and returns a reply
635 message.
636 In this case there's a value in the body of the message we want,
637 so we pull it out with mbody-val.
638 (It's possible for a remote actor to return multiple values, in which
639 case we'd want to use mbody-receive, but that's a bit more
640 complicated.)
641
642 Of course, we need to update our worker accordingly as well.
643
644 @example
645 ;;; Update the worker to add the following new actions:
646 (define-actor <worker> (<actor>)
647   ((work-on-this worker-work-on-this)
648    ;; Add these:
649    (done-yet? worker-done-yet?)
650    (go-home worker-go-home))
651   (task-left #:init-keyword #:task-left
652              #:accessor worker-task-left))
653
654 ;;; New procedures:
655 (define (worker-done-yet? worker message)
656   "Reply with whether or not we're done yet."
657   (let ((am-i-done? (= (worker-task-left worker) 0)))
658     (if am-i-done?
659         (display "worker> Yes, I finished up!\n")
660         (display "worker> No... I'm still working on it...\n"))
661     (<-reply message am-i-done?)))
662
663 (define (worker-go-home worker message)
664   "It's off of work for us!"
665   (display "worker> Whew!  Free at last.\n")
666   (self-destruct worker))
667 @end example
668
669 (As you've probably guessed, you wouldn't normally call @verb{~display~}
670 everywhere as we are in this program@dots{} that's just to make the
671 examples more illustrative.)
672
673 "<-reply" is what actually returns the information to the actor
674 waiting on the reply.
675 It takes as an argument the actor sending the message, the message
676 it is in reply to, and the rest of the arguments are the "body" of
677 the message.
678 (If an actor handles a message that is being "waited on" but does not
679 explicitly reply to it, an auto-reply with an empty body will be
680 triggered so that the waiting actor is not left waiting around.)
681
682 The last thing to note is the call to "self-destruct".
683 This does what you might expect: it removes the actor from the hive.
684 No new messages will be sent to it.
685 Ka-poof!
686
687 Running it is the same as before:
688
689 @example
690 (let* ((hive (make-hive))
691        (worker (bootstrap-actor hive <worker>))
692        (manager (bootstrap-actor hive <manager>
693                                  #:direct-report worker)))
694   (run-hive hive (list (bootstrap-message hive manager 'assign-task 5))))
695 @end example
696
697 But the output is a bit different:
698
699 @example
700 manager> Work on this task for me!
701 worker> Whatever you say, boss!
702 worker> *huff puff*
703 worker> *huff puff*
704 manager> Are you done yet???
705 worker> No... I'm still working on it...
706 manager> Harumph!
707 worker> *huff puff*
708 manager> Are you done yet???
709 worker> *huff puff*
710 worker> No... I'm still working on it...
711 manager> Harumph!
712 worker> *huff puff*
713 manager> Are you done yet???
714 worker> Yes, I finished up!
715 manager> Oh!  I guess you can go home then.
716 worker> Whew!  Free at last.
717 @end example
718
719 \f
720 @node Writing our own network-enabled actor
721 @section Writing our own network-enabled actor
722
723 So, you want to write a networked actor!
724 Well, luckily that's pretty easy, especially with all you know so far.
725
726 @example
727 (use-modules (oop goops)
728              (8sync)
729              (ice-9 rdelim)  ; line delineated i/o
730              (ice-9 match))  ; pattern matching
731
732 (define-actor <telcmd> (<actor>)
733   ((*init* telcmd-init)
734    (*cleanup* telcmd-cleanup)
735    (new-client telcmd-new-client)
736    (handle-line telcmd-handle-line))
737   (socket #:accessor telcmd-socket
738           #:init-value #f))
739 @end example
740
741 Nothing surprising about the actor definition, though we do see that
742 it has a slot for a socket.
743 Unsurprisingly, that will be set up in the @verb{~*init*~} handler.
744
745 @example
746 (define (set-port-nonblocking! port)
747   (let ((flags (fcntl port F_GETFL)))
748     (fcntl port F_SETFL (logior O_NONBLOCK flags))))
749
750 (define (setup-socket)
751   ;; our socket
752   (define s
753     (socket PF_INET SOCK_STREAM 0))
754   ;; reuse port even if busy
755   (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
756   ;; connect to port 8889 on localhost
757   (bind s AF_INET INADDR_LOOPBACK 8889)
758   ;; make it nonblocking and start listening
759   (set-port-nonblocking! s)
760   (listen s 5)
761   s)
762
763 (define (telcmd-init telcmd message)
764   (set! (telcmd-socket telcmd) (setup-socket))
765   (display "Connect like: telnet localhost 8889\n")
766   (while (actor-alive? telcmd)
767     (let ((client-connection (accept (telcmd-socket telcmd))))
768       (<- (actor-id telcmd) 'new-client client-connection))))
769
770 (define (telcmd-cleanup telcmd message)
771   (display "Closing socket!\n")
772   (when (telcmd-socket telcmd)
773     (close (telcmd-socket telcmd))))
774 @end example
775
776 That @verb{~setup-socket~} code looks pretty hard to read!
777 But that's pretty standard code for setting up a socket.
778 One special thing is done though@dots{} the call to
779 @verb{~set-port-nonblocking!~} sets flags on the socket port so that,
780 you guessed it, will be a nonblocking port.
781
782 This is put to immediate use in the telcmd-init method.
783 This code looks suspiciously like it @emph{should} block@dots{} after
784 all, it just keeps looping forever.
785 But since 8sync is using Guile's suspendable ports code feature,
786 so every time this loop hits the @verb{~accept~} call, if that call
787 @emph{would have} blocked, instead this whole procedure suspends
788 to the scheduler@dots{} automatically!@dots{} allowing other code to run.
789
790 So, as soon as we do accept a connection, we send a message to
791 ourselves with the @verb{~new-client~} action.
792 But wait!
793 Aren't actors only supposed to handle one message at a time?
794 If the telcmd-init loop just keeps on looping and looping,
795 when will the @verb{~new-client~} message ever be handled?
796 8sync actors only receive one message at a time, but by default if an
797 actor's message handler suspends to the agenda for some reason (such
798 as to send a message or on handling I/O), that actor may continue to
799 accept other messages, but always in the same thread.@footnote{This is customizable: an actor can be set up to queue messages so
800 that absolutely no messages are handled until the actor completely
801 finishes handling one message.
802 Our loop couldn't look quite like this though!}
803
804 We also see that we've established a @verb{~*cleanup*~} handler.
805 This is run any time either the actor dies, either through self
806 destructing, because the hive completes its work, or because
807 a signal was sent to interrupt or terminate our program.
808 In our case, we politely close the socket when @verb{~<telcmd>~} dies.
809
810 @example
811 (define (telcmd-new-client telcmd message client-connection)
812   (define client (car client-connection))
813   (set-port-nonblocking! client)
814   (let loop ()
815     (let ((line (read-line client)))
816       (cond ((eof-object? line)
817              (close client))
818             (else
819              (<- (actor-id telcmd) 'handle-line
820                  client (string-trim-right line #\return))
821              (when (actor-alive? telcmd)
822                (loop)))))))
823
824 (define (telcmd-handle-line telcmd message client line)
825   (match (string-split line #\space)
826     (("") #f)  ; ignore empty lines
827     (("time" _ ...)
828      (display
829       (strftime "The time is: %c\n" (localtime (current-time)))
830       client))
831     (("echo" rest ...)
832      (format client "~a\n" (string-join rest " ")))
833     ;; default
834     (_ (display "Sorry, I don't know that command.\n" client))))
835 @end example
836
837 Okay, we have a client, so we handle it!
838 And once again@dots{} we see this goes off on a loop of its own!
839 (Also once again, we have to do the @verb{~set-port-nonblocking!~} song and
840 dance.)
841 This loop also automatically suspends when it would otherwise block@dots{}
842 as long as read-line has information to process, it'll keep going, but
843 if it would have blocked waiting for input, then it would suspend the
844 agenda.@footnote{If there's a lot of data coming in and you don't want your I/O loop
845 to become too "greedy", take a look at @verb{~setvbuf~}.}
846
847 The actual method called whenever we have a "line" of input is pretty
848 straightforward@dots{} in fact it looks an awful lot like the IRC bot
849 handle-line procedure we used earlier.
850 No surprises there!@footnote{Well, there may be one surprise to a careful observer.
851 Why are we sending a message to ourselves?
852 Couldn't we have just dropped the argument of "message" to
853 telcmd-handle-line and just called it like any other procedure?
854 Indeed, we @emph{could} do that, but sending a message to ourself has
855 an added advantage: if we accidentally "break" the
856 telcmd-handle-line procedure in some way (say we add a fun new
857 command we're playing with it), raising an exception won't break
858 and disconnect the client's main loop, it'll just break the
859 message handler for that one line, and our telcmd will happily
860 chug along accepting another command from the user while we try
861 to figure out what happened to the last one.}
862
863 Now let's run it:
864
865 @example
866 (let* ((hive (make-hive))
867        (telcmd (bootstrap-actor hive <telcmd>)))
868   (run-hive hive '()))
869 @end example
870
871 Open up another terminal@dots{} you can connect via telnet:
872
873 @example
874 $ telnet localhost 8889
875 Trying 127.0.0.1...
876 Connected to localhost.
877 Escape character is '^]'.
878 time
879 The time is: Thu Jan  5 03:20:17 2017
880 echo this is an echo
881 this is an echo
882 shmmmmmmorp
883 Sorry, I don't know that command.
884 @end example
885
886 Horray, it works!
887 Type @verb{~Ctrl+] Ctrl+d~} to exit telnet.
888
889 Not so bad!
890 There's more that could be optimized, but we'll consider that to be
891 advanced topics of discussion.
892
893 So that's a pretty solid intro to how 8sync works!
894 Now that you've gone through this introduction, we hope you'll have fun
895 writing and hooking together your own actors.
896 Since actors are so modular, it's easy to have a program that has
897 multiple subystems working together.
898 You could build a worker queue system that displayed a web interface
899 and spat out notifications about when tasks finish to IRC, and making
900 all those actors talk to each other should be a piece of cake.
901 The sky's the limit!
902
903 Happy hacking!
904
905 \f
906 @node An intermission on live hacking
907 @section An intermission on live hacking
908
909 This section is optional, but highly recommended.
910 It requires that you're a user of GNU Emacs.
911 If you aren't, don't worry@dots{} you can forge ahead and come back in case
912 you ever do become an Emacs user.
913 (If you're more familiar with Vi/Vim style editing, I hear good things
914 about Spacemacs@dots{})
915
916 Remember all the way back when we were working on the IRC bot?
917 So you may have noticed while updating that section that the
918 start/stop cycle of hacking isn't really ideal.
919 You might either edit a file in your editor, then run it, or
920 type the whole program into the REPL, but then you'll have to spend
921 extra time copying it to a file.
922 Wouldn't it be nice if it were possible to both write code in a
923 file and try it as you go?
924 And wouldn't it be even better if you could live edit a program
925 while it's running?
926
927 Luckily, there's a great Emacs mode called Geiser which makes
928 editing and hacking and experimenting all happen in harmony.
929 And even better, 8sync is optimized for this experience.
930 8sync provides easy drop-in "cooperative REPL" support, and
931 most code can be simply redefined on the fly in 8sync through Geiser
932 and actors will immediately update their behavior, so you can test
933 and tweak things as you go.
934
935 Okay, enough talking.  Let's add it!
936 Redefine run-bot like so:
937
938 @example
939 (define* (run-bot #:key (username "examplebot")
940                   (server "irc.freenode.net")
941                   (channels '("##botchat"))
942                   (repl-path "/tmp/8sync-repl"))
943   (define hive (make-hive))
944   (define irc-bot
945     (bootstrap-actor hive <my-irc-bot>
946                      #:username username
947                      #:server server
948                      #:channels channels))
949   (define repl-manager
950     (bootstrap-actor hive <repl-manager>
951                      #:path repl-path))
952
953   (run-hive hive '()))
954 @end example
955
956 If we put a call to run-bot at the bottom of our file we can call it,
957 and the repl-manager will start something we can connect to automatically.
958 Horray!
959 Now when we run this it'll start up a REPL with a unix domain socket at
960 the repl-path.
961 We can connect to it in emacs like so:
962
963 @example
964 M-x geiser-connect-local <RET> guile <RET> /tmp/8sync-repl <RET>
965
966 @end example
967
968 Okay, so what does this get us?
969 Well, we can now live edit our program.
970 Let's change how our bot behaves a bit.
971 Let's change handle-line and tweak how the bot responds to a botsnack.
972 Change this part:
973
974 @example
975 ;; From this:
976 ("botsnack"
977  (respond "Yippie! *does a dance!*"))
978
979 ;; To this:
980 ("botsnack"
981  (respond "Yippie! *catches botsnack in midair!*"))
982 @end example
983
984 Okay, now let's evaluate the change of the definition.
985 You can hit "C-M-x" anywhere in the definition to re-evaluate.
986 (You can also position your cursor at the end of the definition and press
987 "C-x C-e", but I've come to like "C-M-x" better because I can evaluate as soon
988 as I'm done writing.)
989 Now, on IRC, ask your bot for a botsnack.
990 The bot should give the new message@dots{} with no need to stop and start the
991 program!
992
993 Let's fix a bug live.
994 Our current program works great if you talk to your bot in the same
995 IRC channel, but what if you try to talk to them over private message?
996
997 @example
998 IRC> /query examplebot
999 <foo-user> examplebot: hi!
1000 @end example
1001
1002 Hm, we aren't seeing any response on IRC!
1003 Huh?  What's going on?
1004 It's time to do some debugging.
1005 There are plenty of debugging tools in Guile, but sometimes the simplest
1006 is the nicest, and the simplest debugging route around is good old
1007 fashioned print debugging.
1008
1009 It turns out Guile has an under-advertised feature which makes print
1010 debugging really easy called "pk", pronounced "peek".
1011 What pk accepts a list of arguments, prints out the whole thing,
1012 but returns the last argument.
1013 This makes wrapping bits of our code pretty easy to see what's
1014 going on.
1015 So let's peek into our program with pk.
1016 Edit the respond section to see what channel it's really sending
1017 things to:
1018
1019 @example
1020 (define-method (handle-line (irc-bot <my-irc-bot>) message
1021                             speaker channel line emote?)
1022   ;; [... snip ...]
1023   (define (respond respond-line)
1024     (<- (actor-id irc-bot) 'send-line (pk 'channel channel)
1025         respond-line))
1026   ;; [... snip ...]
1027   )
1028 @end example
1029
1030 Re-evaluate.
1031 Now let's ping our bot in both the channel and over PM.
1032
1033 @example
1034 ;;; (channel "##botchat")
1035
1036 ;;; (channel "sinkbot")
1037 @end example
1038
1039 Oh okay, this makes sense.
1040 When we're talking in a normal multi-user channel, the channel we see
1041 the message coming from is the same one we send to.
1042 But over PM, the channel is a username, and in this case the username
1043 we're sending our line of text to is ourselves.
1044 That isn't what we want.
1045 Let's edit our code so that if we see that the channel we're sending
1046 to looks like our own username that we respond back to the sender.
1047 (We can remove the pk now that we know what's going on.)
1048
1049 @example
1050 (define-method (handle-line (irc-bot <my-irc-bot>) message
1051                             speaker channel line emote?)
1052   ;; [... snip ...]
1053   (define (respond respond-line)
1054     (<- (actor-id irc-bot) 'send-line
1055         (if (looks-like-me? channel)
1056             speaker    ; PM session
1057             channel)   ; normal IRC channel
1058         respond-line))
1059   ;; [... snip ...]
1060   )
1061 @end example
1062
1063 Re-evaluate and test.
1064
1065 @example
1066 IRC> /query examplebot
1067 <foo-user> examplebot: hi!
1068 <examplebot> Oh hi foo-user!
1069 @end example
1070
1071 Horray!
1072
1073 \f
1074 @node API reference
1075 @chapter API reference
1076
1077 \f
1078 @node Systems reference
1079 @chapter Systems reference
1080
1081 @menu
1082 * IRC::
1083 * Web / HTTP::
1084 @end menu
1085
1086 \f
1087 @node IRC
1088 @section IRC
1089
1090 \f
1091 @node Web / HTTP
1092 @section Web / HTTP
1093
1094 \f
1095 @node Addendum
1096 @chapter Addendum
1097
1098 @menu
1099 * Recommended emacs additions::
1100 * 8sync and Fibers::
1101 * 8sync's license and general comments on copyleft::
1102 * Acknowledgements::
1103 @end menu
1104
1105 \f
1106 @node Recommended emacs additions
1107 @section Recommended emacs additions
1108
1109 In order for @verb{~mbody-receive~} to indent properly, put this in your
1110 .emacs:
1111
1112 @lisp
1113 (put 'mbody-receive 'scheme-indent-function 2)
1114 @end lisp
1115
1116 @node 8sync and Fibers
1117 @section 8sync and Fibers
1118
1119 One other major library for asynchronous communication in Guile-land
1120 is @uref{https://github.com/wingo/fibers/,Fibers}.
1121 There's a lot of overlap:
1122
1123 @itemize
1124 @item
1125 Both use Guile's suspendable-ports facility
1126 @item
1127 Both communicate between asynchronous processes using message passing;
1128 you don't have to squint hard to see the relationship between Fibers'
1129 channels and 8sync's actor inboxes.
1130 @end itemize
1131
1132 However, there are clearly differences too.
1133 There's a one to one relationship between 8sync actors and an actor inbox,
1134 whereas each Fibers fiber may read from multiple channels, for example.
1135
1136 Luckily, it turns out there's a clear relationship, based on real,
1137 actual theory!
1138 8sync is based on the @uref{https://en.wikipedia.org/wiki/Actor_model,actor model} whereas fibers follows
1139 @uref{http://usingcsp.com/,Communicating Sequential Processes (CSP)}, which is a form of
1140 @uref{https://en.wikipedia.org/wiki/Process_calculus,process calculi}.
1141 And it turns out, the
1142 @uref{https://en.wikipedia.org/wiki/Actor_model_and_process_calculi,relationship between the actor model and process calculi} is well documented,
1143 and even more precisely, the
1144 @uref{https://en.wikipedia.org/wiki/Communicating_sequential_processes#Comparison_with_the_Actor_Model,relationship between CSP and the actor model} is well understood too.
1145
1146 So, 8sync and Fibers do take somewhat different approaches, but both
1147 have a solid theoretical backing@dots{} and their theories are well
1148 understood in terms of each other.
1149 Good news for theory nerds!
1150
1151 (Since the actors and CSP are @uref{https://en.wikipedia.org/wiki/Dual_%28mathematics%29,dual}, maybe eventually 8sync will be
1152 implemented on top of Fibers@dots{} that remains to be seen!)
1153
1154 \f
1155 @node 8sync's license and general comments on copyleft
1156 @section 8sync's license and general comments on copyleft
1157
1158 8sync is released under the GNU LGPL (Lesser General Public License),
1159 version 3 or later, as published by the Free Software Foundation.
1160 The short version of this is that if you distribute a modifications to
1161 8sync, whether alone or in some larger combination, must release the
1162 corresponding source code.
1163 A program which uses this library, if distributed without source code,
1164 must also allow relinking with a modified version of this library.
1165 In general, it is best to contribute them back to 8sync under the same terms;
1166 we'd appreciate any enhancements or fixes to be contributed upstream to
1167 8sync itself.
1168 (This is an intentional oversimplification for brevity, please read the LGPL
1169 for the precise terms.)
1170
1171 This usage of the LGPL helps us ensure that 8sync and derivatives of
1172 8sync as a library will remain free.
1173 Though it is not a requirement, we request you use 8sync to build free
1174 software rather than use it to contribute to the growing world of
1175 proprietary software.
1176
1177 The choice of the LGPL for 8sync was a strategic one.
1178 This is not a general recommendation to use the LGPL instead of the GPL
1179 for all libraries.
1180 In general, we encourage stronger copyleft.
1181 (For more thinking on this position, see
1182 @uref{https://www.gnu.org/licenses/why-not-lgpl.html,
1183       Why you shouldn't use the Lesser GPL for your next library}.)
1184
1185 Although 8sync provides some unique features, its main functionality
1186 is as an asynchronous programming environment, and there are many
1187 other asynchronous programming environments out there such as Node.js
1188 for Javascript and Asyncio for Python (there are others as well).
1189 It is popular in some of these communities to hold anti-copyleft positions,
1190 which is unfortunate, and many community members seem to be adopting
1191 these positions because other developers they look up to are holding
1192 them.
1193 If you have come from one of these communities and are exploring 8sync, we
1194 hope reading this will help you reconsider your position.
1195
1196 In particular, if you are building a library or application that uses
1197 8sync in some useful way, consider releasing your program under the GNU
1198 GPL or GNU AGPL!
1199 In a world where more and more software is locked down, where software is used
1200 to restrict users, we could use every chance we can get to provide
1201 protections so that software which is free remains free, and encourages even
1202 more software freedom to be built upon it.
1203
1204 So to answer the question, ``Can I build a proprietary program on top of
1205 8sync?'' our response is
1206 ``Yes, but please don't.
1207 Choose to release your software under a freedom-respecting license.
1208 And help us turn the tide towards greater software freedom...
1209 consider a strong copyleft license!''
1210
1211 @node Acknowledgements
1212 @section Acknowledgements
1213
1214 8sync has a number of inspirations:
1215
1216 @itemize @bullet
1217 @item
1218 @uref{https://docs.python.org/3.5/library/asyncio.html, asyncio}
1219 for Python provides a nice asynchronous programming environment, and
1220 makes great use of generator-style coroutines.
1221 It's a bit more difficult to work with than 8sync (or so thinks the author)
1222 because you have to ``line up'' the coroutines.
1223
1224 @item
1225 @uref{http://dthompson.us/pages/software/sly.html, Sly}
1226 by David Thompson is an awesome functional reactive game programming
1227 library for Guile.
1228 If you want to write graphical games, Sly is almost certainly a better choice
1229 than 8sync.
1230 Thanks to David for being very patient in explaining tough concepts;
1231 experience on hacking Sly greatly informed 8sync's development.
1232 (Check out Sly, it rocks!)
1233
1234 @item
1235 Reading @uref{https://mitpress.mit.edu/sicp/, SICP}, particularly
1236 @uref{https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-19.html#%_chap_3,
1237       Chapter 3's writings on concurrent systems},
1238 greatly informed 8sync's design.
1239
1240 @item
1241 Finally, @uref{http://xudd.readthedocs.io/en/latest/, XUDD}
1242 was an earlier ``research project'' that preceeded 8sync.
1243 It attempted to bring an actor model system to Python.
1244 However, the author eventually grew frustrated with some of Python's
1245 limitations, fell in love with Guile, and well... now we have 8sync.
1246 Much of 8sync's actor model design came from experiments in developing
1247 XUDD.
1248
1249 @end itemize
1250
1251 The motivation to build 8sync came out of
1252 @uref{https://lists.gnu.org/archive/html/guile-devel/2015-10/msg00015.html,
1253       a conversation}
1254 at the FSF 30th party between Mark Weaver, David Thompson, Andrew
1255 Engelbrecht, and Christopher Allan Webber over how to build
1256 an asynchronous event loop for Guile and just what would be needed.
1257
1258 A little over a month after that, hacking on 8sync began!
1259
1260 \f
1261
1262 @node Copying This Manual
1263 @appendix Copying This Manual
1264
1265 This manual is licensed under the GNU Free Documentation License, with
1266 no invariant sections.  At your option, it is also available under the
1267 GNU Lesser General Public License, as published by the Free Software
1268 Foundation, version 3 or any later version.
1269
1270 \f
1271
1272 @menu
1273 * GNU Free Documentation License::  License for copying this manual.
1274 @end menu
1275
1276 @c Get fdl.texi from http://www.gnu.org/licenses/fdl.html
1277 @node GNU Free Documentation License
1278 @section GNU Free Documentation License
1279 @include fdl.texi
1280
1281 @node Index
1282 @unnumbered Index
1283
1284 @syncodeindex tp fn
1285 @syncodeindex vr fn
1286 @printindex fn
1287
1288 @bye
1289
1290 @c 8sync.texi ends here