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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
|
// Package natsbroker defines custom Nats Broker for Centrifuge library.
package natsbroker
import (
"context"
"encoding/json"
"fmt"
"math"
"strings"
"sync"
"github.com/centrifugal/centrifuge"
"github.com/nats-io/nats.go"
)
type (
// channelID is unique channel identifier in Nats.
channelID string
)
// Config of NatsEngine.
type Config struct {
Servers string
Prefix string
}
var _ centrifuge.Broker = (*NatsBroker)(nil)
// NatsBroker is a broker on top of Nats messaging system.
type NatsBroker struct {
node *centrifuge.Node
config Config
nc *nats.Conn
subsMu sync.Mutex
subs map[channelID]*nats.Subscription
eventHandler centrifuge.BrokerEventHandler
}
// History ...
func (b *NatsBroker) History(_ string, _ centrifuge.HistoryFilter) ([]*centrifuge.Publication, centrifuge.StreamPosition, error) {
return nil, centrifuge.StreamPosition{}, centrifuge.ErrorNotAvailable
}
// RemoveHistory ...
func (b *NatsBroker) RemoveHistory(_ string) error {
return centrifuge.ErrorNotAvailable
}
// New creates NatsBroker.
func New(n *centrifuge.Node, conf Config) (*NatsBroker, error) {
b := &NatsBroker{
node: n,
config: conf,
subs: make(map[channelID]*nats.Subscription),
}
return b, nil
}
func (b *NatsBroker) controlChannel() channelID {
return channelID(b.config.Prefix + ".control")
}
func (b *NatsBroker) nodeChannel(nodeID string) channelID {
return channelID(b.config.Prefix + ".node." + nodeID)
}
func (b *NatsBroker) clientChannel(ch string) channelID {
return channelID(b.config.Prefix + ".client." + ch)
}
func (b *NatsBroker) extractChannel(subject string) string {
return strings.TrimPrefix(subject, b.config.Prefix+".client.")
}
// Run runs broker after node initialized.
func (b *NatsBroker) Run(h centrifuge.BrokerEventHandler) error {
b.eventHandler = h
servers := b.config.Servers
if servers == "" {
servers = nats.DefaultURL
}
nc, err := nats.Connect(servers, nats.ReconnectBufSize(-1), nats.MaxReconnects(math.MaxInt64))
if err != nil {
return err
}
_, err = nc.Subscribe(string(b.controlChannel()), b.handleControl)
if err != nil {
return err
}
_, err = nc.Subscribe(string(b.nodeChannel(b.node.ID())), b.handleControl)
if err != nil {
return err
}
b.nc = nc
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelInfo, fmt.Sprintf("Nats Broker connected to: %s", servers)))
return nil
}
// Close is not implemented.
func (b *NatsBroker) Close(_ context.Context) error {
return nil
}
type pushType int
const (
pubPushType pushType = 0
joinPushType pushType = 1
leavePushType pushType = 2
)
type push struct {
Type pushType `json:"type,omitempty"`
Data json.RawMessage `json:"data"`
}
// Publish - see centrifuge.Broker interface description.
func (b *NatsBroker) Publish(ch string, data []byte, opts centrifuge.PublishOptions) (centrifuge.StreamPosition, error) {
pub := ¢rifuge.Publication{
Data: data,
Info: opts.ClientInfo,
}
data, err := json.Marshal(pub)
if err != nil {
return centrifuge.StreamPosition{}, err
}
byteMessage, err := json.Marshal(push{
Type: pubPushType,
Data: data,
})
if err != nil {
return centrifuge.StreamPosition{}, err
}
return centrifuge.StreamPosition{}, b.nc.Publish(string(b.clientChannel(ch)), byteMessage)
}
// PublishJoin - see centrifuge.Broker interface description.
func (b *NatsBroker) PublishJoin(ch string, info *centrifuge.ClientInfo) error {
data, err := json.Marshal(info)
if err != nil {
return err
}
byteMessage, err := json.Marshal(push{
Type: joinPushType,
Data: data,
})
if err != nil {
return err
}
return b.nc.Publish(string(b.clientChannel(ch)), byteMessage)
}
// PublishLeave - see centrifuge.Broker interface description.
func (b *NatsBroker) PublishLeave(ch string, info *centrifuge.ClientInfo) error {
data, err := json.Marshal(info)
if err != nil {
return err
}
byteMessage, err := json.Marshal(push{
Type: leavePushType,
Data: data,
})
if err != nil {
return err
}
return b.nc.Publish(string(b.clientChannel(ch)), byteMessage)
}
// PublishControl - see centrifuge.Broker interface description.
func (b *NatsBroker) PublishControl(data []byte, nodeID string) error {
var channelID channelID
if nodeID == "" {
channelID = b.controlChannel()
} else {
channelID = b.nodeChannel(nodeID)
}
return b.nc.Publish(string(channelID), data)
}
func (b *NatsBroker) handleClientMessage(subject string, data []byte) error {
var p push
err := json.Unmarshal(data, &p)
if err != nil {
return err
}
channel := b.extractChannel(subject)
switch p.Type {
case pubPushType:
var pub centrifuge.Publication
err := json.Unmarshal(p.Data, &pub)
if err != nil {
return err
}
_ = b.eventHandler.HandlePublication(channel, &pub, centrifuge.StreamPosition{})
case joinPushType:
var info centrifuge.ClientInfo
err := json.Unmarshal(p.Data, &info)
if err != nil {
return err
}
_ = b.eventHandler.HandleJoin(channel, &info)
case leavePushType:
var info centrifuge.ClientInfo
err := json.Unmarshal(p.Data, &info)
if err != nil {
return err
}
_ = b.eventHandler.HandleLeave(channel, &info)
default:
}
return nil
}
func (b *NatsBroker) handleClient(m *nats.Msg) {
_ = b.handleClientMessage(m.Subject, m.Data)
}
func (b *NatsBroker) handleControl(m *nats.Msg) {
_ = b.eventHandler.HandleControl(m.Data)
}
// Subscribe - see centrifuge.Broker interface description.
func (b *NatsBroker) Subscribe(ch string) error {
if strings.Contains(ch, "*") || strings.Contains(ch, ">") {
// Do not support wildcard subscriptions.
return centrifuge.ErrorBadRequest
}
b.subsMu.Lock()
defer b.subsMu.Unlock()
clientChannel := b.clientChannel(ch)
if _, ok := b.subs[clientChannel]; ok {
return nil
}
subClient, err := b.nc.Subscribe(string(b.clientChannel(ch)), b.handleClient)
if err != nil {
return err
}
b.subs[clientChannel] = subClient
return nil
}
// Unsubscribe - see centrifuge.Broker interface description.
func (b *NatsBroker) Unsubscribe(ch string) error {
b.subsMu.Lock()
defer b.subsMu.Unlock()
if sub, ok := b.subs[b.clientChannel(ch)]; ok {
_ = sub.Unsubscribe()
delete(b.subs, b.clientChannel(ch))
}
return nil
}
|