| 1 |
package tntengine |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"runtime" |
| 8 |
"strings" |
| 9 |
"sync" |
| 10 |
"sync/atomic" |
| 11 |
"time" |
| 12 |
|
| 13 |
"github.com/FZambia/tarantool" |
| 14 |
"github.com/centrifugal/centrifuge" |
| 15 |
"github.com/centrifugal/protocol" |
| 16 |
"github.com/google/uuid" |
| 17 |
"github.com/vmihailenco/msgpack/v5" |
| 18 |
) |
| 19 |
|
| 20 |
const internalChannelPrefix = "__" |
| 21 |
|
| 22 |
const ( |
| 23 |
// tarantoolControlChannel is a name for control channel. |
| 24 |
tarantoolControlChannel = internalChannelPrefix + "control" |
| 25 |
// tarantoolNodeChannelPrefix is a prefix for node channel. |
| 26 |
tarantoolNodeChannelPrefix = internalChannelPrefix + "node." |
| 27 |
) |
| 28 |
|
| 29 |
// Broker uses Tarantool to implement centrifuge.Broker functionality. |
| 30 |
type Broker struct { |
| 31 |
controlRound uint64 // Keep atomic on struct top for 32-bit architectures. |
| 32 |
node *centrifuge.Node |
| 33 |
sharding bool |
| 34 |
config BrokerConfig |
| 35 |
shards []*Shard |
| 36 |
nodeChannel string |
| 37 |
} |
| 38 |
|
| 39 |
var _ centrifuge.Broker = (*Broker)(nil) |
| 40 |
|
| 41 |
// BrokerConfig is a config for Tarantool Broker. |
| 42 |
type BrokerConfig struct { |
| 43 |
// HistoryMetaTTL sets a time of stream meta key expiration in Tarantool. Stream |
| 44 |
// meta key is a Tarantool HASH that contains top offset in channel and epoch value. |
| 45 |
// By default stream meta keys do not expire. |
| 46 |
HistoryMetaTTL time.Duration |
| 47 |
|
| 48 |
// UsePolling allows to turn on polling mode instead of push. |
| 49 |
UsePolling bool |
| 50 |
|
| 51 |
// Shards is a list of Tarantool instances to shard data by channel. |
| 52 |
Shards []*Shard |
| 53 |
} |
| 54 |
|
| 55 |
// NewBroker initializes Tarantool Broker. |
| 56 |
func NewBroker(n *centrifuge.Node, config BrokerConfig) (*Broker, error) { |
| 57 |
if len(config.Shards) == 0 { |
| 58 |
return nil, errors.New("no Tarantool shards provided in configuration") |
| 59 |
} |
| 60 |
if len(config.Shards) > 1 { |
| 61 |
n.Log(centrifuge.NewLogEntry(centrifuge.LogLevelInfo, fmt.Sprintf("Tarantool sharding enabled: %d shards", len(config.Shards)))) |
| 62 |
} |
| 63 |
e := &Broker{ |
| 64 |
node: n, |
| 65 |
shards: config.Shards, |
| 66 |
config: config, |
| 67 |
sharding: len(config.Shards) > 1, |
| 68 |
nodeChannel: nodeChannel(n.ID()), |
| 69 |
} |
| 70 |
return e, nil |
| 71 |
} |
| 72 |
|
| 73 |
// Run runs broker after node initialized. |
| 74 |
func (b *Broker) Run(h centrifuge.BrokerEventHandler) error { |
| 75 |
for _, shard := range b.shards { |
| 76 |
if err := b.runShard(shard, h); err != nil { |
| 77 |
return err |
| 78 |
} |
| 79 |
} |
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
func (b *Broker) runForever(fn func(), minDelay time.Duration) { |
| 84 |
for { |
| 85 |
started := time.Now() |
| 86 |
fn() |
| 87 |
elapsed := time.Since(started) |
| 88 |
if elapsed < minDelay { |
| 89 |
// Sleep for a while to prevent busy loop when reconnecting. |
| 90 |
// If elapsed >= minDelay then fn will be restarted right away – this is |
| 91 |
// intentional for fast reconnect in case of one random error. |
| 92 |
time.Sleep(minDelay - elapsed) |
| 93 |
} |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
const pubSubRoutineMinDelay = 300 * time.Millisecond |
| 98 |
|
| 99 |
// Run Tarantool shard. |
| 100 |
func (b *Broker) runShard(s *Shard, h centrifuge.BrokerEventHandler) error { |
| 101 |
go b.runForever(func() { |
| 102 |
b.runPubSub(s, h) |
| 103 |
}, pubSubRoutineMinDelay) |
| 104 |
go b.runForever(func() { |
| 105 |
b.runControlPubSub(s, h) |
| 106 |
}, pubSubRoutineMinDelay) |
| 107 |
return nil |
| 108 |
} |
| 109 |
|
| 110 |
type pubRequest struct { |
| 111 |
MsgType string |
| 112 |
Channel string |
| 113 |
Data string |
| 114 |
Info string |
| 115 |
HistoryTTL int |
| 116 |
HistorySize int |
| 117 |
HistoryMetaTTL int |
| 118 |
} |
| 119 |
|
| 120 |
type pubResponse struct { |
| 121 |
Offset uint64 |
| 122 |
Epoch string |
| 123 |
} |
| 124 |
|
| 125 |
func (m *pubResponse) DecodeMsgpack(d *msgpack.Decoder) error { |
| 126 |
var err error |
| 127 |
var l int |
| 128 |
if l, err = d.DecodeArrayLen(); err != nil { |
| 129 |
return err |
| 130 |
} |
| 131 |
if l != 2 { |
| 132 |
return fmt.Errorf("malformed array len: %d", l) |
| 133 |
} |
| 134 |
if m.Offset, err = d.DecodeUint64(); err != nil { |
| 135 |
return err |
| 136 |
} |
| 137 |
if m.Epoch, err = d.DecodeString(); err != nil { |
| 138 |
return err |
| 139 |
} |
| 140 |
return nil |
| 141 |
} |
| 142 |
|
| 143 |
// Publish - see centrifuge.Broker interface description. |
| 144 |
func (b *Broker) Publish(ch string, data []byte, opts centrifuge.PublishOptions) (centrifuge.StreamPosition, error) { |
| 145 |
s := consistentShard(ch, b.shards) |
| 146 |
pr := &pubRequest{ |
| 147 |
MsgType: "p", |
| 148 |
Channel: ch, |
| 149 |
Data: string(data), |
| 150 |
Info: b.clientInfoString(opts.ClientInfo), |
| 151 |
HistoryTTL: int(opts.HistoryTTL.Seconds()), |
| 152 |
HistorySize: opts.HistorySize, |
| 153 |
HistoryMetaTTL: int(b.config.HistoryMetaTTL.Seconds()), |
| 154 |
} |
| 155 |
var resp pubResponse |
| 156 |
err := s.ExecTyped(tarantool.Call("centrifuge.publish", pr), &resp) |
| 157 |
if err != nil { |
| 158 |
return centrifuge.StreamPosition{}, err |
| 159 |
} |
| 160 |
return centrifuge.StreamPosition{Offset: resp.Offset, Epoch: resp.Epoch}, err |
| 161 |
} |
| 162 |
|
| 163 |
// PublishJoin - see centrifuge.Broker interface description. |
| 164 |
func (b *Broker) PublishJoin(ch string, info *centrifuge.ClientInfo) error { |
| 165 |
s := consistentShard(ch, b.shards) |
| 166 |
pr := pubRequest{ |
| 167 |
MsgType: "j", |
| 168 |
Channel: ch, |
| 169 |
Info: b.clientInfoString(info), |
| 170 |
} |
| 171 |
_, err := s.Exec(tarantool.Call("centrifuge.publish", pr)) |
| 172 |
return err |
| 173 |
} |
| 174 |
|
| 175 |
// PublishLeave - see centrifuge.Broker interface description. |
| 176 |
func (b *Broker) PublishLeave(ch string, info *centrifuge.ClientInfo) error { |
| 177 |
s := consistentShard(ch, b.shards) |
| 178 |
pr := pubRequest{ |
| 179 |
MsgType: "l", |
| 180 |
Channel: ch, |
| 181 |
Info: b.clientInfoString(info), |
| 182 |
} |
| 183 |
_, err := s.Exec(tarantool.Call("centrifuge.publish", pr)) |
| 184 |
return err |
| 185 |
} |
| 186 |
|
| 187 |
func (b *Broker) clientInfoString(clientInfo *centrifuge.ClientInfo) string { |
| 188 |
var info string |
| 189 |
if clientInfo != nil { |
| 190 |
byteMessage, err := infoToProto(clientInfo).Marshal() |
| 191 |
if err != nil { |
| 192 |
return info |
| 193 |
} |
| 194 |
info = string(byteMessage) |
| 195 |
} |
| 196 |
return info |
| 197 |
} |
| 198 |
|
| 199 |
// PublishControl - see centrifuge.Broker interface description. |
| 200 |
func (b *Broker) PublishControl(data []byte, nodeID string) error { |
| 201 |
currentRound := atomic.AddUint64(&b.controlRound, 1) |
| 202 |
index := currentRound % uint64(len(b.shards)) |
| 203 |
var channel string |
| 204 |
if nodeID != "" { |
| 205 |
channel = nodeChannel(nodeID) |
| 206 |
} else { |
| 207 |
channel = b.controlChannel() |
| 208 |
} |
| 209 |
pr := pubRequest{ |
| 210 |
MsgType: "c", |
| 211 |
Channel: channel, |
| 212 |
Data: string(data), |
| 213 |
} |
| 214 |
_, err := b.shards[index].Exec(tarantool.Call("centrifuge.publish", pr)) |
| 215 |
return err |
| 216 |
} |
| 217 |
|
| 218 |
func (b *Broker) controlChannel() string { |
| 219 |
return tarantoolControlChannel |
| 220 |
} |
| 221 |
|
| 222 |
func nodeChannel(nodeID string) string { |
| 223 |
return tarantoolNodeChannelPrefix + nodeID |
| 224 |
} |
| 225 |
|
| 226 |
// Subscribe - see centrifuge.Broker interface description. |
| 227 |
func (b *Broker) Subscribe(ch string) error { |
| 228 |
if strings.HasPrefix(ch, internalChannelPrefix) { |
| 229 |
return centrifuge.ErrorBadRequest |
| 230 |
} |
| 231 |
if b.node.LogEnabled(centrifuge.LogLevelDebug) { |
| 232 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "subscribe node on channel", map[string]interface{}{"channel": ch})) |
| 233 |
} |
| 234 |
r := newSubRequest([]string{ch}, true) |
| 235 |
s := b.shards[consistentIndex(ch, len(b.shards))] |
| 236 |
return b.sendSubscribe(s, r) |
| 237 |
} |
| 238 |
|
| 239 |
// Unsubscribe - see centrifuge.Broker interface description. |
| 240 |
func (b *Broker) Unsubscribe(ch string) error { |
| 241 |
if b.node.LogEnabled(centrifuge.LogLevelDebug) { |
| 242 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "unsubscribe node from channel", map[string]interface{}{"channel": ch})) |
| 243 |
} |
| 244 |
r := newSubRequest([]string{ch}, false) |
| 245 |
s := b.shards[consistentIndex(ch, len(b.shards))] |
| 246 |
return b.sendSubscribe(s, r) |
| 247 |
} |
| 248 |
|
| 249 |
var errOpTimeout = errors.New("operation timed out") |
| 250 |
|
| 251 |
func (b *Broker) sendSubscribe(shard *Shard, r subRequest) error { |
| 252 |
select { |
| 253 |
case shard.subCh <- r: |
| 254 |
default: |
| 255 |
timer := AcquireTimer(defaultRequestTimeout) |
| 256 |
defer ReleaseTimer(timer) |
| 257 |
select { |
| 258 |
case shard.subCh <- r: |
| 259 |
case <-timer.C: |
| 260 |
return errOpTimeout |
| 261 |
} |
| 262 |
} |
| 263 |
return r.result() |
| 264 |
} |
| 265 |
|
| 266 |
type historyRequest struct { |
| 267 |
Channel string |
| 268 |
Offset uint64 |
| 269 |
Limit int |
| 270 |
IncludePubs bool |
| 271 |
HistoryMetaTTL int |
| 272 |
} |
| 273 |
|
| 274 |
type historyResponse struct { |
| 275 |
Offset uint64 |
| 276 |
Epoch string |
| 277 |
Pubs []*centrifuge.Publication |
| 278 |
} |
| 279 |
|
| 280 |
func (m *historyResponse) DecodeMsgpack(d *msgpack.Decoder) error { |
| 281 |
var err error |
| 282 |
var l int |
| 283 |
if l, err = d.DecodeArrayLen(); err != nil { |
| 284 |
return err |
| 285 |
} |
| 286 |
if l != 3 { |
| 287 |
return fmt.Errorf("malformed array len: %d", l) |
| 288 |
} |
| 289 |
if m.Offset, err = d.DecodeUint64(); err != nil { |
| 290 |
return err |
| 291 |
} |
| 292 |
if m.Epoch, err = d.DecodeString(); err != nil { |
| 293 |
return err |
| 294 |
} |
| 295 |
if l, err = d.DecodeArrayLen(); err != nil { |
| 296 |
return err |
| 297 |
} |
| 298 |
if l == -1 { |
| 299 |
return nil |
| 300 |
} |
| 301 |
|
| 302 |
pubs := make([]*centrifuge.Publication, 0, l) |
| 303 |
|
| 304 |
for i := 0; i < l; i++ { |
| 305 |
var pub centrifuge.Publication |
| 306 |
var l int |
| 307 |
if l, err = d.DecodeArrayLen(); err != nil { |
| 308 |
return err |
| 309 |
} |
| 310 |
if l != 6 { |
| 311 |
return fmt.Errorf("malformed array len: %d", l) |
| 312 |
} |
| 313 |
if _, err = d.DecodeUint64(); err != nil { |
| 314 |
return err |
| 315 |
} |
| 316 |
if _, err = d.DecodeString(); err != nil { |
| 317 |
return err |
| 318 |
} |
| 319 |
if pub.Offset, err = d.DecodeUint64(); err != nil { |
| 320 |
return err |
| 321 |
} |
| 322 |
if _, err = d.DecodeFloat64(); err != nil { |
| 323 |
return err |
| 324 |
} |
| 325 |
if data, err := d.DecodeString(); err != nil { |
| 326 |
return err |
| 327 |
} else { |
| 328 |
if len(data) > 0 { |
| 329 |
pub.Data = []byte(data) |
| 330 |
} |
| 331 |
} |
| 332 |
if info, err := d.DecodeString(); err != nil { |
| 333 |
return err |
| 334 |
} else { |
| 335 |
if len(info) > 0 { |
| 336 |
var i protocol.ClientInfo |
| 337 |
if err = i.Unmarshal([]byte(info)); err != nil { |
| 338 |
return err |
| 339 |
} |
| 340 |
pub.Info = infoFromProto(&i) |
| 341 |
} |
| 342 |
} |
| 343 |
pubs = append(pubs, &pub) |
| 344 |
} |
| 345 |
m.Pubs = pubs |
| 346 |
return nil |
| 347 |
} |
| 348 |
|
| 349 |
// History - see centrifuge.Broker interface description. |
| 350 |
func (b *Broker) History(ch string, filter centrifuge.HistoryFilter) ([]*centrifuge.Publication, centrifuge.StreamPosition, error) { |
| 351 |
var includePubs = true |
| 352 |
var offset uint64 |
| 353 |
if filter.Since != nil { |
| 354 |
offset = filter.Since.Offset + 1 |
| 355 |
} |
| 356 |
var limit int |
| 357 |
if filter.Limit == 0 { |
| 358 |
includePubs = false |
| 359 |
} |
| 360 |
if filter.Limit > 0 { |
| 361 |
limit = filter.Limit |
| 362 |
} |
| 363 |
historyMetaTTLSeconds := int(b.config.HistoryMetaTTL.Seconds()) |
| 364 |
s := consistentShard(ch, b.shards) |
| 365 |
req := historyRequest{ |
| 366 |
Channel: ch, |
| 367 |
Offset: offset, |
| 368 |
Limit: limit, |
| 369 |
IncludePubs: includePubs, |
| 370 |
HistoryMetaTTL: historyMetaTTLSeconds, |
| 371 |
} |
| 372 |
var resp historyResponse |
| 373 |
err := s.ExecTyped(tarantool.Call("centrifuge.history", req), &resp) |
| 374 |
if err != nil { |
| 375 |
return nil, centrifuge.StreamPosition{}, err |
| 376 |
} |
| 377 |
streamPosition := centrifuge.StreamPosition{Offset: resp.Offset, Epoch: resp.Epoch} |
| 378 |
return resp.Pubs, streamPosition, nil |
| 379 |
} |
| 380 |
|
| 381 |
type removeHistoryRequest struct { |
| 382 |
Channel string |
| 383 |
} |
| 384 |
|
| 385 |
// RemoveHistory - see centrifuge.Broker interface description. |
| 386 |
func (b *Broker) RemoveHistory(ch string) error { |
| 387 |
s := consistentShard(ch, b.shards) |
| 388 |
_, err := s.Exec(tarantool.Call("centrifuge.remove_history", removeHistoryRequest{Channel: ch})) |
| 389 |
return err |
| 390 |
} |
| 391 |
|
| 392 |
const ( |
| 393 |
// tarantoolPubSubWorkerChannelSize sets buffer size of channel to which we send all |
| 394 |
// messages received from Tarantool PUB/SUB connection to process in separate goroutine. |
| 395 |
tarantoolPubSubWorkerChannelSize = 512 |
| 396 |
// tarantoolSubscribeBatchLimit is a maximum number of channels to include in a single |
| 397 |
// batch subscribe call. |
| 398 |
tarantoolSubscribeBatchLimit = 512 |
| 399 |
) |
| 400 |
|
| 401 |
func (b *Broker) getShard(channel string) *Shard { |
| 402 |
if !b.sharding { |
| 403 |
return b.shards[0] |
| 404 |
} |
| 405 |
return b.shards[consistentIndex(channel, len(b.shards))] |
| 406 |
} |
| 407 |
|
| 408 |
type pollRequest struct { |
| 409 |
ConnID string |
| 410 |
UsePolling bool |
| 411 |
Timeout int |
| 412 |
} |
| 413 |
|
| 414 |
type subscribeRequest struct { |
| 415 |
ConnID string |
| 416 |
Channels []string |
| 417 |
} |
| 418 |
|
| 419 |
type pubSubMessage struct { |
| 420 |
Type string |
| 421 |
Channel string |
| 422 |
Offset uint64 |
| 423 |
Epoch string |
| 424 |
Data []byte |
| 425 |
Info []byte |
| 426 |
} |
| 427 |
|
| 428 |
func (m *pubSubMessage) DecodeMsgpack(d *msgpack.Decoder) error { |
| 429 |
var err error |
| 430 |
var l int |
| 431 |
if l, err = d.DecodeArrayLen(); err != nil { |
| 432 |
return err |
| 433 |
} |
| 434 |
if l != 6 { |
| 435 |
return fmt.Errorf("wrong array len: %d", l) |
| 436 |
} |
| 437 |
if m.Type, err = d.DecodeString(); err != nil { |
| 438 |
return err |
| 439 |
} |
| 440 |
if m.Channel, err = d.DecodeString(); err != nil { |
| 441 |
return err |
| 442 |
} |
| 443 |
if m.Offset, err = d.DecodeUint64(); err != nil { |
| 444 |
return err |
| 445 |
} |
| 446 |
if m.Epoch, err = d.DecodeString(); err != nil { |
| 447 |
return err |
| 448 |
} |
| 449 |
if data, err := d.DecodeString(); err != nil { |
| 450 |
return err |
| 451 |
} else { |
| 452 |
m.Data = []byte(data) |
| 453 |
} |
| 454 |
if info, err := d.DecodeString(); err != nil { |
| 455 |
return err |
| 456 |
} else { |
| 457 |
m.Info = []byte(info) |
| 458 |
} |
| 459 |
return nil |
| 460 |
} |
| 461 |
|
| 462 |
func (b *Broker) runPubSub(s *Shard, eventHandler centrifuge.BrokerEventHandler) { |
| 463 |
logError := func(errString string) { |
| 464 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "restart pub/sub", map[string]interface{}{"error": errString})) |
| 465 |
} |
| 466 |
|
| 467 |
u, err := uuid.NewRandom() |
| 468 |
if err != nil { |
| 469 |
logError(err.Error()) |
| 470 |
return |
| 471 |
} |
| 472 |
connID := u.String() |
| 473 |
|
| 474 |
conn, cancel, err := s.pubSubConn() |
| 475 |
if err != nil { |
| 476 |
logError(err.Error()) |
| 477 |
return |
| 478 |
} |
| 479 |
defer cancel() |
| 480 |
defer func() { _ = conn.Close() }() |
| 481 |
|
| 482 |
// Register poller with unique ID. |
| 483 |
result, err := conn.Exec(tarantool.Call("centrifuge.get_messages", pollRequest{ConnID: connID, UsePolling: b.config.UsePolling, Timeout: 0})) |
| 484 |
if err != nil { |
| 485 |
logError(err.Error()) |
| 486 |
return |
| 487 |
} |
| 488 |
if result.Error != "" { |
| 489 |
logError(result.Error) |
| 490 |
return |
| 491 |
} |
| 492 |
|
| 493 |
numWorkers := runtime.NumCPU() |
| 494 |
|
| 495 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, fmt.Sprintf("running Tarantool PUB/SUB, num workers: %d", numWorkers))) |
| 496 |
defer func() { |
| 497 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "stopping Tarantool PUB/SUB")) |
| 498 |
}() |
| 499 |
|
| 500 |
done := make(chan struct{}) |
| 501 |
var doneOnce sync.Once |
| 502 |
closeDoneOnce := func() { |
| 503 |
doneOnce.Do(func() { |
| 504 |
close(done) |
| 505 |
_ = conn.Close() |
| 506 |
}) |
| 507 |
} |
| 508 |
defer closeDoneOnce() |
| 509 |
|
| 510 |
// Run subscriber goroutine. |
| 511 |
go func(conn *tarantool.Connection) { |
| 512 |
for { |
| 513 |
select { |
| 514 |
case <-done: |
| 515 |
return |
| 516 |
case r := <-s.subCh: |
| 517 |
isSubscribe := r.subscribe |
| 518 |
channelBatch := []subRequest{r} |
| 519 |
|
| 520 |
chIDs := r.channels |
| 521 |
|
| 522 |
var otherR *subRequest |
| 523 |
|
| 524 |
loop: |
| 525 |
for len(chIDs) < tarantoolSubscribeBatchLimit { |
| 526 |
select { |
| 527 |
case r := <-s.subCh: |
| 528 |
if r.subscribe != isSubscribe { |
| 529 |
// We can not mix subscribe and unsubscribe request into one batch |
| 530 |
// so must stop here. As we consumed a subRequest value from channel |
| 531 |
// we should take care of it later. |
| 532 |
otherR = &r |
| 533 |
break loop |
| 534 |
} |
| 535 |
channelBatch = append(channelBatch, r) |
| 536 |
for _, ch := range r.channels { |
| 537 |
chIDs = append(chIDs, ch) |
| 538 |
} |
| 539 |
default: |
| 540 |
break loop |
| 541 |
} |
| 542 |
} |
| 543 |
|
| 544 |
var opErr error |
| 545 |
if isSubscribe { |
| 546 |
_, err = conn.Exec(tarantool.Call("centrifuge.subscribe", subscribeRequest{ConnID: connID, Channels: chIDs})) |
| 547 |
opErr = err |
| 548 |
} else { |
| 549 |
_, err = conn.Exec(tarantool.Call("centrifuge.unsubscribe", subscribeRequest{ConnID: connID, Channels: chIDs})) |
| 550 |
opErr = err |
| 551 |
} |
| 552 |
|
| 553 |
if opErr != nil { |
| 554 |
for _, r := range channelBatch { |
| 555 |
r.done(opErr) |
| 556 |
} |
| 557 |
if otherR != nil { |
| 558 |
otherR.done(opErr) |
| 559 |
} |
| 560 |
// Close conn, this should cause Receive to return with err below |
| 561 |
// and whole runPubSub method to restart. |
| 562 |
closeDoneOnce() |
| 563 |
return |
| 564 |
} |
| 565 |
for _, r := range channelBatch { |
| 566 |
r.done(nil) |
| 567 |
} |
| 568 |
if otherR != nil { |
| 569 |
chIDs := otherR.channels |
| 570 |
var opErr error |
| 571 |
if otherR.subscribe { |
| 572 |
_, err = conn.Exec(tarantool.Call("centrifuge.subscribe", subscribeRequest{ConnID: connID, Channels: chIDs})) |
| 573 |
opErr = err |
| 574 |
} else { |
| 575 |
_, err = conn.Exec(tarantool.Call("centrifuge.unsubscribe", subscribeRequest{ConnID: connID, Channels: chIDs})) |
| 576 |
opErr = err |
| 577 |
} |
| 578 |
if opErr != nil { |
| 579 |
otherR.done(opErr) |
| 580 |
// Close conn, this should cause Receive to return with err below |
| 581 |
// and whole runPubSub method to restart. |
| 582 |
closeDoneOnce() |
| 583 |
return |
| 584 |
} |
| 585 |
otherR.done(nil) |
| 586 |
} |
| 587 |
} |
| 588 |
} |
| 589 |
}(conn) |
| 590 |
|
| 591 |
// Run workers to spread received message processing work over worker goroutines. |
| 592 |
workers := make(map[int]chan pubSubMessage) |
| 593 |
for i := 0; i < numWorkers; i++ { |
| 594 |
workerCh := make(chan pubSubMessage, tarantoolPubSubWorkerChannelSize) |
| 595 |
workers[i] = workerCh |
| 596 |
go func(ch chan pubSubMessage) { |
| 597 |
for { |
| 598 |
select { |
| 599 |
case <-done: |
| 600 |
return |
| 601 |
case n := <-ch: |
| 602 |
err := b.handleMessage(eventHandler, n) |
| 603 |
if err != nil { |
| 604 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error handling client message", map[string]interface{}{"error": err.Error()})) |
| 605 |
continue |
| 606 |
} |
| 607 |
} |
| 608 |
} |
| 609 |
}(workerCh) |
| 610 |
} |
| 611 |
|
| 612 |
go func() { |
| 613 |
var chIDs []string |
| 614 |
|
| 615 |
channels := b.node.Hub().Channels() |
| 616 |
for i := 0; i < len(channels); i++ { |
| 617 |
if b.getShard(channels[i]) == s { |
| 618 |
chIDs = append(chIDs, channels[i]) |
| 619 |
} |
| 620 |
} |
| 621 |
|
| 622 |
batch := make([]string, 0) |
| 623 |
|
| 624 |
for i, ch := range chIDs { |
| 625 |
if len(batch) > 0 && i%tarantoolSubscribeBatchLimit == 0 { |
| 626 |
r := newSubRequest(batch, true) |
| 627 |
err := b.sendSubscribe(s, r) |
| 628 |
if err != nil { |
| 629 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error subscribing", map[string]interface{}{"error": err.Error()})) |
| 630 |
closeDoneOnce() |
| 631 |
return |
| 632 |
} |
| 633 |
batch = nil |
| 634 |
} |
| 635 |
batch = append(batch, ch) |
| 636 |
} |
| 637 |
if len(batch) > 0 { |
| 638 |
r := newSubRequest(batch, true) |
| 639 |
err := b.sendSubscribe(s, r) |
| 640 |
if err != nil { |
| 641 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error subscribing", map[string]interface{}{"error": err.Error()})) |
| 642 |
closeDoneOnce() |
| 643 |
return |
| 644 |
} |
| 645 |
} |
| 646 |
}() |
| 647 |
|
| 648 |
processPubSubMessages := func(messages []pubSubMessage) { |
| 649 |
for _, msg := range messages { |
| 650 |
// Add message to worker channel preserving message order - i.e. messages |
| 651 |
// from the same channel will be processed in the same worker. |
| 652 |
workers[index(msg.Channel, numWorkers)] <- msg |
| 653 |
} |
| 654 |
} |
| 655 |
|
| 656 |
for { |
| 657 |
err := b.waitPubSubMessages(conn, connID, processPubSubMessages) |
| 658 |
if err != nil { |
| 659 |
logError(err.Error()) |
| 660 |
return |
| 661 |
} |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
func (b *Broker) waitPubSubMessages(conn *tarantool.Connection, connID string, cb func([]pubSubMessage)) error { |
| 666 |
if !b.config.UsePolling { |
| 667 |
ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 668 |
defer cancel() |
| 669 |
_, err := conn.ExecContext(ctx, tarantool.Call( |
| 670 |
"centrifuge.get_messages", |
| 671 |
pollRequest{ConnID: connID, UsePolling: b.config.UsePolling, Timeout: 25}, |
| 672 |
).WithPushTyped(func(decode func(interface{}) error) { |
| 673 |
var m [][]pubSubMessage |
| 674 |
if err := decode(&m); err != nil { |
| 675 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error decoding push", map[string]interface{}{"error": err.Error()})) |
| 676 |
return |
| 677 |
} |
| 678 |
if len(m) == 1 { |
| 679 |
cb(m[0]) |
| 680 |
} |
| 681 |
})) |
| 682 |
if err != nil { |
| 683 |
return err |
| 684 |
} |
| 685 |
} else { |
| 686 |
var m [][]pubSubMessage |
| 687 |
err := conn.ExecTyped(tarantool.Call( |
| 688 |
"centrifuge.get_messages", |
| 689 |
pollRequest{ConnID: connID, UsePolling: b.config.UsePolling, Timeout: 25}), |
| 690 |
&m, |
| 691 |
) |
| 692 |
if err != nil { |
| 693 |
return err |
| 694 |
} |
| 695 |
if len(m) == 1 { |
| 696 |
cb(m[0]) |
| 697 |
} |
| 698 |
} |
| 699 |
return nil |
| 700 |
} |
| 701 |
|
| 702 |
func (b *Broker) handleMessage(eventHandler centrifuge.BrokerEventHandler, msg pubSubMessage) error { |
| 703 |
switch msg.Type { |
| 704 |
case "p": |
| 705 |
pub := ¢rifuge.Publication{ |
| 706 |
Offset: msg.Offset, |
| 707 |
Data: msg.Data, |
| 708 |
} |
| 709 |
if len(msg.Info) > 0 { |
| 710 |
var info protocol.ClientInfo |
| 711 |
err := info.Unmarshal(msg.Info) |
| 712 |
if err == nil { |
| 713 |
pub.Info = infoFromProto(&info) |
| 714 |
} |
| 715 |
} |
| 716 |
_ = eventHandler.HandlePublication(msg.Channel, pub, centrifuge.StreamPosition{Offset: msg.Offset, Epoch: msg.Epoch}) |
| 717 |
case "j": |
| 718 |
var info protocol.ClientInfo |
| 719 |
err := info.Unmarshal(msg.Info) |
| 720 |
if err == nil { |
| 721 |
_ = eventHandler.HandleJoin(msg.Channel, infoFromProto(&info)) |
| 722 |
} |
| 723 |
case "l": |
| 724 |
var info protocol.ClientInfo |
| 725 |
err := info.Unmarshal(msg.Info) |
| 726 |
if err == nil { |
| 727 |
_ = eventHandler.HandleLeave(msg.Channel, infoFromProto(&info)) |
| 728 |
} |
| 729 |
} |
| 730 |
return nil |
| 731 |
} |
| 732 |
|
| 733 |
func (b *Broker) runControlPubSub(s *Shard, eventHandler centrifuge.BrokerEventHandler) { |
| 734 |
logError := func(errString string) { |
| 735 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "restart control pub/sub", map[string]interface{}{"error": errString})) |
| 736 |
} |
| 737 |
|
| 738 |
u, err := uuid.NewRandom() |
| 739 |
if err != nil { |
| 740 |
logError(err.Error()) |
| 741 |
return |
| 742 |
} |
| 743 |
connID := u.String() |
| 744 |
|
| 745 |
conn, cancel, err := s.pubSubConn() |
| 746 |
if err != nil { |
| 747 |
logError(err.Error()) |
| 748 |
return |
| 749 |
} |
| 750 |
defer cancel() |
| 751 |
defer func() { _ = conn.Close() }() |
| 752 |
|
| 753 |
// Register poller with unique ID. |
| 754 |
result, err := conn.Exec(tarantool.Call("centrifuge.get_messages", pollRequest{ConnID: connID, UsePolling: b.config.UsePolling, Timeout: 0})) |
| 755 |
if err != nil { |
| 756 |
logError(err.Error()) |
| 757 |
return |
| 758 |
} |
| 759 |
if result.Error != "" { |
| 760 |
logError(result.Error) |
| 761 |
return |
| 762 |
} |
| 763 |
|
| 764 |
numWorkers := runtime.NumCPU() |
| 765 |
|
| 766 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, fmt.Sprintf("running Tarantool control PUB/SUB, num workers: %d", numWorkers))) |
| 767 |
defer func() { |
| 768 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "stopping Tarantool control PUB/SUB")) |
| 769 |
}() |
| 770 |
|
| 771 |
done := make(chan struct{}) |
| 772 |
var doneOnce sync.Once |
| 773 |
closeDoneOnce := func() { |
| 774 |
doneOnce.Do(func() { |
| 775 |
close(done) |
| 776 |
_ = conn.Close() |
| 777 |
}) |
| 778 |
} |
| 779 |
defer closeDoneOnce() |
| 780 |
|
| 781 |
// Run workers to spread message processing work over worker goroutines. |
| 782 |
workCh := make(chan pubSubMessage) |
| 783 |
for i := 0; i < numWorkers; i++ { |
| 784 |
go func() { |
| 785 |
for { |
| 786 |
select { |
| 787 |
case <-done: |
| 788 |
return |
| 789 |
case n := <-workCh: |
| 790 |
err := eventHandler.HandleControl(n.Data) |
| 791 |
if err != nil { |
| 792 |
b.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error handling control message", map[string]interface{}{"error": err.Error()})) |
| 793 |
continue |
| 794 |
} |
| 795 |
} |
| 796 |
} |
| 797 |
}() |
| 798 |
} |
| 799 |
|
| 800 |
controlChannel := b.controlChannel() |
| 801 |
result, err = conn.Exec(tarantool.Call("centrifuge.subscribe", subscribeRequest{ConnID: connID, Channels: []string{controlChannel, b.nodeChannel}})) |
| 802 |
if err != nil || result.Error != "" { |
| 803 |
if err != nil { |
| 804 |
logError(err.Error()) |
| 805 |
} else { |
| 806 |
logError(result.Error) |
| 807 |
} |
| 808 |
return |
| 809 |
} |
| 810 |
|
| 811 |
processPubSubMessages := func(messages []pubSubMessage) { |
| 812 |
for _, msg := range messages { |
| 813 |
workCh <- msg |
| 814 |
} |
| 815 |
} |
| 816 |
|
| 817 |
for { |
| 818 |
err := b.waitPubSubMessages(conn, connID, processPubSubMessages) |
| 819 |
if err != nil { |
| 820 |
logError(err.Error()) |
| 821 |
return |
| 822 |
} |
| 823 |
} |
| 824 |
} |