/
rtmapi.go
186 lines (155 loc) · 5.76 KB
/
rtmapi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package slack
import (
"context"
"fmt"
"github.com/oklahomer/go-kasumi/logger"
"github.com/oklahomer/go-kasumi/retry"
"github.com/oklahomer/go-sarah/v4"
"github.com/oklahomer/golack/v2/event"
"github.com/oklahomer/golack/v2/rtmapi"
"strings"
"time"
)
const pingSignalChannelID = "ping"
type rtmAPIAdapter struct {
config *Config
client SlackClient
handlePayload func(context.Context, *Config, rtmapi.DecodedPayload, func(sarah.Input) error)
}
var _ apiSpecificAdapter = (*rtmAPIAdapter)(nil)
func (r *rtmAPIAdapter) run(ctx context.Context, enqueueInput func(sarah.Input) error, notifyErr func(error)) {
for {
conn, err := r.connect(ctx)
if err != nil {
// Failed to establish a WebSocket connection with max retrials.
// Notify the unrecoverable state and give up.
notifyErr(sarah.NewBotNonContinuableError(err.Error()))
return
}
// Create a connection specific context so each connection-scoped goroutine can receive the connection closing signal and eventually return.
connCtx, connCancel := context.WithCancel(ctx)
// This channel is not subject to close. This channel can be accessed in a parallel manner with nonBlockSignal function,
// and the receiver is NOT waiting for a close signal. Let GC run when this channel is no longer referred.
//
// http://stackoverflow.com/a/8593986
// "Note that it is only necessary to close a channel if the receiver is looking for a close.
// Closing the channel is a control signal on the channel indicating that no more data follows."
tryPing := make(chan struct{}, 1)
go r.receivePayload(connCtx, conn, tryPing, enqueueInput)
// Payload reception and other connection-related tasks must run in separate goroutines since receivePayload function
// internally blocks till the per-connection context is cancelled.
connErr := r.superviseConnection(connCtx, conn, tryPing)
// superviseConnection returns when parent context is canceled or the connection is hopelessly unstable.
// Close the current connection and do some cleanup.
_ = conn.Close()
connCancel()
if connErr == nil {
// Connection is intentionally closed by the caller.
// No more interaction follows.
return
}
logger.Errorf("Will try re-connection due to previous connection's fatal state: %+v", connErr)
}
}
func (r *rtmAPIAdapter) connect(ctx context.Context) (rtmapi.Connection, error) {
var conn rtmapi.Connection
err := retry.WithPolicy(r.config.RetryPolicy, func() (e error) {
conn, e = r.client.ConnectRTM(ctx)
return e
})
return conn, err
}
func (r *rtmAPIAdapter) receivePayload(connCtx context.Context, payloadReceiver rtmapi.PayloadReceiver, tryPing chan<- struct{}, enqueueInput func(sarah.Input) error) {
for {
select {
case <-connCtx.Done():
logger.Info("Stop receiving payload due to context cancel")
return
default:
payload, err := payloadReceiver.Receive()
// TODO should io.EOF and io.ErrUnexpectedEOF treated differently than other errors?
if err == event.ErrEmptyPayload {
continue
}
switch err.(type) {
case nil:
// O.K. Do nothing and proceed to the payload handling
case *event.MalformedPayloadError:
logger.Warnf("Ignore malformed payload: %+v", err)
continue
case *rtmapi.UnexpectedMessageTypeError:
logger.Warnf("Ignore a payload with unexpected message type: %+v", err)
continue
default:
// Connection might not be stable or is closed already.
logger.Infof("Try ping caused by error: %+v", err)
nonBlockSignal(pingSignalChannelID, tryPing)
continue
}
if payload == nil {
continue
}
r.handlePayload(connCtx, r.config, payload, enqueueInput)
}
}
}
func (r *rtmAPIAdapter) superviseConnection(connCtx context.Context, payloadSender rtmapi.PayloadSender, tryPing chan struct{}) error {
ticker := time.NewTicker(r.config.PingInterval)
defer ticker.Stop()
for {
select {
case <-connCtx.Done():
return nil
case <-ticker.C:
nonBlockSignal(pingSignalChannelID, tryPing)
case <-tryPing:
logger.Debug("Send ping")
err := payloadSender.Ping()
if err != nil {
return fmt.Errorf("error on ping: %w", err)
}
}
}
}
// DefaultRTMPayloadHandler receives incoming events, converts them to sarah.Input, and then passes them to enqueueInput.
// To replace this default behavior, define a function with the same signature and replace this.
//
// myHandler := func(_ context.Context, config *Config, _ rtmapi.DecodedPayload, _ func(sarah.Input) error) {}
// slackAdapter, _ := slack.NewAdapter(slackConfig, slack.WithRTMPayloadHandler(myHandler))
func DefaultRTMPayloadHandler(_ context.Context, config *Config, payload rtmapi.DecodedPayload, enqueueInput func(sarah.Input) error) {
switch p := payload.(type) {
case *rtmapi.OKReply:
logger.Debugf("Successfully sent. ID: %d. Text: %s.", p.ReplyTo, p.Text)
case *rtmapi.NGReply:
logger.Errorf(
"Something was wrong with previous message sending. id: %d. error code: %d. error message: %s.",
p.ReplyTo, p.Error.Code, p.Error.Message)
case *rtmapi.Pong:
logger.Debug("Pong message received.")
case *event.Hello:
logger.Debugf("Successfully connected.")
default:
input, err := EventToInput(p)
if err == ErrNonSupportedEvent {
logger.Debugf("Event given, but no corresponding action is defined. %#v", payload)
return
}
if err != nil {
logger.Errorf("Failed to convert %T event: %s", p, err.Error())
return
}
trimmed := strings.TrimSpace(input.Message())
if config.HelpCommand != "" && trimmed == config.HelpCommand {
// Help command
help := sarah.NewHelpInput(input)
_ = enqueueInput(help)
} else if config.AbortCommand != "" && trimmed == config.AbortCommand {
// Abort command
abort := sarah.NewAbortInput(input)
_ = enqueueInput(abort)
} else {
// Regular input
_ = enqueueInput(input)
}
}
}