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

feat(slack) add rate limiting #6

Merged
merged 2 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/slack-go/slack v0.13.0
github.com/stretchr/testify v1.9.0
github.com/traefik/traefik/v2 v2.11.5
golang.org/x/time v0.5.0
golang.org/x/tools v0.22.0
k8s.io/apimachinery v0.30.2
k8s.io/client-go v0.30.2
Expand Down Expand Up @@ -72,7 +73,6 @@ require (
golang.org/x/sys v0.21.0 // indirect
golang.org/x/term v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
Expand Down
17 changes: 16 additions & 1 deletion internal/service/slack.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,38 @@ import (

"github.com/PDOK/uptime-operator/internal/model"
"github.com/slack-go/slack"
"golang.org/x/time/rate"
"sigs.k8s.io/controller-runtime/pkg/log"
)

const (
nrOfMessagesPerSec = 1
nrOfMessagesPerBurst = 10
)

type Slack struct {
webhookURL string
channelID string

rateLimit *rate.Limiter
}

func NewSlack(webhookURL, channelID string) *Slack {
return &Slack{
webhookURL: webhookURL,
channelID: channelID,

// see https://api.slack.com/apis/rate-limits
rateLimit: rate.NewLimiter(nrOfMessagesPerSec, nrOfMessagesPerBurst),
}
}

func (s *Slack) Send(ctx context.Context, message string) {
err := slack.PostWebhook(s.webhookURL, &slack.WebhookMessage{
err := s.rateLimit.Wait(ctx)
if err != nil {
log.FromContext(ctx).Error(err, "failed waiting for slack rate limit")
}
err = slack.PostWebhook(s.webhookURL, &slack.WebhookMessage{
Channel: s.channelID,
Text: message,
Username: model.OperatorName,
Expand Down
Loading