Skip to content

Commit 45b8a1a

Browse files
authored
Merge pull request #6 from PDOK/slack-ratelimit
feat(slack) add rate limiting
2 parents d840d00 + 19c96f0 commit 45b8a1a

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ require (
99
github.com/slack-go/slack v0.13.0
1010
github.com/stretchr/testify v1.9.0
1111
github.com/traefik/traefik/v2 v2.11.5
12+
golang.org/x/time v0.5.0
1213
golang.org/x/tools v0.22.0
1314
k8s.io/apimachinery v0.30.2
1415
k8s.io/client-go v0.30.2
@@ -72,7 +73,6 @@ require (
7273
golang.org/x/sys v0.21.0 // indirect
7374
golang.org/x/term v0.21.0 // indirect
7475
golang.org/x/text v0.16.0 // indirect
75-
golang.org/x/time v0.5.0 // indirect
7676
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect
7777
google.golang.org/protobuf v1.34.2 // indirect
7878
gopkg.in/inf.v0 v0.9.1 // indirect

internal/service/slack.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,38 @@ import (
55

66
"github.com/PDOK/uptime-operator/internal/model"
77
"github.com/slack-go/slack"
8+
"golang.org/x/time/rate"
89
"sigs.k8s.io/controller-runtime/pkg/log"
910
)
1011

12+
const (
13+
nrOfMessagesPerSec = 1
14+
nrOfMessagesPerBurst = 10
15+
)
16+
1117
type Slack struct {
1218
webhookURL string
1319
channelID string
20+
21+
rateLimit *rate.Limiter
1422
}
1523

1624
func NewSlack(webhookURL, channelID string) *Slack {
1725
return &Slack{
1826
webhookURL: webhookURL,
1927
channelID: channelID,
28+
29+
// see https://api.slack.com/apis/rate-limits
30+
rateLimit: rate.NewLimiter(nrOfMessagesPerSec, nrOfMessagesPerBurst),
2031
}
2132
}
2233

2334
func (s *Slack) Send(ctx context.Context, message string) {
24-
err := slack.PostWebhook(s.webhookURL, &slack.WebhookMessage{
35+
err := s.rateLimit.Wait(ctx)
36+
if err != nil {
37+
log.FromContext(ctx).Error(err, "failed waiting for slack rate limit")
38+
}
39+
err = slack.PostWebhook(s.webhookURL, &slack.WebhookMessage{
2540
Channel: s.channelID,
2641
Text: message,
2742
Username: model.OperatorName,

0 commit comments

Comments
 (0)