From b415ce8acfb71522eefaeb4bab5b76a701b07567 Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:29:29 +0300 Subject: [PATCH] MSP-437 implement throttling repository --- repository/throttling.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 repository/throttling.go diff --git a/repository/throttling.go b/repository/throttling.go new file mode 100644 index 0000000..cd1090e --- /dev/null +++ b/repository/throttling.go @@ -0,0 +1,37 @@ +package repository + +import ( + "context" + "fmt" + + "github.com/go-redis/redis/v8" + "github.com/go-redis/redis_rate/v9" + "github.com/pkg/errors" + "isp-gate-service/domain" +) + +type Throttling struct { + cli *redis_rate.Limiter +} + +func NewThrottling(cli redis.UniversalClient) Throttling { + return Throttling{ + cli: redis_rate.NewLimiter(cli), + } +} + +func (r Throttling) IsAllowRequestPerSecond(ctx context.Context, applicationId int, rate int) (*domain.RateLimitResult, error) { + result, err := r.cli.Allow(ctx, r.key(applicationId), redis_rate.PerSecond(rate)) + if err != nil { + return nil, errors.WithMessage(err, "redis_rate/Allow") + } + return &domain.RateLimitResult{ + Allow: result.Allowed > 0, + Remaining: result.Remaining, + RetryAfter: result.RetryAfter, + }, nil +} + +func (r Throttling) key(applicationId int) string { + return fmt.Sprintf("throttling:%d", applicationId) +}