Debian Codegraph @

_examples/custom_broker_nats/natsbroker/broker.go

raw symbols SCIP
1 // Package natsbroker defines custom Nats Broker for Centrifuge library.
2 package natsbroker
3
4 import (
5 "context"
6 "encoding/json"
7 "fmt"
8 "math"
9 "strings"
10 "sync"
11
12 "github.com/centrifugal/centrifuge"
13 "github.com/nats-io/nats.go"
14 )
15
16 type (
17 // channelID is unique channel identifier in Nats.
18 channelID string
19 )
20
21 // Config of NatsEngine.
22 type Config struct {
23 Servers string
24 Prefix string
25 }
26
27 var _ centrifuge.Broker = (*NatsBroker)(nil)
28
29 // NatsBroker is a broker on top of Nats messaging system.
30 type NatsBroker struct {
31 node *centrifuge.Node
32 config Config
33
34 nc *nats.Conn
35 subsMu sync.Mutex
36 subs map[channelID]*nats.Subscription
37 eventHandler centrifuge.BrokerEventHandler
38 }
39
40 // History ...
41 func (b *NatsBroker) History(_ string, _ centrifuge.HistoryFilter) ([]*centrifuge.Publication, centrifuge.StreamPosition, error) {
42 return nil, centrifuge.StreamPosition{}, centrifuge.ErrorNotAvailable
43 }
44
45 // RemoveHistory ...
46 func (b *NatsBroker) RemoveHistory(_ string) error {
47 return centrifuge.ErrorNotAvailable
48 }
49
50 // New creates NatsBroker.
51 func New(n *centrifuge.Node, conf Config) (*NatsBroker, error) {
52 b := &NatsBroker{
53 node: n,
54 config: conf,
55 subs: make(map[channelID]*nats.Subscription),
56 }
57 return b, nil
58 }
59
60 func (b *NatsBroker) controlChannel() channelID {
61 return channelID(b.config.Prefix + ".control")
62 }
63
64 func (b *NatsBroker) nodeChannel(nodeID string) channelID {
65 return channelID(b.config.Prefix + ".node." + nodeID)
66 }
67
68 func (b *NatsBroker) clientChannel(ch string) channelID {
69 return channelID(b.config.Prefix + ".client." + ch)
70 }
71
72 func (b *NatsBroker) extractChannel(subject string) string {
73 return strings.TrimPrefix(subject, b.config.Prefix+".client.")
74 }
75
76 // Run runs broker after node initialized.
77 func (b *NatsBroker) Run(h centrifuge.BrokerEventHandler) error {
78 b.eventHandler = h
79 servers := b.config.Servers
80 if servers == "" {
81 servers = nats.DefaultURL
82 }
83 nc, err := nats.Connect(servers, nats.ReconnectBufSize(-1), nats.MaxReconnects(math.MaxInt64))
84 if err != nil {
85 return err
86 }
87 _, err = nc.Subscribe(string(b.controlChannel()), b.handleControl)
88 if err != nil {
89 return err
90 }
91 _, err = nc.Subscribe(string(b.nodeChannel(b.node.ID())), b.handleControl)
92 if err != nil {
93 return err
94 }
95 b.nc = nc
96 b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelInfo, fmt.Sprintf("Nats Broker connected to: %s", servers)))
97 return nil
98 }
99
100 // Close is not implemented.
101 func (b *NatsBroker) Close(_ context.Context) error {
102 return nil
103 }
104
105 type pushType int
106
107 const (
108 pubPushType pushType = 0
109 joinPushType pushType = 1
110 leavePushType pushType = 2
111 )
112
113 type push struct {
114 Type pushType `json:"type,omitempty"`
115 Data json.RawMessage `json:"data"`
116 }
117
118 // Publish - see centrifuge.Broker interface description.
119 func (b *NatsBroker) Publish(ch string, data []byte, opts centrifuge.PublishOptions) (centrifuge.StreamPosition, error) {
120 pub := &centrifuge.Publication{
121 Data: data,
122 Info: opts.ClientInfo,
123 }
124 data, err := json.Marshal(pub)
125 if err != nil {
126 return centrifuge.StreamPosition{}, err
127 }
128 byteMessage, err := json.Marshal(push{
129 Type: pubPushType,
130 Data: data,
131 })
132 if err != nil {
133 return centrifuge.StreamPosition{}, err
134 }
135 return centrifuge.StreamPosition{}, b.nc.Publish(string(b.clientChannel(ch)), byteMessage)
136 }
137
138 // PublishJoin - see centrifuge.Broker interface description.
139 func (b *NatsBroker) PublishJoin(ch string, info *centrifuge.ClientInfo) error {
140 data, err := json.Marshal(info)
141 if err != nil {
142 return err
143 }
144 byteMessage, err := json.Marshal(push{
145 Type: joinPushType,
146 Data: data,
147 })
148 if err != nil {
149 return err
150 }
151 return b.nc.Publish(string(b.clientChannel(ch)), byteMessage)
152 }
153
154 // PublishLeave - see centrifuge.Broker interface description.
155 func (b *NatsBroker) PublishLeave(ch string, info *centrifuge.ClientInfo) error {
156 data, err := json.Marshal(info)
157 if err != nil {
158 return err
159 }
160 byteMessage, err := json.Marshal(push{
161 Type: leavePushType,
162 Data: data,
163 })
164 if err != nil {
165 return err
166 }
167 return b.nc.Publish(string(b.clientChannel(ch)), byteMessage)
168 }
169
170 // PublishControl - see centrifuge.Broker interface description.
171 func (b *NatsBroker) PublishControl(data []byte, nodeID string) error {
172 var channelID channelID
173 if nodeID == "" {
174 channelID = b.controlChannel()
175 } else {
176 channelID = b.nodeChannel(nodeID)
177 }
178 return b.nc.Publish(string(channelID), data)
179 }
180
181 func (b *NatsBroker) handleClientMessage(subject string, data []byte) error {
182 var p push
183 err := json.Unmarshal(data, &p)
184 if err != nil {
185 return err
186 }
187 channel := b.extractChannel(subject)
188 switch p.Type {
189 case pubPushType:
190 var pub centrifuge.Publication
191 err := json.Unmarshal(p.Data, &pub)
192 if err != nil {
193 return err
194 }
195 _ = b.eventHandler.HandlePublication(channel, &pub, centrifuge.StreamPosition{})
196 case joinPushType:
197 var info centrifuge.ClientInfo
198 err := json.Unmarshal(p.Data, &info)
199 if err != nil {
200 return err
201 }
202 _ = b.eventHandler.HandleJoin(channel, &info)
203 case leavePushType:
204 var info centrifuge.ClientInfo
205 err := json.Unmarshal(p.Data, &info)
206 if err != nil {
207 return err
208 }
209 _ = b.eventHandler.HandleLeave(channel, &info)
210 default:
211 }
212 return nil
213 }
214
215 func (b *NatsBroker) handleClient(m *nats.Msg) {
216 _ = b.handleClientMessage(m.Subject, m.Data)
217 }
218
219 func (b *NatsBroker) handleControl(m *nats.Msg) {
220 _ = b.eventHandler.HandleControl(m.Data)
221 }
222
223 // Subscribe - see centrifuge.Broker interface description.
224 func (b *NatsBroker) Subscribe(ch string) error {
225 if strings.Contains(ch, "*") || strings.Contains(ch, ">") {
226 // Do not support wildcard subscriptions.
227 return centrifuge.ErrorBadRequest
228 }
229 b.subsMu.Lock()
230 defer b.subsMu.Unlock()
231 clientChannel := b.clientChannel(ch)
232 if _, ok := b.subs[clientChannel]; ok {
233 return nil
234 }
235 subClient, err := b.nc.Subscribe(string(b.clientChannel(ch)), b.handleClient)
236 if err != nil {
237 return err
238 }
239 b.subs[clientChannel] = subClient
240 return nil
241 }
242
243 // Unsubscribe - see centrifuge.Broker interface description.
244 func (b *NatsBroker) Unsubscribe(ch string) error {
245 b.subsMu.Lock()
246 defer b.subsMu.Unlock()
247 if sub, ok := b.subs[b.clientChannel(ch)]; ok {
248 _ = sub.Unsubscribe()
249 delete(b.subs, b.clientChannel(ch))
250 }
251 return nil
252 }