-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroker.go
103 lines (93 loc) · 2.07 KB
/
broker.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
package memq
import (
"sync"
)
// Broker handles topics, subscriptions and message delivery.
type Broker interface {
// Publish publishes a message to a topic.
// The message is delivered to all subscribers of the topic.
Publish(topic string, msg interface{})
// Subscribe subscribes to a topic.
// The handler is called for each message published to the topic.
// The returned Subscription can be used to unsubscribe from the topic.
Subscribe(topic string, handler func(interface{})) Subscription
}
// Subscription handles unsubscribing from a topic.
type Subscription interface {
// Unsubscribe unsubscribes from a topic.
Unsubscribe()
}
type broker struct {
identity int
subscribers map[string]map[int]subscription
m *sync.Mutex
}
type subscription struct {
topic string
id int
b *broker
ch chan interface{}
done chan struct{}
}
// NewBroker creates a new Broker.
// The returned Broker is safe for concurrent use by multiple goroutines.
func NewBroker() Broker {
return &broker{
subscribers: make(map[string]map[int]subscription),
m: &sync.Mutex{},
}
}
func (b *broker) Subscribe(topic string, handler func(interface{})) Subscription {
b.m.Lock()
defer b.m.Unlock()
if _, ok := b.subscribers[topic]; !ok {
b.subscribers[topic] = make(map[int]subscription)
}
topicSubs := b.subscribers[topic]
subID := b.identity
b.identity++
ch := make(chan interface{})
done := make(chan struct{})
sub := subscription{
topic: topic,
id: subID,
b: b,
ch: ch,
done: done,
}
topicSubs[subID] = sub
go func() {
for {
select {
case <-done:
return
case msg := <-ch:
handler(msg)
}
}
}()
return &sub
}
func (s *subscription) Unsubscribe() {
s.b.m.Lock()
defer s.b.m.Unlock()
delete(s.b.subscribers[s.topic], s.id)
close(s.done)
close(s.ch)
}
func (b *broker) Publish(topic string, msg interface{}) {
if b.subscribers == nil {
return
}
topicSubs, ok := b.subscribers[topic]
if !ok {
return
}
for _, sub := range topicSubs {
select {
case <-sub.done:
continue
case sub.ch <- msg:
}
}
}