This repository has been archived by the owner on Nov 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
170 lines (137 loc) · 3.79 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
package kv
import (
crand "crypto/rand"
"encoding/binary"
"fmt"
mrand "math/rand"
"net/http"
"go.uber.org/zap"
jsoniter "github.com/json-iterator/go"
)
type Message struct {
Client Client
Data []byte
}
type HubOptions struct {
Password string
}
type Hub struct {
options HubOptions
clients *clientList
incoming chan Message
register chan Client
unregister chan Client
subscriptions *subscriptionManager
db Driver
logger *zap.Logger
}
var json = jsoniter.ConfigDefault
func NewHub(db Driver, options HubOptions, logger *zap.Logger) (*Hub, error) {
if logger == nil {
logger, _ = zap.NewProduction()
}
clients := newClientList()
subscriptions := makeSubscriptionManager()
hub := &Hub{
incoming: make(chan Message, 10),
register: make(chan Client, 10),
unregister: make(chan Client, 10),
clients: clients,
db: db,
logger: logger,
options: options,
subscriptions: subscriptions,
}
subscriptions.hub = hub
return hub, nil
}
func (hub *Hub) Close() {
}
func (hub *Hub) SetOptions(options HubOptions) {
hub.options = options
}
func (hub *Hub) handleCmd(client Client, message Message) {
// Decode request
var msg Request
err := json.Unmarshal(message.Data, &msg)
if err != nil {
sendErr(message.Client, ErrInvalidFmt, err.Error(), msg.RequestID)
return
}
// Get handler for command
handler, ok := handlers[msg.CmdName]
if !ok {
// No handler found, send invalid command
sendErr(client, ErrUnknownCmd, fmt.Sprintf("command \"%s\" is mistyped or not supported", msg.CmdName), msg.RequestID)
return
}
// Run handler
handler(hub, client, msg)
}
func (hub *Hub) randomBytes() []byte {
saltBytes := make([]byte, 32)
_, err := crand.Read(saltBytes)
if err != nil {
hub.logger.Warn("failed to generate secure bytes, falling back to insecure PRNG", zap.Error(err))
insecureBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(insecureBytes, mrand.Uint64()) //nolint:gosec
return insecureBytes
}
return saltBytes
}
func sendErr(client Client, err ErrCode, details string, requestID string) {
client.SendJSON(Error{false, err, details, requestID})
}
func (hub *Hub) Run() {
hub.logger.Info("running")
for {
select {
case client := <-hub.register:
// Generate ID
hub.clients.AddClient(client)
// Send welcome message
client.SendJSON(Hello{CmdType: "hello", Version: ProtoVersion})
case client := <-hub.unregister:
// Unsubscribe from all keys
hub.subscriptions.UnsubscribeAll(client.UID())
// Delete entry and close channel
hub.clients.RemoveClient(client)
client.Close()
case message := <-hub.incoming:
hub.handleCmd(message.Client, message)
}
}
}
func (hub *Hub) AddClient(client Client) {
hub.register <- client
}
func (hub *Hub) RemoveClient(client Client) {
hub.unregister <- client
}
func (hub *Hub) SetAuthenticated(id int64, authenticated bool) error {
return hub.clients.SetAuthenticated(id, authenticated)
}
func (hub *Hub) SendMessage(msg Message) {
hub.incoming <- msg
}
// ServeWs is the legacy handler for WS
func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
hub.CreateWebsocketClient(w, r, ClientOptions{})
}
// CreateWebsocketClient upgrades a HTTP request to websocket and makes it a client for the hub
func (hub *Hub) CreateWebsocketClient(w http.ResponseWriter, r *http.Request, options ClientOptions) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
hub.logger.Error("error starting websocket session", zap.Error(err))
return
}
client := &WebsocketClient{
hub: hub, conn: conn,
send: make(chan []byte, 256), options: options,
}
client.hub.register <- client
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump(hub)
}