Debian Codegraph @

client.go

raw
1 package centrifuge
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "sync"
8 "time"
9
10 "github.com/centrifugal/centrifuge/internal/bufpool"
11 "github.com/centrifugal/centrifuge/internal/clientproto"
12 "github.com/centrifugal/centrifuge/internal/prepared"
13 "github.com/centrifugal/centrifuge/internal/recovery"
14
15 "github.com/centrifugal/protocol"
16 "github.com/google/uuid"
17 )
18
19 // clientEventHub allows to deal with client event handlers.
20 // All its methods are not goroutine-safe and supposed to be called
21 // once inside Node ConnectHandler.
22 type clientEventHub struct {
23 aliveHandler AliveHandler
24 disconnectHandler DisconnectHandler
25 subscribeHandler SubscribeHandler
26 unsubscribeHandler UnsubscribeHandler
27 publishHandler PublishHandler
28 refreshHandler RefreshHandler
29 subRefreshHandler SubRefreshHandler
30 rpcHandler RPCHandler
31 messageHandler MessageHandler
32 presenceHandler PresenceHandler
33 presenceStatsHandler PresenceStatsHandler
34 historyHandler HistoryHandler
35 }
36
37 // OnAlive allows setting AliveHandler.
38 // AliveHandler called periodically for active client connection.
39 func (c *Client) OnAlive(h AliveHandler) {
40 c.eventHub.aliveHandler = h
41 }
42
43 // OnRefresh allows setting RefreshHandler.
44 // RefreshHandler called when it's time to refresh expiring client connection.
45 func (c *Client) OnRefresh(h RefreshHandler) {
46 c.eventHub.refreshHandler = h
47 }
48
49 // OnDisconnect allows setting DisconnectHandler.
50 // DisconnectHandler called when client disconnected.
51 func (c *Client) OnDisconnect(h DisconnectHandler) {
52 c.eventHub.disconnectHandler = h
53 }
54
55 // OnMessage allows setting MessageHandler.
56 // MessageHandler called when client sent asynchronous message.
57 func (c *Client) OnMessage(h MessageHandler) {
58 c.eventHub.messageHandler = h
59 }
60
61 // OnRPC allows setting RPCHandler.
62 // RPCHandler will be executed on every incoming RPC call.
63 func (c *Client) OnRPC(h RPCHandler) {
64 c.eventHub.rpcHandler = h
65 }
66
67 // OnSubRefresh allows setting SubRefreshHandler.
68 // SubRefreshHandler called when it's time to refresh client subscription.
69 func (c *Client) OnSubRefresh(h SubRefreshHandler) {
70 c.eventHub.subRefreshHandler = h
71 }
72
73 // OnSubscribe allows setting SubscribeHandler.
74 // SubscribeHandler called when client subscribes on a channel.
75 func (c *Client) OnSubscribe(h SubscribeHandler) {
76 c.eventHub.subscribeHandler = h
77 }
78
79 // OnUnsubscribe allows setting UnsubscribeHandler.
80 // UnsubscribeHandler called when client unsubscribes from channel.
81 func (c *Client) OnUnsubscribe(h UnsubscribeHandler) {
82 c.eventHub.unsubscribeHandler = h
83 }
84
85 // OnPublish allows setting PublishHandler.
86 // PublishHandler called when client publishes message into channel.
87 func (c *Client) OnPublish(h PublishHandler) {
88 c.eventHub.publishHandler = h
89 }
90
91 // OnPresence allows setting PresenceHandler.
92 // PresenceHandler called when Presence request from client received.
93 // At this moment you can only return a custom error or disconnect client.
94 func (c *Client) OnPresence(h PresenceHandler) {
95 c.eventHub.presenceHandler = h
96 }
97
98 // OnPresenceStats allows settings PresenceStatsHandler.
99 // PresenceStatsHandler called when Presence Stats request from client received.
100 // At this moment you can only return a custom error or disconnect client.
101 func (c *Client) OnPresenceStats(h PresenceStatsHandler) {
102 c.eventHub.presenceStatsHandler = h
103 }
104
105 // OnHistory allows settings HistoryHandler.
106 // HistoryHandler called when History request from client received.
107 // At this moment you can only return a custom error or disconnect client.
108 func (c *Client) OnHistory(h HistoryHandler) {
109 c.eventHub.historyHandler = h
110 }
111
112 // We poll current position in channel from history storage periodically.
113 // If client position is wrong maxCheckPositionFailures times in a row
114 // then client will be disconnected with InsufficientState reason. Polling
115 // not used in channels with high frequency updates since we can check position
116 // comparing client offset with offset in incoming Publication.
117 const maxCheckPositionFailures uint8 = 2
118
119 // Note: up to 8 possible flags here.
120 const (
121 flagPresence uint8 = 1 << iota
122 flagJoinLeave
123 flagPosition
124 flagRecover
125 flagServerSide
126 flagClientSideRefresh
127 )
128
129 // channelContext contains extra context for channel connection subscribed to.
130 // Note: this struct is aligned to consume less memory.
131 type channelContext struct {
132 Info []byte
133 expireAt int64
134 positionCheckTime int64
135 streamPosition StreamPosition
136 positionCheckFailures uint8
137 flags uint8
138 }
139
140 func channelHasFlag(flags, flag uint8) bool {
141 return flags&flag != 0
142 }
143
144 type timerOp uint8
145
146 const (
147 timerOpStale timerOp = 1
148 timerOpPresence timerOp = 2
149 timerOpExpire timerOp = 3
150 )
151
152 type status uint8
153
154 const (
155 statusConnecting status = 1
156 statusConnected status = 2
157 statusClosed status = 3
158 )
159
160 // Client represents client connection to server.
161 type Client struct {
162 mu sync.RWMutex
163 connectMu sync.Mutex // allows to sync connect with disconnect.
164 presenceMu sync.Mutex // allows to sync presence routine with client closing.
165 ctx context.Context
166 transport Transport
167 node *Node
168 exp int64
169 channels map[string]channelContext
170 messageWriter *writer
171 pubSubSync *recovery.PubSubSync
172 uid string
173 user string
174 info []byte
175 authenticated bool
176 clientSideRefresh bool
177 status status
178 timerOp timerOp
179 nextPresence int64
180 nextExpire int64
181 eventHub *clientEventHub
182 timer *time.Timer
183 }
184
185 // ClientCloseFunc must be called on Transport handler close to clean up Client.
186 type ClientCloseFunc func() error
187
188 // NewClient initializes new Client.
189 func NewClient(ctx context.Context, n *Node, t Transport) (*Client, ClientCloseFunc, error) {
190 uuidObject, err := uuid.NewRandom()
191 if err != nil {
192 return nil, nil, err
193 }
194
195 c := &Client{
196 ctx: ctx,
197 uid: uuidObject.String(),
198 node: n,
199 transport: t,
200 channels: make(map[string]channelContext),
201 pubSubSync: recovery.NewPubSubSync(),
202 status: statusConnecting,
203 eventHub: &clientEventHub{},
204 }
205
206 messageWriterConf := writerConfig{
207 MaxQueueSize: n.config.ClientQueueMaxSize,
208 WriteFn: func(data []byte) error {
209 if err := t.Write(data); err != nil {
210 go func() { _ = c.close(DisconnectWriteError) }()
211 return err
212 }
213 incTransportMessagesSent(t.Name())
214 return nil
215 },
216 WriteManyFn: func(data ...[]byte) error {
217 buf := bufpool.GetBuffer()
218 for _, payload := range data {
219 buf.Write(payload)
220 }
221 if err := t.Write(buf.Bytes()); err != nil {
222 go func() { _ = c.close(DisconnectWriteError) }()
223 bufpool.PutBuffer(buf)
224 return err
225 }
226 bufpool.PutBuffer(buf)
227 addTransportMessagesSent(t.Name(), float64(len(data)))
228 return nil
229 },
230 }
231
232 c.messageWriter = newWriter(messageWriterConf)
233 go c.messageWriter.run()
234
235 staleCloseDelay := n.config.ClientStaleCloseDelay
236 if staleCloseDelay > 0 && !c.authenticated {
237 c.mu.Lock()
238 c.timerOp = timerOpStale
239 c.timer = time.AfterFunc(staleCloseDelay, c.onTimerOp)
240 c.mu.Unlock()
241 }
242
243 return c, func() error { return c.close(nil) }, nil
244 }
245
246 func (c *Client) onTimerOp() {
247 c.mu.Lock()
248 if c.status == statusClosed {
249 c.mu.Unlock()
250 return
251 }
252 timerOp := c.timerOp
253 c.mu.Unlock()
254 switch timerOp {
255 case timerOpStale:
256 c.closeUnauthenticated()
257 case timerOpPresence:
258 c.updatePresence()
259 case timerOpExpire:
260 c.expire()
261 }
262 }
263
264 // Lock must be held outside.
265 func (c *Client) scheduleNextTimer() {
266 if c.status == statusClosed {
267 return
268 }
269 c.stopTimer()
270 var minEventTime int64
271 var nextTimerOp timerOp
272 var needTimer bool
273 if c.nextExpire > 0 {
274 nextTimerOp = timerOpExpire
275 minEventTime = c.nextExpire
276 needTimer = true
277 }
278 if c.nextPresence > 0 && (minEventTime == 0 || c.nextPresence < minEventTime) {
279 nextTimerOp = timerOpPresence
280 minEventTime = c.nextPresence
281 needTimer = true
282 }
283 if needTimer {
284 c.timerOp = nextTimerOp
285 afterDuration := time.Duration(minEventTime-time.Now().UnixNano()) * time.Nanosecond
286 c.timer = time.AfterFunc(afterDuration, c.onTimerOp)
287 }
288 }
289
290 // Lock must be held outside.
291 func (c *Client) stopTimer() {
292 if c.timer != nil {
293 c.timer.Stop()
294 }
295 }
296
297 // Lock must be held outside.
298 func (c *Client) addPresenceUpdate() {
299 config := c.node.config
300 presenceInterval := config.ClientPresenceUpdateInterval
301 c.nextPresence = time.Now().Add(presenceInterval).UnixNano()
302 c.scheduleNextTimer()
303 }
304
305 // Lock must be held outside.
306 func (c *Client) addExpireUpdate(after time.Duration) {
307 c.nextExpire = time.Now().Add(after).UnixNano()
308 c.scheduleNextTimer()
309 }
310
311 // closeUnauthenticated closes connection if it's not authenticated yet.
312 // At moment used to close client connections which have not sent valid
313 // connect command in a reasonable time interval after established connection
314 // with server.
315 func (c *Client) closeUnauthenticated() {
316 c.mu.RLock()
317 authenticated := c.authenticated
318 closed := c.status == statusClosed
319 c.mu.RUnlock()
320 if !authenticated && !closed {
321 _ = c.close(DisconnectStale)
322 }
323 }
324
325 func (c *Client) transportEnqueue(reply *prepared.Reply) error {
326 data := reply.Data()
327 c.trace("-->", data)
328 disconnect := c.messageWriter.enqueue(data)
329 if disconnect != nil {
330 // close in goroutine to not block message broadcast.
331 go func() { _ = c.close(disconnect) }()
332 return io.EOF
333 }
334 return nil
335 }
336
337 // updateChannelPresence updates client presence info for channel so it
338 // won't expire until client disconnect.
339 func (c *Client) updateChannelPresence(ch string, chCtx channelContext) error {
340 if !channelHasFlag(chCtx.flags, flagPresence) {
341 return nil
342 }
343 return c.node.addPresence(ch, c.uid, &ClientInfo{
344 UserID: c.user,
345 ClientID: c.uid,
346 ConnInfo: c.info,
347 ChanInfo: chCtx.Info,
348 })
349 }
350
351 // Context returns client Context. This context will be canceled
352 // as soon as client connection closes.
353 func (c *Client) Context() context.Context {
354 return c.ctx
355 }
356
357 func (c *Client) checkSubscriptionExpiration(channel string, channelContext channelContext, delay time.Duration, resultCB func(bool)) {
358 now := c.node.nowTimeGetter().Unix()
359 expireAt := channelContext.expireAt
360 clientSideRefresh := channelHasFlag(channelContext.flags, flagClientSideRefresh)
361 if expireAt > 0 && now > expireAt+int64(delay.Seconds()) {
362 // Subscription expired.
363 if clientSideRefresh || c.eventHub.subRefreshHandler == nil {
364 // The only way subscription could be refreshed in this case is via
365 // SUB_REFRESH command sent from client but looks like that command
366 // with new refreshed token have not been received in configured window.
367 resultCB(false)
368 return
369 }
370 cb := func(reply SubRefreshReply, err error) {
371 if err != nil {
372 resultCB(false)
373 return
374 }
375 if reply.Expired || (reply.ExpireAt > 0 && reply.ExpireAt < now) {
376 resultCB(false)
377 return
378 }
379 c.mu.Lock()
380 if ctx, ok := c.channels[channel]; ok {
381 if len(reply.Info) > 0 {
382 ctx.Info = reply.Info
383 }
384 ctx.expireAt = reply.ExpireAt
385 c.channels[channel] = ctx
386 }
387 c.mu.Unlock()
388 resultCB(true)
389 }
390 // Give subscription a chance to be refreshed via SubRefreshHandler.
391 event := SubRefreshEvent{Channel: channel}
392 c.eventHub.subRefreshHandler(event, cb)
393 return
394 }
395 resultCB(true)
396 }
397
398 // updatePresence used for various periodic actions we need to do with client connections.
399 func (c *Client) updatePresence() {
400 c.presenceMu.Lock()
401 defer c.presenceMu.Unlock()
402 config := c.node.config
403 c.mu.Lock()
404 if c.status == statusClosed {
405 c.mu.Unlock()
406 return
407 }
408 channels := make(map[string]channelContext, len(c.channels))
409 for channel, channelContext := range c.channels {
410 channels[channel] = channelContext
411 }
412 c.mu.Unlock()
413 if c.eventHub.aliveHandler != nil {
414 c.eventHub.aliveHandler()
415 }
416 for channel, channelContext := range channels {
417 c.checkSubscriptionExpiration(channel, channelContext, config.ClientExpiredSubCloseDelay, func(result bool) {
418 // Ideally we should deal with single expired subscription in this
419 // case - i.e. unsubscribe client from channel and give an advice
420 // to resubscribe. But there is scenario when browser goes online
421 // after computer was in sleeping mode which I have not managed to
422 // handle reliably on client side when unsubscribe with resubscribe
423 // flag was used. So I decided to stick with disconnect for now -
424 // it seems to work fine and drastically simplifies client code.
425 if !result {
426 go func() { _ = c.close(DisconnectSubExpired) }()
427 }
428 })
429
430 checkDelay := config.ClientChannelPositionCheckDelay
431 if checkDelay > 0 && !c.checkPosition(checkDelay, channel, channelContext) {
432 go func() { _ = c.close(DisconnectInsufficientState) }()
433 // No need to proceed after close.
434 return
435 }
436
437 err := c.updateChannelPresence(channel, channelContext)
438 if err != nil {
439 c.node.logger.log(newLogEntry(LogLevelError, "error updating presence for channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
440 }
441 }
442 c.mu.Lock()
443 c.addPresenceUpdate()
444 c.mu.Unlock()
445 }
446
447 func (c *Client) checkPosition(checkDelay time.Duration, ch string, chCtx channelContext) bool {
448 if !channelHasFlag(chCtx.flags, flagRecover|flagPosition) {
449 return true
450 }
451 nowUnix := c.node.nowTimeGetter().Unix()
452
453 isInitialCheck := chCtx.positionCheckTime == 0
454 isTimeToCheck := nowUnix-chCtx.positionCheckTime > int64(checkDelay.Seconds())
455 needCheckPosition := isInitialCheck || isTimeToCheck
456
457 if !needCheckPosition {
458 return true
459 }
460 position := chCtx.streamPosition
461 streamTop, err := c.node.streamTop(ch)
462 if err != nil {
463 return true
464 }
465
466 isValidPosition := streamTop.Offset == position.Offset && streamTop.Epoch == position.Epoch
467 keepConnection := true
468 c.mu.Lock()
469 if chContext, ok := c.channels[ch]; ok {
470 chContext.positionCheckTime = nowUnix
471 if !isValidPosition {
472 chContext.positionCheckFailures++
473 keepConnection = chContext.positionCheckFailures < maxCheckPositionFailures
474 } else {
475 chContext.positionCheckFailures = 0
476 }
477 c.channels[ch] = chContext
478 }
479 c.mu.Unlock()
480 return keepConnection
481 }
482
483 // ID returns unique client connection id.
484 func (c *Client) ID() string {
485 return c.uid
486 }
487
488 // UserID returns user id associated with client connection.
489 func (c *Client) UserID() string {
490 return c.user
491 }
492
493 // Transport returns client connection transport information.
494 func (c *Client) Transport() TransportInfo {
495 return c.transport
496 }
497
498 // Channels returns a slice of channels client connection currently subscribed to.
499 func (c *Client) Channels() []string {
500 c.mu.RLock()
501 defer c.mu.RUnlock()
502 channels := make([]string, 0, len(c.channels))
503 for ch := range c.channels {
504 channels = append(channels, ch)
505 }
506 return channels
507 }
508
509 // IsSubscribed returns true if client subscribed to a channel.
510 func (c *Client) IsSubscribed(ch string) bool {
511 c.mu.RLock()
512 defer c.mu.RUnlock()
513 _, ok := c.channels[ch]
514 return ok
515 }
516
517 // Send data to client. This sends an asynchronous message – data will be
518 // just written to connection. on client side this message can be handled
519 // with Message handler.
520 func (c *Client) Send(data []byte) error {
521 p := &protocol.Message{
522 Data: data,
523 }
524
525 pushEncoder := protocol.GetPushEncoder(c.transport.Protocol().toProto())
526 data, err := pushEncoder.EncodeMessage(p)
527 if err != nil {
528 return err
529 }
530 result, err := pushEncoder.Encode(clientproto.NewMessagePush(data))
531 if err != nil {
532 return err
533 }
534
535 reply := prepared.NewReply(&protocol.Reply{
536 Result: result,
537 }, c.transport.Protocol().toProto())
538
539 return c.transportEnqueue(reply)
540 }
541
542 // Unsubscribe allows to unsubscribe client from channel.
543 func (c *Client) Unsubscribe(ch string, opts ...UnsubscribeOption) error {
544 unsubscribeOpts := &UnsubscribeOptions{}
545 for _, opt := range opts {
546 opt(unsubscribeOpts)
547 }
548
549 c.mu.RLock()
550 if c.status == statusClosed {
551 c.mu.RUnlock()
552 return nil
553 }
554 c.mu.RUnlock()
555
556 err := c.unsubscribe(ch)
557 if err != nil {
558 return err
559 }
560 return c.sendUnsub(ch, unsubscribeOpts.Resubscribe)
561 }
562
563 func (c *Client) sendUnsub(ch string, resubscribe bool) error {
564 pushEncoder := protocol.GetPushEncoder(c.transport.Protocol().toProto())
565
566 data, err := pushEncoder.EncodeUnsub(&protocol.Unsub{Resubscribe: resubscribe})
567 if err != nil {
568 return err
569 }
570 result, err := pushEncoder.Encode(clientproto.NewUnsubPush(ch, data))
571 if err != nil {
572 return err
573 }
574
575 reply := prepared.NewReply(&protocol.Reply{
576 Result: result,
577 }, c.transport.Protocol().toProto())
578
579 _ = c.transportEnqueue(reply)
580
581 return nil
582 }
583
584 // Disconnect client connection with specific disconnect code and reason.
585 // This method internally creates a new goroutine at moment to do
586 // closing stuff. An extra goroutine is required to solve disconnect
587 // and alive callback ordering/sync problems. Will be a noop if client
588 // already closed. As this method runs a separate goroutine client
589 // connection will be closed eventually (i.e. not immediately).
590 func (c *Client) Disconnect(disconnect *Disconnect) {
591 go func() {
592 _ = c.close(disconnect)
593 }()
594 }
595
596 func (c *Client) close(disconnect *Disconnect) error {
597 c.presenceMu.Lock()
598 defer c.presenceMu.Unlock()
599 c.connectMu.Lock()
600 defer c.connectMu.Unlock()
601 c.mu.Lock()
602 if c.status == statusClosed {
603 c.mu.Unlock()
604 return nil
605 }
606 prevStatus := c.status
607 c.status = statusClosed
608
609 c.stopTimer()
610
611 channels := make(map[string]channelContext, len(c.channels))
612 for channel, channelContext := range c.channels {
613 channels[channel] = channelContext
614 }
615 c.mu.Unlock()
616
617 if len(channels) > 0 {
618 // Unsubscribe from all channels.
619 for channel := range channels {
620 err := c.unsubscribe(channel)
621 if err != nil {
622 c.node.logger.log(newLogEntry(LogLevelError, "error unsubscribing client from channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
623 }
624 }
625 }
626
627 c.mu.RLock()
628 authenticated := c.authenticated
629 c.mu.RUnlock()
630
631 if authenticated {
632 err := c.node.removeClient(c)
633 if err != nil {
634 c.node.logger.log(newLogEntry(LogLevelError, "error removing client", map[string]interface{}{"user": c.user, "client": c.uid, "error": err.Error()}))
635 }
636 }
637
638 // close writer and send messages remaining in writer queue if any.
639 _ = c.messageWriter.close()
640
641 _ = c.transport.Close(disconnect)
642
643 if disconnect != nil && disconnect.Reason != "" {
644 c.node.logger.log(newLogEntry(LogLevelDebug, "closing client connection", map[string]interface{}{"client": c.uid, "user": c.user, "reason": disconnect.Reason, "reconnect": disconnect.Reconnect}))
645 }
646 if disconnect != nil {
647 incServerDisconnect(disconnect.Code)
648 }
649 if c.eventHub.disconnectHandler != nil && prevStatus == statusConnected {
650 c.eventHub.disconnectHandler(DisconnectEvent{
651 Disconnect: disconnect,
652 })
653 }
654 return nil
655 }
656
657 func (c *Client) trace(msg string, data []byte) {
658 if !c.node.LogEnabled(LogLevelTrace) {
659 return
660 }
661 c.mu.RLock()
662 user := c.user
663 c.mu.RUnlock()
664 c.node.logger.log(newLogEntry(LogLevelTrace, msg, map[string]interface{}{"client": c.ID(), "user": user, "data": fmt.Sprintf("%#v", string(data))}))
665 }
666
667 // Lock must be held outside.
668 func (c *Client) clientInfo(ch string) *ClientInfo {
669 var channelInfo protocol.Raw
670 channelContext, ok := c.channels[ch]
671 if ok {
672 channelInfo = channelContext.Info
673 }
674 return &ClientInfo{
675 UserID: c.user,
676 ClientID: c.uid,
677 ConnInfo: c.info,
678 ChanInfo: channelInfo,
679 }
680 }
681
682 // Handle raw data encoded with Centrifuge protocol. Not goroutine-safe, supposed to be
683 // called only from transport reader.
684 func (c *Client) Handle(data []byte) bool {
685 c.mu.Lock()
686 if c.status == statusClosed {
687 c.mu.Unlock()
688 return false
689 }
690 c.mu.Unlock()
691
692 if len(data) == 0 {
693 c.node.logger.log(newLogEntry(LogLevelError, "empty client request received", map[string]interface{}{"client": c.ID(), "user": c.UserID()}))
694 go func() { _ = c.close(DisconnectBadRequest) }()
695 return false
696 }
697
698 c.trace("<--", data)
699
700 protoType := c.transport.Protocol().toProto()
701 decoder := protocol.GetCommandDecoder(protoType, data)
702 defer protocol.PutCommandDecoder(protoType, decoder)
703
704 for {
705 cmd, err := decoder.Decode()
706 if err != nil {
707 if err == io.EOF {
708 break
709 }
710 c.node.logger.log(newLogEntry(LogLevelInfo, "error decoding command", map[string]interface{}{"data": string(data), "client": c.ID(), "user": c.UserID(), "error": err.Error()}))
711 go func() { _ = c.close(DisconnectBadRequest) }()
712 return false
713 }
714
715 if cmd.Method != protocol.MethodTypeConnect && !c.authenticated {
716 // Client must send connect command to authenticate itself first.
717 c.node.logger.log(newLogEntry(LogLevelInfo, "client not authenticated to handle command", map[string]interface{}{"client": c.ID(), "user": c.UserID(), "command": fmt.Sprintf("%v", cmd)}))
718 go func() { _ = c.close(DisconnectBadRequest) }()
719 return false
720 }
721
722 if cmd.ID == 0 && cmd.Method != protocol.MethodTypeSend {
723 // Only send command from client can be sent without incremental ID.
724 c.node.logger.log(newLogEntry(LogLevelInfo, "command ID required for commands with reply expected", map[string]interface{}{"client": c.ID(), "user": c.UserID()}))
725 go func() { _ = c.close(DisconnectBadRequest) }()
726 return false
727 }
728
729 select {
730 case <-c.ctx.Done():
731 return false
732 default:
733 }
734
735 disconnect := c.handleCommand(cmd)
736
737 select {
738 case <-c.ctx.Done():
739 return false
740 default:
741 }
742 if disconnect != nil {
743 if disconnect != DisconnectNormal {
744 c.node.logger.log(newLogEntry(LogLevelInfo, "disconnect after handling command", map[string]interface{}{"command": fmt.Sprintf("%v", cmd), "client": c.ID(), "user": c.UserID(), "reason": disconnect.Reason}))
745 }
746 go func() { _ = c.close(disconnect) }()
747 return false
748 }
749 }
750 return true
751 }
752
753 type replyWriter struct {
754 write func(*protocol.Reply) error
755 flush func() error
756 done func()
757 }
758
759 // handleCommand dispatches Command into correct command handler.
760 func (c *Client) handleCommand(cmd *protocol.Command) *Disconnect {
761 c.mu.Lock()
762 if c.status == statusClosed {
763 c.mu.Unlock()
764 return nil
765 }
766 c.mu.Unlock()
767
768 method := cmd.Method
769 params := cmd.Params
770
771 protoType := c.transport.Protocol().toProto()
772 encoder := protocol.GetReplyEncoder(protoType)
773
774 var encodeErr error
775
776 started := time.Now()
777
778 write := func(rep *protocol.Reply) error {
779 rep.ID = cmd.ID
780 if rep.Error != nil {
781 c.node.logger.log(newLogEntry(LogLevelInfo, "client command error", map[string]interface{}{"reply": fmt.Sprintf("%v", rep), "command": fmt.Sprintf("%v", cmd), "client": c.ID(), "user": c.UserID(), "error": rep.Error.Message, "code": rep.Error.Code}))
782 incReplyError(cmd.Method, rep.Error.Code)
783 }
784
785 encodeErr = encoder.Encode(rep)
786 if encodeErr != nil {
787 c.node.logger.log(newLogEntry(LogLevelError, "error encoding reply", map[string]interface{}{"reply": fmt.Sprintf("%v", rep), "client": c.ID(), "user": c.UserID(), "error": encodeErr.Error()}))
788 }
789 return encodeErr
790 }
791
792 flush := func() error {
793 buf := encoder.Finish()
794 if len(buf) > 0 {
795 c.trace("-->", buf)
796 disconnect := c.messageWriter.enqueue(buf)
797 if disconnect != nil {
798 if c.node.logger.enabled(LogLevelDebug) {
799 c.node.logger.log(newLogEntry(LogLevelDebug, "disconnect after sending reply", map[string]interface{}{"client": c.ID(), "user": c.UserID(), "reason": disconnect.Reason}))
800 }
801 go func() { _ = c.close(disconnect) }()
802 return fmt.Errorf("flush error")
803 }
804 }
805 encoder.Reset()
806 return nil
807 }
808
809 // done should be called after command fully processed.
810 done := func() {
811 protocol.PutReplyEncoder(protoType, encoder)
812 observeCommandDuration(method, time.Since(started))
813 }
814
815 // The rule is as follows: if command handler returns an
816 // error then we handle it here: write error into connection
817 // or return disconnect further to caller and call rw.done()
818 // in the end.
819 // If handler returned nil error then we assume that all
820 // rw operations will be executed inside handler itself.
821 rw := &replyWriter{write, flush, done}
822
823 var handleErr error
824
825 switch method {
826 case protocol.MethodTypeConnect:
827 handleErr = c.handleConnect(params, rw)
828 case protocol.MethodTypePing:
829 handleErr = c.handlePing(params, rw)
830 case protocol.MethodTypeSubscribe:
831 handleErr = c.handleSubscribe(params, rw)
832 case protocol.MethodTypeUnsubscribe:
833 handleErr = c.handleUnsubscribe(params, rw)
834 case protocol.MethodTypePublish:
835 handleErr = c.handlePublish(params, rw)
836 case protocol.MethodTypePresence:
837 handleErr = c.handlePresence(params, rw)
838 case protocol.MethodTypePresenceStats:
839 handleErr = c.handlePresenceStats(params, rw)
840 case protocol.MethodTypeHistory:
841 handleErr = c.handleHistory(params, rw)
842 case protocol.MethodTypeRPC:
843 handleErr = c.handleRPC(params, rw)
844 case protocol.MethodTypeSend:
845 handleErr = c.handleSend(params, rw)
846 case protocol.MethodTypeRefresh:
847 handleErr = c.handleRefresh(params, rw)
848 case protocol.MethodTypeSubRefresh:
849 handleErr = c.handleSubRefresh(params, rw)
850 default:
851 handleErr = ErrorMethodNotFound
852 }
853 if encodeErr != nil {
854 return DisconnectServerError
855 }
856 if handleErr != nil {
857 defer rw.done()
858 switch t := handleErr.(type) {
859 case *Disconnect:
860 return t
861 default:
862 c.writeErrorFlush(rw, toClientErr(handleErr))
863 }
864 }
865 return nil
866 }
867
868 func (c *Client) checkExpired() {
869 c.mu.RLock()
870 closed := c.status == statusClosed
871 clientSideRefresh := c.clientSideRefresh
872 exp := c.exp
873 c.mu.RUnlock()
874 if closed || exp == 0 {
875 return
876 }
877 now := time.Now().Unix()
878 ttl := exp - now
879
880 if !clientSideRefresh && c.eventHub.refreshHandler != nil {
881 if ttl > 0 {
882 c.mu.Lock()
883 if c.status != statusClosed {
884 c.addExpireUpdate(time.Duration(ttl) * time.Second)
885 }
886 c.mu.Unlock()
887 }
888 }
889
890 if ttl > 0 {
891 // Connection was successfully refreshed.
892 return
893 }
894
895 _ = c.close(DisconnectExpired)
896 }
897
898 func (c *Client) expire() {
899 c.mu.RLock()
900 closed := c.status == statusClosed
901 clientSideRefresh := c.clientSideRefresh
902 c.mu.RUnlock()
903 if closed {
904 return
905 }
906 if !clientSideRefresh && c.eventHub.refreshHandler != nil {
907 cb := func(reply RefreshReply, err error) {
908 if err != nil {
909 switch t := err.(type) {
910 case *Disconnect:
911 _ = c.close(t)
912 return
913 default:
914 _ = c.close(DisconnectServerError)
915 return
916 }
917 }
918 if reply.Expired {
919 _ = c.close(DisconnectExpired)
920 return
921 }
922 if reply.ExpireAt > 0 {
923 c.mu.Lock()
924 c.exp = reply.ExpireAt
925 if reply.Info != nil {
926 c.info = reply.Info
927 }
928 c.mu.Unlock()
929 }
930 c.checkExpired()
931 }
932 c.eventHub.refreshHandler(RefreshEvent{}, cb)
933 } else {
934 c.checkExpired()
935 }
936 }
937
938 func (c *Client) handleConnect(params protocol.Raw, rw *replyWriter) error {
939 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeConnect(params)
940 if err != nil {
941 return c.logDisconnectBadRequestWithError(err, "error decoding connect")
942 }
943 disconnect := c.connectCmd(cmd, rw)
944 if disconnect != nil {
945 return disconnect
946 }
947 c.triggerConnect()
948 c.scheduleOnConnectTimers()
949 return nil
950 }
951
952 func (c *Client) triggerConnect() {
953 c.connectMu.Lock()
954 defer c.connectMu.Unlock()
955 if c.status != statusConnecting {
956 return
957 }
958 if c.node.clientEvents.connectHandler == nil {
959 c.status = statusConnected
960 return
961 }
962 c.node.clientEvents.connectHandler(c)
963 c.status = statusConnected
964 }
965
966 func (c *Client) scheduleOnConnectTimers() {
967 // Make presence and refresh handlers always run after client connect event.
968 c.mu.Lock()
969 c.addPresenceUpdate()
970 if c.exp > 0 {
971 expireAfter := time.Duration(c.exp-time.Now().Unix()) * time.Second
972 if c.clientSideRefresh {
973 conf := c.node.config
974 expireAfter += conf.ClientExpiredCloseDelay
975 }
976 c.addExpireUpdate(expireAfter)
977 }
978 c.mu.Unlock()
979 }
980
981 func (c *Client) handleRefresh(params protocol.Raw, rw *replyWriter) error {
982 if c.eventHub.refreshHandler == nil {
983 return ErrorNotAvailable
984 }
985
986 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeRefresh(params)
987 if err != nil {
988 return c.logDisconnectBadRequestWithError(err, "error decoding refresh")
989 }
990
991 if cmd.Token == "" {
992 return c.logDisconnectBadRequest("client token required to refresh")
993 }
994
995 c.mu.RLock()
996 clientSideRefresh := c.clientSideRefresh
997 c.mu.RUnlock()
998
999 if !clientSideRefresh {
1000 // Client not supposed to send refresh command in case of server-side refresh mechanism.
1001 return c.logDisconnectBadRequest("server-side refresh expected")
1002 }
1003
1004 event := RefreshEvent{
1005 ClientSideRefresh: true,
1006 Token: cmd.Token,
1007 }
1008
1009 cb := func(reply RefreshReply, err error) {
1010 defer rw.done()
1011
1012 if err != nil {
1013 c.writeDisconnectOrErrorFlush(rw, err)
1014 return
1015 }
1016
1017 if reply.Expired {
1018 c.Disconnect(DisconnectExpired)
1019 return
1020 }
1021
1022 expireAt := reply.ExpireAt
1023 info := reply.Info
1024
1025 res := &protocol.RefreshResult{
1026 Version: c.node.config.Version,
1027 Expires: expireAt > 0,
1028 Client: c.uid,
1029 }
1030
1031 ttl := expireAt - time.Now().Unix()
1032
1033 if ttl > 0 {
1034 res.TTL = uint32(ttl)
1035 }
1036
1037 if expireAt > 0 {
1038 // connection check enabled
1039 if ttl > 0 {
1040 // connection refreshed, update client timestamp and set new expiration timeout
1041 c.mu.Lock()
1042 c.exp = expireAt
1043 if len(info) > 0 {
1044 c.info = info
1045 }
1046 duration := time.Duration(ttl)*time.Second + c.node.config.ClientExpiredCloseDelay
1047 c.addExpireUpdate(duration)
1048 c.mu.Unlock()
1049 } else {
1050 c.writeErrorFlush(rw, ErrorExpired)
1051 return
1052 }
1053 }
1054
1055 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeRefreshResult(res)
1056 if err != nil {
1057 c.logWriteInternalErrorFlush(rw, err, "error encoding refresh")
1058 return
1059 }
1060
1061 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1062 }
1063
1064 c.eventHub.refreshHandler(event, cb)
1065 return nil
1066 }
1067
1068 func (c *Client) handleSubscribe(params protocol.Raw, rw *replyWriter) error {
1069 if c.eventHub.subscribeHandler == nil {
1070 return ErrorNotAvailable
1071 }
1072
1073 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeSubscribe(params)
1074 if err != nil {
1075 return c.logDisconnectBadRequestWithError(err, "error decoding subscribe")
1076 }
1077
1078 replyError, disconnect := c.validateSubscribeRequest(cmd)
1079 if disconnect != nil || replyError != nil {
1080 if disconnect != nil {
1081 return disconnect
1082 }
1083 return replyError
1084 }
1085
1086 event := SubscribeEvent{
1087 Channel: cmd.Channel,
1088 Token: cmd.Token,
1089 }
1090
1091 cb := func(reply SubscribeReply, err error) {
1092 defer rw.done()
1093
1094 if err != nil {
1095 c.writeDisconnectOrErrorFlush(rw, err)
1096 return
1097 }
1098
1099 ctx := c.subscribeCmd(cmd, reply, rw, false)
1100
1101 if ctx.disconnect != nil {
1102 c.Disconnect(ctx.disconnect)
1103 return
1104 }
1105 if ctx.err != nil {
1106 c.writeDisconnectOrErrorFlush(rw, ctx.err)
1107 return
1108 }
1109
1110 _ = rw.flush()
1111
1112 if channelHasFlag(ctx.channelContext.flags, flagJoinLeave) && ctx.clientInfo != nil {
1113 go func() { _ = c.node.publishJoin(cmd.Channel, ctx.clientInfo) }()
1114 }
1115 }
1116 c.eventHub.subscribeHandler(event, cb)
1117 return nil
1118 }
1119
1120 func (c *Client) handleSubRefresh(params protocol.Raw, rw *replyWriter) error {
1121 if c.eventHub.subRefreshHandler == nil {
1122 return ErrorNotAvailable
1123 }
1124
1125 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeSubRefresh(params)
1126 if err != nil {
1127 return c.logDisconnectBadRequestWithError(err, "error decoding sub refresh")
1128 }
1129
1130 channel := cmd.Channel
1131 if channel == "" {
1132 return c.logDisconnectBadRequest("channel required for sub refresh")
1133 }
1134
1135 c.mu.RLock()
1136 ctx, okChannel := c.channels[channel]
1137 clientSideRefresh := channelHasFlag(ctx.flags, flagClientSideRefresh)
1138 c.mu.RUnlock()
1139 if !okChannel {
1140 // Must be subscribed to refresh subscription.
1141 return ErrorPermissionDenied
1142 }
1143
1144 if !clientSideRefresh {
1145 // Client not supposed to send sub refresh command in case of server-side
1146 // subscription refresh mechanism.
1147 return c.logDisconnectBadRequest("server-side sub refresh expected")
1148 }
1149
1150 if cmd.Token == "" {
1151 c.node.logger.log(newLogEntry(LogLevelInfo, "subscription refresh token required", map[string]interface{}{"client": c.uid, "user": c.UserID()}))
1152 return ErrorBadRequest
1153 }
1154
1155 event := SubRefreshEvent{
1156 ClientSideRefresh: true,
1157 Channel: cmd.Channel,
1158 Token: cmd.Token,
1159 }
1160
1161 cb := func(reply SubRefreshReply, err error) {
1162 defer rw.done()
1163
1164 if err != nil {
1165 c.writeDisconnectOrErrorFlush(rw, err)
1166 return
1167 }
1168
1169 res := &protocol.SubRefreshResult{}
1170
1171 if reply.ExpireAt > 0 {
1172 res.Expires = true
1173 now := time.Now().Unix()
1174 if reply.ExpireAt < now {
1175 c.writeErrorFlush(rw, ErrorExpired)
1176 return
1177 }
1178 res.TTL = uint32(reply.ExpireAt - now)
1179 }
1180
1181 c.mu.Lock()
1182 channelContext, okChan := c.channels[channel]
1183 if okChan {
1184 channelContext.Info = reply.Info
1185 channelContext.expireAt = reply.ExpireAt
1186 }
1187 c.channels[channel] = channelContext
1188 c.mu.Unlock()
1189
1190 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeSubRefreshResult(res)
1191 if err != nil {
1192 c.logWriteInternalErrorFlush(rw, err, "error encoding sub refresh")
1193 return
1194 }
1195 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1196 }
1197
1198 c.eventHub.subRefreshHandler(event, cb)
1199 return nil
1200 }
1201
1202 func (c *Client) handleUnsubscribe(params protocol.Raw, rw *replyWriter) error {
1203 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeUnsubscribe(params)
1204 if err != nil {
1205 return c.logDisconnectBadRequestWithError(err, "error decoding unsubscribe")
1206 }
1207
1208 channel := cmd.Channel
1209 if channel == "" {
1210 return c.logDisconnectBadRequest("channel required for unsubscribe")
1211 }
1212
1213 if err := c.unsubscribe(channel); err != nil {
1214 return err
1215 }
1216
1217 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeUnsubscribeResult(&protocol.UnsubscribeResult{})
1218 if err != nil {
1219 c.node.logger.log(newLogEntry(LogLevelError, "error encoding unsubscribe", map[string]interface{}{"error": err.Error()}))
1220 return DisconnectServerError
1221 }
1222
1223 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1224 rw.done()
1225 return nil
1226 }
1227
1228 func (c *Client) handlePublish(params protocol.Raw, rw *replyWriter) error {
1229 if c.eventHub.publishHandler == nil {
1230 return ErrorNotAvailable
1231 }
1232
1233 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePublish(params)
1234 if err != nil {
1235 return c.logDisconnectBadRequestWithError(err, "error decoding publish")
1236 }
1237
1238 channel := cmd.Channel
1239 data := cmd.Data
1240
1241 if channel == "" || len(data) == 0 {
1242 return c.logDisconnectBadRequest("channel and data required for publish")
1243 }
1244
1245 c.mu.RLock()
1246 info := c.clientInfo(channel)
1247 c.mu.RUnlock()
1248
1249 event := PublishEvent{
1250 Channel: channel,
1251 Data: data,
1252 ClientInfo: info,
1253 }
1254
1255 cb := func(reply PublishReply, err error) {
1256 defer rw.done()
1257
1258 if err != nil {
1259 c.writeDisconnectOrErrorFlush(rw, err)
1260 return
1261 }
1262
1263 if reply.Result == nil {
1264 _, err := c.node.Publish(
1265 event.Channel, event.Data,
1266 WithHistory(reply.Options.HistorySize, reply.Options.HistoryTTL),
1267 WithClientInfo(reply.Options.ClientInfo),
1268 )
1269 if err != nil {
1270 c.logWriteInternalErrorFlush(rw, err, "error publish")
1271 return
1272 }
1273 }
1274
1275 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodePublishResult(&protocol.PublishResult{})
1276 if err != nil {
1277 c.logWriteInternalErrorFlush(rw, err, "error encoding publish")
1278 return
1279 }
1280 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1281 }
1282
1283 c.eventHub.publishHandler(event, cb)
1284 return nil
1285 }
1286
1287 func (c *Client) handlePresence(params protocol.Raw, rw *replyWriter) error {
1288 if c.eventHub.presenceHandler == nil {
1289 return ErrorNotAvailable
1290 }
1291
1292 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePresence(params)
1293 if err != nil {
1294 return c.logDisconnectBadRequestWithError(err, "error decoding presence")
1295 }
1296
1297 channel := cmd.Channel
1298 if channel == "" {
1299 return c.logDisconnectBadRequest("channel required for presence")
1300 }
1301
1302 event := PresenceEvent{
1303 Channel: channel,
1304 }
1305
1306 cb := func(reply PresenceReply, err error) {
1307 defer rw.done()
1308 if err != nil {
1309 c.writeDisconnectOrErrorFlush(rw, err)
1310 return
1311 }
1312
1313 var presence map[string]*ClientInfo
1314 if reply.Result == nil {
1315 result, err := c.node.Presence(event.Channel)
1316 if err != nil {
1317 c.logWriteInternalErrorFlush(rw, err, "error getting presence")
1318 return
1319 }
1320 presence = result.Presence
1321 } else {
1322 presence = reply.Result.Presence
1323 }
1324
1325 protoPresence := make(map[string]*protocol.ClientInfo, len(presence))
1326 for k, v := range presence {
1327 protoPresence[k] = infoToProto(v)
1328 }
1329
1330 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodePresenceResult(&protocol.PresenceResult{
1331 Presence: protoPresence,
1332 })
1333 if err != nil {
1334 c.logWriteInternalErrorFlush(rw, err, "error encoding presence")
1335 return
1336 }
1337 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1338 }
1339
1340 c.eventHub.presenceHandler(event, cb)
1341 return nil
1342 }
1343
1344 func (c *Client) handlePresenceStats(params protocol.Raw, rw *replyWriter) error {
1345 if c.eventHub.presenceStatsHandler == nil {
1346 return ErrorNotAvailable
1347 }
1348
1349 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePresenceStats(params)
1350 if err != nil {
1351 return c.logDisconnectBadRequestWithError(err, "error decoding presence stats")
1352 }
1353
1354 channel := cmd.Channel
1355 if channel == "" {
1356 return c.logDisconnectBadRequest("channel required for presence stats")
1357 }
1358
1359 event := PresenceStatsEvent{
1360 Channel: channel,
1361 }
1362
1363 cb := func(reply PresenceStatsReply, err error) {
1364 defer rw.done()
1365 if err != nil {
1366 c.writeDisconnectOrErrorFlush(rw, err)
1367 return
1368 }
1369
1370 var presenceStats PresenceStats
1371 if reply.Result == nil {
1372 result, err := c.node.PresenceStats(event.Channel)
1373 if err != nil {
1374 c.logWriteInternalErrorFlush(rw, err, "error getting presence stats")
1375 return
1376 }
1377 presenceStats = result.PresenceStats
1378 } else {
1379 presenceStats = reply.Result.PresenceStats
1380 }
1381
1382 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodePresenceStatsResult(&protocol.PresenceStatsResult{
1383 NumClients: uint32(presenceStats.NumClients),
1384 NumUsers: uint32(presenceStats.NumUsers),
1385 })
1386 if err != nil {
1387 c.logWriteInternalErrorFlush(rw, err, "error encoding presence stats")
1388 return
1389 }
1390 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1391 }
1392
1393 c.eventHub.presenceStatsHandler(event, cb)
1394 return nil
1395 }
1396
1397 func (c *Client) handleHistory(params protocol.Raw, rw *replyWriter) error {
1398 if c.eventHub.historyHandler == nil {
1399 return ErrorNotAvailable
1400 }
1401
1402 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeHistory(params)
1403 if err != nil {
1404 return c.logDisconnectBadRequestWithError(err, "error decoding history")
1405 }
1406
1407 channel := cmd.Channel
1408 if channel == "" {
1409 return c.logDisconnectBadRequest("channel required for history")
1410 }
1411
1412 var filter HistoryFilter
1413 if cmd.UseSince {
1414 filter.Since = &StreamPosition{
1415 Offset: cmd.Offset,
1416 Epoch: cmd.Epoch,
1417 }
1418 }
1419 if cmd.UseLimit {
1420 filter.Limit = int(cmd.Limit)
1421 } else {
1422 filter.Limit = NoLimit
1423 }
1424 maxPublicationLimit := c.node.config.HistoryMaxPublicationLimit
1425 if maxPublicationLimit > 0 && (filter.Limit < 0 || filter.Limit > maxPublicationLimit) {
1426 filter.Limit = maxPublicationLimit
1427 }
1428
1429 event := HistoryEvent{
1430 Channel: channel,
1431 Filter: filter,
1432 }
1433
1434 cb := func(reply HistoryReply, err error) {
1435 defer rw.done()
1436 if err != nil {
1437 c.writeDisconnectOrErrorFlush(rw, err)
1438 return
1439 }
1440
1441 var pubs []*Publication
1442 var offset uint64
1443 var epoch string
1444 if reply.Result == nil {
1445 result, err := c.node.History(event.Channel, WithLimit(event.Filter.Limit), Since(event.Filter.Since))
1446 if err != nil {
1447 c.logWriteInternalErrorFlush(rw, err, "error getting history")
1448 return
1449 }
1450 pubs = result.Publications
1451 offset = result.Offset
1452 epoch = result.Epoch
1453 } else {
1454 pubs = reply.Result.Publications
1455 offset = reply.Result.Offset
1456 epoch = reply.Result.Epoch
1457 }
1458
1459 if event.Filter.Since != nil {
1460 sinceEpoch := event.Filter.Since.Epoch
1461 sinceOffset := event.Filter.Since.Offset
1462 epochOK := sinceEpoch == "" || sinceEpoch == epoch
1463 offsetOK := event.Filter.Limit <= 0 || sinceOffset == offset || (sinceOffset < offset && (len(pubs) > 0 && pubs[0].Offset == sinceOffset+1))
1464 if !epochOK || !offsetOK {
1465 c.writeErrorFlush(rw, ErrorUnrecoverablePosition)
1466 return
1467 }
1468 }
1469
1470 protoPubs := make([]*protocol.Publication, 0, len(pubs))
1471 for _, pub := range pubs {
1472 protoPub := pubToProto(pub)
1473 if hasFlag(CompatibilityFlags, UseSeqGen) {
1474 protoPub.Seq, protoPub.Gen = recovery.UnpackUint64(protoPub.Offset)
1475 }
1476 protoPubs = append(protoPubs, protoPub)
1477 }
1478
1479 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeHistoryResult(&protocol.HistoryResult{
1480 Publications: protoPubs,
1481 Offset: offset,
1482 Epoch: epoch,
1483 })
1484 if err != nil {
1485 c.logWriteInternalErrorFlush(rw, err, "error encoding history")
1486 return
1487 }
1488 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1489 }
1490
1491 c.eventHub.historyHandler(event, cb)
1492 return nil
1493 }
1494
1495 func (c *Client) handlePing(params protocol.Raw, rw *replyWriter) error {
1496 _, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodePing(params)
1497 if err != nil {
1498 return c.logDisconnectBadRequestWithError(err, "error decoding ping")
1499 }
1500 _ = writeReplyFlush(rw, &protocol.Reply{})
1501 defer rw.done()
1502 return nil
1503 }
1504
1505 func (c *Client) writeErrorFlush(rw *replyWriter, error *Error) {
1506 _ = rw.write(&protocol.Reply{Error: error.toProto()})
1507 _ = rw.flush()
1508 }
1509
1510 func (c *Client) writeDisconnectOrErrorFlush(rw *replyWriter, replyError error) {
1511 switch t := replyError.(type) {
1512 case *Disconnect:
1513 go func() { _ = c.close(t) }()
1514 return
1515 default:
1516 c.writeErrorFlush(rw, toClientErr(replyError))
1517 }
1518 }
1519
1520 func writeReplyFlush(rw *replyWriter, reply *protocol.Reply) error {
1521 err := rw.write(reply)
1522 if err != nil {
1523 return err
1524 }
1525 err = rw.flush()
1526 if err != nil {
1527 return err
1528 }
1529 return nil
1530 }
1531
1532 func (c *Client) handleRPC(params protocol.Raw, rw *replyWriter) error {
1533 if c.eventHub.rpcHandler == nil {
1534 return ErrorNotAvailable
1535 }
1536 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeRPC(params)
1537 if err != nil {
1538 return c.logDisconnectBadRequestWithError(err, "error decoding rpc")
1539 }
1540
1541 event := RPCEvent{
1542 Method: cmd.Method,
1543 Data: cmd.Data,
1544 }
1545
1546 cb := func(reply RPCReply, err error) {
1547 defer rw.done()
1548 if err != nil {
1549 c.writeDisconnectOrErrorFlush(rw, err)
1550 return
1551 }
1552 result := &protocol.RPCResult{
1553 Data: reply.Data,
1554 }
1555 var replyRes []byte
1556 replyRes, err = protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeRPCResult(result)
1557 if err != nil {
1558 c.logWriteInternalErrorFlush(rw, err, "error encoding rpc")
1559 return
1560 }
1561 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1562 }
1563
1564 c.eventHub.rpcHandler(event, cb)
1565 return nil
1566 }
1567
1568 func (c *Client) handleSend(params protocol.Raw, rw *replyWriter) error {
1569 if c.eventHub.messageHandler == nil {
1570 // send handler is a bit special since it is only one way
1571 // request: client does not expect any reply.
1572 rw.done()
1573 return nil
1574 }
1575 cmd, err := protocol.GetParamsDecoder(c.transport.Protocol().toProto()).DecodeSend(params)
1576 if err != nil {
1577 return c.logDisconnectBadRequestWithError(err, "error decoding message")
1578 }
1579 defer rw.done()
1580 c.eventHub.messageHandler(MessageEvent{
1581 Data: cmd.Data,
1582 })
1583 return nil
1584 }
1585
1586 func (c *Client) unlockServerSideSubscriptions(subCtxMap map[string]subscribeContext) {
1587 for channel := range subCtxMap {
1588 c.pubSubSync.StopBuffering(channel)
1589 }
1590 }
1591
1592 // connectCmd handles connect command from client - client must send connect
1593 // command immediately after establishing connection with server.
1594 func (c *Client) connectCmd(cmd *protocol.ConnectRequest, rw *replyWriter) error {
1595 c.mu.RLock()
1596 authenticated := c.authenticated
1597 closed := c.status == statusClosed
1598 c.mu.RUnlock()
1599
1600 if closed {
1601 return DisconnectNormal
1602 }
1603
1604 if authenticated {
1605 return c.logDisconnectBadRequest("client already authenticated")
1606 }
1607
1608 config := c.node.config
1609 version := config.Version
1610 userConnectionLimit := config.UserConnectionLimit
1611
1612 var (
1613 credentials *Credentials
1614 authData protocol.Raw
1615 subscriptions map[string]SubscribeOptions
1616 clientSideRefresh bool
1617 )
1618
1619 if c.node.clientEvents.connectingHandler != nil {
1620 reply, err := c.node.clientEvents.connectingHandler(c.ctx, ConnectEvent{
1621 ClientID: c.ID(),
1622 Data: cmd.Data,
1623 Token: cmd.Token,
1624 Name: cmd.Name,
1625 Version: cmd.Version,
1626 Transport: c.transport,
1627 })
1628 if err != nil {
1629 return err
1630 }
1631 if reply.Credentials != nil {
1632 credentials = reply.Credentials
1633 }
1634 if reply.Context != nil {
1635 c.mu.Lock()
1636 c.ctx = reply.Context
1637 c.mu.Unlock()
1638 }
1639 if reply.Data != nil {
1640 authData = reply.Data
1641 }
1642 clientSideRefresh = reply.ClientSideRefresh
1643 if len(reply.Subscriptions) > 0 {
1644 subscriptions = make(map[string]SubscribeOptions, len(reply.Subscriptions))
1645 for ch, opts := range reply.Subscriptions {
1646 subscriptions[ch] = opts
1647 }
1648 }
1649 }
1650
1651 if credentials == nil {
1652 // Try to find Credentials in context.
1653 if cred, ok := GetCredentials(c.ctx); ok {
1654 credentials = cred
1655 }
1656 }
1657
1658 var (
1659 expires bool
1660 ttl uint32
1661 )
1662
1663 c.mu.Lock()
1664 c.clientSideRefresh = clientSideRefresh
1665 c.mu.Unlock()
1666
1667 if credentials == nil {
1668 return c.logDisconnectBadRequest("client credentials not found")
1669 }
1670
1671 c.mu.Lock()
1672 c.user = credentials.UserID
1673 c.info = credentials.Info
1674 c.exp = credentials.ExpireAt
1675
1676 user := c.user
1677 exp := c.exp
1678 closed = c.status == statusClosed
1679 c.mu.Unlock()
1680
1681 if closed {
1682 return DisconnectNormal
1683 }
1684
1685 c.node.logger.log(newLogEntry(LogLevelDebug, "client authenticated", map[string]interface{}{"client": c.uid, "user": c.user}))
1686
1687 if userConnectionLimit > 0 && user != "" && len(c.node.hub.userConnections(user)) >= userConnectionLimit {
1688 c.node.logger.log(newLogEntry(LogLevelInfo, "limit of connections for user reached", map[string]interface{}{"user": user, "client": c.uid, "limit": userConnectionLimit}))
1689 return DisconnectConnectionLimit
1690 }
1691
1692 c.mu.RLock()
1693 if exp > 0 {
1694 expires = true
1695 now := time.Now().Unix()
1696 if exp < now {
1697 c.mu.RUnlock()
1698 c.node.logger.log(newLogEntry(LogLevelInfo, "connection expiration must be greater than now", map[string]interface{}{"client": c.uid, "user": c.UserID()}))
1699 return ErrorExpired
1700 }
1701 ttl = uint32(exp - now)
1702 }
1703 c.mu.RUnlock()
1704
1705 res := &protocol.ConnectResult{
1706 Version: version,
1707 Expires: expires,
1708 TTL: ttl,
1709 }
1710
1711 // Client successfully connected.
1712 c.mu.Lock()
1713 c.authenticated = true
1714 c.mu.Unlock()
1715
1716 err := c.node.addClient(c)
1717 if err != nil {
1718 c.node.logger.log(newLogEntry(LogLevelError, "error adding client", map[string]interface{}{"client": c.uid, "error": err.Error()}))
1719 return DisconnectServerError
1720 }
1721
1722 if !clientSideRefresh {
1723 // Server will do refresh itself.
1724 res.Expires = false
1725 res.TTL = 0
1726 }
1727
1728 res.Client = c.uid
1729 if authData != nil {
1730 res.Data = authData
1731 }
1732
1733 var subCtxMap map[string]subscribeContext
1734 if len(subscriptions) > 0 {
1735 var subMu sync.Mutex
1736 subCtxMap = make(map[string]subscribeContext, len(subscriptions))
1737 subs := make(map[string]*protocol.SubscribeResult, len(subscriptions))
1738 var subDisconnect *Disconnect
1739 var subError *Error
1740 var wg sync.WaitGroup
1741
1742 wg.Add(len(subscriptions))
1743 for ch, opts := range subscriptions {
1744 go func(ch string, opts SubscribeOptions) {
1745 defer wg.Done()
1746 subCmd := &protocol.SubscribeRequest{
1747 Channel: ch,
1748 }
1749 if subReq, ok := cmd.Subs[ch]; ok {
1750 subCmd.Recover = subReq.Recover
1751 subCmd.Offset = subReq.Offset
1752 subCmd.Epoch = subReq.Epoch
1753 }
1754
1755 var subCtx subscribeContext
1756 validateErr, validateDisconnect := c.validateSubscribeRequest(subCmd)
1757 if subError != nil || subDisconnect != nil {
1758 subCtx = subscribeContext{
1759 err: validateErr,
1760 disconnect: validateDisconnect,
1761 }
1762 } else {
1763 subCtx = c.subscribeCmd(subCmd, SubscribeReply{
1764 Options: opts,
1765 }, rw, true)
1766 }
1767 subMu.Lock()
1768 subs[ch] = subCtx.result
1769 subCtxMap[ch] = subCtx
1770 if subCtx.disconnect != nil {
1771 subDisconnect = subCtx.disconnect
1772 }
1773 if subCtx.err != nil {
1774 subError = subCtx.err
1775 }
1776 subMu.Unlock()
1777 }(ch, opts)
1778 }
1779 wg.Wait()
1780
1781 if subDisconnect != nil || subError != nil {
1782 c.unlockServerSideSubscriptions(subCtxMap)
1783 if subDisconnect != nil {
1784 return subDisconnect
1785 }
1786 return subError
1787 }
1788 res.Subs = subs
1789 }
1790
1791 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeConnectResult(res)
1792 if err != nil {
1793 c.unlockServerSideSubscriptions(subCtxMap)
1794 c.node.logger.log(newLogEntry(LogLevelError, "error encoding connect", map[string]interface{}{"error": err.Error()}))
1795 return DisconnectServerError
1796 }
1797 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
1798 defer rw.done()
1799
1800 c.mu.Lock()
1801 for channel, subCtx := range subCtxMap {
1802 c.channels[channel] = subCtx.channelContext
1803 }
1804 c.mu.Unlock()
1805
1806 c.unlockServerSideSubscriptions(subCtxMap)
1807
1808 if len(subCtxMap) > 0 {
1809 for channel, subCtx := range subCtxMap {
1810 go func(channel string, subCtx subscribeContext) {
1811 if channelHasFlag(subCtx.channelContext.flags, flagJoinLeave) && subCtx.clientInfo != nil {
1812 _ = c.node.publishJoin(channel, subCtx.clientInfo)
1813 }
1814 }(channel, subCtx)
1815 }
1816 }
1817
1818 return nil
1819 }
1820
1821 // Subscribe client to channel.
1822 func (c *Client) Subscribe(channel string) error {
1823 subCmd := &protocol.SubscribeRequest{
1824 Channel: channel,
1825 }
1826 validateErr, validateDisconnect := c.validateSubscribeRequest(subCmd)
1827 if validateErr != nil {
1828 return validateErr
1829 }
1830 if validateDisconnect != nil {
1831 return validateDisconnect
1832 }
1833 subCtx := c.subscribeCmd(subCmd, SubscribeReply{}, nil, true)
1834 if subCtx.err != nil {
1835 return subCtx.err
1836 }
1837 defer c.pubSubSync.StopBuffering(channel)
1838 c.mu.Lock()
1839 c.channels[channel] = subCtx.channelContext
1840 c.mu.Unlock()
1841 pushEncoder := protocol.GetPushEncoder(c.transport.Protocol().toProto())
1842 sub := &protocol.Sub{
1843 Offset: subCtx.result.GetOffset(),
1844 Epoch: subCtx.result.GetEpoch(),
1845 Recoverable: subCtx.result.GetRecoverable(),
1846 Positioned: subCtx.result.GetPositioned(),
1847 }
1848 if hasFlag(CompatibilityFlags, UseSeqGen) {
1849 sub.Seq, sub.Gen = recovery.UnpackUint64(subCtx.result.GetOffset())
1850 }
1851 data, err := pushEncoder.EncodeSub(sub)
1852 if err != nil {
1853 return err
1854 }
1855 result, err := pushEncoder.Encode(clientproto.NewSubPush(channel, data))
1856 if err != nil {
1857 return err
1858 }
1859 reply := prepared.NewReply(&protocol.Reply{
1860 Result: result,
1861 }, c.transport.Protocol().toProto())
1862 return c.transportEnqueue(reply)
1863 }
1864
1865 func (c *Client) validateSubscribeRequest(cmd *protocol.SubscribeRequest) (*Error, *Disconnect) {
1866 channel := cmd.Channel
1867 if channel == "" {
1868 c.node.logger.log(newLogEntry(LogLevelInfo, "channel required for subscribe", map[string]interface{}{"user": c.user, "client": c.uid}))
1869 return nil, DisconnectBadRequest
1870 }
1871
1872 config := c.node.config
1873 channelMaxLength := config.ChannelMaxLength
1874 channelLimit := config.ClientChannelLimit
1875
1876 if channelMaxLength > 0 && len(channel) > channelMaxLength {
1877 c.node.logger.log(newLogEntry(LogLevelInfo, "channel too long", map[string]interface{}{"max": channelMaxLength, "channel": channel, "user": c.user, "client": c.uid}))
1878 return ErrorLimitExceeded, nil
1879 }
1880
1881 c.mu.RLock()
1882 numChannels := len(c.channels)
1883 c.mu.RUnlock()
1884
1885 if channelLimit > 0 && numChannels >= channelLimit {
1886 c.node.logger.log(newLogEntry(LogLevelInfo, "maximum limit of channels per client reached", map[string]interface{}{"limit": channelLimit, "user": c.user, "client": c.uid}))
1887 return ErrorLimitExceeded, nil
1888 }
1889
1890 c.mu.RLock()
1891 _, ok := c.channels[channel]
1892 c.mu.RUnlock()
1893 if ok {
1894 c.node.logger.log(newLogEntry(LogLevelInfo, "client already subscribed on channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid}))
1895 return ErrorAlreadySubscribed, nil
1896 }
1897
1898 return nil, nil
1899 }
1900
1901 func errorDisconnectContext(replyError *Error, disconnect *Disconnect) subscribeContext {
1902 ctx := subscribeContext{}
1903 if disconnect != nil {
1904 ctx.disconnect = disconnect
1905 return ctx
1906 }
1907 ctx.err = replyError
1908 return ctx
1909 }
1910
1911 type subscribeContext struct {
1912 result *protocol.SubscribeResult
1913 clientInfo *ClientInfo
1914 err *Error
1915 disconnect *Disconnect
1916 channelContext channelContext
1917 }
1918
1919 func isRecovered(historyResult HistoryResult, cmdOffset uint64, cmdEpoch string) ([]*protocol.Publication, bool) {
1920 latestOffset := historyResult.Offset
1921 latestEpoch := historyResult.Epoch
1922
1923 recoveredPubs := make([]*protocol.Publication, 0, len(historyResult.Publications))
1924 for _, pub := range historyResult.Publications {
1925 protoPub := pubToProto(pub)
1926 recoveredPubs = append(recoveredPubs, protoPub)
1927 }
1928
1929 nextOffset := cmdOffset + 1
1930 var recovered bool
1931 if len(recoveredPubs) == 0 {
1932 recovered = latestOffset == cmdOffset && latestEpoch == cmdEpoch
1933 } else {
1934 recovered = recoveredPubs[0].Offset == nextOffset &&
1935 recoveredPubs[len(recoveredPubs)-1].Offset == latestOffset &&
1936 latestEpoch == cmdEpoch
1937 }
1938
1939 return recoveredPubs, recovered
1940 }
1941
1942 // subscribeCmd handles subscribe command - clients send this when subscribe
1943 // on channel, if channel if private then we must validate provided sign here before
1944 // actually subscribe client on channel. Optionally we can send missed messages to
1945 // client if it provided last message id seen in channel.
1946 func (c *Client) subscribeCmd(cmd *protocol.SubscribeRequest, reply SubscribeReply, rw *replyWriter, serverSide bool) subscribeContext {
1947
1948 ctx := subscribeContext{}
1949 res := &protocol.SubscribeResult{}
1950
1951 if reply.Options.ExpireAt > 0 {
1952 ttl := reply.Options.ExpireAt - time.Now().Unix()
1953 if ttl <= 0 {
1954 c.node.logger.log(newLogEntry(LogLevelInfo, "subscription expiration must be greater than now", map[string]interface{}{"client": c.uid, "user": c.UserID()}))
1955 return errorDisconnectContext(ErrorExpired, nil)
1956 }
1957 if reply.ClientSideRefresh {
1958 res.Expires = true
1959 res.TTL = uint32(ttl)
1960 }
1961 }
1962
1963 channel := cmd.Channel
1964
1965 info := &ClientInfo{
1966 ClientID: c.uid,
1967 UserID: c.user,
1968 ConnInfo: c.info,
1969 ChanInfo: reply.Options.ChannelInfo,
1970 }
1971
1972 if reply.Options.Recover {
1973 // Start syncing recovery and PUB/SUB.
1974 // The important thing is to call StopBuffering for this channel
1975 // after response with Publications written to connection.
1976 c.pubSubSync.StartBuffering(channel)
1977 }
1978
1979 err := c.node.addSubscription(channel, c)
1980 if err != nil {
1981 c.node.logger.log(newLogEntry(LogLevelError, "error adding subscription", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
1982 c.pubSubSync.StopBuffering(channel)
1983 if clientErr, ok := err.(*Error); ok && clientErr != ErrorInternal {
1984 return errorDisconnectContext(clientErr, nil)
1985 }
1986 ctx.disconnect = DisconnectServerError
1987 return ctx
1988 }
1989
1990 if reply.Options.Presence {
1991 err = c.node.addPresence(channel, c.uid, info)
1992 if err != nil {
1993 c.node.logger.log(newLogEntry(LogLevelError, "error adding presence", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
1994 c.pubSubSync.StopBuffering(channel)
1995 ctx.disconnect = DisconnectServerError
1996 return ctx
1997 }
1998 }
1999
2000 var (
2001 latestOffset uint64
2002 latestEpoch string
2003 recoveredPubs []*protocol.Publication
2004 )
2005
2006 useSeqGen := hasFlag(CompatibilityFlags, UseSeqGen)
2007
2008 if reply.Options.Recover {
2009 res.Recoverable = true
2010 if cmd.Recover {
2011 cmdOffset := cmd.Offset
2012 if cmd.Seq > 0 || cmd.Gen > 0 {
2013 // Fallback to deprecated fields.
2014 cmdOffset = recovery.PackUint64(cmd.Seq, cmd.Gen)
2015 }
2016
2017 // Client provided subscribe request with recover flag on. Try to recover missed
2018 // publications automatically from history (we suppose here that history configured wisely).
2019 historyResult, err := c.node.recoverHistory(channel, StreamPosition{cmdOffset, cmd.Epoch})
2020 if err != nil {
2021 c.node.logger.log(newLogEntry(LogLevelError, "error on recover", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
2022 c.pubSubSync.StopBuffering(channel)
2023 if clientErr, ok := err.(*Error); ok && clientErr != ErrorInternal {
2024 return errorDisconnectContext(clientErr, nil)
2025 }
2026 ctx.disconnect = DisconnectServerError
2027 return ctx
2028 }
2029 latestOffset = historyResult.Offset
2030 latestEpoch = historyResult.Epoch
2031 var recovered bool
2032 recoveredPubs, recovered = isRecovered(historyResult, cmdOffset, cmd.Epoch)
2033 res.Recovered = recovered
2034 incRecover(res.Recovered)
2035 } else {
2036 streamTop, err := c.node.streamTop(channel)
2037 if err != nil {
2038 c.node.logger.log(newLogEntry(LogLevelError, "error getting recovery state for channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
2039 c.pubSubSync.StopBuffering(channel)
2040 if clientErr, ok := err.(*Error); ok && clientErr != ErrorInternal {
2041 return errorDisconnectContext(clientErr, nil)
2042 }
2043 ctx.disconnect = DisconnectServerError
2044 return ctx
2045 }
2046 latestOffset = streamTop.Offset
2047 latestEpoch = streamTop.Epoch
2048 }
2049
2050 res.Epoch = latestEpoch
2051
2052 if useSeqGen {
2053 res.Seq, res.Gen = recovery.UnpackUint64(latestOffset)
2054 } else {
2055 res.Offset = latestOffset
2056 }
2057
2058 c.pubSubSync.LockBuffer(channel)
2059 bufferedPubs := c.pubSubSync.ReadBuffered(channel)
2060 var okMerge bool
2061 recoveredPubs, okMerge = recovery.MergePublications(recoveredPubs, bufferedPubs, useSeqGen)
2062 if !okMerge {
2063 c.pubSubSync.StopBuffering(channel)
2064 ctx.disconnect = DisconnectServerError
2065 return ctx
2066 }
2067 } else if reply.Options.Position {
2068 streamTop, err := c.node.streamTop(channel)
2069 if err != nil {
2070 c.node.logger.log(newLogEntry(LogLevelError, "error getting stream top for channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
2071 if clientErr, ok := err.(*Error); ok && clientErr != ErrorInternal {
2072 return errorDisconnectContext(clientErr, nil)
2073 }
2074 ctx.disconnect = DisconnectServerError
2075 return ctx
2076 }
2077
2078 latestOffset = streamTop.Offset
2079 latestEpoch = streamTop.Epoch
2080
2081 res.Positioned = true
2082 res.Offset = streamTop.Offset
2083 res.Epoch = streamTop.Epoch
2084 }
2085
2086 if len(recoveredPubs) > 0 {
2087 if useSeqGen {
2088 // recoveredPubs are in descending order.
2089 latestOffset = recoveredPubs[0].Offset
2090 } else {
2091 latestOffset = recoveredPubs[len(recoveredPubs)-1].Offset
2092 }
2093 }
2094
2095 res.Publications = recoveredPubs
2096 if useSeqGen && len(res.Publications) > 0 {
2097 for i := range res.Publications {
2098 res.Publications[i].Seq, res.Publications[i].Gen = recovery.UnpackUint64(res.Publications[i].Offset)
2099 res.Publications[i].Offset = 0
2100 }
2101 }
2102
2103 if !serverSide {
2104 // Write subscription reply only if initiated by client.
2105 replyRes, err := protocol.GetResultEncoder(c.transport.Protocol().toProto()).EncodeSubscribeResult(res)
2106 if err != nil {
2107 c.node.logger.log(newLogEntry(LogLevelError, "error encoding subscribe", map[string]interface{}{"error": err.Error()}))
2108 if !serverSide {
2109 // Will be called later in case of server side sub.
2110 c.pubSubSync.StopBuffering(channel)
2111 }
2112 ctx.disconnect = DisconnectServerError
2113 return ctx
2114 }
2115 // Need to flush data from writer so subscription response is
2116 // sent before any subscription publication.
2117 _ = writeReplyFlush(rw, &protocol.Reply{Result: replyRes})
2118 }
2119
2120 var channelFlags uint8
2121 if serverSide {
2122 channelFlags |= flagServerSide
2123 }
2124 if reply.ClientSideRefresh {
2125 channelFlags |= flagClientSideRefresh
2126 }
2127 if reply.Options.Recover {
2128 channelFlags |= flagRecover
2129 }
2130 if reply.Options.Position {
2131 channelFlags |= flagPosition
2132 }
2133 if reply.Options.Presence {
2134 channelFlags |= flagPresence
2135 }
2136 if reply.Options.JoinLeave {
2137 channelFlags |= flagJoinLeave
2138 }
2139
2140 channelContext := channelContext{
2141 Info: reply.Options.ChannelInfo,
2142 flags: channelFlags,
2143 expireAt: reply.Options.ExpireAt,
2144 streamPosition: StreamPosition{
2145 Offset: latestOffset,
2146 Epoch: latestEpoch,
2147 },
2148 }
2149 if reply.Options.Recover || reply.Options.Position {
2150 channelContext.positionCheckTime = time.Now().Unix()
2151 }
2152
2153 if !serverSide {
2154 // In case of server-side sub this will be done later by the caller.
2155 c.mu.Lock()
2156 c.channels[channel] = channelContext
2157 c.mu.Unlock()
2158 // Stop syncing recovery and PUB/SUB.
2159 // In case of server side subscription we will do this later.
2160 c.pubSubSync.StopBuffering(channel)
2161 }
2162
2163 if c.node.logger.enabled(LogLevelDebug) {
2164 c.node.logger.log(newLogEntry(LogLevelDebug, "client subscribed to channel", map[string]interface{}{"client": c.uid, "user": c.user, "channel": cmd.Channel}))
2165 }
2166
2167 ctx.result = res
2168 ctx.clientInfo = info
2169 ctx.channelContext = channelContext
2170 return ctx
2171 }
2172
2173 func (c *Client) writePublicationUpdatePosition(ch string, pub *protocol.Publication, reply *prepared.Reply, sp StreamPosition) error {
2174 c.mu.Lock()
2175 channelContext, ok := c.channels[ch]
2176 if !ok {
2177 c.mu.Unlock()
2178 return nil
2179 }
2180 currentPositionOffset := channelContext.streamPosition.Offset
2181 nextExpectedOffset := currentPositionOffset + 1
2182 pubOffset := pub.Offset
2183 pubEpoch := sp.Epoch
2184 if pubEpoch != channelContext.streamPosition.Epoch {
2185 if c.node.logger.enabled(LogLevelDebug) {
2186 c.node.logger.log(newLogEntry(LogLevelDebug, "client insufficient state", map[string]interface{}{"channel": ch, "user": c.user, "client": c.uid, "epoch": pubEpoch, "expectedEpoch": channelContext.streamPosition.Epoch}))
2187 }
2188 // Oops: sth lost, let client reconnect to recover its state.
2189 go func() { _ = c.close(DisconnectInsufficientState) }()
2190 c.mu.Unlock()
2191 return nil
2192 }
2193 if pubOffset != nextExpectedOffset {
2194 if c.node.logger.enabled(LogLevelDebug) {
2195 c.node.logger.log(newLogEntry(LogLevelDebug, "client insufficient state", map[string]interface{}{"channel": ch, "user": c.user, "client": c.uid, "offset": pubOffset, "expectedOffset": nextExpectedOffset}))
2196 }
2197 // Oops: sth lost, let client reconnect to recover its state.
2198 go func() { _ = c.close(DisconnectInsufficientState) }()
2199 c.mu.Unlock()
2200 return nil
2201 }
2202 channelContext.positionCheckTime = time.Now().Unix()
2203 channelContext.positionCheckFailures = 0
2204 channelContext.streamPosition.Offset = pub.Offset
2205 c.channels[ch] = channelContext
2206 c.mu.Unlock()
2207 return c.transportEnqueue(reply)
2208 }
2209
2210 func (c *Client) writePublication(ch string, pub *protocol.Publication, reply *prepared.Reply, sp StreamPosition) error {
2211 if pub.Offset == 0 {
2212 return c.transportEnqueue(reply)
2213 }
2214
2215 // This locking should be fast.
2216 c.mu.Lock()
2217 channelContext, ok := c.channels[ch]
2218 if !ok {
2219 c.mu.Unlock()
2220 return nil
2221 }
2222 channelFlags := channelContext.flags
2223 c.mu.Unlock()
2224
2225 if !channelHasFlag(channelFlags, flagRecover|flagPosition) {
2226 return c.transportEnqueue(reply)
2227 }
2228
2229 c.pubSubSync.SyncPublication(ch, pub, func() {
2230 _ = c.writePublicationUpdatePosition(ch, pub, reply, sp)
2231 })
2232 return nil
2233 }
2234
2235 func (c *Client) writeJoin(_ string, reply *prepared.Reply) error {
2236 return c.transportEnqueue(reply)
2237 }
2238
2239 func (c *Client) writeLeave(_ string, reply *prepared.Reply) error {
2240 return c.transportEnqueue(reply)
2241 }
2242
2243 // Lock must be held outside.
2244 func (c *Client) unsubscribe(channel string) error {
2245 c.mu.RLock()
2246 info := c.clientInfo(channel)
2247 chCtx, ok := c.channels[channel]
2248 serverSide := channelHasFlag(chCtx.flags, flagServerSide)
2249 c.mu.RUnlock()
2250
2251 if ok {
2252 c.mu.Lock()
2253 delete(c.channels, channel)
2254 c.mu.Unlock()
2255
2256 if channelHasFlag(chCtx.flags, flagPresence) {
2257 err := c.node.removePresence(channel, c.uid)
2258 if err != nil {
2259 c.node.logger.log(newLogEntry(LogLevelError, "error removing channel presence", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
2260 }
2261 }
2262
2263 if channelHasFlag(chCtx.flags, flagJoinLeave) {
2264 _ = c.node.publishLeave(channel, info)
2265 }
2266
2267 if err := c.node.removeSubscription(channel, c); err != nil {
2268 c.node.logger.log(newLogEntry(LogLevelError, "error removing subscription", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid, "error": err.Error()}))
2269 return err
2270 }
2271
2272 if !serverSide && c.eventHub.unsubscribeHandler != nil {
2273 c.eventHub.unsubscribeHandler(UnsubscribeEvent{
2274 Channel: channel,
2275 })
2276 }
2277 }
2278 if c.node.logger.enabled(LogLevelDebug) {
2279 c.node.logger.log(newLogEntry(LogLevelDebug, "client unsubscribed from channel", map[string]interface{}{"channel": channel, "user": c.user, "client": c.uid}))
2280 }
2281 return nil
2282 }
2283
2284 func (c *Client) logDisconnectBadRequest(message string) *Disconnect {
2285 c.node.logger.log(newLogEntry(LogLevelInfo, message, map[string]interface{}{"user": c.user, "client": c.uid}))
2286 return DisconnectBadRequest
2287 }
2288
2289 func (c *Client) logDisconnectBadRequestWithError(err error, message string) *Disconnect {
2290 c.node.logger.log(newLogEntry(LogLevelInfo, message, map[string]interface{}{"error": err.Error(), "user": c.user, "client": c.uid}))
2291 return DisconnectBadRequest
2292 }
2293
2294 func (c *Client) logWriteInternalErrorFlush(rw *replyWriter, err error, message string) {
2295 c.node.logger.log(newLogEntry(LogLevelError, message, map[string]interface{}{"error": err.Error()}))
2296 c.writeErrorFlush(rw, ErrorInternal)
2297 }
2298
2299 func toClientErr(err error) *Error {
2300 if clientErr, ok := err.(*Error); ok {
2301 return clientErr
2302 }
2303 return ErrorInternal
2304 }
2305
2306 func errLogLevel(err error) LogLevel {
2307 logLevel := LogLevelInfo
2308 if err != ErrorNotAvailable {
2309 logLevel = LogLevelError
2310 }
2311 return logLevel
2312 }