-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1121 lines (945 loc) · 35.4 KB
/
index.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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pub/Sub from Scratch in Go – Code Craft August 2016</title>
<meta name="author" content="Tim Penhey">
<meta name="description" content="Publish/Subscribe project in Go.">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<style>
.reveal pre {
width: 100%;
margin: 0;
}
.reveal section img {
padding: 1em;
background-color:#ddd;
}
.reveal p code {
color: yellow;
font-size: 80%;
}
</style>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h2>Code Craft</h2>
<ul style="line-height: 2em">
<li>We meet here the first Tuesday of the month.</li>
<li>Meetings are organised on meetup.com
<ul>
<li><a href="http://www.meetup.com/Code-Craft-Dunedin/">www.meetup.com/Code-Craft-Dunedin/</a></li>
</ul>
</li>
<li>The mailing list is hosted on google groups
<ul>
<li><a href="http://groups.google.com/group/codecraft-dunedin">groups.google.com/group/codecraft-dunedin</a></li>
</ul>
</li>
<li>Come and talk about something you are interested in.</li>
<li>Let us know what you want to hear about.</li>
</ul>
</section>
<section>
<h1>Pub/Sub</h1>
<h1>from Scratch</h1>
<h1>in Go</h1>
<p>
<small><a href="http://github.com/howbazaar">Tim Penhey</a> / <a href="http://twitter.com/howbazaar">@howbazaar</a></small>
</p>
</section>
<section>
<h2>What's Pub/Sub?</h2>
<ul style="line-height: 2em">
<li>Short for Publish and Subscribe.</li>
<li>A method of decoupling the producer of the information (the Publisher) from the consumer (the Subscriber).</li>
</ul>
</section>
<section>
<h2>This talk</h2>
<ul style="line-height: 2em">
<li>Getting to a publish and subscribe abstraction.</li>
<li>Walk through the development process of a library.</li>
<li>End up with a quick look at <a href="http://github.com/juju/pubsub">http://github.com/juju/pubsub</a>.</li>
</ul>
</section>
<section>
<h2>In the beginning...</h2>
</section>
<section>
<section>
<h2>Tight Coupling</h2>
<p>Traditional method calling.</p>
<img src="producer-consumer.png">
</section>
<section>
<h2>The Consumer</h2>
<p>We have a consumer that wants structured data.</p>
<pre><code class="go" data-trim>
type Consumer struct {
// internal fields, doesn't matter here
}
type Data struct {
// some useful data types
}
// This function has a receiver, the (*Consumer) bit, that
// makes it a method on Consumer.
func (*Consumer) Notify(data Data) {
// do stuff with data
}
</code></pre>
</section>
<section>
<h2>The Producer</h2>
<p>The producer, that creates the data, </p>
<p>has a reference to a consumer.</p>
<pre><code class="go" data-trim>
type Producer struct {
// This is a pointer to a Consumer structure.
consumer *Consumer
}
func NewProducer(consumer *Consumer) *Producer {
// & takes the address of the thing. This is how
// Go gets pointers to things. The {...} is a struct
// initialiser.
return &Producer{consumer}
}
</code></pre>
</section>
<section>
<h2>Method Calling</h2>
<p>The producer calls the method directly on the consumer.</p>
<pre><code class="go" data-trim>
// This receiver as a name "p", and is used to access
// the elements of the Producer struct. It is the "Go"
// way to generally use a single character for this,
// and not use words like "this" or "self".
func (p *Producer) Call() {
data := Data{...}
// do stuff
p.consumer.Notify(data)
}
</code></pre>
</section>
</section>
<section>
<section>
<h2>Reducing Coupling</h2>
<p>Step one is to use an interface.</p>
</section>
<section>
<h2>The Consumer interface</h2>
<p>Instead of taking a concerte type, the Consumer interface is declared with the Producer.</p>
<pre><code class="go" data-trim>
// An interface is just a collection of methods.
type Consumer interface {
Notify(data Data)
}
type Producer struct {
consumer Consumer
}
// Any type that implements the Notify method
// can be passed as the Consumer.
func NewProducer(consumer Consumer) *Producer {
return &Producer{consumer}
}
</code></pre>
</section>
<section>
<h2>Defining Consumers</h2>
<p>Any structure that implements the methods defined by the Consumer interface can now be passed to the NewProducer function.</p>
<pre><code class="go" data-trim>
type MyConsumer struct {
// internal fields, doesn't matter here
}
// Notify implements the Consumer insterface.
func (*MyConsumer) Notify(data Data) {
// do stuff with data
}
// in some function...
consumer := &MyConsumer{...}
producer := NewProducer(consumer)
</code></pre>
</section>
<section>
<h2>Method Calling</h2>
<p>The producer still calls the method directly on the consumer.</p>
<pre><code class="go" data-trim>
// This isn't a trick, it hasn't changed.
func (p *Producer) Call() {
data := Data{...}
// do stuff
p.consumer.Notify(data)
}
</code></pre>
</section>
</section>
<section>
<h2>What if there is more than one consumer?</h2>
<img src="producer-consumers.png" >
</section>
<section>
<section>
<h2>Enter the Observer Pattern</h2>
<figure>
<img src="observer.png" >
<figcaption style="font-size: 75%">Source: wikipedia</figcaption>
</figure>
</section>
<section>
<h2>Multiple Consumers</h2>
<p>Now the Producer has a slice of consumers.</p>
<pre><code class="go" data-trim>
type Producer struct {
// consumers is now a slice
consumers []Consumer
}
func (p *Producer) AddConsumer(consumer Consumer) {
p.consumers = append(p.consumers, consumer)
}
</code></pre>
</section>
<section>
<h2>Notifying Consumers</h2>
<p>Iterating over the consumers calling each one.</p>
<pre><code class="go" data-trim>
func (p *Producer) Call() {
data := Data{...}
// do stuff
// when iterating over a slice the first element
// is the index into the slice, and the second
// is the value in the slice, we don't care about
// the index here so we assign it to the "special"
// variable _.
for _, consumer := range p.consumers {
consumer.Notify(data)
}
}
</code></pre>
</section>
</section>
<section>
<section>
<h2>Decoupling the Producer and Consumer</h2>
<img src="hub.png" >
</section>
<section>
<h2>The Hub stores the consumers</h2>
<pre><code class="go" data-trim>
type Hub struct {
// the hub stores the consumers
consumers []Consumer
}
func (h *Hub) AddConsumer(consumer Consumer) {
h.consumers = append(h.consumers, consumer)
}
</code></pre>
</section>
<section>
<h2>Notifying Consumers</h2>
<pre><code class="go" data-trim>
// Calling Notify on the hub just calls Notify
// on all the consumers.
func (h *Hub) Notify(data Data) {
for _, consumer := range h.consumers {
consumer.Notify(data)
}
}
</code></pre>
</section>
<section>
<h2>The Producer becomes smiple again</h2>
<pre><code class="go" data-trim>
// We could use the concrete type Hub, but Hub
// implements the Consumer interface.
type Producer struct {
consumer Consumer
}
func NewProducer(consumer Consumer) *Producer {
return &Producer{consumer}
}
func (p *Producer) Call() {
data := Data{...}
// do stuff
p.consumer.Notify(data)
}
</code></pre>
</section>
</section>
<section>
<h2>Quick Glossary</h2>
<ul>
<li class="fragment">Publisher — the entity that generates the event</li>
<li class="fragment">Publishing — the act notifying the subscribers</li>
<li class="fragment">Subscriber — an entity wanting to be notified of an event</li>
<li class="fragment">Callback — a function passed by the subscriber to be called for the event</li>
</ul>
</section>
<section>
<section>
<h2>Making the Hub more generic</h2>
<ul>
<li class="fragment">Handle multiple event types</li>
<li class="fragment">Publish arbitrary message data</li>
<li class="fragment">Notify subscribers asynchronously</li>
</ul>
</section>
<section>
<h2>Multiple event types</h2>
<p>Use a name for an event, let's call them <em>topics</em>.</p>
<pre><code class="go" data-trim>
type Topic string
func (h *Hub) Publish(topic Topic, ...) {
// implementation
}
func (h *Hub) Subscribe(topic Topic, ...) {
// implementation
}
</code></pre>
</section>
<section>
<h2>Arbitrary message data</h2>
<p>The <code>interface{}</code> type can be anything.</p>
<pre><code class="go" data-trim>
// Publish a topic with some data.
func (h *Hub) Publish(topic Topic, data interface{}) {
// implementation
}
// Subscribe to a topic, and provide the callback that
// gets told the topic and the data.
func (h *Hub) Subscribe(topic Topic, func (Topic, interface{})) {
// implementation
}
</code></pre>
</section>
<section>
<h2>The subscriber</h2>
<pre><code class="go" data-trim>
type subscriber struct {
topic Topic
callback func(Topic, interface{})
}
type Hub struct {
mutex sync.Mutex
subscribers []*subscriber
}
func (h *Hub) Subscribe(topic Topic, callback func (Topic, interface{})) {
h.mutex.Lock()
// The "defer" keyword queues up the function to be called at the
// end of the function. Multiple defer calls work LIFO.
defer h.mutex.Unlock()
h.subscribers = append(h.subscribers, &subscriber{topic, callback})
}
</code></pre>
</section>
<section>
<h2>Async callback</h2>
<pre><code class="go" data-trim>
func (h *Hub) Publish(topic Topic, data interface{}) {
h.mutex.Lock()
defer h.mutex.Unlock()
for _, subscriber := range h.subscribers {
if subscriber.topic == topic {
// The "go" key word calls the function in
// a different goroutine.
go subscriber.callback(topic, data)
}
}
}
</code></pre>
</section>
</section>
<section>
<h2>Hub Guarantees</h2>
<ul>
<li class="fragment">Publish and Subscribe are goroutine safe</li>
<li class="fragment">Slow subscribers won't block Publish</li>
<li class="fragment">Slow subscribers won't interfere with other subscribers</li>
</ul>
</section>
<section>
<h2>Issues</h2>
<ul>
<li class="fragment">How do you unsubscribe?</li>
<li class="fragment">How do you test?</li>
<li class="fragment">What about callback ordering?</li>
</ul>
</section>
<section>
<section>
<h2>Unsubscribing</h2>
<p>Have the <code>Subscribe</code> function return something that can be used to unsubscribe.</p>
<pre><code class="go" data-trim>
type Unsubscriber interface {
Unsubscribe()
}
func (h *Hub) Subscribe(...) Unsubscriber {
// implementation
}
</code></pre>
</section>
<section>
<h2>Identifying the subscription</h2>
<p>Each subscription has a unique identifier.</p>
<pre><code class="go" data-trim data-noescape>
type subscriber struct {
<mark>id int</mark>
topic Topic
callback func(Topic, interface{})
}
type Hub struct {
mutex sync.Mutex
<mark>index int</mark>
subscribers []*subscriber
}
</code></pre>
</section>
<section>
<h2>The private unsubscribe method</h2>
<pre><code class="go" data-trim>
func (h *Hub) unsubscribe(id int) {
h.mutex.Lock()
defer h.mutex.Unlock()
for i, sub := range h.subscribers {
if sub.id == id {
h.subscribers = append(
h.subscribers[0:i],
h.subscribers[i+1:]...)
return
}
}
}
</code></pre>
</section>
<section>
<h2>The unsubscriber</h2>
<pre><code class="go" data-trim>
type handle struct {
hub *Hub
id int
}
// Unsubscribe implements Unsubscriber.
func (h *handle) Unsubscribe() {
h.hub.unsubscribe(h.id)
}
</code></pre>
</section>
<section>
<h2>Identifying the subscription</h2>
<p>Each subscription has a unique identifier.</p>
<pre><code class="go" data-noescape data-trim>
func (h *Hub) Subscribe(topic Topic,
callback func (Topic, interface{})) Unsubscriber {
h.mutex.Lock()
defer h.mutex.Unlock()
h.index++
h.subscribers = append(h.subscribers, &subscriber{
id: h.index, topic: topic, callback: callback})
return &handle{hub: h, id: h.index}
}
</code></pre>
</section>
</section>
<section>
<section>
<h2>Testing</h2>
<pre><code class="go" data-trim>
func (*Suite) TestPublishOneSubscriber(c *gc.C) {
var called bool
var topic pubsub.Topic = "test topic"
hub := pubsub.NewHub()
hub.Subscribe(topic, func(call pubsub.Topic, data interface{}) {
c.Check(call, gc.Equals, topic)
c.Check(data, gc.IsNil)
called = true
})
hub.Publish(topic, nil)
// How long do we wait, how do we know it was called?
c.Assert(called, jc.IsTrue)
}
</code></pre>
</section>
<section>
<h2>Knowing we're done</h2>
<p>Go channels are used for signalling.</p>
<pre><code class="go" data-trim>
func waitForMessageHandlingToBeComplete(c *gc.C, done <-chan struct{}) {
select {
case <-done:
case <-time.After(time.Second):
// We expect message handling to be done in under 1ms
// so waiting for a second is 1000x as long.
c.Fatal("publish did not complete")
}
}
</code></pre>
</section>
<section>
<h2>Publish returns a channel</h2>
<pre><code class="go" data-trim>
func (h *Hub) Publish(topic Topic, data interface{}) <-chan struct{} {
h.mutex.Lock()
defer h.mutex.Unlock()
done := make(chan struct{})
wait := sync.WaitGroup{}
for _, subscriber := range h.subscribers {
if subscriber.topic == topic {
wait.Add(1)
go func(){
defer wait.Done()
subscriber.callback(topic, data)
}
}
}
go func() {
wait.Wait()
close(done)
}()
return done
}
</code></pre>
</section>
<section>
<h2>Testing</h2>
<pre><code class="go" data-trim>
func (*Suite) TestPublishOneSubscriber(c *gc.C) {
var called bool
var topic pubsub.Topic = "test topic"
hub := pubsub.NewHub()
hub.Subscribe(topic, func(call pubsub.Topic, data interface{}) {
c.Check(call, gc.Equals, topic)
c.Check(data, gc.IsNil)
called = true
})
done := hub.Publish(topic, nil)
waitForMessageHandlingToBeComplete(c, done)
c.Assert(called, jc.IsTrue)
}
</code></pre>
</section>
</section>
<section>
<section>
<h2>Ordering</h2>
<p>If multiple calls to <code>Publish</code> are made that match a subscriber, what order does the subscriber get told about the events?</p>
<p class="fragment fade-up" style="color: red">It depends</p>
</section>
<section>
<h2>Desired Guarantees</h2>
<ul>
<li>Publish and Subscribe are goroutine safe</li>
<li>Slow subscribers won't block Publish</li>
<li>Slow subscribers won't interfere with other subscribers</li>
<li class="fragment highlight-green">Subscriber's callback is called in the order that Publish was called</li>
</ul>
</section>
<section>
<h2>Smarter Subscribers</h2>
<ul>
<li class="fragment">Each subscriber has its own goroutine</li>
<li class="fragment">Each subscriber has its own queue of callbacks</li>
<li class="fragment">Unsubscribing stops all pending callbacks</li>
<li class="fragment">Cleared callbacks also decrement the wait group</li>
</ul>
</section>
<section>
<h2>The subscriber type</h2>
<pre><code class="go" data-trim>
type subscriber struct {
id int
topic Topic
handler func(topic Topic, data interface{})
mutex sync.Mutex
pending *deque.Deque
closed chan struct{}
data chan struct{}
done chan struct{}
}
</code></pre>
</section>
<section>
<h2>Creating the subscriber starts a goroutine</h2>
<pre><code class="go" data-trim>
func newSubscriber(topic Topic, handler func(Topic, interface{}))
*subscriber {
// A closed channel is used to provide an immediate
// route through a select call in the loop function.
closed := make(chan struct{})
close(closed)
sub := &subscriber{
topic: topic,
handler: handler,
pending: deque.New(),
data: make(chan struct{}, 1),
done: make(chan struct{}),
closed: closed,
}
go sub.loop()
return sub
}
</code></pre>
</section>
<section>
<h2>Encapsulating the event</h2>
<pre><code class="go" data-trim>
type handlerCallback struct {
topic Topic
data interface{}
wg *sync.WaitGroup
}
func (h *handlerCallback) done() {
h.wg.Done()
}
</code></pre>
</section>
<section>
<h2>Notifying the Subscriber</h2>
<pre><code class="go" data-trim>
func (s *subscriber) notify(call *handlerCallback) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.pending.PushBack(call)
if s.pending.Len() == 1 {
s.data <- struct{}{}
}
}
</code></pre>
</section>
<section>
<h2>Popping off the deque</h2>
<pre><code class="go" data-trim>
func (s *subscriber) popOne() (*handlerCallback, bool) {
s.mutex.Lock()
defer s.mutex.Unlock()
val, ok := s.pending.PopFront()
if !ok {
// nothing to do
return nil, true
}
empty := s.pending.Len() == 0
return val.(*handlerCallback), empty
}
</code></pre>
</section>
<section>
<h2>Subscriber loop goroutine</h2>
<pre><code class="go" data-trim>
func (s *subscriber) loop() {
var next <-chan struct{}
for {
select {
case <-s.done:
return
case <-s.data:
// Has new data been pushed on?
case <-next:
// If there was already data, next is a closed channel.
// otherwise it is nil so won't pass through.
}
call, empty := s.popOne()
if empty {
next = nil
} else {
next = s.closed
}
// call *should* never be nil as we should only be calling
// popOne in the situations where there is actually
// something to pop.
if call != nil {
s.handler(call.topic, call.data)
call.done()
}
}
}
</code></pre>
</section>
<section>
<h2>Stopping the goroutine</h2>
<pre><code class="go" data-trim>
func (s *subscriber) close() {
s.mutex.Lock()
defer s.mutex.Unlock()
// Need to iterate through all the pending calls and make
// sure the wait group is decremented.
for call, ok := s.pending.PopFront(); ok;
call, ok = s.pending.PopFront() {
call.(*handlerCallback).done()
}
close(s.done)
}
</code></pre>
</section>
<section>
<h2>Unsubscribing closes the subscriber</h2>
<pre><code class="go" data-trim data-noescape>
func (h *Hub) unsubscribe(id int) {
h.mutex.Lock()
defer h.mutex.Unlock()
for i, sub := range h.subscribers {
if sub.id == id {
<mark>sub.close()</mark>
h.subscribers = append(
h.subscribers[0:i],
h.subscribers[i+1:]...)
return
}
}
}
</code></pre>
</section>
</section>
<section>
<h2>There we have it</h2>
<p class="fragment">The SimpleHub</p>
<p class="fragment">Now what?</p>
<p class="fragment">How about not having callbacks with <code>interface{}</code>?</p>
<p class="fragment">Better topic matching</code>?</p>
</section>
<section>
<section>
<h2>The structured Hub</h2>
<p>Hander functions for a structured hub can get all the published data available
by defining a callback with the signature:</p>
<pre><code class="go" data-trim data-noescape>
func (Topic, map[string]interface{})
</code></pre>
<p>Or alternatively, define a struct type, and use that type as the second argument.</p>
<pre><code class="go" data-trim data-noescape>
func (Topic, SomeStruct, error)
</code></pre>
</section>
<section>
<h2>Structured Hub Publish</h2>
<p>Uses the simple hub, and wraps all callbacks so the <code>data interface{}</code>
used for the simple hub publish method is always given a <code>map[string]interface{}</code></p>
<p>Converting the <code>data</code> value can now generate an error.</p>
<pre><code class="go" data-trim data-noescape>
func (h *StructuredHub) Publish(topic Topic, data interface{})
(<-chan struct{}, error) {
// convert data to map[string]interface{}
// call the simple hub Publish with the map
}
</code></pre>
</section>
<section>
<h2>Marshallers</h2>
<pre><code class="go" data-trim data-noescape>
// Marshaller defines the Marshal and Unmarshal methods used to
// serialize and deserialize the structures used in Publish and
// Subscription handlers of the structured hub.
type Marshaller interface {
// Marshal converts the argument into a byte streem that it
// can then Unmarshal.
Marshal(interface{}) ([]byte, error)
// Unmarshal attempts to convert the byte stream into type
// passed in as the second arg.
Unmarshal([]byte, interface{}) error
}
</code></pre>
</section>
<section>
<h2>JSON Marshaller</h2>
<pre><code class="go" data-trim data-noescape>
import "encoding/json"
// JSONMarshaller simply wraps the json.Marshal and json.Unmarshal
// calls for the Marshaller interface.
var JSONMarshaller = &jsonMarshaller{}
type jsonMarshaller struct{}
func (*jsonMarshaller) Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func (*jsonMarshaller) Unmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}
</code></pre>
</section>
<section>
<h2>Marshalling Structures</h2>
<pre><code class="go" data-trim data-noescape>
type Emitter struct {
Origin string `json:"origin"`
Message string `json:"message"`
ID int `json:"id"`
}
value := Emitter{"master", "hello world", 42}
// JSON Marshalling
`{"origin":"master","message":"hello world","id":42}`
// Unmarshalled into map[string]interface{} gives
map[string]interface{}{
"origin": "master",
"message": "hello world",
"id": 42,
}
</code></pre>
</section>
<section>
<h2>Converting data</h2>
<pre><code class="go" data-trim data-noescape>
func (h *StructuredHub) toStringMap(data interface{})
(map[string]interface{}, error) {
if cast, ok := data.(map[string]interface{}); ok {
return cast, nil
}
var result map[string]interface{}
// convert to a map by marshalling the structure
// out and back into a map
bytes, err := h.marshaller.Marshal(data)
if err != nil {
return nil, errors.Annotate(err, "marshalling")
}
err = h.marshaller.Unmarshal(bytes, &result)
if err != nil {
return nil, errors.Annotate(err, "unmarshalling")
}
return result, nil
}
</code></pre>
</section>
<section>
<h2>Structured Hub Subscribe</h2>
<p>Subscribing can now also generate an error if the handler
function doesn't match the expected signatures.</p>
<pre><code class="go" data-trim data-noescape>
func (h *StructuredHub) Subscribe(topic Topic, handler interface{})
(Unsubscriber, error) {
// reflection to interrogate the handler to make
// sure it is a function that matches either
// `func(Topic, map[string]interface{})`
// or
// `func(Topic, SomeStruct, error)`
}
</code></pre>
</section>
</section>
<section>
<section>
<h2>The topic matcher</h2>
<p>Originally I started with regular expressions.</p>
<pre><code class="go" data-trim data-noescape>
// Topic represents a message that can be subscribed to.
type Topic string
// TopicMatcher defines the Match method that is used to determine
// if the subscriber should be notified about a particular message.
type TopicMatcher interface {
Match(Topic) bool
}