Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

platform async message handling #1176

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ require (
github.com/sha1sum/aws_signing_client v0.0.0-20200229211254-f7815c59d5c1
github.com/sirupsen/logrus v1.9.0
github.com/slack-go/slack v0.12.2
github.com/sourcegraph/conc v0.3.0
github.com/spf13/cobra v1.7.0
github.com/spf13/pflag v1.0.5
github.com/spiffe/spire v1.5.6
Expand Down Expand Up @@ -239,6 +240,8 @@ require (
go.opentelemetry.io/otel/metric v1.16.0 // indirect
go.opentelemetry.io/otel/trace v1.16.0 // indirect
go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.10.0 // indirect
golang.org/x/net v0.11.0 // indirect
golang.org/x/sys v0.9.0 // indirect
Expand Down
8 changes: 6 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1122,6 +1122,8 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:UdhH50NIW0fCiwBSr0co2m7BnFLdv4fQTgdqdJTHFeE=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
Expand Down Expand Up @@ -1246,10 +1248,12 @@ go.szostok.io/version v1.2.0 h1:8eMMdfsonjbibwZRLJ8TnrErY8bThFTQsZYV16mcXms=
go.szostok.io/version v1.2.0/go.mod h1:EiU0gPxaXb6MZ+apSN0WgDO6F4JXyC99k9PIXf2k2E8=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
Expand Down
81 changes: 54 additions & 27 deletions pkg/bot/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/bwmarrin/discordgo"
"github.com/sirupsen/logrus"
"github.com/sourcegraph/conc/pool"

"github.com/kubeshop/botkube/pkg/api"
"github.com/kubeshop/botkube/pkg/bot/interactive"
Expand Down Expand Up @@ -39,17 +40,20 @@ const (

// Discord listens for user's message, execute commands and sends back the response.
type Discord struct {
log logrus.FieldLogger
executorFactory ExecutorFactory
reporter AnalyticsReporter
api *discordgo.Session
botID string
channelsMutex sync.RWMutex
channels map[string]channelConfigByID
notifyMutex sync.Mutex
botMentionRegex *regexp.Regexp
commGroupName string
renderer *DiscordRenderer
log logrus.FieldLogger
executorFactory ExecutorFactory
reporter AnalyticsReporter
api *discordgo.Session
botID string
channelsMutex sync.RWMutex
channels map[string]channelConfigByID
notifyMutex sync.Mutex
botMentionRegex *regexp.Regexp
commGroupName string
renderer *DiscordRenderer
messages chan discordMessage
discordMessageWorkers *pool.Pool
shutdownOnce sync.Once
}

// discordMessage contains message details to execute command and send back the result.
Expand All @@ -75,19 +79,33 @@ func NewDiscord(log logrus.FieldLogger, commGroupName string, cfg config.Discord
}

return &Discord{
log: log,
reporter: reporter,
executorFactory: executorFactory,
api: api,
botID: cfg.BotID,
commGroupName: commGroupName,
channels: channelsCfg,
botMentionRegex: botMentionRegex,
renderer: NewDiscordRenderer(),
log: log,
reporter: reporter,
executorFactory: executorFactory,
api: api,
botID: cfg.BotID,
commGroupName: commGroupName,
channels: channelsCfg,
botMentionRegex: botMentionRegex,
renderer: NewDiscordRenderer(),
messages: make(chan discordMessage, 100),
discordMessageWorkers: pool.New().WithMaxGoroutines(10),
}, nil
}

// Start starts the Discord websocket connection and listens for messages.
func (b *Discord) startMessageProcessor(ctx context.Context) {
b.log.Info("Starting discord message processor...")
defer b.log.Info("Stopped discord message processor...")

for msg := range b.messages {
mszostok marked this conversation as resolved.
Show resolved Hide resolved
b.discordMessageWorkers.Go(func() {
err := b.handleMessage(ctx, msg)
if err != nil {
b.log.Errorf("while handling message: %s", err.Error())
mszostok marked this conversation as resolved.
Show resolved Hide resolved
}
})
}
} // Start starts the Discord websocket connection and listens for messages.
func (b *Discord) Start(ctx context.Context) error {
b.log.Info("Starting bot")

Expand All @@ -113,14 +131,10 @@ func (b *Discord) Start(ctx context.Context) error {
}

b.log.Info("Botkube connected to Discord!")

go b.startMessageProcessor(ctx)
<-ctx.Done()
b.log.Info("Shutdown requested. Finishing...")
err = b.api.Close()
if err != nil {
return fmt.Errorf("while closing connection: %w", err)
}

b.shutdown()
return nil
}

Expand Down Expand Up @@ -345,6 +359,19 @@ func (b *Discord) formatMessage(msg interactive.CoreMessage) (*discordgo.Message
}, nil
}

func (b *Discord) shutdown() {
b.shutdownOnce.Do(func() {
b.log.Info("Shutting down discord message processor...")
close(b.messages)
b.discordMessageWorkers.Wait()

err := b.api.Close()
mszostok marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
b.log.Errorf("While closing connection: %v", err)
mszostok marked this conversation as resolved.
Show resolved Hide resolved
}
})
}

func discordChannelsConfigFrom(log logrus.FieldLogger, api *discordgo.Session, channelsCfg config.IdentifiableMap[config.ChannelBindingsByID]) (map[string]channelConfigByID, error) {
res := make(map[string]channelConfigByID)
for channAlias, channCfg := range channelsCfg {
Expand Down
105 changes: 66 additions & 39 deletions pkg/bot/mattermost.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/mattermost/mattermost/server/public/model"
"github.com/sirupsen/logrus"
"github.com/sourcegraph/conc/pool"

"github.com/kubeshop/botkube/pkg/api"
"github.com/kubeshop/botkube/pkg/bot/interactive"
Expand Down Expand Up @@ -46,23 +47,26 @@ const (

// Mattermost listens for user's message, execute commands and sends back the response.
type Mattermost struct {
log logrus.FieldLogger
executorFactory ExecutorFactory
reporter AnalyticsReporter
serverURL string
botName string
botUserID string
teamName string
webSocketURL string
wsClient *model.WebSocketClient
apiClient *model.Client4
channelsMutex sync.RWMutex
commGroupName string
channels map[string]channelConfigByID
notifyMutex sync.Mutex
botMentionRegex *regexp.Regexp
renderer *MattermostRenderer
userNamesForID map[string]string
log logrus.FieldLogger
executorFactory ExecutorFactory
reporter AnalyticsReporter
serverURL string
botName string
botUserID string
teamName string
webSocketURL string
wsClient *model.WebSocketClient
apiClient *model.Client4
channelsMutex sync.RWMutex
commGroupName string
channels map[string]channelConfigByID
notifyMutex sync.Mutex
botMentionRegex *regexp.Regexp
renderer *MattermostRenderer
userNamesForID map[string]string
messages chan mattermostMessage
mmMessageWorkers *pool.Pool
shutdownOnce sync.Once
}

// mattermostMessage contains message details to execute command and send back the result
Expand Down Expand Up @@ -121,24 +125,39 @@ func NewMattermost(ctx context.Context, log logrus.FieldLogger, commGroupName st
}

return &Mattermost{
log: log,
executorFactory: executorFactory,
reporter: reporter,
serverURL: cfg.URL,
botName: cfg.BotName,
botUserID: botUserID,
teamName: cfg.Team,
apiClient: client,
webSocketURL: webSocketURL,
commGroupName: commGroupName,
channels: channelsByIDCfg,
botMentionRegex: botMentionRegex,
renderer: NewMattermostRenderer(),
userNamesForID: map[string]string{},
log: log,
executorFactory: executorFactory,
reporter: reporter,
serverURL: cfg.URL,
botName: cfg.BotName,
botUserID: botUserID,
teamName: cfg.Team,
apiClient: client,
webSocketURL: webSocketURL,
commGroupName: commGroupName,
channels: channelsByIDCfg,
botMentionRegex: botMentionRegex,
renderer: NewMattermostRenderer(),
userNamesForID: map[string]string{},
messages: make(chan mattermostMessage, 100),
mmMessageWorkers: pool.New().WithMaxGoroutines(10),
}, nil
}

// Start establishes mattermost connection and listens for messages
func (b *Mattermost) startMessageProcessor(ctx context.Context) {
b.log.Info("Starting mattermost message processor...")
defer b.log.Info("Stopped mattermost message processor...")

for msg := range b.messages {
b.mmMessageWorkers.Go(func() {
err := b.handleMessage(ctx, msg)
if err != nil {
wrappedErr := fmt.Errorf("while handling message: %w", err)
b.log.Errorf(wrappedErr.Error())
}
mszostok marked this conversation as resolved.
Show resolved Hide resolved
})
}
} // Start establishes mattermost connection and listens for messages
func (b *Mattermost) Start(ctx context.Context) error {
b.log.Info("Starting bot")

Expand All @@ -157,10 +176,14 @@ func (b *Mattermost) Start(ctx context.Context) error {
// For now, we are adding retry logic to reconnect to the server
// https://github.com/kubeshop/botkube/issues/201
b.log.Info("Botkube connected to Mattermost!")

go b.startMessageProcessor(ctx)

for {
select {
case <-ctx.Done():
b.log.Info("Shutdown requested. Finishing...")
b.shutdown()
return nil
default:
var appErr error
Expand Down Expand Up @@ -213,7 +236,7 @@ func (b *Mattermost) SetNotificationsEnabled(channelID string, enabled bool) err
}

// Check incoming message and take action
func (b *Mattermost) handleMessage(ctx context.Context, mm *mattermostMessage) error {
func (b *Mattermost) handleMessage(ctx context.Context, mm mattermostMessage) error {
post, err := postFromEvent(mm.Event)
if err != nil {
return fmt.Errorf("while getting post from event: %w", err)
Expand Down Expand Up @@ -387,14 +410,10 @@ func (b *Mattermost) listen(ctx context.Context) {
continue
}

mm := &mattermostMessage{
mm := mattermostMessage{
Event: event,
}
err := b.handleMessage(ctx, mm)
if err != nil {
wrappedErr := fmt.Errorf("while handling message: %w", err)
b.log.Errorf(wrappedErr.Error())
}
b.messages <- mm
}
}
}
Expand Down Expand Up @@ -482,6 +501,14 @@ func (b *Mattermost) getUserName(ctx context.Context, userID string) (string, er
return user.Username, nil
}

func (b *Mattermost) shutdown() {
b.shutdownOnce.Do(func() {
b.log.Info("Shutting down mattermost message processor...")
close(b.messages)
b.mmMessageWorkers.Wait()
})
}

func getBotUserID(ctx context.Context, client *model.Client4, teamID, botName string) (string, error) {
users, _, err := client.AutocompleteUsersInTeam(ctx, teamID, botName, 1, "")
if err != nil {
Expand Down
Loading
Loading