doc: Add pk debugging section.
[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 ** Intro to the tutorial
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.
87
88 In the 1990s I remember stumbling into some funky IRC chat rooms and
89 being astounded that people there had what they called "bots" hanging
90 around.
91 From then until now, I've always enjoyed encountering bots whose range
92 of functionality has spanned from saying absurd things, to taking
93 messages when their "owners" were offline, to reporting the weather,
94 to logging meetings for participants.
95 And it turns out, IRC bots are a great way to cut your teeth on
96 networked programming; since IRC is a fairly simple line-delineated
97 protocol, it's a great way to learn to interact with sockets.
98 (My first IRC bot helped my team pick a place to go to lunch, previously
99 a source of significant dispute!)
100 At the time of writing, venture capital awash startups are trying to
101 turn chatbots into "big business"... a strange (and perhaps absurd)
102 thing given chat bots being a fairly mundane novelty amongst hackers
103 and teenagers everywhere in the 1990s.
104
105 We ourselves are going to explore chat bots as a basis for getting our
106 feet wet in 8sync.
107 We'll start from a minimalist example using an irc bot with most of
108 the work done for us, then move on to constructing our own actors as
109 "game pieces" which interface with our bot, then experiment with just
110 how easy it is to add new networked layers by tacking on a high score
111 to our game, and as a finale we'll dive into writing our own little
112 irc bot framework "from scratch" on top of the 8sync actor model.
113
114 Alright, let's get started.
115 This should be a lot of fun!
116
117 ** A silly little IRC bot
118
119 First of all, we're going to need to import some modules.  Put this at
120 the top of your file:
121
122 #+BEGIN_SRC scheme
123   (use-modules (8sync)               ; 8sync's agenda and actors
124                (8sync systems irc)   ; the irc bot subsystem
125                (oop goops)           ; 8sync's actors use GOOPS
126                (ice-9 format)        ; basic string formatting
127                (ice-9 match))        ; pattern matching
128 #+END_SRC
129
130 Now we need to add our bot.  Initially, it won't do much.
131
132 #+BEGIN_SRC scheme
133   (define-class <my-irc-bot> (<irc-bot>))
134
135   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
136                               line emote?)
137     (if emote?
138         (format #t "~a emoted ~s in channel ~a\n"
139                 speaker line channel)
140         (format #t "~a said ~s in channel ~a\n"
141                 speaker line channel)))
142 #+END_SRC
143
144 We've just defined our own IRC bot!
145 This is an 8sync actor.
146 (8sync uses GOOPS to define actors.)
147 We extended the handle-line generic method, so this is the code that
148 will be called whenever the IRC bot "hears" anything.
149 For now the code is pretty basic: it just outputs whatever it "hears"
150 from a user in a channel to the current output port.
151 Pretty boring!
152 But it should help us make sure we have things working when we kick
153 things off.
154
155 Speaking of, even though we've defined our actor, it's not running
156 yet.  Time to fix that!
157
158 #+BEGIN_SRC scheme
159 (define* (run-bot #:key (username "examplebot")
160                   (server "irc.freenode.net")
161                   (channels '("##botchat")))
162   (define hive (make-hive))
163   (define irc-bot
164     (hive-create-actor* hive <my-irc-bot> "irc-bot"
165                         #:username username
166                         #:server server
167                         #:channels channels))
168   (run-hive hive (list (bootstrap-message hive irc-bot 'init))))
169 #+END_SRC
170
171 Actors are connected to something called a "hive", which is a
172 special kind of actor that runs all the other actors.
173 Actors can spawn other actors, but before we start the hive we use
174 this special "hive-create-actor*" method.
175 It takes the hive as its first argument, the actor class as the second
176 argument, a decorative "cookie" as the third argument (this is
177 optional, but it helps with debugging... you can skip it by setting it
178 to #f if you prefer), and the rest are initialization arguments to the
179 actor.  hive-create-actor* passes back not the actor itself (we don't
180 get access to that usually) but the *id* of the actor.
181 (More on this later.)
182 Finally we run the hive with run-hive and pass it a list of
183 "bootstrapped" messages.
184 Normally actors send messages to each other (and sometimes themselves),
185 but we need to send a message or messages to start things or else
186 nothing is going to happen.
187
188 We can run it like:
189
190 #+BEGIN_SRC scheme
191 (run-bot #:username "some-bot-username") ; be creative!
192 #+END_SRC
193
194 Assuming all the tubes on the internet are properly connected, you
195 should be able to join the "##botchat" channel on irc.freenode.net and
196 see your bot join as well.
197 Now, as you probably guessed, you can't really /do/ much yet.
198 If you talk to the bot, it'll send messages to the terminal informing
199 you as such, but it's hardly a chat bot if it's not chatting yet.
200
201 So let's do the most boring (and annoying) thing possible.
202 Let's get it to echo whatever we say back to us.
203 Change handle-line to this:
204
205 #+BEGIN_SRC scheme
206   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
207                               line emote?)
208     (<- irc-bot (actor-id irc-bot) 'send-line channel
209         (format #f "Bawwwwk! ~a says: ~a" speaker line)))
210 #+END_SRC
211
212 This will do exactly what it looks like: repeat back whatever anyone
213 says like an obnoxious parrot.
214 Give it a try, but don't keep it running for too long... this
215 bot is so annoying it's likely to get banned from whatever channel
216 you put it in.
217
218 This method handler does have the advantage of being simple though.
219 It introduces a new concept simply... sending a message!
220 Whenever you see "<-", you can think of that as saying "send this
221 message".
222 The arguments to "<-" are as follows: the actor sending the message,
223 the id of the actor the message is being sent to, the "action" we
224 want to invoke (a symbol), and the rest are arguments to the
225 "action handler" which is in this case send-line (with itself takes
226 two arguments: the channel our bot should send a message to, and
227 the line we want it to spit out to the channel).
228
229 (Footnote: 8sync's name for sending a message, "<-", comes from older,
230 early lisp object oriented systems which were, as it turned out,
231 inspired by the actor model!
232 Eventually message passing was dropped in favor of something called
233 "generic functions" or "generic methods"
234 (you may observe we made use of such a thing in extending
235 handle-line).
236 Many lispers believe that there is no need for message passing
237 with generic methods and some advanced functional techniques,
238 but in a concurrent environment message passing becomes useful
239 again, especially when the communicating objects / actors are not
240 in the same address space.)
241
242 Normally in the actor model, we don't have direct references to
243 an actor, only an identifier.
244 This is for two reasons: to quasi-enforce the "shared nothing"
245 environment (actors absolutely control their own resources, and
246 "all you can do is send a message" to request that they modify
247 them) and because... well, you don't even know where that actor is!
248 Actors can be anything, and anywhere.
249 It's possible in 8sync to have an actor on a remote hive, which means
250 the actor could be on a remote process or even remote machine, and
251 in most cases message passing will look exactly the same.
252 (There are some exceptions; it's possible for two actors on the same
253 hive to "hand off" some special types of data that can't be serialized
254 across processes or the network, eg a socket or a closure, perhaps even
255 one with mutable state.
256 This must be done with care, and the actors should be careful both
257 to ensure that they are both local and that the actor handing things
258 off no longer accesses that value to preserve the actor model.
259 But this is an advanced topic, and we are getting ahead of ourselves.)
260 We have to supply the id of the receiving actor, and usually we'd have
261 only the identifier.
262 But since in this case, since the actor we're sending this to is
263 ourselves, we have to pass in our identifier, since the Hive won't
264 deliver to anything other than an address.
265
266 Astute readers may observe, since this is a case where we are just
267 referencing our own object, couldn't we just call "sending a line"
268 as a method of our own object without all the message passing?
269 Indeed, we do have such a method, so we /could/ rewrite handle-line
270 like so:
271
272 #+BEGIN_SRC scheme
273   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
274                               line emote?)
275     (irc-bot-send-line irc-bot channel
276                        (format #f "Bawwwwk! ~a says: ~a" speaker line)))
277 #+END_SRC
278
279 ... but we want to get you comfortable and familiar with message
280 passing, and we'll be making use of this same message passing shortly
281 so that /other/ actors may participate in communicating with IRC
282 through our IRC bot.
283
284 Anyway, our current message handler is simply too annoying.
285 What would be much more interesting is if we could recognize
286 when an actor could repeat messages /only/ when someone is speaking
287 to it directly.
288 Luckily this is an easy adjustment to make.
289
290 #+BEGIN_SRC scheme
291   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
292                               line emote?)
293     (define my-name (irc-bot-username irc-bot))
294     (define (looks-like-me? str)
295       (or (equal? str my-name)
296           (equal? str (string-concatenate (list my-name ":")))))
297     (when (looks-like-me?)
298       (<- irc-bot (actor-id irc-bot) 'send-line channel
299           (format #f "Bawwwwk! ~a says: ~a" speaker line))))
300 #+END_SRC
301
302 This is relatively straightforward, but it isn't very interesting.
303 What we would really like to do is have our bot respond to individual
304 "commands" like this:
305
306 #+BEGIN_SRC text
307   <foo-user> examplebot: hi!
308   <examplebot> Oh hi foo-user!
309   <foo-user> examplebot: botsnack
310   <examplebot> Yippie! *does a dance!*
311   <foo-user> examplebot: echo I'm a very silly bot
312   <examplebot> I'm a very silly bot
313 #+END_SRC
314
315 Whee, that looks like fun!
316 To implement it, we're going to pull out Guile's pattern matcher.
317
318 #+BEGIN_SRC scheme
319   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
320                               line emote?)
321     (define my-name (irc-bot-username irc-bot))
322     (define (looks-like-me? str)
323       (or (equal? str my-name)
324           (equal? str (string-concatenate (list my-name ":")))))
325     (match (string-split line #\space)
326       (((? looks-like-me? _) action action-args ...)
327        (match action
328          ;; The classic botsnack!
329          ("botsnack"
330           (<- irc-bot (actor-id irc-bot) 'send-line channel
331               "Yippie! *does a dance!*"))
332          ;; Return greeting
333          ((or "hello" "hello!" "hello." "greetings" "greetings." "greetings!"
334               "hei" "hei." "hei!" "hi" "hi!")
335           (<- irc-bot (actor-id irc-bot) 'send-line channel
336               (format #f "Oh hi ~a!" speaker)))
337          ("echo"
338           (<- irc-bot (actor-id irc-bot) 'send-line channel
339               (string-join action-args " ")))
340
341          ;; --->  Add yours here <---
342
343          ;; Default
344          (_
345           (<- irc-bot (actor-id irc-bot) 'send-line channel
346               "*stupid puppy look*"))))))
347 #+END_SRC
348
349 Parsing the pattern matcher syntax is left as an exercise for the
350 reader.
351
352 If you're getting the sense that we could make this a bit less wordy,
353 you're right:
354
355 #+BEGIN_SRC scheme
356   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
357                               line emote?)
358     (define my-name (irc-bot-username irc-bot))
359     (define (looks-like-me? str)
360       (or (equal? str my-name)
361           (equal? str (string-concatenate (list my-name ":")))))
362     (define (respond respond-line)
363       (<- irc-bot (actor-id irc-bot) 'send-line channel
364           respond-line))
365     (match (string-split line #\space)
366       (((? looks-like-me? _) action action-args ...)
367        (match action
368          ;; The classic botsnack!
369          ("botsnack"
370           (respond "Yippie! *does a dance!*"))
371          ;; Return greeting
372          ((or "hello" "hello!" "hello." "greetings" "greetings." "greetings!"
373               "hei" "hei." "hei!" "hi" "hi." "hi!")
374           (respond (format #f "Oh hi ~a!" speaker)))
375          ("echo"
376           (respond (string-join action-args " ")))
377
378          ;; --->  Add yours here <---
379
380          ;; Default
381          (_
382           (respond "*stupid puppy look*"))))))
383 #+END_SRC
384
385 Okay, that looks pretty good!
386 Now we have enough information to build an IRC bot that can do a lot
387 of things.
388 Take some time to experiment with extending the bot a bit before
389 moving on to the next section!
390 What cool commands can you add?
391
392 ** An intermission: about live hacking
393
394 This section is optional, but highly recommended.
395 It requires that you're a user of GNU Emacs.
396 If you aren't, don't worry... you can forge ahead and come back in case
397 you ever do become an Emacs user.
398 (If you're more familiar with Vi/Vim style editing, I hear good things
399 about Spacemacs...)
400
401 So you may have noticed while updating the last section that the
402 start/stop cycle of hacking isn't really ideal.
403 You might either edit a file in your editor, then run it, or
404 type the whole program into the REPL, but then you'll have to spend
405 extra time copying it to a file.
406 Wouldn't it be nice if it were possible to both write code in a
407 file and try it as you go?
408 And wouldn't it be even better if you could live edit a program
409 while it's running?
410
411 Luckily, there's a great Emacs mode called Geiser which makes
412 editing and hacking and experimenting all happen in harmony.
413 And even better, 8sync is optimized for this experience.
414 8sync provides easy drop-in "cooperative REPL" support, and
415 most code can be simply redefined on the fly in 8sync through Geiser
416 and actors will immediately update their behavior, so you can test
417 and tweak things as you go.
418
419 Okay, enough talking.  Let's add it!
420 Redefine run-bot like so:
421
422 #+BEGIN_SRC scheme
423   (define* (run-bot #:key (username "examplebot")
424                     (server "irc.freenode.net")
425                     (channels '("##botchat"))
426                     (repl-path "/tmp/8sync-repl"))
427     (define hive (make-hive))
428     (define irc-bot
429       (hive-create-actor* hive <my-irc-bot> "irc-bot"
430                           #:username username
431                           #:server server
432                           #:channels channels))
433     (define repl-manager
434       (hive-create-actor* hive <repl-manager> "repl"
435                           #:path repl-path))
436
437     (run-hive hive (list (bootstrap-message hive irc-bot 'init)
438                          (bootstrap-message hive repl-manager 'init))))
439 #+END_SRC
440
441 If we put a call to run-bot at the bottom of our file we can call it,
442 and the repl-manager will start something we can connect to automatically.
443 Horray!
444 Now when we run this it'll start up a REPL with a unix domain socket at
445 the repl-path.
446 We can connect to it in emacs like so:
447
448 : M-x geiser-connect-local <RET> guile <RET> /tmp/8sync-repl <RET>
449
450 Okay, so what does this get us?
451 Well, we can now live edit our program.
452 Let's change how our bot behaves a bit.
453 Let's change handle-line and tweak how the bot responds to a botsnack.
454 Change this part:
455
456 #+BEGIN_SRC scheme
457   ;; From this:
458   ("botsnack"
459    (respond "Yippie! *does a dance!*"))
460
461   ;; To this:
462   ("botsnack"
463    (respond "Yippie! *catches botsnack in midair!*"))
464 #+END_SRC
465
466 Okay, now let's evaluate the change of the definition.
467 You can hit "C-M-x" anywhere in the definition to re-evaluate.
468 (You can also position your cursor at the end of the definition and press
469 "C-x C-e", but I've come to like "C-M-x" better because I can evaluate as soon
470 as I'm done writing.)
471 Now, on IRC, ask your bot for a botsnack.
472 The bot should give the new message... with no need to stop and start the
473 program!
474
475 Let's fix a bug live.
476 Our current program works great if you talk to your bot in the same
477 IRC channel, but what if you try to talk to them over private message?
478
479 #+BEGIN_SRC text
480 IRC> /query examplebot
481 <foo-user> examplebot: hi!
482 #+END_SRC
483
484 Hm, we aren't seeing any response on IRC!
485 Huh?  What's going on?
486 It's time to do some debugging.
487 There are plenty of debugging tools in Guile, but sometimes the simplest
488 is the nicest, and the simplest debugging route around is good old
489 fashioned print debugging.
490
491 It turns out Guile has an under-advertised feature which makes print
492 debugging really easy called "pk", pronounced "peek".
493 What pk accepts a list of arguments, prints out the whole thing,
494 but returns the last argument.
495 This makes wrapping bits of our code pretty easy to see what's
496 going on.
497 So let's peek into our program with pk.
498 Edit the respond section to see what channel it's really sending
499 things to:
500
501 #+BEGIN_SRC scheme
502   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
503                               line emote?)
504     ;; [... snip ...]
505     (define (respond respond-line)
506       (<- irc-bot (actor-id irc-bot) 'send-line (pk 'channel channel)
507           respond-line))
508     ;; [... snip ...]
509     )
510 #+END_SRC
511
512 Re-evaluate.
513 Now let's ping our bot in both the channel and over PM.
514
515 #+BEGIN_SRC text
516 ;;; (channel "##botchat")
517
518 ;;; (channel "sinkbot")
519 #+END_SRC
520
521 Oh okay, this makes sense.
522 When we're talking in a normal multi-user channel, the channel we see
523 the message coming from is the same one we send to.
524 But over PM, the channel is a username, and in this case the username
525 we're sending our line of text to is ourselves.
526 That isn't what we want.
527 Let's edit our code so that if we see that the channel we're sending
528 to looks like our own username that we respond back to the sender.
529 (We can remove the pk now that we know what's going on.)
530
531 #+BEGIN_SRC scheme
532   (define-method (handle-line (irc-bot <my-irc-bot>) speaker channel
533                               line emote?)
534     ;; [... snip ...]
535     (define (respond respond-line)
536       (<- irc-bot (actor-id irc-bot) 'send-line
537           (if (looks-like-me? channel)
538               speaker    ; PM session
539               channel)   ; normal IRC channel
540           respond-line))
541     ;; [... snip ...]
542     )
543 #+END_SRC
544
545 Re-evaluate and test.
546
547 #+BEGIN_SRC text
548 IRC> /query examplebot
549 <foo-user> examplebot: hi!
550 <examplebot> Oh hi foo-user!
551 #+END_SRC
552
553 Horray!
554
555 ** Battle bot!
556
557 ** Adding a "rankings" web page
558
559 ** Writing our own <irc-bot> from scratch
560
561 * API reference
562