-
Notifications
You must be signed in to change notification settings - Fork 2
/
session2.html
834 lines (581 loc) Β· 16.2 KB
/
session2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
<!DOCTYPE html>
<html>
<head>
<title>Haskell - Adventures in IO</title>
<meta charset="utf-8">
<style>
/* @import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic); */
@import url(css/metropolis.css);
</style>
</head>
<body>
<textarea id="source">
class: center, middle, title-slide
count: false
![Haskell - Adventures in IO](img/session2.png)
.less-line-height[
Alejandro Serrano @ ZuriHac 2022
.grey[π¦ @trupill - πββ¬ serras - π¨βπ» Tweag]
]
---
# π₯
Overall goal
### .grey[How do we build software with Haskell?]
1. ~~Domain-specific languages <br /> Representing actions and scripts <br /> Property-based testing~~
2. Communicating over the network <br /> Serialization (without boilerplate) <br /> Error handling <br /> Concurrency across threads
---
# π Overall goal
### .grey[Build an interactive card game]
1. Represent the cards and the actions
2. Communicate different clients
<table>
<tr>
<td style="vertical-align: top"><img src="img/pikachucard.png" width="100%" /></td>
<td width="82%" style="padding-left: 20px; line-height: 1.3;">
<h3 style="margin-bottom: -20px"><img src="img/pikachu.png" width="32px" /> PokΓ©mon Trading Card Game</h3>
<p>Goal: knock out 6 of your opponent's PokΓ©mon using attacks</p>
</td>
</tr>
</table>
---
# π Overall goal
### .grey[Build an interactive card game]
1. Represent the cards and the actions
2. Communicate different clients
<table>
<tr>
<td style="vertical-align: top"><img src="img/pikachucard.png" width="100%" /></td>
<td width="82%" style="padding-left: 20px; line-height: 1.3;">
<h3><img src="img/pikachu.png" width="32px" /> PokΓ©mon Trading Card Game</h3>
<h2>Waaaay too complex for 1.5h!</h2>
</td>
</tr>
</table>
---
# π² Dice roll
<img src="img/diceroll.jpg" width="90%" />
---
# π² Dice roll in the cloud βοΈ
<img src="img/diceroll.jpg" width="90%" />
---
# π Our stack
<img src="img/haskell-rainbow.gif" height="40px" /> Haskell (of course)
`network-simple` for networking
`binary` and `aeson` for serialization
`stm` for concurrency
---
# π² One-person dice roll
π’ Client requests a roll of _n_ faces
βοΈ Server returns a random value
<img src="img/random_number.png" width="80%" />
.smaller[.little-margin-top[
_(mandatory XKCD strip)_
]]
---
# π§ Server-side `network-simple`
Let's practice signature-reading skills
.code70[
```haskell
serve
:: MonadIO m
=> HostPreference
-- ^ Host to bind.
-> ServiceName
-- ^ Server service port to bind.
-> ((Socket, SockAddr) -> IO ())
-- ^ Computation to run in a different thread
-- once an incoming connection is accepted.
-> m a -- ^ This function never returns.
```
]
---
# π§ Server-side `network-simple`
`serve` takes care of:
- Listening all the time at the given port
- Whenever a new connection request comes <br/> 1οΈβ£ accept it, <br /> 2οΈβ£ **spawn a new thread**, <br /> 3οΈβ£ run the callback.
---
# βΏ `go` pattern
Once we accept, we go into an (infinite) _loop_
- Usually with a recursive `go` function
.code70[
```haskell
diceServer :: IO ()
diceServer = serve "*" "8080" $ \(skt, _) -> do
-- initialization
go skt
where go :: Socket -> IO ()
go skt = do
-- read and parse request
-- send a response
go skt -- and over again!
```
]
---
# π§ Server-side `network-simple`
Requests and responses are 64-bit numbers
.little-margin-top[.code70[
```haskell
go :: Socket -> IO ()
go skt = do
-- read and parse request
mayBytes <- recv skt 8
case mayBytes of
Nothing -> pure () -- done
Just bytes -> do
let Right max = decode @Word64 bytes
response <- encode <$> randomRIO (0, max)
-- send a response
send skt response
go skt -- and over again!
```
]]
---
# π Recognizing end-of-connection
If `recv` returns nothing, we stop the loop
```haskell
go skt = do
-- read and parse request
mayBytes <- recv skt 8
case mayBytes of
Nothing -> pure () -- done
Just bytes -> do
...
go skt -- and over again!
```
---
# π Serialization
Conversion to and from `ByteString`
- `cereal` for binary encoding
- `aeson` for JSON
- `avro` for Avro (used in Kafka)
- ...
---
# π Serialization
Users implement instances of some classes
- Just one, like `Serialize` in `cereal`
- Two, like `ToJSON` and `FromJSON`
And then conversion is provided by generic
```haskell
encode :: Serialize a {- or -} ToFormat a
=> a -> ByteString
decode :: Serialize a {- or -} FromFormat a
=> ByteString -> Either Error a
```
---
# πͺ’ Type applications
Help the compiler to disambiguate types
```haskell
decode @Word64 bytes
```
Other possibility is `ScopedTypeVariables`
---
# π² One-person dice roll client
## .grey[π§βπ» Time for practice!] .font50[`serras.github.io/zurihac-workshop`]
.code70[
```haskell
connect
:: (MonadIO m, MonadMask m)
=> HostName
-- ^ Server hostname or IP address.
-> ServiceName
-- ^ Server service port.
-> ((Socket, SockAddr) -> m r)
-- ^ Computation taking the communication
-- socket and the server address.
-> m r
```
]
---
# π² One-person dice roll client
## .grey[π€ How do I test this?] .font50[`serras.github.io/zurihac-workshop`]
.code60[
```haskell
$ cabal repl session2
> import DiceRoll
DiceRoll> diceServer
^C -- use Ctrl + C to stop
```
```haskell
$ cabal repl session2
> import DiceRoll
DiceRoll> diceClient 6
3
DiceRoll> diceClient 10
9
```
]
---
# βΌοΈ Exceptions
You forget to start the server and...
```
> DiceRoll.diceClient 3
*** Exception: Network.Socket.connect:
<socket: 12>: does not exist
(Connection refused)
```
## π± WAAAAAAT????
---
# βΌοΈ Exceptions
Haskell's `IO` runtime uses **exceptions**
- Network or connection problems
- File (or resource) not found
- and many more input/output problems
Even some built-in features use exceptions
- Pattern match failure
- `undefined` and `error`
---
# βοΈ Dealing with exceptions
~~Use `Control.Exception` from `base`~~
π
°οΈ Use `Control.Exception.Safe` <br /> from `safe-exceptions`
π
±οΈ Use `UnliftIO.Exception` from `unliftio`
### .grey[All three provide the same API]
---
# βοΈ Dealing with exceptions
If you want to perform some handling
```haskell
catch :: (MonadCatch m, Exception e)
=> m a -> (e -> m a) -> m a
```
If you want to "purify" the problem
```haskell
try :: (MonadCatch m, Exception e)
=> m a -> m (Either e a)
```
---
# βοΈ Idiomatic usage of `catch`
.code70[
```haskell
diceClient :: Word64 -> IO (Maybe Word64)
diceClient n =
connect "127.0.0.1" "8080" (\(skt, _) -> do
...)
`catch`
(\(e :: IOException) -> pure Nothing)
```
]
- Use `catch` infix
- Use `ScopedTypeVariables` to indicate which exceptions are to be caught
---
# π«
Exception hierarchy
Exception types for a hierarchy
- The top is called `SomeException`
However, if you want to "swallow" all exceptions, better use
.code70[
```haskell
catchAny :: MonadCatch m
=> m a -> (SomeException -> m a) -> m a
tryAny :: MonadCatch m
=> m a -> m (Either SomeException a)
```
]
---
# π§° Resource management
### .grey[Exception + laziness = π΅βπ«]
This makes resource management challenging <br /> (even more than usual)
π
°οΈ Use `resourcet` <br />
π
±οΈ Use `managed` <br />
β `resource-pool` to handle pools of resources
---
# π² Dice roll and increment
### .grey[We want to extend the functionality]
How do we (de)serialize command and data?
1. Express them as data types
2. Implement `Serialize` instances
---
# π² Dice roll and increment
### .grey[We want to extend the functionality]
How do we (de)serialize command and data?
1. Express them as data types
```haskell
data Request
= DiceRoll { max :: Word64 }
| Increment { number :: Word64 }
type Response = Word64
```
---
# π² Dice roll and increment
### .grey[We want to extend the functionality]
How do we (de)serialize command and data?
1. Express them as data types
2. ~~Implement `Serialize` instances~~
## Use automatic deriving!
---
# π€ Automatic deriving
Compiler writes instances for us
- `Eq`, `Show`, and others are built-in
- Extensible with the `Generic` mechanism
.code70[
```haskell
{-# language DeriveGeneric, DeriveAnyClass #-}
data Request
= DiceRoll { max :: Word64 }
| Increment { number :: Word64 }
deriving (Generic, Serialize)
```
]
---
# π§ Updated server-side
```haskell
let Right max = decode @Word64 bytes
response <- encode <$> randomRIO (1, max)
```
Deserialize with the new type
```haskell
let Right req = decode @Request bytes
response <- case req of
DiceRoll max -> randomRIO (1, max)
Increment n -> pure (n + 1)
```
---
# π§ Updated server-side
```haskell
let Right max = decode @Word64 bytes
response <- encode <$> randomRIO (1, max)
```
Deserialize with the new type
```haskell
let Right req = decode bytes
response <- case req of
DiceRoll max -> randomRIO (1, max)
Increment n -> pure (n + 1)
```
The type `Request` can be inferred
---
# π¬ Greeting
## .grey[π§βπ» Time for practice!] .font50[`serras.github.io/zurihac-workshop`]
Add a new command to say "hi!" to people
Make it as flexible as you want:
- Name of the person to be greeted
- Language
- Time of the day
---
# βοΈπ² Cloudy Rolly
βοΈ Central server which processes requests
1οΈβ£ Player #1 joins and gets a code
2οΈβ£ Player #2 joins the session using that code
.grey[
π² Players send a new request for rolling
- The server sends the winner to both players
]
---
# βοΈπ² Cloudy Rolly
.grey[
βοΈ Central server which processes requests
1οΈβ£ Player #1 joins and gets a code
2οΈβ£ Player #2 joins the session using that code
]
## 𧡠Each player runs in a different thread
πͺ‘ How to communicate across boundaries?
---
# πͺ‘ Communication across threads
~~Use `Control.Concurrent` from `base`~~
Use `stm` (Software Transactional Memory)
- Similar concept as in databases
- Transactions are isolated and atomic
- One cannot read the dirty state of another
---
# πͺ‘ Software Transactional Memory
One cannot read the dirty state of another
```haskell
do v <- newTVarIO 0
replicateM 3 $ async $ -- 3 threads
atomically $ do -- tx. boundary
n <- readTVar v -- β
writeTVar (n + 1) -- ββ
```
The end value of `v` is **guaranteed** to be 3
---
# β»οΈ Server as state machine
When a user connects...
- If they send `NewGame`, send a `GameCode`
- When the other player connects, </br> send `GameStarts`
- If they send `JoinGame` and the code
- If the code exists, send `GameStarts`
- Otherwise, send `GameNotFound` and close
- Otherwise, close the connection
---
# πͺ‘ Shared state
Dictionary (key-value map)
- Keys are `GameCode`s
- Values are the sockets
--
```haskell
crServer = do
-- initialize shared state
state <- newTVarIO @State Map.empty
serve "127.0.0.1" "8080" $ \(skt, _) ->
worker state skt
worker :: TVar State -> Socket -> IO ()
```
---
# π· Cloudy Rolly worker
Trick to avoid repeating `state` and `skt`
.code70[
```haskell
worker :: TVar State -> Socket -> IO ()
worker state skt = start
where
start = do
...
newGame = ...
joinGame code = ...
play = putStrLn "play!"
```
]
---
# π· Cloudy Rolly worker
Wait for the first message to come
.little-margin-top[.code70[
```haskell
worker state skt = start
where
start = do
Just req <- recvJson skt
case req of
NewGame -> newGame
JoinGame code -> joinGame code
```
```haskell
-- read a line and deserialize
recvJson :: (MonadIO m, FromJSON a)
=> Socket -> m (Maybe a)
```
]
]
---
# π· Cloudy Rolly worker
.code60[
```haskell
worker state skt = start
where
newGame = do
-- record ourselves in new code
code <- randomCode
atomically $
modifyTVar state (Map.insert code [skt])
sendJson skt (GameCode code)
-- wait for the other message
atomically $ do
Just skts <- Map.lookup code <$> readTVar state
check (length skts > 1)
sendJson skt GameStarts
-- go!
play
```
]
---
# π Retry transactions
.code70[
```haskell
-- wait for the other message
atomically $ do
Just skts <- Map.lookup code <$> readTVar state
check (length skts > 1)
```
]
- `check` aborts the tx. if the condition is `False`
- The tx. is only retried when any `TVar` mentioned changes its value
### `TVar` works as a synchronization mechanism
---
# π· Cloudy Rolly worker
.code60[
```haskell
worker state skt = start
where
joinGame code = do
found <- atomically $ do
-- tx. boundary βββββββββββββββββββββββββββββββββ
result <- Map.lookup code <$> readTVar state -- β
case result of -- β
Nothing -> pure False -- β
Just skts -> do -- β
modifyTVar state $ -- β
Map.insertWith (<>) code [skt] -- β
pure True -- β
-- ββββββββββββββββββββββββββββββββββββββββββββββ
if found
then sendJson skt GameStarts >> play
else sendJson skt GameNotFound
```
]
---
# π· Cloudy Rolly worker
.code60[
```haskell
worker state skt = start
where
joinGame code = do
found <- atomically $ do
-- tx. boundary βββββββββββββββββββββββββββββββββ
result <- Map.lookup code <$> readTVar state -- β
case result of -- β
Nothing -> pure False -- β
Just skts -> do -- β
modifyTVar state $ -- β
Map.insertWith (<>) code [skt] -- β
pure True -- β
-- ββββββββββββββββββββββββββββββββββββββββββββββ
```
]
Transaction may include pure computations
---
# βοΈπ² Cloudy Rolly
## .grey[π π§βπ» (No more) time for practice!]
### Finish the implementation of the server
1. Change `State` to represent on-going games
2. Use `TVar` as synchronization mechanism
3. Write a single `play` implementation
### Finish the implementation of the clients
---
# πͺ‘ STM-enabled data structures
Many users `==>` lots of contention
- Every `JoinGame` "wakes up" every `NewGame`
- But we only care about one code!
--
### More fine-grained data structures
.margin-top[
- `stm-containers` brings maps and sets
- `stm` includes unbounded queues
- `stm-chans` adds bounded queues
]
---
# π Summary
### .grey[Lots of practice in the `IO` monad]
.margin-top[
- GHC uses exceptions for I/O errors
- High-level networking with `network-simple`
- Automatic deriving = <br /> serialization without the boilerplate
- `stm` for communication across threads
]
--
- Spawning and controlling threads with `async`
- `MonadIO` and `MonadUnliftIO`
---
# πΈ A word from our sponsor
## `leanpub.com/haskell-stdlibs`
<table style="margin-top: 40px;">
<tr>
<td style="vertical-align: top"><img src="img/libs.png" width="100%" /></td>
<td width="70%">
<ul style="margin-top: -60px; margin-bottom: -30px">
<li>More on exceptions and resource management</li>
<li>I/O using streaming</li>
<li>Servers and clients with HTTP</li>
</ul>
</td>
</tr>
</table>
<div class="grey"><b>Many other useful libraries in the ecosystem</b></div>
---
class: center, middle, title-slide
# π€© It's been a pleasure
## Enjoy the rest of ZuriHac!
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js">
</script>
<script>
var slideshow = remark.create();
</script>
</body>
</html>