Skip to content

Commit

Permalink
Merge pull request #6 from PDOK/slack-ratelimit
Browse files Browse the repository at this point in the history
feat(slack) add rate limiting
  • Loading branch information
rkettelerij authored Jun 25, 2024
2 parents d840d00 + 19c96f0 commit 45b8a1a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
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

0 comments on commit 45b8a1a

Please sign in to comment.