From 6a8c6285707a4dc3f1a6e027241b27296fd8247e Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:28:48 +0300 Subject: [PATCH] MSP-437 implement daily limit service --- service/daily_limit.go | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 service/daily_limit.go diff --git a/service/daily_limit.go b/service/daily_limit.go new file mode 100644 index 0000000..e7f058b --- /dev/null +++ b/service/daily_limit.go @@ -0,0 +1,43 @@ +package service + +import ( + "context" + "time" + + "github.com/pkg/errors" + "isp-gate-service/conf" +) + +type DailyLimitRepo interface { + Increment(ctx context.Context, applicationId int, today time.Time) (int64, error) +} + +type DailyLimit struct { + repo DailyLimitRepo + limits map[int]int64 +} + +func NewDailyLimit(repo DailyLimitRepo, configs []conf.DailyLimit) DailyLimit { + limits := make(map[int]int64) + for _, config := range configs { + limits[config.ApplicationId] = config.RequestsPerDay + } + return DailyLimit{ + repo: repo, + limits: limits, + } +} + +func (s DailyLimit) IncrementAndCheck(ctx context.Context, applicationId int) (bool, error) { + max, ok := s.limits[applicationId] + if !ok { + return true, nil + } + + newValue, err := s.repo.Increment(ctx, applicationId, time.Now()) + if err != nil { + return false, errors.WithMessage(err, "increment") + } + + return newValue <= max, nil +}