/
hub.go
209 lines (176 loc) · 4.67 KB
/
hub.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package hub
import (
"sync"
"github.com/panjf2000/ants/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog/log"
"go.uber.org/atomic"
"github.com/synycboom/algorand-notification/event"
"github.com/synycboom/algorand-notification/metrics"
)
// Client represents a contract for websocket client
type Client interface {
// ID returns a client id
ID() uint64
// OnClose sets a close handler
OnClose(h func())
// OnSubscribe sets a subscribing handler
OnSubscribe(h func(params []string))
// OnSubscribe sets a unsubscribing handler
OnUnsubscribe(h func(params []string))
// Send sends a message to the client
Send(msg []byte)
}
// SubscribeEvent is a subscription detail
type SubscribeEvent struct {
ClientID uint64
Types []string
}
// UnsubscribeEvent is a unsubscription detail
type UnsubscribeEvent struct {
ClientID uint64
Types []string
}
// Hub maintains a set of active clients
type Hub struct {
closeChan chan struct{}
count atomic.Uint64
clients map[uint64]Client
pool *ants.Pool
subscriptions map[string]map[uint64]struct{}
subscribeChan chan SubscribeEvent
unsubscribeChan chan UnsubscribeEvent
registerChan chan Client
unregisterChan chan Client
eventChan chan *event.Event
}
// New creates a new hub
func New(workerPoolSize int) (*Hub, error) {
pool, err := ants.NewPool(workerPoolSize)
if err != nil {
return nil, err
}
return &Hub{
closeChan: make(chan struct{}),
clients: make(map[uint64]Client),
pool: pool,
subscriptions: make(map[string]map[uint64]struct{}),
eventChan: make(chan *event.Event, 1024),
subscribeChan: make(chan SubscribeEvent),
unsubscribeChan: make(chan UnsubscribeEvent),
registerChan: make(chan Client),
unregisterChan: make(chan Client),
}, nil
}
// Close closes a hub (not thread safe)
func (h *Hub) Close() {
close(h.closeChan)
}
// Register registers a client to the hub
func (h *Hub) Register(c Client) {
c.OnClose(func() {
h.Unsubscribe(UnsubscribeEvent{
ClientID: c.ID(),
Types: event.AllEvents,
})
h.UnRegister(c)
})
c.OnSubscribe(func(params []string) {
h.Subscribe(SubscribeEvent{
ClientID: c.ID(),
Types: params,
})
})
c.OnUnsubscribe(func(params []string) {
h.Unsubscribe(UnsubscribeEvent{
ClientID: c.ID(),
Types: params,
})
})
h.registerChan <- c
}
// UnRegister unregisters a client from the hub
func (h *Hub) UnRegister(c Client) {
h.unregisterChan <- c
}
// Subscribe handle subscribing
func (h *Hub) Subscribe(e SubscribeEvent) {
h.subscribeChan <- e
}
// Unsubscribe handle unsubscribing
func (h *Hub) Unsubscribe(e UnsubscribeEvent) {
h.unsubscribeChan <- e
}
// SendEvent sends an event to clients
func (h *Hub) SendEvent(e *event.Event) {
h.eventChan <- e
}
// Run runs worker to manage clients
func (h *Hub) Run() {
for {
select {
case <-h.closeChan:
return
case c := <-h.registerChan:
h.clients[c.ID()] = c
h.count.Inc()
metrics.ActiveConnections.Set(float64(h.count.Load()))
log.Info().Msgf("hub: %v active sessions", h.count.Load())
case c := <-h.unregisterChan:
delete(h.clients, c.ID())
h.count.Dec()
metrics.ActiveConnections.Set(float64(h.count.Load()))
log.Info().Msgf("hub: %v active sessions", h.count.Load())
case e := <-h.subscribeChan:
for _, evtType := range e.Types {
if _, exist := h.subscriptions[evtType]; !exist {
h.subscriptions[evtType] = make(map[uint64]struct{})
}
h.subscriptions[evtType][e.ClientID] = struct{}{}
}
h.updateMetrics()
case e := <-h.unsubscribeChan:
for _, evtType := range e.Types {
delete(h.subscriptions[evtType], e.ClientID)
if len(h.subscriptions[evtType]) == 0 {
delete(h.subscriptions, evtType)
}
h.updateMetrics()
}
case event := <-h.eventChan:
var clients []Client
var wg sync.WaitGroup
for clientID := range h.subscriptions[event.Type] {
clients = append(clients, h.clients[clientID])
}
logger := log.With().Fields(map[string]interface{}{
"event_type": event.Type,
"event_payload": string(event.Payload),
}).Logger()
for _, client := range clients {
client := client
wg.Add(1)
err := h.pool.Submit(func() {
defer wg.Done()
client.Send(event.Payload)
})
if err != nil {
wg.Done()
logger.Error().Msg("hub: cannot submit task to the worker pool")
}
}
wg.Wait()
}
}
}
func (h *Hub) updateMetrics() {
for _, evtType := range event.AllEvents {
metric, err := metrics.ActiveSubscriptions.GetMetricWith(
prometheus.Labels{"name": evtType},
)
if err != nil {
continue
}
metric.Set(float64(len(h.subscriptions[evtType])))
}
}