-
Notifications
You must be signed in to change notification settings - Fork 1
/
fanout.go
73 lines (65 loc) · 1.63 KB
/
fanout.go
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
package mawt
import (
"fmt"
"sync"
"time"
"github.com/TeamNorCal/mawt/model"
)
var (
subs = &Subs{
subs: []chan *model.PortalMsg{},
}
)
type Subs struct {
subs []chan *model.PortalMsg
sync.Mutex
}
// startFanOut implement a broadcast mechanisim for accepting portal state messages
// and relaying then to subscribers. The function returns a single channel
// to which portal update messages get sent and, a channel that can be used to add
// listeners
//
func startFanOut(quitC <-chan struct{}) (inC chan *model.PortalMsg, subC chan chan *model.PortalMsg) {
inC = make(chan *model.PortalMsg, 1)
subC = make(chan chan *model.PortalMsg, 1)
go func(quitC <-chan struct{}) {
defer fmt.Println("fanout stopped")
for {
select {
case <-quitC:
return
case sub := <-subC:
if nil != sub {
subs.Lock()
subs.subs = append(subs.subs, sub)
subs.Unlock()
fmt.Println("subscription added")
}
case msg := <-inC:
// The subscriptions are notified of a message and are groomed out
// on unrecoverable failures using https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
subs.Lock()
newSubs := subs.subs[:0]
for _, ch := range subs.subs {
func() {
defer func() {
if r := recover(); r == nil {
newSubs = append(newSubs, ch)
return
}
fmt.Println("subscription dropped failed to send")
}()
select {
case ch <- msg:
case <-time.After(250 * time.Millisecond):
fmt.Println("subscription failed to send")
}
}()
}
subs.subs = newSubs
subs.Unlock()
}
}
}(quitC)
return inC, subC
}