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
138 lines (114 loc) · 2.98 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
package kv
import (
"context"
"fmt"
"github.com/dgraph-io/badger/v3"
"github.com/dgraph-io/badger/v3/pb"
jsoniter "github.com/json-iterator/go"
"github.com/sirupsen/logrus"
)
type rawMessage struct {
Client Client
Data []byte
}
type Hub struct {
clients *clientList
incoming chan rawMessage
register chan Client
unregister chan Client
db *badger.DB
memdb *badger.DB
logger logrus.FieldLogger
}
var json = jsoniter.ConfigDefault
func NewHub(db *badger.DB, logger logrus.FieldLogger) (*Hub, error) {
if logger == nil {
logger = logrus.New()
}
// Create temporary DB for subscriptions
inmemdb, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
if err != nil {
return nil, err
}
hub := &Hub{
incoming: make(chan rawMessage, 10),
register: make(chan Client, 10),
unregister: make(chan Client, 10),
clients: newClientList(),
db: db,
memdb: inmemdb,
logger: logger,
}
go func() {
err := db.Subscribe(context.Background(), hub.update, []byte{})
if err != nil {
logger.WithError(err).Error("db subscription halted because of error")
}
}()
return hub, nil
}
func (h *Hub) Close() {
h.memdb.Close()
}
func (h *Hub) update(kvs *pb.KVList) error {
for _, kv := range kvs.Kv {
// Get subscribers
subscribers, err := dbGetSubscribersForKey(h.memdb, kv.Key)
if err != nil {
return err
}
// Notify subscribers
for _, clientid := range subscribers {
client, ok := h.clients.GetByID(clientid)
if ok {
options := client.Options()
submsg, _ := json.Marshal(Push{"push", string(kv.Key[len(options.Namespace):]), string(kv.Value)})
client.SendMessage(submsg)
}
}
}
return nil
}
func (h *Hub) handleCmd(client Client, message rawMessage) {
// 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(h, client, msg)
}
func sendErr(client Client, err ErrCode, details string, requestID string) {
client.SendJSON(Error{false, err, details, requestID})
}
func (h *Hub) Run() {
h.logger.Info("running")
for {
select {
case client := <-h.register:
// Generate ID
h.clients.AddClient(client)
// Send welcome message
client.SendJSON(Hello{CmdType: "hello", Version: ProtoVersion})
case client := <-h.unregister:
// Unsubscribe from all keys
if err := dbUnsubscribeFromAll(h.memdb, client); err != nil {
h.logger.WithError(err).WithField("clientid", client.UID()).Error("error removing subscriptions for client")
}
// Delete entry and close channel
h.clients.RemoveClient(client)
client.Close()
case message := <-h.incoming:
h.handleCmd(message.Client, message)
}
}
}