forked from joltify-finance/tss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_id_subscriber.go
65 lines (57 loc) · 1.38 KB
/
message_id_subscriber.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
package p2p
import (
"sync"
"time"
)
// MessageIDSubscriber
type MessageIDSubscriber struct {
lock *sync.Mutex
subscribers map[string]chan *Message
}
// NewMessageIDSubscriber create a new instance of MessageIDSubscriber
func NewMessageIDSubscriber() *MessageIDSubscriber {
return &MessageIDSubscriber{
lock: &sync.Mutex{},
subscribers: make(map[string]chan *Message),
}
}
// Subscribe a message id
func (ms *MessageIDSubscriber) Subscribe(msgID string, channel chan *Message) {
ms.lock.Lock()
defer ms.lock.Unlock()
ms.subscribers[msgID] = channel
}
// UnSubscribe a messageid
func (ms *MessageIDSubscriber) UnSubscribe(msgID string) {
ms.lock.Lock()
defer ms.lock.Unlock()
sb, ok := ms.subscribers[msgID]
if !ok {
return
}
delete(ms.subscribers, msgID)
// we clean up the channel as handler in communication.go L180 may be blocked as it need to write to the channel
for {
select {
case <-sb:
case <-time.After(time.Second):
return
}
}
}
// GetSubscribers return a subscriber of given message id
func (ms *MessageIDSubscriber) GetSubscriber(msgID string) chan *Message {
ms.lock.Lock()
defer ms.lock.Unlock()
c, ok := ms.subscribers[msgID]
if !ok {
return nil
}
return c
}
// IsEmpty check whether there is subscribers
func (ms *MessageIDSubscriber) IsEmpty() bool {
ms.lock.Lock()
defer ms.lock.Unlock()
return len(ms.subscribers) == 0
}