Debian Codegraph @

websocket_managed_conn.go

raw symbols SCIP
1 package slack
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 stdurl "net/url"
9 "reflect"
10 "time"
11
12 "github.com/gorilla/websocket"
13
14 "github.com/slack-go/slack/internal/backoff"
15 "github.com/slack-go/slack/internal/errorsx"
16 "github.com/slack-go/slack/internal/timex"
17 )
18
19 // UnmappedError represents error occurred when there is no mapping between given event name
20 // and corresponding Go struct.
21 type UnmappedError struct {
22 // EventType returns event type name.
23 EventType string
24 // RawEvent returns raw event body.
25 RawEvent json.RawMessage
26
27 ctxMsg string
28 }
29
30 // NewUnmappedError returns new UnmappedError instance.
31 func NewUnmappedError(ctxMsg, eventType string, raw json.RawMessage) *UnmappedError {
32 return &UnmappedError{
33 ctxMsg: ctxMsg,
34 EventType: eventType,
35 RawEvent: raw,
36 }
37 }
38
39 // Error returns human-readable error message.
40 func (u UnmappedError) Error() string {
41 return fmt.Sprintf("%s: Received unmapped event %q", u.ctxMsg, u.EventType)
42 }
43
44 // ManageConnection can be called on a Slack RTM instance returned by the
45 // NewRTM method. It will connect to the slack RTM API and handle all incoming
46 // and outgoing events. If a connection fails then it will attempt to reconnect
47 // and will notify any listeners through an error event on the IncomingEvents
48 // channel.
49 //
50 // If the connection ends and the disconnect was unintentional then this will
51 // attempt to reconnect.
52 //
53 // This should only be called once per slack API! Otherwise expect undefined
54 // behavior.
55 //
56 // The defined error events are located in websocket_internals.go.
57 func (rtm *RTM) ManageConnection() {
58 var (
59 err error
60 info *Info
61 conn *websocket.Conn
62 )
63
64 for connectionCount := 0; ; connectionCount++ {
65 // start trying to connect
66 // the returned err is already passed onto the IncomingEvents channel
67 if info, conn, err = rtm.connect(connectionCount, rtm.useRTMStart); err != nil {
68 // when the connection is unsuccessful its fatal, and we need to bail out.
69 rtm.Debugf("Failed to connect with RTM on try %d: %s", connectionCount, err)
70 rtm.disconnect()
71 return
72 }
73
74 // lock to prevent data races with Disconnect particularly around isConnected
75 // and conn.
76 rtm.mu.Lock()
77 rtm.conn = conn
78 rtm.info = info
79 rtm.mu.Unlock()
80
81 rtm.IncomingEvents <- RTMEvent{"connected", &ConnectedEvent{
82 ConnectionCount: connectionCount,
83 Info: info,
84 }}
85
86 rtm.Debugf("RTM connection succeeded on try %d", connectionCount)
87
88 rawEvents := make(chan json.RawMessage)
89 // we're now connected so we can set up listeners
90 go rtm.handleIncomingEvents(rawEvents)
91 // this should be a blocking call until the connection has ended
92 rtm.handleEvents(rawEvents)
93
94 select {
95 case <-rtm.disconnected:
96 // after handle events returns we need to check if we're disconnected
97 // when this happens we need to cleanup the newly created connection.
98 if err = conn.Close(); err != nil {
99 rtm.Debugln("failed to close conn on disconnected RTM", err)
100 }
101 return
102 default:
103 // otherwise continue and run the loop again to reconnect
104 }
105 }
106 }
107
108 // connect attempts to connect to the slack websocket API. It handles any
109 // errors that occur while connecting and will return once a connection
110 // has been successfully opened.
111 // If useRTMStart is false then it uses rtm.connect to create the connection,
112 // otherwise it uses rtm.start.
113 func (rtm *RTM) connect(connectionCount int, useRTMStart bool) (*Info, *websocket.Conn, error) {
114 const (
115 errInvalidAuth = "invalid_auth"
116 errInactiveAccount = "account_inactive"
117 errMissingAuthToken = "not_authed"
118 errTokenRevoked = "token_revoked"
119 )
120
121 // used to provide exponential backoff wait time with jitter before trying
122 // to connect to slack again
123 boff := &backoff.Backoff{
124 Max: 5 * time.Minute,
125 }
126
127 for {
128 var (
129 backoff time.Duration
130 )
131
132 // send connecting event
133 rtm.IncomingEvents <- RTMEvent{"connecting", &ConnectingEvent{
134 Attempt: boff.Attempts() + 1,
135 ConnectionCount: connectionCount,
136 }}
137
138 // attempt to start the connection
139 info, conn, err := rtm.startRTMAndDial(useRTMStart)
140 if err == nil {
141 return info, conn, nil
142 }
143
144 // check for fatal errors
145 switch err.Error() {
146 case errInvalidAuth, errInactiveAccount, errMissingAuthToken, errTokenRevoked:
147 rtm.Debugf("invalid auth when connecting with RTM: %s", err)
148 rtm.IncomingEvents <- RTMEvent{"invalid_auth", &InvalidAuthEvent{}}
149 return nil, nil, err
150 default:
151 }
152
153 switch actual := err.(type) {
154 case StatusCodeError:
155 if actual.Code == http.StatusNotFound {
156 rtm.Debugf("invalid auth when connecting with RTM: %s", err)
157 rtm.IncomingEvents <- RTMEvent{"invalid_auth", &InvalidAuthEvent{}}
158 return nil, nil, err
159 }
160 case *RateLimitedError:
161 backoff = actual.RetryAfter
162 default:
163 }
164
165 backoff = timex.Max(backoff, boff.Duration())
166 // any other errors are treated as recoverable and we try again after
167 // sending the event along the IncomingEvents channel
168 rtm.IncomingEvents <- RTMEvent{"connection_error", &ConnectionErrorEvent{
169 Attempt: boff.Attempts(),
170 Backoff: backoff,
171 ErrorObj: err,
172 }}
173
174 // get time we should wait before attempting to connect again
175 rtm.Debugf("reconnection %d failed: %s reconnecting in %v\n", boff.Attempts(), err, backoff)
176
177 // wait for one of the following to occur,
178 // backoff duration has elapsed, killChannel is signalled, or
179 // the rtm finishes disconnecting.
180 select {
181 case <-time.After(backoff): // retry after the backoff.
182 case intentional := <-rtm.killChannel:
183 if intentional {
184 rtm.killConnection(intentional, ErrRTMDisconnected)
185 return nil, nil, ErrRTMDisconnected
186 }
187 case <-rtm.disconnected:
188 return nil, nil, ErrRTMDisconnected
189 }
190 }
191 }
192
193 // startRTMAndDial attempts to connect to the slack websocket. If useRTMStart is true,
194 // then it returns the full information returned by the "rtm.start" method on the
195 // slack API. Else it uses the "rtm.connect" method to connect
196 func (rtm *RTM) startRTMAndDial(useRTMStart bool) (info *Info, _ *websocket.Conn, err error) {
197 var (
198 url string
199 )
200
201 if useRTMStart {
202 rtm.Debugf("Starting RTM")
203 info, url, err = rtm.StartRTM()
204 } else {
205 rtm.Debugf("Connecting to RTM")
206 info, url, err = rtm.ConnectRTM()
207 }
208 if err != nil {
209 rtm.Debugf("Failed to start or connect to RTM: %s", err)
210 return nil, nil, err
211 }
212
213 // install connection parameters
214 u, err := stdurl.Parse(url)
215 if err != nil {
216 return nil, nil, err
217 }
218 u.RawQuery = rtm.connParams.Encode()
219 url = u.String()
220
221 rtm.Debugf("Dialing to websocket on url %s", url)
222 // Only use HTTPS for connections to prevent MITM attacks on the connection.
223 upgradeHeader := http.Header{}
224 upgradeHeader.Add("Origin", "https://api.slack.com")
225 dialer := websocket.DefaultDialer
226 if rtm.dialer != nil {
227 dialer = rtm.dialer
228 }
229 conn, _, err := dialer.Dial(url, upgradeHeader)
230 if err != nil {
231 rtm.Debugf("Failed to dial to the websocket: %s", err)
232 return nil, nil, err
233 }
234 return info, conn, err
235 }
236
237 // killConnection stops the websocket connection and signals to all goroutines
238 // that they should cease listening to the connection for events.
239 //
240 // This should not be called directly! Instead a boolean value (true for
241 // intentional, false otherwise) should be sent to the killChannel on the RTM.
242 func (rtm *RTM) killConnection(intentional bool, cause error) (err error) {
243 rtm.Debugln("killing connection", cause)
244
245 if rtm.conn != nil {
246 err = rtm.conn.Close()
247 }
248
249 rtm.IncomingEvents <- RTMEvent{"disconnected", &DisconnectedEvent{Intentional: intentional, Cause: cause}}
250
251 if intentional {
252 rtm.disconnect()
253 }
254
255 return err
256 }
257
258 // handleEvents is a blocking function that handles all events. This sends
259 // pings when asked to (on rtm.forcePing) and upon every given elapsed
260 // interval. This also sends outgoing messages that are received from the RTM's
261 // outgoingMessages channel. This also handles incoming raw events from the RTM
262 // rawEvents channel.
263 func (rtm *RTM) handleEvents(events chan json.RawMessage) {
264 ticker := time.NewTicker(rtm.pingInterval)
265 defer ticker.Stop()
266 for {
267 select {
268 // catch "stop" signal on channel close
269 case intentional := <-rtm.killChannel:
270 _ = rtm.killConnection(intentional, errorsx.String("signaled"))
271 return
272 // detect when the connection is dead.
273 case <-rtm.pingDeadman.C:
274 _ = rtm.killConnection(false, ErrRTMDeadman)
275 return
276 // send pings on ticker interval
277 case <-ticker.C:
278 if err := rtm.ping(); err != nil {
279 _ = rtm.killConnection(false, err)
280 return
281 }
282 case <-rtm.forcePing:
283 if err := rtm.ping(); err != nil {
284 _ = rtm.killConnection(false, err)
285 return
286 }
287 // listen for messages that need to be sent
288 case msg := <-rtm.outgoingMessages:
289 rtm.sendOutgoingMessage(msg)
290 // listen for incoming messages that need to be parsed
291 case rawEvent := <-events:
292 switch rtm.handleRawEvent(rawEvent) {
293 case rtmEventTypeGoodbye:
294 // kill the connection, but DO NOT RETURN, a follow up kill signal will
295 // be sent that still needs to be processed. this duplication is because
296 // the event reader restarts once it emits the goodbye event.
297 // unlike the other cases in this function a final read will be triggered
298 // against the connection which will emit a kill signal. if we return early
299 // this kill signal will be processed by the next connection.
300 _ = rtm.killConnection(false, ErrRTMGoodbye)
301 default:
302 }
303 }
304 }
305 }
306
307 // handleIncomingEvents monitors the RTM's opened websocket for any incoming
308 // events. It pushes the raw events into the channel.
309 //
310 // This will stop executing once the RTM's when a fatal error is detected, or
311 // a disconnect occurs.
312 func (rtm *RTM) handleIncomingEvents(events chan json.RawMessage) {
313 for {
314 if err := rtm.receiveIncomingEvent(events); err != nil {
315 select {
316 case rtm.killChannel <- false:
317 case <-rtm.disconnected:
318 }
319 return
320 }
321 }
322 }
323
324 func (rtm *RTM) sendWithDeadline(msg interface{}) error {
325 // set a write deadline on the connection
326 if err := rtm.conn.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil {
327 return err
328 }
329 if err := rtm.conn.WriteJSON(msg); err != nil {
330 return err
331 }
332 // remove write deadline
333 return rtm.conn.SetWriteDeadline(time.Time{})
334 }
335
336 // sendOutgoingMessage sends the given OutgoingMessage to the slack websocket.
337 //
338 // It does not currently detect if a outgoing message fails due to a disconnect
339 // and instead lets a future failed 'PING' detect the failed connection.
340 func (rtm *RTM) sendOutgoingMessage(msg OutgoingMessage) {
341 rtm.Debugln("Sending message:", msg)
342 if len([]rune(msg.Text)) > MaxMessageTextLength {
343 rtm.IncomingEvents <- RTMEvent{"outgoing_error", &MessageTooLongEvent{
344 Message: msg,
345 MaxLength: MaxMessageTextLength,
346 }}
347 return
348 }
349
350 if err := rtm.sendWithDeadline(msg); err != nil {
351 rtm.IncomingEvents <- RTMEvent{"outgoing_error", &OutgoingErrorEvent{
352 Message: msg,
353 ErrorObj: err,
354 }}
355 }
356 }
357
358 // ping sends a 'PING' message to the RTM's websocket. If the 'PING' message
359 // fails to send then this returns an error signifying that the connection
360 // should be considered disconnected.
361 //
362 // This does not handle incoming 'PONG' responses but does store the time of
363 // each successful 'PING' send so latency can be detected upon a 'PONG'
364 // response.
365 func (rtm *RTM) ping() error {
366 id := rtm.idGen.Next()
367 rtm.Debugln("Sending PING ", id)
368 msg := &Ping{ID: id, Type: "ping", Timestamp: time.Now().Unix()}
369
370 if err := rtm.sendWithDeadline(msg); err != nil {
371 rtm.Debugf("RTM Error sending 'PING %d': %s", id, err.Error())
372 return err
373 }
374 return nil
375 }
376
377 // receiveIncomingEvent attempts to receive an event from the RTM's websocket.
378 // This will block until a frame is available from the websocket.
379 // If the read from the websocket results in a fatal error, this function will return non-nil.
380 func (rtm *RTM) receiveIncomingEvent(events chan json.RawMessage) error {
381 event := json.RawMessage{}
382 err := rtm.conn.ReadJSON(&event)
383
384 // check if the connection was closed.
385 if websocket.IsUnexpectedCloseError(err) {
386 return err
387 }
388
389 switch {
390 case err == io.ErrUnexpectedEOF:
391 // EOF's don't seem to signify a failed connection so instead we ignore
392 // them here and detect a failed connection upon attempting to send a
393 // 'PING' message
394
395 // trigger a 'PING' to detect potential websocket disconnect
396 select {
397 case rtm.forcePing <- true:
398 case <-rtm.disconnected:
399 }
400 case err != nil:
401 // All other errors from ReadJSON come from NextReader, and should
402 // kill the read loop and force a reconnect.
403 rtm.IncomingEvents <- RTMEvent{"incoming_error", &IncomingEventError{
404 ErrorObj: err,
405 }}
406
407 return err
408 case len(event) == 0:
409 rtm.Debugln("Received empty event")
410 default:
411 rtm.Debugln("Incoming Event:", string(event))
412 select {
413 case events <- event:
414 case <-rtm.disconnected:
415 rtm.Debugln("disonnected while attempting to send raw event")
416 }
417 }
418
419 return nil
420 }
421
422 // handleRawEvent takes a raw JSON message received from the slack websocket
423 // and handles the encoded event.
424 // returns the event type of the message.
425 func (rtm *RTM) handleRawEvent(rawEvent json.RawMessage) string {
426 event := &Event{}
427 err := json.Unmarshal(rawEvent, event)
428 if err != nil {
429 rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}}
430 return ""
431 }
432
433 switch event.Type {
434 case rtmEventTypeAck:
435 rtm.handleAck(rawEvent)
436 case rtmEventTypeHello:
437 rtm.IncomingEvents <- RTMEvent{"hello", &HelloEvent{}}
438 case rtmEventTypePong:
439 rtm.handlePong(rawEvent)
440 case rtmEventTypeGoodbye:
441 // just return the event type up for goodbye, will be handled by caller.
442 default:
443 rtm.handleEvent(event.Type, rawEvent)
444 }
445
446 return event.Type
447 }
448
449 // handleAck handles an incoming 'ACK' message.
450 func (rtm *RTM) handleAck(event json.RawMessage) {
451 ack := &AckMessage{}
452 if err := json.Unmarshal(event, ack); err != nil {
453 rtm.Debugln("RTM Error unmarshalling 'ack' event:", err)
454 rtm.Debugln(" -> Erroneous 'ack' event:", string(event))
455 return
456 }
457
458 if ack.Ok {
459 rtm.IncomingEvents <- RTMEvent{"ack", ack}
460 } else if ack.RTMResponse.Error != nil {
461 // As there is no documentation for RTM error-codes, this
462 // identification of a rate-limit warning is very brittle.
463 if ack.RTMResponse.Error.Code == -1 && ack.RTMResponse.Error.Msg == "slow down, too many messages..." {
464 rtm.IncomingEvents <- RTMEvent{"ack_error", &RateLimitEvent{}}
465 } else {
466 rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{ack.Error, ack.ReplyTo}}
467 }
468 } else {
469 rtm.IncomingEvents <- RTMEvent{"ack_error", &AckErrorEvent{ErrorObj: fmt.Errorf("ack decode failure")}}
470 }
471 }
472
473 // handlePong handles an incoming 'PONG' message which should be in response to
474 // a previously sent 'PING' message. This is then used to compute the
475 // connection's latency.
476 func (rtm *RTM) handlePong(event json.RawMessage) {
477 var (
478 p Pong
479 )
480
481 rtm.resetDeadman()
482
483 if err := json.Unmarshal(event, &p); err != nil {
484 rtm.Client.log.Println("RTM Error unmarshalling 'pong' event:", err)
485 return
486 }
487
488 latency := time.Since(time.Unix(p.Timestamp, 0))
489 rtm.IncomingEvents <- RTMEvent{"latency_report", &LatencyReport{Value: latency}}
490 }
491
492 // handleEvent is the "default" response to an event that does not have a
493 // special case. It matches the command's name to a mapping of defined events
494 // and then sends the corresponding event struct to the IncomingEvents channel.
495 // If the event type is not found or the event cannot be unmarshalled into the
496 // correct struct then this sends an UnmarshallingErrorEvent to the
497 // IncomingEvents channel.
498 func (rtm *RTM) handleEvent(typeStr string, event json.RawMessage) {
499 v, exists := EventMapping[typeStr]
500 if !exists {
501 rtm.Debugf("RTM Error - received unmapped event %q: %s\n", typeStr, string(event))
502 err := NewUnmappedError("RTM Error", typeStr, event)
503 rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}}
504 return
505 }
506 t := reflect.TypeOf(v)
507 recvEvent := reflect.New(t).Interface()
508 err := json.Unmarshal(event, recvEvent)
509 if err != nil {
510 rtm.Debugf("RTM Error, could not unmarshall event %q: %s\n", typeStr, string(event))
511 err := fmt.Errorf("RTM Error: Could not unmarshall event %q", typeStr)
512 rtm.IncomingEvents <- RTMEvent{"unmarshalling_error", &UnmarshallingErrorEvent{err}}
513 return
514 }
515 rtm.IncomingEvents <- RTMEvent{typeStr, recvEvent}
516 }
517
518 // EventMapping holds a mapping of event names to their corresponding struct
519 // implementations. The structs should be instances of the unmarshalling
520 // target for the matching event type.
521 var EventMapping = map[string]interface{}{
522 "message": MessageEvent{},
523 "presence_change": PresenceChangeEvent{},
524 "user_typing": UserTypingEvent{},
525
526 "channel_marked": ChannelMarkedEvent{},
527 "channel_created": ChannelCreatedEvent{},
528 "channel_joined": ChannelJoinedEvent{},
529 "channel_left": ChannelLeftEvent{},
530 "channel_deleted": ChannelDeletedEvent{},
531 "channel_rename": ChannelRenameEvent{},
532 "channel_archive": ChannelArchiveEvent{},
533 "channel_unarchive": ChannelUnarchiveEvent{},
534 "channel_history_changed": ChannelHistoryChangedEvent{},
535
536 "dnd_updated": DNDUpdatedEvent{},
537 "dnd_updated_user": DNDUpdatedEvent{},
538
539 "im_created": IMCreatedEvent{},
540 "im_open": IMOpenEvent{},
541 "im_close": IMCloseEvent{},
542 "im_marked": IMMarkedEvent{},
543 "im_history_changed": IMHistoryChangedEvent{},
544
545 "group_marked": GroupMarkedEvent{},
546 "group_open": GroupOpenEvent{},
547 "group_joined": GroupJoinedEvent{},
548 "group_left": GroupLeftEvent{},
549 "group_close": GroupCloseEvent{},
550 "group_rename": GroupRenameEvent{},
551 "group_archive": GroupArchiveEvent{},
552 "group_unarchive": GroupUnarchiveEvent{},
553 "group_history_changed": GroupHistoryChangedEvent{},
554
555 "file_created": FileCreatedEvent{},
556 "file_shared": FileSharedEvent{},
557 "file_unshared": FileUnsharedEvent{},
558 "file_public": FilePublicEvent{},
559 "file_private": FilePrivateEvent{},
560 "file_change": FileChangeEvent{},
561 "file_deleted": FileDeletedEvent{},
562 "file_comment_added": FileCommentAddedEvent{},
563 "file_comment_edited": FileCommentEditedEvent{},
564 "file_comment_deleted": FileCommentDeletedEvent{},
565
566 "pin_added": PinAddedEvent{},
567 "pin_removed": PinRemovedEvent{},
568
569 "star_added": StarAddedEvent{},
570 "star_removed": StarRemovedEvent{},
571
572 "reaction_added": ReactionAddedEvent{},
573 "reaction_removed": ReactionRemovedEvent{},
574
575 "pref_change": PrefChangeEvent{},
576
577 "team_join": TeamJoinEvent{},
578 "team_rename": TeamRenameEvent{},
579 "team_pref_change": TeamPrefChangeEvent{},
580 "team_domain_change": TeamDomainChangeEvent{},
581 "team_migration_started": TeamMigrationStartedEvent{},
582
583 "manual_presence_change": ManualPresenceChangeEvent{},
584
585 "user_change": UserChangeEvent{},
586
587 "emoji_changed": EmojiChangedEvent{},
588
589 "commands_changed": CommandsChangedEvent{},
590
591 "email_domain_changed": EmailDomainChangedEvent{},
592
593 "bot_added": BotAddedEvent{},
594 "bot_changed": BotChangedEvent{},
595
596 "accounts_changed": AccountsChangedEvent{},
597
598 "reconnect_url": ReconnectUrlEvent{},
599
600 "member_joined_channel": MemberJoinedChannelEvent{},
601 "member_left_channel": MemberLeftChannelEvent{},
602
603 "subteam_created": SubteamCreatedEvent{},
604 "subteam_members_changed": SubteamMembersChangedEvent{},
605 "subteam_self_added": SubteamSelfAddedEvent{},
606 "subteam_self_removed": SubteamSelfRemovedEvent{},
607 "subteam_updated": SubteamUpdatedEvent{},
608
609 "desktop_notification": DesktopNotificationEvent{},
610 "mobile_in_app_notification": MobileInAppNotificationEvent{},
611 }