-
Notifications
You must be signed in to change notification settings - Fork 4k
/
pubsub.go
106 lines (90 loc) · 1.79 KB
/
pubsub.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
package pubsub
import (
"errors"
"sync"
"time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/signal/done"
"github.com/xtls/xray-core/common/task"
)
type Subscriber struct {
buffer chan interface{}
done *done.Instance
}
func (s *Subscriber) push(msg interface{}) {
select {
case s.buffer <- msg:
default:
}
}
func (s *Subscriber) Wait() <-chan interface{} {
return s.buffer
}
func (s *Subscriber) Close() error {
return s.done.Close()
}
func (s *Subscriber) IsClosed() bool {
return s.done.Done()
}
type Service struct {
sync.RWMutex
subs map[string][]*Subscriber
ctask *task.Periodic
}
func NewService() *Service {
s := &Service{
subs: make(map[string][]*Subscriber),
}
s.ctask = &task.Periodic{
Execute: s.Cleanup,
Interval: time.Second * 30,
}
return s
}
// Cleanup cleans up internal caches of subscribers.
// Visible for testing only.
func (s *Service) Cleanup() error {
s.Lock()
defer s.Unlock()
if len(s.subs) == 0 {
return errors.New("nothing to do")
}
for name, subs := range s.subs {
newSub := make([]*Subscriber, 0, len(s.subs))
for _, sub := range subs {
if !sub.IsClosed() {
newSub = append(newSub, sub)
}
}
if len(newSub) == 0 {
delete(s.subs, name)
} else {
s.subs[name] = newSub
}
}
if len(s.subs) == 0 {
s.subs = make(map[string][]*Subscriber)
}
return nil
}
func (s *Service) Subscribe(name string) *Subscriber {
sub := &Subscriber{
buffer: make(chan interface{}, 16),
done: done.New(),
}
s.Lock()
subs := append(s.subs[name], sub)
s.subs[name] = subs
s.Unlock()
common.Must(s.ctask.Start())
return sub
}
func (s *Service) Publish(name string, message interface{}) {
s.RLock()
defer s.RUnlock()
for _, sub := range s.subs[name] {
if !sub.IsClosed() {
sub.push(message)
}
}
}