MSP-4680 implement in memory rate limiter method /rate_limit/inmem
This commit is contained in:
1 parent
91f8e40e70
commit
0a1ec74ddb
7 files changed
+144
-22
No files matched your search
+25
-10
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/rc"
|
||||
"isp-lock-service/conf"
|
||||
"isp-lock-service/repository"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
@@ -17,23 +18,29 @@ import (
|
||||
)
|
||||
|
||||
type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
server *grpc.Server
|
||||
redisCli *goredislib.Client
|
||||
logger *log.Adapter
|
||||
boot *bootstrap.Bootstrap
|
||||
server *grpc.Server
|
||||
redisCli *goredislib.Client
|
||||
logger *log.Adapter
|
||||
rateLimiterRepo *repository.RateLimiter
|
||||
}
|
||||
|
||||
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
server := grpc.DefaultServer()
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
server: server,
|
||||
redisCli: nil,
|
||||
logger: boot.App.Logger(),
|
||||
boot: boot,
|
||||
server: server,
|
||||
redisCli: nil,
|
||||
logger: boot.App.Logger(),
|
||||
rateLimiterRepo: nil,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
|
||||
if a.rateLimiterRepo != nil {
|
||||
a.rateLimiterRepo.Close()
|
||||
}
|
||||
|
||||
newCfg, _, err := rc.Upgrade[conf.Remote](a.boot.RemoteConfig, remoteConfig)
|
||||
if err != nil {
|
||||
a.boot.Fatal(errors.WithMessage(err, "upgrade remote config"))
|
||||
@@ -48,8 +55,10 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
|
||||
logger := sentry.WrapErrorLogger(a.logger, a.boot.SentryHub)
|
||||
locator := NewLocator(logger, a.redisCli, newCfg)
|
||||
handler := locator.Handler()
|
||||
a.server.Upgrade(handler)
|
||||
locatorCfg := locator.Config()
|
||||
|
||||
a.rateLimiterRepo = locatorCfg.rateLimiterRepo
|
||||
a.server.Upgrade(locatorCfg.handler)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -91,6 +100,12 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
if a.rateLimiterRepo != nil {
|
||||
a.rateLimiterRepo.Close()
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-5
@@ -27,12 +27,17 @@ func NewLocator(logger log.Logger, redisCli goredislib.UniversalClient, cfg conf
|
||||
}
|
||||
}
|
||||
|
||||
func (l Locator) Handler() *grpc.Mux {
|
||||
type locatorConfig struct {
|
||||
handler *grpc.Mux
|
||||
rateLimiterRepo *repository.RateLimiter
|
||||
}
|
||||
|
||||
func (l Locator) Config() locatorConfig {
|
||||
lockRepo := repository.NewLocker(l.logger, l.redisCli, l.cfg.Redis)
|
||||
lockerService := service.NewLocker(l.logger, lockRepo)
|
||||
lockerController := controller.NewLocker(l.logger, lockerService)
|
||||
|
||||
rateLimiterRepo := repository.NewRateLimiter(l.logger, l.redisCli, l.cfg.Redis)
|
||||
rateLimiterRepo := repository.NewRateLimiter(l.logger, l.redisCli, l.cfg)
|
||||
rateLimiterService := service.NewRateLimiter(rateLimiterRepo)
|
||||
rateLimiterController := controller.NewRateLimiter(rateLimiterService)
|
||||
|
||||
@@ -45,7 +50,10 @@ func (l Locator) Handler() *grpc.Mux {
|
||||
RateLimiter: rateLimiterController,
|
||||
DailyLimiter: dailyLimiterController,
|
||||
}
|
||||
mapper := endpoint.DefaultWrapper(l.logger, endpoint.BodyLogger(l.logger))
|
||||
handler := routes.Handler(mapper, c)
|
||||
return handler
|
||||
mapper := endpoint.DefaultWrapper(l.logger, endpoint.Log(l.logger, true))
|
||||
|
||||
return locatorConfig{
|
||||
handler: routes.Handler(mapper, c),
|
||||
rateLimiterRepo: rateLimiterRepo,
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
type limiterService interface {
|
||||
Limit(ctx context.Context, req domain.RateLimiterRequest) (*domain.RateLimiterResponse, error)
|
||||
LimitInMem(ctx context.Context, req domain.RateLimiterRequest) (*domain.InMemRateLimiterResponse, error)
|
||||
}
|
||||
|
||||
type RateLimiter struct {
|
||||
@@ -21,3 +22,7 @@ func NewRateLimiter(svc limiterService) RateLimiter {
|
||||
func (c RateLimiter) Limit(ctx context.Context, req domain.RateLimiterRequest) (*domain.RateLimiterResponse, error) {
|
||||
return c.svc.Limit(ctx, req)
|
||||
}
|
||||
|
||||
func (c RateLimiter) LimitInMem(ctx context.Context, req domain.RateLimiterRequest) (*domain.InMemRateLimiterResponse, error) {
|
||||
return c.svc.LimitInMem(ctx, req)
|
||||
}
|
||||
@@ -14,3 +14,7 @@ type RateLimiterResponse struct {
|
||||
Remaining int
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
type InMemRateLimiterResponse struct {
|
||||
PassAfter time.Duration
|
||||
}
|
||||
@@ -2,30 +2,50 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis_rate/v10"
|
||||
"github.com/pkg/errors"
|
||||
goredislib "github.com/redis/go-redis/v9"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/time/rate"
|
||||
"isp-lock-service/conf"
|
||||
"isp-lock-service/domain"
|
||||
)
|
||||
|
||||
type rateLimiter struct {
|
||||
type RateLimiter struct {
|
||||
logger log.Logger
|
||||
cli *redis_rate.Limiter
|
||||
prefix string
|
||||
|
||||
inMemLimiters map[string]*limiter
|
||||
mu sync.Locker
|
||||
cancelFn context.CancelFunc
|
||||
}
|
||||
|
||||
func NewRateLimiter(logger log.Logger, cli goredislib.UniversalClient, cfg conf.Redis) rateLimiter {
|
||||
return rateLimiter{
|
||||
logger: logger,
|
||||
cli: redis_rate.NewLimiter(cli),
|
||||
prefix: cfg.Prefix + "::rate-limiter",
|
||||
type limiter struct {
|
||||
*rate.Limiter
|
||||
lastUse time.Time
|
||||
}
|
||||
|
||||
func NewRateLimiter(logger log.Logger, cli goredislib.UniversalClient, cfg conf.Remote) *RateLimiter {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
limiter := &RateLimiter{
|
||||
logger: logger,
|
||||
cli: redis_rate.NewLimiter(cli),
|
||||
prefix: cfg.Redis.Prefix + "::rate-limiter",
|
||||
inMemLimiters: make(map[string]*limiter),
|
||||
mu: new(sync.Mutex),
|
||||
cancelFn: cancel,
|
||||
}
|
||||
go limiter.clearInMemLimiters(ctx, cfg.InMemLimiter)
|
||||
|
||||
return limiter
|
||||
}
|
||||
|
||||
func (r rateLimiter) Limit(ctx context.Context, key string, maxRps int) (*domain.RateLimiterResponse, error) {
|
||||
func (r *RateLimiter) Limit(ctx context.Context, key string, maxRps int) (*domain.RateLimiterResponse, error) {
|
||||
res, err := r.cli.Allow(ctx, makeKey(r.prefix, key), redis_rate.PerSecond(maxRps))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "allow request")
|
||||
@@ -37,3 +57,63 @@ func (r rateLimiter) Limit(ctx context.Context, key string, maxRps int) (*domain
|
||||
RetryAfter: res.RetryAfter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *RateLimiter) LimitInMem(_ context.Context, key string, maxRps int) (*domain.InMemRateLimiterResponse, error) {
|
||||
key = fmt.Sprintf("%s:::%d", key, maxRps)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
lim, ok := r.inMemLimiters[key]
|
||||
if !ok {
|
||||
lim = &limiter{Limiter: rate.NewLimiter(rate.Limit(maxRps), 1)}
|
||||
r.inMemLimiters[key] = lim
|
||||
}
|
||||
lim.lastUse = time.Now()
|
||||
|
||||
res := lim.ReserveN(lim.lastUse, 1)
|
||||
if !res.OK() {
|
||||
return nil, errors.Errorf("can't reserve time; key='%s'", key)
|
||||
}
|
||||
|
||||
return &domain.InMemRateLimiterResponse{
|
||||
PassAfter: res.DelayFrom(lim.lastUse),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *RateLimiter) clearInMemLimiters(ctx context.Context, cfg conf.InMemLimiter) {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "limiterCleaner"))
|
||||
var (
|
||||
lastUseThreshold = time.Duration(cfg.LastUseThresholdInSec) * time.Second
|
||||
ticker = time.NewTicker(time.Duration(cfg.ClearPeriodInSec) * time.Second)
|
||||
)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
count := r.removeUnusedLimiters(lastUseThreshold)
|
||||
r.logger.Debug(ctx, fmt.Sprintf("removed %d unused limiters", count))
|
||||
case <-ctx.Done():
|
||||
r.logger.Info(ctx, errors.WithMessage(ctx.Err(), "limiter cleaner worker done"))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RateLimiter) removeUnusedLimiters(lastUseThreshold time.Duration) int {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
limiterCount := len(r.inMemLimiters)
|
||||
for k, v := range r.inMemLimiters {
|
||||
if time.Since(v.lastUse) >= lastUseThreshold {
|
||||
delete(r.inMemLimiters, k)
|
||||
}
|
||||
}
|
||||
|
||||
return limiterCount - len(r.inMemLimiters)
|
||||
}
|
||||
|
||||
func (r *RateLimiter) Close() {
|
||||
r.cancelFn()
|
||||
}
|
||||
@@ -57,5 +57,10 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.DailyLimiter.Get,
|
||||
}, {
|
||||
Path: "isp-lock-service/rate_limit/inmem",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.RateLimiter.LimitInMem,
|
||||
}}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
type limiterRepo interface {
|
||||
Limit(ctx context.Context, key string, maxRps int) (*domain.RateLimiterResponse, error)
|
||||
LimitInMem(ctx context.Context, key string, maxRps int) (*domain.InMemRateLimiterResponse, error)
|
||||
}
|
||||
|
||||
type rateLimiter struct {
|
||||
@@ -21,3 +22,7 @@ func NewRateLimiter(repo limiterRepo) rateLimiter {
|
||||
func (s rateLimiter) Limit(ctx context.Context, req domain.RateLimiterRequest) (*domain.RateLimiterResponse, error) {
|
||||
return s.repo.Limit(ctx, req.Key, req.MaxRps) // nolint:wrapcheck
|
||||
}
|
||||
|
||||
func (s rateLimiter) LimitInMem(ctx context.Context, req domain.RateLimiterRequest) (*domain.InMemRateLimiterResponse, error) {
|
||||
return s.repo.LimitInMem(ctx, req.Key, req.MaxRps) // nolint:wrapcheck
|
||||
}
|
||||
Reference in new issue
Block a user