| 1 |
package centrifuge |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"sync/atomic" |
| 9 |
"testing" |
| 10 |
"time" |
| 11 |
|
| 12 |
"github.com/centrifugal/centrifuge/internal/controlpb" |
| 13 |
"github.com/centrifugal/centrifuge/internal/controlproto" |
| 14 |
|
| 15 |
"github.com/centrifugal/protocol" |
| 16 |
"github.com/stretchr/testify/require" |
| 17 |
) |
| 18 |
|
| 19 |
type TestBroker struct { |
| 20 |
errorOnRun bool |
| 21 |
errorOnSubscribe bool |
| 22 |
errorOnUnsubscribe bool |
| 23 |
errorOnPublish bool |
| 24 |
errorOnPublishJoin bool |
| 25 |
errorOnPublishLeave bool |
| 26 |
errorOnPublishControl bool |
| 27 |
errorOnHistory bool |
| 28 |
errorOnRemoveHistory bool |
| 29 |
|
| 30 |
publishCount int32 |
| 31 |
publishJoinCount int32 |
| 32 |
publishLeaveCount int32 |
| 33 |
publishControlCount int32 |
| 34 |
} |
| 35 |
|
| 36 |
func NewTestBroker() *TestBroker { |
| 37 |
return &TestBroker{} |
| 38 |
} |
| 39 |
|
| 40 |
func (e *TestBroker) Run(_ BrokerEventHandler) error { |
| 41 |
if e.errorOnRun { |
| 42 |
return errors.New("boom") |
| 43 |
} |
| 44 |
return nil |
| 45 |
} |
| 46 |
|
| 47 |
func (e *TestBroker) Publish(_ string, _ []byte, _ PublishOptions) (StreamPosition, error) { |
| 48 |
atomic.AddInt32(&e.publishCount, 1) |
| 49 |
if e.errorOnPublish { |
| 50 |
return StreamPosition{}, errors.New("boom") |
| 51 |
} |
| 52 |
return StreamPosition{}, nil |
| 53 |
} |
| 54 |
|
| 55 |
func (e *TestBroker) PublishJoin(_ string, _ *ClientInfo) error { |
| 56 |
atomic.AddInt32(&e.publishJoinCount, 1) |
| 57 |
if e.errorOnPublishJoin { |
| 58 |
return errors.New("boom") |
| 59 |
} |
| 60 |
return nil |
| 61 |
} |
| 62 |
|
| 63 |
func (e *TestBroker) PublishLeave(_ string, _ *ClientInfo) error { |
| 64 |
atomic.AddInt32(&e.publishLeaveCount, 1) |
| 65 |
if e.errorOnPublishLeave { |
| 66 |
return errors.New("boom") |
| 67 |
} |
| 68 |
return nil |
| 69 |
} |
| 70 |
|
| 71 |
func (e *TestBroker) PublishControl(_ []byte, _ string) error { |
| 72 |
atomic.AddInt32(&e.publishControlCount, 1) |
| 73 |
if e.errorOnPublishControl { |
| 74 |
return errors.New("boom") |
| 75 |
} |
| 76 |
return nil |
| 77 |
} |
| 78 |
|
| 79 |
func (e *TestBroker) Subscribe(_ string) error { |
| 80 |
if e.errorOnSubscribe { |
| 81 |
return errors.New("boom") |
| 82 |
} |
| 83 |
return nil |
| 84 |
} |
| 85 |
|
| 86 |
func (e *TestBroker) Unsubscribe(_ string) error { |
| 87 |
if e.errorOnUnsubscribe { |
| 88 |
return errors.New("boom") |
| 89 |
} |
| 90 |
return nil |
| 91 |
} |
| 92 |
|
| 93 |
func (e *TestBroker) History(_ string, _ HistoryFilter) ([]*Publication, StreamPosition, error) { |
| 94 |
if e.errorOnHistory { |
| 95 |
return nil, StreamPosition{}, errors.New("boom") |
| 96 |
} |
| 97 |
return nil, StreamPosition{}, nil |
| 98 |
} |
| 99 |
|
| 100 |
func (e *TestBroker) RemoveHistory(_ string) error { |
| 101 |
if e.errorOnRemoveHistory { |
| 102 |
return errors.New("boom") |
| 103 |
} |
| 104 |
return nil |
| 105 |
} |
| 106 |
|
| 107 |
type TestPresenceManager struct { |
| 108 |
errorOnPresence bool |
| 109 |
errorOnPresenceStats bool |
| 110 |
errorOnAddPresence bool |
| 111 |
errorOnRemovePresence bool |
| 112 |
} |
| 113 |
|
| 114 |
func NewTestPresenceManager() *TestPresenceManager { |
| 115 |
return &TestPresenceManager{} |
| 116 |
} |
| 117 |
|
| 118 |
func (e *TestPresenceManager) AddPresence(_ string, _ string, _ *ClientInfo) error { |
| 119 |
if e.errorOnAddPresence { |
| 120 |
return errors.New("boom") |
| 121 |
} |
| 122 |
return nil |
| 123 |
} |
| 124 |
|
| 125 |
func (e *TestPresenceManager) RemovePresence(_ string, _ string) error { |
| 126 |
if e.errorOnRemovePresence { |
| 127 |
return errors.New("boom") |
| 128 |
} |
| 129 |
return nil |
| 130 |
} |
| 131 |
|
| 132 |
func (e *TestPresenceManager) Presence(_ string) (map[string]*ClientInfo, error) { |
| 133 |
if e.errorOnPresence { |
| 134 |
return nil, errors.New("boom") |
| 135 |
} |
| 136 |
return map[string]*ClientInfo{}, nil |
| 137 |
} |
| 138 |
|
| 139 |
func (e *TestPresenceManager) PresenceStats(_ string) (PresenceStats, error) { |
| 140 |
if e.errorOnPresenceStats { |
| 141 |
return PresenceStats{}, errors.New("boom") |
| 142 |
} |
| 143 |
return PresenceStats{}, nil |
| 144 |
} |
| 145 |
|
| 146 |
func nodeWithBroker(broker Broker) *Node { |
| 147 |
c := DefaultConfig |
| 148 |
n, err := New(c) |
| 149 |
if err != nil { |
| 150 |
panic(err) |
| 151 |
} |
| 152 |
n.SetBroker(broker) |
| 153 |
err = n.Run() |
| 154 |
if err != nil { |
| 155 |
panic(err) |
| 156 |
} |
| 157 |
return n |
| 158 |
} |
| 159 |
|
| 160 |
func nodeWithTestBroker() *Node { |
| 161 |
return nodeWithBroker(NewTestBroker()) |
| 162 |
} |
| 163 |
|
| 164 |
func nodeWithPresenceManager(presenceManager PresenceManager) *Node { |
| 165 |
c := DefaultConfig |
| 166 |
n, err := New(c) |
| 167 |
if err != nil { |
| 168 |
panic(err) |
| 169 |
} |
| 170 |
n.SetPresenceManager(presenceManager) |
| 171 |
err = n.Run() |
| 172 |
if err != nil { |
| 173 |
panic(err) |
| 174 |
} |
| 175 |
return n |
| 176 |
} |
| 177 |
|
| 178 |
func defaultNodeNoHandlers() *Node { |
| 179 |
c := DefaultConfig |
| 180 |
c.LogLevel = LogLevelTrace |
| 181 |
c.LogHandler = func(entry LogEntry) {} |
| 182 |
n, err := New(c) |
| 183 |
if err != nil { |
| 184 |
panic(err) |
| 185 |
} |
| 186 |
err = n.Run() |
| 187 |
if err != nil { |
| 188 |
panic(err) |
| 189 |
} |
| 190 |
return n |
| 191 |
} |
| 192 |
|
| 193 |
func defaultTestNodeBenchmark(b *testing.B) *Node { |
| 194 |
c := DefaultConfig |
| 195 |
c.LogLevel = LogLevelError |
| 196 |
c.LogHandler = func(entry LogEntry) { |
| 197 |
b.Fatal(entry.Message, entry.Fields) |
| 198 |
} |
| 199 |
n, err := New(c) |
| 200 |
if err != nil { |
| 201 |
panic(err) |
| 202 |
} |
| 203 |
n.OnConnect(func(client *Client) { |
| 204 |
client.OnSubscribe(func(e SubscribeEvent, cb SubscribeCallback) { |
| 205 |
cb(SubscribeReply{}, nil) |
| 206 |
}) |
| 207 |
client.OnPublish(func(e PublishEvent, cb PublishCallback) { |
| 208 |
cb(PublishReply{}, nil) |
| 209 |
}) |
| 210 |
}) |
| 211 |
err = n.Run() |
| 212 |
if err != nil { |
| 213 |
panic(err) |
| 214 |
} |
| 215 |
return n |
| 216 |
} |
| 217 |
|
| 218 |
func defaultTestNode() *Node { |
| 219 |
n := defaultNodeNoHandlers() |
| 220 |
n.OnConnect(func(client *Client) { |
| 221 |
client.OnSubscribe(func(e SubscribeEvent, cb SubscribeCallback) { |
| 222 |
cb(SubscribeReply{}, nil) |
| 223 |
}) |
| 224 |
client.OnPublish(func(e PublishEvent, cb PublishCallback) { |
| 225 |
cb(PublishReply{}, nil) |
| 226 |
}) |
| 227 |
}) |
| 228 |
return n |
| 229 |
} |
| 230 |
|
| 231 |
func TestErrorMessage(t *testing.T) { |
| 232 |
errMessage := ErrorTooManyRequests.Error() |
| 233 |
require.Equal(t, "111: too many requests", errMessage) |
| 234 |
} |
| 235 |
|
| 236 |
func TestNode_Shutdown(t *testing.T) { |
| 237 |
n := defaultNodeNoHandlers() |
| 238 |
require.NoError(t, n.Shutdown(context.Background())) |
| 239 |
require.True(t, n.shutdown) |
| 240 |
// Test second call does not return error. |
| 241 |
require.NoError(t, n.Shutdown(context.Background())) |
| 242 |
} |
| 243 |
|
| 244 |
func TestClientEventHub(t *testing.T) { |
| 245 |
n := defaultNodeNoHandlers() |
| 246 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 247 |
n.OnConnect(func(_ *Client) {}) |
| 248 |
require.NotNil(t, n.clientEvents.connectHandler) |
| 249 |
} |
| 250 |
|
| 251 |
func TestNodeRegistry(t *testing.T) { |
| 252 |
registry := newNodeRegistry("node1") |
| 253 |
nodeInfo1 := controlpb.Node{UID: "node1"} |
| 254 |
nodeInfo2 := controlpb.Node{UID: "node2"} |
| 255 |
registry.add(&nodeInfo1) |
| 256 |
registry.add(&nodeInfo2) |
| 257 |
require.Equal(t, 2, len(registry.list())) |
| 258 |
info := registry.get("node1") |
| 259 |
require.Equal(t, "node1", info.UID) |
| 260 |
registry.clean(10 * time.Second) |
| 261 |
time.Sleep(2 * time.Second) |
| 262 |
registry.clean(time.Second) |
| 263 |
// Current node info should still be in node registry - we never delete it. |
| 264 |
require.Equal(t, 1, len(registry.list())) |
| 265 |
} |
| 266 |
|
| 267 |
func TestNodeLogHandler(t *testing.T) { |
| 268 |
c := DefaultConfig |
| 269 |
doneCh := make(chan struct{}) |
| 270 |
c.LogHandler = func(entry LogEntry) { |
| 271 |
require.Equal(t, LogLevelInfo, entry.Level) |
| 272 |
require.Equal(t, "test2", entry.Message) |
| 273 |
close(doneCh) |
| 274 |
} |
| 275 |
c.LogLevel = LogLevelInfo |
| 276 |
n, _ := New(c) |
| 277 |
// Debug should not be logged. |
| 278 |
n.Log(NewLogEntry(LogLevelDebug, "test1", nil)) |
| 279 |
n.Log(NewLogEntry(LogLevelInfo, "test2", nil)) |
| 280 |
select { |
| 281 |
case <-doneCh: |
| 282 |
case <-time.After(5 * time.Second): |
| 283 |
t.Fatal("timeout processing log in handler") |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
func TestNode_SetBroker(t *testing.T) { |
| 288 |
n, _ := New(DefaultConfig) |
| 289 |
broker := testMemoryBroker() |
| 290 |
n.SetBroker(broker) |
| 291 |
require.Equal(t, n.broker, broker) |
| 292 |
} |
| 293 |
|
| 294 |
func TestNode_SetPresenceManager_NilPresenceManager(t *testing.T) { |
| 295 |
n, _ := New(DefaultConfig) |
| 296 |
n.SetPresenceManager(nil) |
| 297 |
require.NoError(t, n.addPresence("test", "uid", nil)) |
| 298 |
require.NoError(t, n.removePresence("test", "uid")) |
| 299 |
_, err := n.Presence("test") |
| 300 |
require.Equal(t, ErrorNotAvailable, err) |
| 301 |
_, err = n.PresenceStats("test") |
| 302 |
require.Equal(t, ErrorNotAvailable, err) |
| 303 |
} |
| 304 |
|
| 305 |
func TestNode_LogEnabled(t *testing.T) { |
| 306 |
c := DefaultConfig |
| 307 |
c.LogLevel = LogLevelInfo |
| 308 |
c.LogHandler = func(entry LogEntry) {} |
| 309 |
n, _ := New(c) |
| 310 |
require.False(t, n.LogEnabled(LogLevelDebug)) |
| 311 |
require.True(t, n.LogEnabled(LogLevelInfo)) |
| 312 |
} |
| 313 |
|
| 314 |
func TestNode_RunError(t *testing.T) { |
| 315 |
broker := NewTestBroker() |
| 316 |
broker.errorOnRun = true |
| 317 |
node, err := New(DefaultConfig) |
| 318 |
require.NoError(t, err) |
| 319 |
node.SetBroker(broker) |
| 320 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 321 |
require.Error(t, node.Run()) |
| 322 |
} |
| 323 |
|
| 324 |
func TestNode_RunPubControlError(t *testing.T) { |
| 325 |
broker := NewTestBroker() |
| 326 |
broker.errorOnPublishControl = true |
| 327 |
node, err := New(DefaultConfig) |
| 328 |
require.NoError(t, err) |
| 329 |
node.SetBroker(broker) |
| 330 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 331 |
require.Error(t, node.Run()) |
| 332 |
} |
| 333 |
|
| 334 |
func TestNode_SetPresenceManager(t *testing.T) { |
| 335 |
n, _ := New(DefaultConfig) |
| 336 |
presenceManager := testMemoryPresenceManager() |
| 337 |
n.SetPresenceManager(presenceManager) |
| 338 |
require.Equal(t, n.presenceManager, presenceManager) |
| 339 |
} |
| 340 |
|
| 341 |
func TestNode_Info(t *testing.T) { |
| 342 |
n := defaultNodeNoHandlers() |
| 343 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 344 |
info, err := n.Info() |
| 345 |
require.NoError(t, err) |
| 346 |
require.Len(t, info.Nodes, 1) |
| 347 |
} |
| 348 |
|
| 349 |
func TestNode_handleJoin(t *testing.T) { |
| 350 |
n := defaultNodeNoHandlers() |
| 351 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 352 |
err := n.handleJoin("test", &protocol.Join{ |
| 353 |
Info: protocol.ClientInfo{}, |
| 354 |
}) |
| 355 |
require.NoError(t, err) |
| 356 |
} |
| 357 |
|
| 358 |
func TestNode_handleLeave(t *testing.T) { |
| 359 |
n := defaultNodeNoHandlers() |
| 360 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 361 |
err := n.handleLeave("test", &protocol.Leave{ |
| 362 |
Info: protocol.ClientInfo{}, |
| 363 |
}) |
| 364 |
require.NoError(t, err) |
| 365 |
} |
| 366 |
|
| 367 |
func TestNode_Unsubscribe(t *testing.T) { |
| 368 |
n := defaultNodeNoHandlers() |
| 369 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 370 |
|
| 371 |
err := n.Unsubscribe("42", "test_channel") |
| 372 |
require.NoError(t, err) |
| 373 |
|
| 374 |
done := make(chan struct{}) |
| 375 |
n.OnConnect(func(client *Client) { |
| 376 |
client.OnSubscribe(func(event SubscribeEvent, cb SubscribeCallback) { |
| 377 |
cb(SubscribeReply{}, nil) |
| 378 |
}) |
| 379 |
client.OnUnsubscribe(func(event UnsubscribeEvent) { |
| 380 |
require.Equal(t, "42", client.UserID()) |
| 381 |
close(done) |
| 382 |
}) |
| 383 |
}) |
| 384 |
|
| 385 |
client := newTestSubscribedClient(t, n, "42", "test_channel") |
| 386 |
|
| 387 |
err = n.Unsubscribe("42", "test_channel", WithResubscribe(false)) |
| 388 |
require.NoError(t, err) |
| 389 |
select { |
| 390 |
case <-done: |
| 391 |
case <-time.After(time.Second): |
| 392 |
require.Fail(t, "timeout") |
| 393 |
} |
| 394 |
require.Zero(t, n.hub.NumSubscribers("test_channel")) |
| 395 |
require.NotContains(t, client.channels, "test_channel") |
| 396 |
} |
| 397 |
|
| 398 |
func TestNode_Disconnect(t *testing.T) { |
| 399 |
n := defaultNodeNoHandlers() |
| 400 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 401 |
|
| 402 |
err := n.Disconnect("42") |
| 403 |
require.NoError(t, err) |
| 404 |
|
| 405 |
done := make(chan struct{}) |
| 406 |
n.OnConnect(func(client *Client) { |
| 407 |
client.OnDisconnect(func(event DisconnectEvent) { |
| 408 |
require.Equal(t, "42", client.UserID()) |
| 409 |
require.Equal(t, DisconnectBadRequest, event.Disconnect) |
| 410 |
close(done) |
| 411 |
}) |
| 412 |
}) |
| 413 |
|
| 414 |
newTestConnectedClient(t, n, "42") |
| 415 |
|
| 416 |
err = n.Disconnect("42", WithDisconnect(DisconnectBadRequest)) |
| 417 |
require.NoError(t, err) |
| 418 |
select { |
| 419 |
case <-done: |
| 420 |
case <-time.After(time.Second): |
| 421 |
require.Fail(t, "timeout") |
| 422 |
} |
| 423 |
require.True(t, len(n.hub.userConnections("42")) == 0) |
| 424 |
} |
| 425 |
|
| 426 |
func TestNode_pubUnsubscribe(t *testing.T) { |
| 427 |
node := nodeWithTestBroker() |
| 428 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 429 |
|
| 430 |
testBroker, _ := node.broker.(*TestBroker) |
| 431 |
require.EqualValues(t, 1, testBroker.publishControlCount) |
| 432 |
|
| 433 |
err := node.pubUnsubscribe("42", "holypeka") |
| 434 |
require.NoError(t, err) |
| 435 |
require.EqualValues(t, 2, testBroker.publishControlCount) |
| 436 |
} |
| 437 |
|
| 438 |
func TestNode_pubDisconnect(t *testing.T) { |
| 439 |
node := nodeWithTestBroker() |
| 440 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 441 |
|
| 442 |
testBroker, _ := node.broker.(*TestBroker) |
| 443 |
require.EqualValues(t, 1, testBroker.publishControlCount) |
| 444 |
|
| 445 |
err := node.pubDisconnect("42", DisconnectForceNoReconnect, nil) |
| 446 |
require.NoError(t, err) |
| 447 |
require.EqualValues(t, 2, testBroker.publishControlCount) |
| 448 |
} |
| 449 |
|
| 450 |
func TestNode_publishJoin(t *testing.T) { |
| 451 |
n := nodeWithTestBroker() |
| 452 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 453 |
|
| 454 |
testBroker, _ := n.broker.(*TestBroker) |
| 455 |
require.EqualValues(t, 0, testBroker.publishJoinCount) |
| 456 |
|
| 457 |
// Publish without options. |
| 458 |
err := n.publishJoin("test_channel", &ClientInfo{}) |
| 459 |
require.NoError(t, err) |
| 460 |
require.EqualValues(t, 1, testBroker.publishJoinCount) |
| 461 |
|
| 462 |
// Publish with default/correct options. |
| 463 |
err = n.publishJoin("test_channel", &ClientInfo{}) |
| 464 |
require.NoError(t, err) |
| 465 |
require.EqualValues(t, 2, testBroker.publishJoinCount) |
| 466 |
} |
| 467 |
|
| 468 |
func TestNode_publishLeave(t *testing.T) { |
| 469 |
n := nodeWithTestBroker() |
| 470 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 471 |
|
| 472 |
testBroker, _ := n.broker.(*TestBroker) |
| 473 |
require.EqualValues(t, 0, testBroker.publishLeaveCount) |
| 474 |
|
| 475 |
// Publish without options. |
| 476 |
err := n.publishLeave("test_channel", &ClientInfo{}) |
| 477 |
require.NoError(t, err) |
| 478 |
require.EqualValues(t, 1, testBroker.publishLeaveCount) |
| 479 |
|
| 480 |
// Publish with default/correct options. |
| 481 |
err = n.publishLeave("test_channel", &ClientInfo{}) |
| 482 |
require.NoError(t, err) |
| 483 |
require.EqualValues(t, 2, testBroker.publishLeaveCount) |
| 484 |
} |
| 485 |
|
| 486 |
func TestNode_RemoveHistory(t *testing.T) { |
| 487 |
n := defaultNodeNoHandlers() |
| 488 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 489 |
|
| 490 |
err := n.RemoveHistory("test_user") |
| 491 |
require.NoError(t, err) |
| 492 |
} |
| 493 |
|
| 494 |
func TestIndex(t *testing.T) { |
| 495 |
require.Equal(t, 0, index("2121", 1)) |
| 496 |
} |
| 497 |
|
| 498 |
var testPayload = map[string]interface{}{ |
| 499 |
"_id": "5adece493c1a23736b037c52", |
| 500 |
"index": 2, |
| 501 |
"guid": "478a00f4-19b1-4567-8097-013b8cc846b8", |
| 502 |
"isActive": false, |
| 503 |
"balance": "$2,199.02", |
| 504 |
"picture": "http://placehold.it/32x32", |
| 505 |
"age": 25, |
| 506 |
"eyeColor": "blue", |
| 507 |
"name": "Swanson Walker", |
| 508 |
"gender": "male", |
| 509 |
"company": "SHADEASE", |
| 510 |
"email": "[email protected]", |
| 511 |
"phone": "+1 (885) 410-3991", |
| 512 |
"address": "768 Paerdegat Avenue, Gouglersville, Oklahoma, 5380", |
| 513 |
"registered": "2016-01-24T07:40:09 -03:00", |
| 514 |
"latitude": -71.336378, |
| 515 |
"longitude": -28.155956, |
| 516 |
"tags": []string{ |
| 517 |
"magna", |
| 518 |
"nostrud", |
| 519 |
"irure", |
| 520 |
"aliquip", |
| 521 |
"culpa", |
| 522 |
"sint", |
| 523 |
}, |
| 524 |
"greeting": "Hello, Swanson Walker! You have 9 unread messages.", |
| 525 |
"favoriteFruit": "apple", |
| 526 |
} |
| 527 |
|
| 528 |
func BenchmarkNodePublishWithNoopBroker(b *testing.B) { |
| 529 |
node := nodeWithTestBroker() |
| 530 |
|
| 531 |
payload, err := json.Marshal(testPayload) |
| 532 |
if err != nil { |
| 533 |
panic(err.Error()) |
| 534 |
} |
| 535 |
b.ResetTimer() |
| 536 |
for i := 0; i < b.N; i++ { |
| 537 |
_, err := node.Publish("bench", payload) |
| 538 |
if err != nil { |
| 539 |
b.Fatal(err) |
| 540 |
} |
| 541 |
} |
| 542 |
b.StopTimer() |
| 543 |
_ = node.Shutdown(context.Background()) |
| 544 |
} |
| 545 |
|
| 546 |
func newFakeConn(b testing.TB, node *Node, channel string, protoType ProtocolType, sink chan []byte) { |
| 547 |
ctx, cancelFn := context.WithCancel(context.Background()) |
| 548 |
transport := newTestTransport(cancelFn) |
| 549 |
transport.setProtocolType(protoType) |
| 550 |
transport.setSink(sink) |
| 551 |
newCtx := SetCredentials(ctx, &Credentials{UserID: "test"}) |
| 552 |
client, _ := newClient(newCtx, node, transport) |
| 553 |
connectClient(b, client) |
| 554 |
rwWrapper := testReplyWriterWrapper() |
| 555 |
subCtx := client.subscribeCmd(&protocol.SubscribeRequest{ |
| 556 |
Channel: channel, |
| 557 |
}, SubscribeReply{}, rwWrapper.rw, false) |
| 558 |
require.Nil(b, subCtx.disconnect) |
| 559 |
} |
| 560 |
|
| 561 |
func newFakeConnJSON(b testing.TB, node *Node, channel string, sink chan []byte) { |
| 562 |
newFakeConn(b, node, channel, ProtocolTypeJSON, sink) |
| 563 |
} |
| 564 |
|
| 565 |
func newFakeConnProtobuf(b testing.TB, node *Node, channel string, sink chan []byte) { |
| 566 |
newFakeConn(b, node, channel, ProtocolTypeProtobuf, sink) |
| 567 |
} |
| 568 |
|
| 569 |
func BenchmarkBroadcastMemory(b *testing.B) { |
| 570 |
benchmarks := []struct { |
| 571 |
name string |
| 572 |
getFakeConn func(b testing.TB, n *Node, channel string, sink chan []byte) |
| 573 |
numSubscribers int |
| 574 |
}{ |
| 575 |
{"JSON", newFakeConnJSON, 1}, |
| 576 |
{"Protobuf", newFakeConnProtobuf, 1}, |
| 577 |
{"JSON", newFakeConnJSON, 10000}, |
| 578 |
{"Protobuf", newFakeConnProtobuf, 10000}, |
| 579 |
} |
| 580 |
|
| 581 |
for _, bm := range benchmarks { |
| 582 |
b.Run(fmt.Sprintf("%s_%d_sub", bm.name, bm.numSubscribers), func(b *testing.B) { |
| 583 |
n := defaultTestNode() |
| 584 |
payload := []byte(`{"input": "test"}`) |
| 585 |
sink := make(chan []byte, bm.numSubscribers) |
| 586 |
for i := 0; i < bm.numSubscribers; i++ { |
| 587 |
bm.getFakeConn(b, n, "test", sink) |
| 588 |
} |
| 589 |
b.ResetTimer() |
| 590 |
for i := 0; i < b.N; i++ { |
| 591 |
_, err := n.Publish("test", payload) |
| 592 |
if err != nil { |
| 593 |
panic(err) |
| 594 |
} |
| 595 |
for j := 0; j < bm.numSubscribers; j++ { |
| 596 |
<-sink |
| 597 |
} |
| 598 |
} |
| 599 |
b.StopTimer() |
| 600 |
_ = n.Shutdown(context.Background()) |
| 601 |
b.ReportAllocs() |
| 602 |
}) |
| 603 |
} |
| 604 |
} |
| 605 |
|
| 606 |
func BenchmarkHistory(b *testing.B) { |
| 607 |
broker := testMemoryBroker() |
| 608 |
numMessages := 100 |
| 609 |
|
| 610 |
channel := "test" |
| 611 |
|
| 612 |
for i := 1; i <= numMessages; i++ { |
| 613 |
_, err := broker.node.Publish(channel, []byte(`{}`), WithHistory(numMessages, time.Minute)) |
| 614 |
require.NoError(b, err) |
| 615 |
} |
| 616 |
|
| 617 |
b.ResetTimer() |
| 618 |
|
| 619 |
b.ResetTimer() |
| 620 |
for i := 0; i < b.N; i++ { |
| 621 |
_, err := broker.node.History(channel) |
| 622 |
if err != nil { |
| 623 |
b.Fatal(err) |
| 624 |
} |
| 625 |
|
| 626 |
} |
| 627 |
b.StopTimer() |
| 628 |
b.ReportAllocs() |
| 629 |
} |
| 630 |
|
| 631 |
func TestNode_handleControl(t *testing.T) { |
| 632 |
t.Run("BrokenData", func(t *testing.T) { |
| 633 |
t.Parallel() |
| 634 |
|
| 635 |
n := nodeWithTestBroker() |
| 636 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 637 |
|
| 638 |
err := n.handleControl([]byte("random")) |
| 639 |
require.EqualError(t, err, "unexpected EOF") |
| 640 |
}) |
| 641 |
|
| 642 |
t.Run("Node", func(t *testing.T) { |
| 643 |
t.Parallel() |
| 644 |
|
| 645 |
n := nodeWithTestBroker() |
| 646 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 647 |
|
| 648 |
enc := controlproto.NewProtobufEncoder() |
| 649 |
brokenCmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 650 |
Method: controlpb.MethodTypeNode, |
| 651 |
Params: []byte("random"), |
| 652 |
}) |
| 653 |
require.NoError(t, err) |
| 654 |
paramsBytes, err := enc.EncodeNode(&controlpb.Node{ |
| 655 |
Name: "new_node", |
| 656 |
}) |
| 657 |
require.NoError(t, err) |
| 658 |
cmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 659 |
Method: controlpb.MethodTypeNode, |
| 660 |
Params: paramsBytes, |
| 661 |
}) |
| 662 |
require.NoError(t, err) |
| 663 |
|
| 664 |
err = n.handleControl(brokenCmdBytes) |
| 665 |
require.EqualError(t, err, "unexpected EOF") |
| 666 |
err = n.handleControl(cmdBytes) |
| 667 |
require.NoError(t, err) |
| 668 |
require.NotContains(t, n.nodes.nodes, "new_node") |
| 669 |
}) |
| 670 |
|
| 671 |
t.Run("Unsubscribe", func(t *testing.T) { |
| 672 |
t.Parallel() |
| 673 |
|
| 674 |
n := defaultNodeNoHandlers() |
| 675 |
done := make(chan struct{}) |
| 676 |
n.OnConnect(func(client *Client) { |
| 677 |
client.OnSubscribe(func(e SubscribeEvent, cb SubscribeCallback) { |
| 678 |
cb(SubscribeReply{}, nil) |
| 679 |
}) |
| 680 |
client.OnUnsubscribe(func(event UnsubscribeEvent) { |
| 681 |
require.Equal(t, "42", client.UserID()) |
| 682 |
close(done) |
| 683 |
}) |
| 684 |
}) |
| 685 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 686 |
|
| 687 |
client := newTestSubscribedClient(t, n, "42", "test_channel") |
| 688 |
|
| 689 |
enc := controlproto.NewProtobufEncoder() |
| 690 |
brokenCmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 691 |
UID: client.uid, |
| 692 |
Method: controlpb.MethodTypeUnsubscribe, |
| 693 |
Params: []byte("random"), |
| 694 |
}) |
| 695 |
require.NoError(t, err) |
| 696 |
paramsBytes, err := enc.EncodeUnsubscribe(&controlpb.Unsubscribe{ |
| 697 |
Channel: "test_channel", |
| 698 |
User: "42", |
| 699 |
}) |
| 700 |
require.NoError(t, err) |
| 701 |
cmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 702 |
UID: client.uid, |
| 703 |
Method: controlpb.MethodTypeUnsubscribe, |
| 704 |
Params: paramsBytes, |
| 705 |
}) |
| 706 |
require.NoError(t, err) |
| 707 |
|
| 708 |
err = n.handleControl(brokenCmdBytes) |
| 709 |
require.EqualError(t, err, "unexpected EOF") |
| 710 |
err = n.handleControl(cmdBytes) |
| 711 |
select { |
| 712 |
case <-done: |
| 713 |
case <-time.After(time.Second): |
| 714 |
require.Fail(t, "timeout") |
| 715 |
} |
| 716 |
require.NoError(t, err) |
| 717 |
require.Zero(t, n.hub.NumSubscribers("test_channel")) |
| 718 |
}) |
| 719 |
|
| 720 |
t.Run("Disconnect", func(t *testing.T) { |
| 721 |
t.Parallel() |
| 722 |
|
| 723 |
n := defaultTestNode() |
| 724 |
done := make(chan struct{}) |
| 725 |
n.OnConnect(func(client *Client) { |
| 726 |
client.OnSubscribe(func(e SubscribeEvent, cb SubscribeCallback) { |
| 727 |
cb(SubscribeReply{}, nil) |
| 728 |
}) |
| 729 |
client.OnDisconnect(func(event DisconnectEvent) { |
| 730 |
require.Equal(t, "42", client.UserID()) |
| 731 |
close(done) |
| 732 |
}) |
| 733 |
}) |
| 734 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 735 |
|
| 736 |
client := newTestSubscribedClient(t, n, "42", "test_channel") |
| 737 |
|
| 738 |
enc := controlproto.NewProtobufEncoder() |
| 739 |
brokenCmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 740 |
UID: client.uid, |
| 741 |
Method: controlpb.MethodTypeDisconnect, |
| 742 |
Params: []byte("random"), |
| 743 |
}) |
| 744 |
require.NoError(t, err) |
| 745 |
paramsBytes, err := enc.EncodeDisconnect(&controlpb.Disconnect{ |
| 746 |
User: "42", |
| 747 |
}) |
| 748 |
require.NoError(t, err) |
| 749 |
cmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 750 |
UID: client.uid, |
| 751 |
Method: controlpb.MethodTypeDisconnect, |
| 752 |
Params: paramsBytes, |
| 753 |
}) |
| 754 |
require.NoError(t, err) |
| 755 |
|
| 756 |
err = n.handleControl(brokenCmdBytes) |
| 757 |
require.EqualError(t, err, "unexpected EOF") |
| 758 |
err = n.handleControl(cmdBytes) |
| 759 |
select { |
| 760 |
case <-done: |
| 761 |
case <-time.After(time.Second): |
| 762 |
require.Fail(t, "timeout") |
| 763 |
} |
| 764 |
require.NoError(t, err) |
| 765 |
require.Zero(t, n.hub.NumSubscribers("test_channel")) |
| 766 |
require.Zero(t, len(n.hub.userConnections("42"))) |
| 767 |
}) |
| 768 |
|
| 769 |
t.Run("Unknown", func(t *testing.T) { |
| 770 |
t.Parallel() |
| 771 |
|
| 772 |
n := defaultTestNode() |
| 773 |
defer func() { _ = n.Shutdown(context.Background()) }() |
| 774 |
|
| 775 |
client := newTestSubscribedClient(t, n, "42", "test_channel") |
| 776 |
|
| 777 |
enc := controlproto.NewProtobufEncoder() |
| 778 |
cmdBytes, err := enc.EncodeCommand(&controlpb.Command{ |
| 779 |
UID: client.uid, |
| 780 |
Method: -1, |
| 781 |
Params: nil, |
| 782 |
}) |
| 783 |
require.NoError(t, err) |
| 784 |
|
| 785 |
err = n.handleControl(cmdBytes) |
| 786 |
require.EqualError(t, err, "control method not found: -1") |
| 787 |
}) |
| 788 |
} |
| 789 |
|
| 790 |
func Test_infoFromProto(t *testing.T) { |
| 791 |
info := infoFromProto(nil) |
| 792 |
require.Nil(t, info) |
| 793 |
|
| 794 |
info = infoFromProto(&protocol.ClientInfo{ |
| 795 |
User: "user", |
| 796 |
Client: "client", |
| 797 |
}) |
| 798 |
require.NotNil(t, info) |
| 799 |
require.Equal(t, info.UserID, "user") |
| 800 |
require.Equal(t, info.ClientID, "client") |
| 801 |
require.Nil(t, info.ConnInfo) |
| 802 |
require.Nil(t, info.ChanInfo) |
| 803 |
|
| 804 |
info = infoFromProto(&protocol.ClientInfo{ |
| 805 |
User: "user", |
| 806 |
Client: "client", |
| 807 |
ConnInfo: []byte("conn_info"), |
| 808 |
ChanInfo: []byte("chan_info"), |
| 809 |
}) |
| 810 |
require.NotNil(t, info) |
| 811 |
require.Equal(t, info.UserID, "user") |
| 812 |
require.Equal(t, info.ClientID, "client") |
| 813 |
require.Equal(t, info.ConnInfo, []byte("conn_info")) |
| 814 |
require.Equal(t, info.ChanInfo, []byte("chan_info")) |
| 815 |
} |
| 816 |
|
| 817 |
func Test_infoToProto(t *testing.T) { |
| 818 |
info := infoToProto(nil) |
| 819 |
require.Nil(t, info) |
| 820 |
|
| 821 |
info = infoToProto(&ClientInfo{ |
| 822 |
UserID: "user", |
| 823 |
ClientID: "client", |
| 824 |
}) |
| 825 |
require.NotNil(t, info) |
| 826 |
require.Equal(t, info.User, "user") |
| 827 |
require.Equal(t, info.Client, "client") |
| 828 |
require.Nil(t, info.ConnInfo) |
| 829 |
require.Nil(t, info.ChanInfo) |
| 830 |
|
| 831 |
info = infoToProto(&ClientInfo{ |
| 832 |
UserID: "user", |
| 833 |
ClientID: "client", |
| 834 |
ConnInfo: []byte("conn_info"), |
| 835 |
ChanInfo: []byte("chan_info"), |
| 836 |
}) |
| 837 |
require.NotNil(t, info) |
| 838 |
require.Equal(t, info.User, "user") |
| 839 |
require.Equal(t, info.Client, "client") |
| 840 |
require.Equal(t, info.ConnInfo, protocol.Raw("conn_info")) |
| 841 |
require.Equal(t, info.ChanInfo, protocol.Raw("chan_info")) |
| 842 |
} |
| 843 |
|
| 844 |
func Test_pubToProto(t *testing.T) { |
| 845 |
pub := pubToProto(nil) |
| 846 |
require.Nil(t, pub) |
| 847 |
|
| 848 |
pub = pubToProto(&Publication{ |
| 849 |
Offset: 42, |
| 850 |
Data: []byte("data"), |
| 851 |
Info: &ClientInfo{ |
| 852 |
ClientID: "client_id", |
| 853 |
}, |
| 854 |
}) |
| 855 |
require.Equal(t, uint64(42), pub.Offset) |
| 856 |
require.Equal(t, protocol.Raw("data"), pub.Data) |
| 857 |
require.NotNil(t, pub.Info) |
| 858 |
require.Equal(t, pub.Info.Client, "client_id") |
| 859 |
} |
| 860 |
|
| 861 |
func Test_pubFromProto(t *testing.T) { |
| 862 |
pub := pubFromProto(nil) |
| 863 |
require.Nil(t, pub) |
| 864 |
|
| 865 |
pub = pubFromProto(&protocol.Publication{ |
| 866 |
Data: []byte("data"), |
| 867 |
Info: &protocol.ClientInfo{ |
| 868 |
Client: "client_id", |
| 869 |
}, |
| 870 |
Offset: 42, |
| 871 |
}) |
| 872 |
require.Equal(t, uint64(42), pub.Offset) |
| 873 |
require.Equal(t, []byte("data"), pub.Data) |
| 874 |
require.NotNil(t, pub.Info) |
| 875 |
require.Equal(t, pub.Info.ClientID, "client_id") |
| 876 |
} |
| 877 |
|
| 878 |
func TestNode_OnSurvey(t *testing.T) { |
| 879 |
node := defaultNodeNoHandlers() |
| 880 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 881 |
|
| 882 |
node.OnSurvey(func(event SurveyEvent, callback SurveyCallback) { |
| 883 |
go func() { |
| 884 |
require.Nil(t, event.Data) |
| 885 |
require.Equal(t, "test_op", event.Op) |
| 886 |
callback(SurveyReply{ |
| 887 |
Data: []byte("1"), |
| 888 |
Code: 1, |
| 889 |
}) |
| 890 |
}() |
| 891 |
}) |
| 892 |
|
| 893 |
results, err := node.Survey(context.Background(), "test_op", nil) |
| 894 |
require.NoError(t, err) |
| 895 |
require.Len(t, results, 1) |
| 896 |
res, ok := results[node.ID()] |
| 897 |
require.True(t, ok) |
| 898 |
require.Equal(t, uint32(1), res.Code) |
| 899 |
require.Equal(t, []byte("1"), res.Data) |
| 900 |
} |
| 901 |
|
| 902 |
func TestNode_OnSurvey_NoHandler(t *testing.T) { |
| 903 |
node := defaultNodeNoHandlers() |
| 904 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 905 |
|
| 906 |
_, err := node.Survey(context.Background(), "test_op", nil) |
| 907 |
require.Error(t, err) |
| 908 |
require.Equal(t, errSurveyHandlerNotRegistered, err) |
| 909 |
} |
| 910 |
|
| 911 |
func TestNode_OnSurvey_Timeout(t *testing.T) { |
| 912 |
node := defaultNodeNoHandlers() |
| 913 |
defer func() { _ = node.Shutdown(context.Background()) }() |
| 914 |
|
| 915 |
done := make(chan struct{}) |
| 916 |
|
| 917 |
node.OnSurvey(func(event SurveyEvent, callback SurveyCallback) { |
| 918 |
go func() { |
| 919 |
select { |
| 920 |
case <-done: |
| 921 |
case <-time.After(time.Second): |
| 922 |
} |
| 923 |
time.Sleep(time.Second) |
| 924 |
callback(SurveyReply{ |
| 925 |
Data: []byte("1"), |
| 926 |
Code: 1, |
| 927 |
}) |
| 928 |
}() |
| 929 |
}) |
| 930 |
|
| 931 |
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) |
| 932 |
defer cancel() |
| 933 |
_, err := node.Survey(ctx, "test_op", nil) |
| 934 |
require.Error(t, err) |
| 935 |
require.Equal(t, context.DeadlineExceeded, err) |
| 936 |
close(done) |
| 937 |
} |
| 938 |
|
| 939 |
func TestErrors(t *testing.T) { |
| 940 |
err := ErrorUnauthorized |
| 941 |
protoErr := err.toProto() |
| 942 |
require.Equal(t, ErrorUnauthorized.Code, protoErr.Code) |
| 943 |
err = ErrorUnknownChannel |
| 944 |
errText := err.Error() |
| 945 |
require.Equal(t, "102: unknown channel", errText) |
| 946 |
} |