-
Notifications
You must be signed in to change notification settings - Fork 13
/
registry.go
76 lines (59 loc) · 1.79 KB
/
registry.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
package socket
import (
"fmt"
"sync"
"time"
"github.com/coretrix/hitrix/service/component/goroutine"
)
const (
// Time allowed to write a broadcastMessage to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong broadcastMessage from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum broadcastMessage size allowed from peer.
maxMessageSize = 512
)
type Registry struct {
Register chan *Socket
Unregister chan *Socket
Sockets *sync.Map
ServiceGoroutine goroutine.IGoroutine
}
func NewSocketRegistry(eventHandlersMap NamespaceEventHandlerMap, serviceGoroutine goroutine.IGoroutine) *Registry {
registry := &Registry{
Register: make(chan *Socket),
Unregister: make(chan *Socket),
Sockets: &sync.Map{},
ServiceGoroutine: serviceGoroutine,
}
registry.ServiceGoroutine.GoroutineWithRestart(func() {
registry.run(eventHandlersMap)
})
return registry
}
func (registry *Registry) run(eventHandlersMap NamespaceEventHandlerMap) {
for {
select {
case s := <-registry.Register: //new connection
registry.Sockets.Store(s.ID, s)
eventHandlers, ok := eventHandlersMap[s.Namespace]
if !ok {
panic(fmt.Errorf("register handler for namespace %v not found", s.Namespace))
}
eventHandlers.RegisterHandler(s)
case s := <-registry.Unregister:
registry.Sockets.Delete(s.ID)
eventHandlers, ok := eventHandlersMap[s.Namespace]
if !ok {
panic(fmt.Errorf("unregister handler for namespace %v not found", s.Namespace))
}
eventHandlers.UnregisterHandler(s)
}
}
}
type NamespaceEventHandlerMap map[string]*EventHandlers
type EventHandlers struct {
RegisterHandler, UnregisterHandler func(s *Socket)
}