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