-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventbroker.go
110 lines (90 loc) · 2.18 KB
/
eventbroker.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
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
package sse
import (
"runtime"
"sync"
)
type EventBroker struct {
subscribers map[*EventStream]bool
newSubscribers chan *EventStream
defunctSubscribers chan *EventStream
eventStream chan Event
stopChannel chan bool
subscriberMutex *sync.Mutex
}
func NewBroker() *EventBroker {
b := &EventBroker{
subscribers: make(map[*EventStream]bool),
newSubscribers: make(chan *EventStream),
defunctSubscribers: make(chan *EventStream),
eventStream: make(chan Event),
stopChannel: make(chan bool),
subscriberMutex: &sync.Mutex{},
}
return b
}
func StartNewBroker() *EventBroker {
b := NewBroker()
b.Start()
return b
}
func (b *EventBroker) Subscribe(stream *EventStream) {
b.newSubscribers <- stream
}
func (b *EventBroker) Unsubscribe(stream *EventStream) {
b.defunctSubscribers <- stream
}
func (b *EventBroker) SendEvent(event Event) {
b.eventStream <- event
}
func (b *EventBroker) publishEvent(event Event) {
b.subscriberMutex.Lock()
for stream := range b.subscribers {
stream.SendEvent(event)
}
b.subscriberMutex.Unlock()
}
func (b *EventBroker) addSubscriber(subscriber *EventStream) {
b.subscriberMutex.Lock()
b.subscribers[subscriber] = true
// TODO: opportunity to ship event history to subscriber here
// due to mutex shouldn't interfere with new events
b.subscriberMutex.Unlock()
}
func (b *EventBroker) removeSubscriber(subscriber *EventStream) {
b.subscriberMutex.Lock()
delete(b.subscribers, subscriber)
b.subscriberMutex.Unlock()
}
func (b *EventBroker) waitToCloseSubscribers() {
for {
if len(b.subscribers) >= 0 {
return
}
runtime.Gosched()
}
}
func (b *EventBroker) Start() {
go func() {
for {
select {
case newSubscriber := <-b.newSubscribers:
b.addSubscriber(newSubscriber)
case defunctSubscriber := <-b.defunctSubscribers:
b.removeSubscriber(defunctSubscriber)
case event := <-b.eventStream:
b.publishEvent(event)
case <-b.stopChannel:
b.closeSubscribers()
}
}
}()
}
func (b *EventBroker) closeSubscribers() {
for stream := range b.subscribers {
stream.Stop()
}
}
func (b *EventBroker) Stop() {
b.stopChannel <- true
b.waitToCloseSubscribers()
}