Debian Codegraph @

socketmode/socket_mode_managed_conn.go

raw symbols SCIP
1 package socketmode
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "sync"
12 "time"
13
14 "github.com/gorilla/websocket"
15
16 "github.com/slack-go/slack"
17 "github.com/slack-go/slack/internal/backoff"
18 "github.com/slack-go/slack/internal/timex"
19 "github.com/slack-go/slack/slackevents"
20 )
21
22 // Run is a blocking function that connects the Slack Socket Mode API and handles all incoming
23 // requests and outgoing responses.
24 //
25 // The consumer of the Client and this function should read the Client.Events channel to receive
26 // `socketmode.Event`s that includes the client-specific events that may or may not wrap Socket Mode requests.
27 //
28 // Note that this function automatically reconnect on requested by Slack through a `disconnect` message.
29 // This function exists with an error only when a reconnection is failued due to some reason.
30 // If you want to retry even on reconnection failure, you'd need to write your own wrapper for this function
31 // to do so.
32 func (smc *Client) Run() error {
33 return smc.RunContext(context.TODO())
34 }
35
36 // RunContext is a blocking function that connects the Slack Socket Mode API and handles all incoming
37 // requests and outgoing responses.
38 //
39 // The consumer of the Client and this function should read the Client.Events channel to receive
40 // `socketmode.Event`s that includes the client-specific events that may or may not wrap Socket Mode requests.
41 //
42 // Note that this function automatically reconnect on requested by Slack through a `disconnect` message.
43 // This function exists with an error only when a reconnection is failued due to some reason.
44 // If you want to retry even on reconnection failure, you'd need to write your own wrapper for this function
45 // to do so.
46 func (smc *Client) RunContext(ctx context.Context) error {
47 for connectionCount := 0; ; connectionCount++ {
48 if err := smc.run(ctx, connectionCount); err != nil {
49 return err
50 }
51
52 // Continue and run the loop again to reconnect
53 }
54 }
55
56 func (smc *Client) run(ctx context.Context, connectionCount int) error {
57 messages := make(chan json.RawMessage)
58 defer close(messages)
59
60 deadmanTimer := newDeadmanTimer(smc.maxPingInterval)
61
62 pingHandler := func(_ string) error {
63 deadmanTimer.Reset()
64
65 return nil
66 }
67
68 // Start trying to connect
69 // the returned err is already passed onto the Events channel
70 //
71 // We also configures an additional ping handler for the deadmanTimer that triggers a timeout when
72 // Slack did not send us WebSocket PING for more than Client.maxPingInterval.
73 // We can use `<-smc.pingTimeout.C` to wait for the timeout.
74 info, conn, err := smc.connect(ctx, connectionCount, pingHandler)
75 if err != nil {
76 // when the connection is unsuccessful its fatal, and we need to bail out.
77 smc.Debugf("Failed to connect with Socket Mode on try %d: %s", connectionCount, err)
78
79 return err
80 }
81
82 ctx, cancel := context.WithCancel(ctx)
83 defer cancel()
84
85 smc.Events <- newEvent(EventTypeConnected, &ConnectedEvent{
86 ConnectionCount: connectionCount,
87 Info: info,
88 })
89
90 smc.Debugf("WebSocket connection succeeded on try %d", connectionCount)
91
92 // We're now connected so we can set up listeners
93
94 var (
95 wg sync.WaitGroup
96 firstErr error
97 firstErrOnce sync.Once
98 )
99
100 wg.Add(1)
101 go func() {
102 defer wg.Done()
103 defer cancel()
104
105 // The response sender sends Socket Mode responses over the WebSocket conn
106 if err := smc.runResponseSender(ctx, conn); err != nil {
107 firstErrOnce.Do(func() {
108 firstErr = err
109 })
110 }
111 }()
112
113 wg.Add(1)
114 go func() {
115 defer wg.Done()
116 defer cancel()
117
118 // The handler reads Socket Mode requests, and enqueues responses for sending by the response sender
119 if err := smc.runRequestHandler(ctx, messages); err != nil {
120 firstErrOnce.Do(func() {
121 firstErr = err
122 })
123 }
124 }()
125
126 // We don't wait on runMessageReceiver because it doesn't block on a select with the context,
127 // so we'd have to wait for the ReadJSON to time out, which can take a while.
128 go func() {
129 defer cancel()
130
131 // The receiver reads WebSocket messages, and enqueues parsed Socket Mode requests to be handled by
132 // the request handler
133 if err := smc.runMessageReceiver(ctx, conn, messages); err != nil {
134 firstErrOnce.Do(func() {
135 firstErr = err
136 })
137 }
138 }()
139
140 wg.Add(1)
141 go func() {
142 defer wg.Done()
143
144 select {
145 case <-ctx.Done():
146 // Detect when the connection is dead and try close connection.
147 if err = conn.Close(); err != nil {
148 smc.Debugf("Failed to close connection: %v", err)
149 }
150 case <-deadmanTimer.Elapsed():
151 firstErrOnce.Do(func() {
152 firstErr = errors.New("ping timeout: Slack did not send us WebSocket PING for more than Client.maxInterval")
153 })
154
155 cancel()
156 }
157 }()
158
159 wg.Wait()
160
161 if firstErr == context.Canceled {
162 return firstErr
163 }
164
165 // wg.Wait() finishes only after any of the above go routines finishes and cancels the
166 // context, allowing the other threads to shut down gracefully.
167 // Also, we can expect firstErr to be not nil, as goroutines can finish only on error.
168 smc.Debugf("Reconnecting due to %v", firstErr)
169
170 return nil
171 }
172
173 // connect attempts to connect to the slack websocket API. It handles any
174 // errors that occur while connecting and will return once a connection
175 // has been successfully opened.
176 func (smc *Client) connect(ctx context.Context, connectionCount int, additionalPingHandler func(string) error) (*slack.SocketModeConnection, *websocket.Conn, error) {
177 const (
178 errInvalidAuth = "invalid_auth"
179 errInactiveAccount = "account_inactive"
180 errMissingAuthToken = "not_authed"
181 errTokenRevoked = "token_revoked"
182 )
183
184 // used to provide exponential backoff wait time with jitter before trying
185 // to connect to slack again
186 boff := &backoff.Backoff{
187 Max: 5 * time.Minute,
188 }
189
190 for {
191 var (
192 backoff time.Duration
193 )
194
195 // send connecting event
196 smc.Events <- newEvent(EventTypeConnecting, &slack.ConnectingEvent{
197 Attempt: boff.Attempts() + 1,
198 ConnectionCount: connectionCount,
199 })
200
201 // attempt to start the connection
202 info, conn, err := smc.openAndDial(ctx, additionalPingHandler)
203 if err == nil {
204 return info, conn, nil
205 }
206
207 // check for fatal errors
208 switch err.Error() {
209 case errInvalidAuth, errInactiveAccount, errMissingAuthToken, errTokenRevoked:
210 smc.Debugf("invalid auth when connecting with SocketMode: %s", err)
211 return nil, nil, err
212 default:
213 }
214
215 switch actual := err.(type) {
216 case slack.StatusCodeError:
217 if actual.Code == http.StatusNotFound {
218 smc.Debugf("invalid auth when connecting with Socket Mode: %s", err)
219 smc.Events <- newEvent(EventTypeInvalidAuth, &slack.InvalidAuthEvent{})
220 return nil, nil, err
221 }
222 case *slack.RateLimitedError:
223 backoff = actual.RetryAfter
224 default:
225 }
226
227 backoff = timex.Max(backoff, boff.Duration())
228 // any other errors are treated as recoverable and we try again after
229 // sending the event along the Events channel
230 smc.Events <- newEvent(EventTypeConnectionError, &slack.ConnectionErrorEvent{
231 Attempt: boff.Attempts(),
232 Backoff: backoff,
233 ErrorObj: err,
234 })
235
236 // get time we should wait before attempting to connect again
237 smc.Debugf("reconnection %d failed: %s reconnecting in %v\n", boff.Attempts(), err, backoff)
238
239 // wait for one of the following to occur,
240 // backoff duration has elapsed, disconnectCh is signalled, or
241 // the smc finishes disconnecting.
242 select {
243 case <-time.After(backoff): // retry after the backoff.
244 case <-ctx.Done():
245 return nil, nil, ctx.Err()
246 }
247 }
248 }
249
250 // openAndDial attempts to open a Socket Mode connection and dial to the connection endpoint using WebSocket.
251 // It returns the full information returned by the "apps.connections.open" method on the
252 // Slack API.
253 func (smc *Client) openAndDial(ctx context.Context, additionalPingHandler func(string) error) (info *slack.SocketModeConnection, _ *websocket.Conn, err error) {
254 var (
255 url string
256 )
257
258 smc.Debugf("Starting SocketMode")
259 info, url, err = smc.OpenContext(ctx)
260
261 if err != nil {
262 smc.Debugf("Failed to start or connect with SocketMode: %s", err)
263 return nil, nil, err
264 }
265
266 smc.Debugf("Dialing to websocket on url %s", url)
267 // Only use HTTPS for connections to prevent MITM attacks on the connection.
268 upgradeHeader := http.Header{}
269 upgradeHeader.Add("Origin", "https://api.slack.com")
270 dialer := websocket.DefaultDialer
271 if smc.dialer != nil {
272 dialer = smc.dialer
273 }
274 conn, _, err := dialer.DialContext(ctx, url, upgradeHeader)
275 if err != nil {
276 smc.Debugf("Failed to dial to the websocket: %s", err)
277 return nil, nil, err
278 }
279
280 conn.SetPingHandler(func(appData string) error {
281 if additionalPingHandler != nil {
282 if err := additionalPingHandler(appData); err != nil {
283 return err
284 }
285 }
286
287 smc.handlePing(conn, appData)
288
289 return nil
290 })
291
292 // We don't need to conn.SetCloseHandler because the default handler is effective enough that
293 // it sends back the CLOSE message to the server and let conn.ReadJSON() fail with CloseError.
294 // The CloseError must be handled normally in our receiveMessagesInto function.
295 //conn.SetCloseHandler(func(code int, text string) error {
296 // ...
297 // })
298
299 return info, conn, err
300 }
301
302 // runResponseSender runs the handler that reads Socket Mode responses enqueued onto Client.socketModeResponses channel
303 // and sends them one by one over the WebSocket connection.
304 // Gorilla WebSocket is not goroutine safe hence this needs to be the single place you write to the WebSocket connection.
305 func (smc *Client) runResponseSender(ctx context.Context, conn *websocket.Conn) error {
306 for {
307 select {
308 case <-ctx.Done():
309 return ctx.Err()
310 // 3. listen for messages that need to be sent
311 case res := <-smc.socketModeResponses:
312 smc.Debugf("Sending Socket Mode response with envelope ID %q: %v", res.EnvelopeID, res)
313
314 if err := unsafeWriteSocketModeResponse(conn, res); err != nil {
315 smc.Events <- newEvent(EventTypeErrorWriteFailed, &ErrorWriteFailed{
316 Cause: err,
317 Response: res,
318 })
319 }
320
321 smc.Debugf("Finished sending Socket Mode response with envelope ID %q", res.EnvelopeID)
322 }
323 }
324 }
325
326 // runRequestHandler is a blocking function that runs the Socket Mode request receiver.
327 //
328 // It reads WebSocket messages sent from Slack's Socket Mode WebSocket connection,
329 // parses them as Socket Mode requests, and processes them and optionally emit our own events into Client.Events channel.
330 func (smc *Client) runRequestHandler(ctx context.Context, websocket chan json.RawMessage) error {
331 for {
332 select {
333 case <-ctx.Done():
334 return ctx.Err()
335 case message := <-websocket:
336 smc.Debugf("Received WebSocket message: %s", message)
337
338 // listen for incoming messages that need to be parsed
339 evt, err := smc.parseEvent(message)
340 if err != nil {
341 smc.Events <- newEvent(EventTypeErrorBadMessage, &ErrorBadMessage{
342 Cause: err,
343 Message: message,
344 })
345 } else if evt != nil {
346 if evt.Type == EventTypeDisconnect {
347 // We treat the `disconnect` request from Slack as an error internally,
348 // so that we can tell the consumer of this function to reopen the connection on it.
349 return errorRequestedDisconnect{}
350 }
351
352 smc.Events <- *evt
353 }
354 }
355 }
356 }
357
358 // runMessageReceiver monitors the Socket Mode opened WebSocket connection for any incoming
359 // messages. It pushes the raw events into the channel.
360 // The receiver runs until the context is closed.
361 func (smc *Client) runMessageReceiver(ctx context.Context, conn *websocket.Conn, sink chan json.RawMessage) error {
362 for {
363 if err := smc.receiveMessagesInto(ctx, conn, sink); err != nil {
364 return err
365 }
366 }
367 }
368
369 // unsafeWriteSocketModeResponse sends a WebSocket message back to Slack.
370 // WARNING: Call to this function must be serialized!
371 //
372 // Here's why - Gorilla WebSocket's Writes functions are not concurrency-safe.
373 // That is, we must serialize all the writes to it with e.g. a goroutine or mutex.
374 // We intentionally chose to use goroutine, which makes it harder to propagate write errors to the caller,
375 // but is more computationally efficient.
376 //
377 // See the below for more information on this topic:
378 // https://stackoverflow.com/questions/43225340/how-to-ensure-concurrency-in-golang-gorilla-websocket-package
379 func unsafeWriteSocketModeResponse(conn *websocket.Conn, res *Response) error {
380 // set a write deadline on the connection
381 if err := conn.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil {
382 return err
383 }
384
385 // Remove write deadline regardless of WriteJSON succeeds or not
386 defer conn.SetWriteDeadline(time.Time{})
387
388 if err := conn.WriteJSON(res); err != nil {
389 return err
390 }
391
392 return nil
393 }
394
395 func newEvent(tpe EventType, data interface{}, req ...*Request) Event {
396 evt := Event{Type: tpe, Data: data}
397
398 if len(req) > 0 {
399 evt.Request = req[0]
400 }
401
402 return evt
403 }
404
405 // Ack acknowledges the Socket Mode request with the payload.
406 //
407 // This tells Slack that the we have received the request denoted by the envelope ID,
408 // by sending back the envelope ID over the WebSocket connection.
409 func (smc *Client) Ack(req Request, payload ...interface{}) {
410 res := Response{
411 EnvelopeID: req.EnvelopeID,
412 }
413
414 if len(payload) > 0 {
415 res.Payload = payload[0]
416 }
417
418 smc.Send(res)
419 }
420
421 // Send sends the Socket Mode response over a WebSocket connection.
422 // This is usually used for acknowledging requests, but if you need more control over Client.Ack().
423 // It's normally recommended to use Client.Ack() instead of this.
424 func (smc *Client) Send(res Response) {
425 js, err := json.Marshal(res)
426 if err != nil {
427 panic(err)
428 }
429
430 smc.Debugf("Scheduling Socket Mode response for envelope ID %s: %s", res.EnvelopeID, js)
431
432 smc.socketModeResponses <- &res
433 }
434
435 // receiveMessagesInto attempts to receive an event from the WebSocket connection for Socket Mode.
436 // This will block until a frame is available from the WebSocket.
437 // If the read from the WebSocket results in a fatal error, this function will return non-nil.
438 func (smc *Client) receiveMessagesInto(ctx context.Context, conn *websocket.Conn, sink chan json.RawMessage) error {
439 smc.Debugf("Starting to receive message")
440 defer smc.Debugf("Finished to receive message")
441
442 event := json.RawMessage{}
443 err := conn.ReadJSON(&event)
444
445 // check if the connection was closed.
446 if websocket.IsUnexpectedCloseError(err) {
447 return err
448 }
449
450 switch {
451 case err == io.ErrUnexpectedEOF:
452 // EOF's don't seem to signify a failed connection so instead we ignore
453 // them here and detect a failed connection upon attempting to send a
454 // 'PING' message
455
456 // Unlike RTM, we don't ping from the our end as there seem to have no client ping.
457 // We just continue to the next loop so that we `smc.disconnected` should be received if
458 // this EOF error was actually due to disconnection.
459
460 return nil
461 case err != nil:
462 // All other errors from ReadJSON come from NextReader, and should
463 // kill the read loop and force a reconnect.
464 smc.Events <- newEvent(EventTypeIncomingError, &slack.IncomingEventError{
465 ErrorObj: err,
466 })
467
468 return err
469 case len(event) == 0:
470 smc.Debugln("Received empty event")
471 default:
472 if smc.debug {
473 buf := &bytes.Buffer{}
474 d := json.NewEncoder(buf)
475 d.SetIndent("", " ")
476 if err := d.Encode(event); err != nil {
477 smc.Debugln("Failed encoding decoded json:", err)
478 }
479 reencoded := buf.String()
480
481 smc.Debugln("Incoming WebSocket message:", reencoded)
482 }
483
484 select {
485 case sink <- event:
486 case <-ctx.Done():
487 smc.Debugln("cancelled while attempting to send raw event")
488
489 return ctx.Err()
490 }
491 }
492
493 return nil
494 }
495
496 // parseEvent takes a raw JSON message received from the slack websocket
497 // and handles the encoded event.
498 // returns the our own event that wraps the socket mode request.
499 func (smc *Client) parseEvent(wsMsg json.RawMessage) (*Event, error) {
500 req := &Request{}
501 err := json.Unmarshal(wsMsg, req)
502 if err != nil {
503 return nil, fmt.Errorf("unmarshalling WebSocket message: %v", err)
504 }
505
506 var evt Event
507
508 // See below two links for all the available message types.
509 // - https://github.com/slackapi/node-slack-sdk/blob/c3f4d7109062a0356fb765d53794b7b5f6b3b5ae/packages/socket-mode/src/SocketModeClient.ts#L533
510 // - https://api.slack.com/apis/connections/socket-implement
511 switch req.Type {
512 case RequestTypeHello:
513 evt = newEvent(EventTypeHello, nil, req)
514 case RequestTypeEventsAPI:
515 payloadEvent := req.Payload
516
517 eventsAPIEvent, err := slackevents.ParseEvent(payloadEvent, slackevents.OptionNoVerifyToken())
518 if err != nil {
519 return nil, fmt.Errorf("parsing Events API event: %v", err)
520 }
521
522 evt = newEvent(EventTypeEventsAPI, eventsAPIEvent, req)
523 case RequestTypeDisconnect:
524 // See https://api.slack.com/apis/connections/socket-implement#disconnect
525
526 evt = newEvent(EventTypeDisconnect, nil, req)
527 case RequestTypeSlashCommands:
528 // See https://api.slack.com/apis/connections/socket-implement#command
529 var cmd slack.SlashCommand
530
531 if err := json.Unmarshal(req.Payload, &cmd); err != nil {
532 return nil, fmt.Errorf("parsing slash command: %v", err)
533 }
534
535 evt = newEvent(EventTypeSlashCommand, cmd, req)
536 case RequestTypeInteractive:
537 // See belows:
538 // - https://api.slack.com/apis/connections/socket-implement#button
539 // - https://api.slack.com/apis/connections/socket-implement#home
540 // - https://api.slack.com/apis/connections/socket-implement#modal
541 // - https://api.slack.com/apis/connections/socket-implement#menu
542
543 var callback slack.InteractionCallback
544
545 if err := json.Unmarshal(req.Payload, &callback); err != nil {
546 return nil, fmt.Errorf("parsing interaction callback: %v", err)
547 }
548
549 evt = newEvent(EventTypeInteractive, callback, req)
550 default:
551 return nil, fmt.Errorf("processing WebSocket message: encountered unsupported type %q", req.Type)
552 }
553
554 return &evt, nil
555 }
556
557 // handlePing handles an incoming 'PONG' message which should be in response to
558 // a previously sent 'PING' message. This is then used to compute the
559 // connection's latency.
560 func (smc *Client) handlePing(conn *websocket.Conn, event string) {
561 smc.Debugf("WebSocket ping message received: %s", event)
562
563 // In WebSocket, we need to respond a PING from the server with a PONG with the same payload as the PING.
564 if err := conn.WriteControl(websocket.PongMessage, []byte(event), time.Now().Add(10*time.Second)); err != nil {
565 smc.Debugf("Failed writing WebSocket PONG message: %v", err)
566 }
567 }