Skip to content

Commit

Permalink
feat(slack) add rate limiting
Browse files Browse the repository at this point in the history
  • Loading branch information
rkettelerij committed Jun 24, 2024
1 parent d840d00 commit 4962f47
Showing 1 changed file with 16 additions and 1 deletion.
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 4962f47

Please sign in to comment.