From b6b498e20800f82afcb56ad7b5ab5ff8cd79d3f7 Mon Sep 17 00:00:00 2001 From: txix Date: Fri, 10 Jan 2025 10:59:06 +0300 Subject: [PATCH] 2025-01-10 10:59:06: merge [main:eec0f5de668f1e516250795c3bdac06c746c787e]; --- .version | 2 +- CHANGELOG.md | 3 + assembly/assembly.go | 35 +++++--- assembly/locator.go | 18 +++-- conf/default_remote_config.json | 4 + conf/remote.go | 10 ++- controller/rate_limiter.go | 5 ++ domain/rate_limiter.go | 4 + go.mod | 51 ++++++------ go.sum | 107 +++++++++++++------------ repository/rate_limiter.go | 94 ++++++++++++++++++++-- routes/routes.go | 5 ++ service/rate_limiter.go | 5 ++ tests/rate_limiter_test.go | 136 ++++++++++++++++++++++++++++++-- 14 files changed, 373 insertions(+), 106 deletions(-) diff --git a/.version b/.version index 9df886c..bc80560 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.4.2 +1.5.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index ea531b1..e11deca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +# v1.5.0 +* добавлен метод `/rate_limit/inmem` +* обновлены зависимости # v1.4.1 * добавлена обработка ошибки при закрытии клиента `redis` # v1.4.0 diff --git a/assembly/assembly.go b/assembly/assembly.go index 6866194..2ba4bb5 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -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 + }), } } diff --git a/assembly/locator.go b/assembly/locator.go index 9b29bfa..2c88b47 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -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, + } } diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 5966c0a..eb0de2a 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -5,5 +5,9 @@ "password": "", "db": 0, "prefix": "isp-lock-service" + }, + "inMemLimiter": { + "lastUseThresholdInSec": 10, + "clearPeriodInSec": 60 } } diff --git a/conf/remote.go b/conf/remote.go index fa922b0..007f294 100644 --- a/conf/remote.go +++ b/conf/remote.go @@ -17,8 +17,9 @@ func init() { } type Remote struct { - LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"` - Redis Redis `schema:"Настройки redis"` + LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"` + Redis Redis `schema:"Настройки redis"` + InMemLimiter InMemLimiter `schema:"Настройка rate limiter в оперативной памяти"` } type Redis struct { @@ -37,3 +38,8 @@ type RedisSentinel struct { Username string `schema:"Имя пользователя в sentinel"` Password string `schema:"Пароль в sentinel"` } + +type InMemLimiter struct { + ClearPeriodInSec int `validate:"required,min=1" schema:"Интервал очистки неиспользуемых лимитеров в секундах"` + LastUseThresholdInSec int `validate:"required,min=1" schema:"Пороговое значение в секундах, после которого лимитер считается неиспользуемым"` +} diff --git a/controller/rate_limiter.go b/controller/rate_limiter.go index 0995f71..d84141a 100644 --- a/controller/rate_limiter.go +++ b/controller/rate_limiter.go @@ -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) +} diff --git a/domain/rate_limiter.go b/domain/rate_limiter.go index 5d4a9b5..14413ff 100644 --- a/domain/rate_limiter.go +++ b/domain/rate_limiter.go @@ -14,3 +14,7 @@ type RateLimiterResponse struct { Remaining int RetryAfter time.Duration } + +type InMemRateLimiterResponse struct { + PassAfter time.Duration +} diff --git a/go.mod b/go.mod index bc8fd06..7dfa697 100644 --- a/go.mod +++ b/go.mod @@ -7,9 +7,10 @@ require ( github.com/go-redsync/redsync/v4 v4.13.0 github.com/pkg/errors v0.9.1 github.com/redis/go-redis/v9 v9.6.1 - github.com/txix-open/isp-kit v1.38.1 + github.com/txix-open/isp-kit v1.41.1 github.com/txix-open/jsonschema v1.2.0 - golang.org/x/sync v0.8.0 + golang.org/x/sync v0.9.0 + golang.org/x/time v0.8.0 ) require ( @@ -21,19 +22,19 @@ require ( github.com/coder/websocket v1.8.12 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/gabriel-vasile/mimetype v1.4.5 // indirect - github.com/getsentry/sentry-go v0.29.0 // indirect - github.com/go-faker/faker/v4 v4.4.2 // indirect + github.com/gabriel-vasile/mimetype v1.4.7 // indirect + github.com/getsentry/sentry-go v0.29.1 // indirect + github.com/go-faker/faker/v4 v4.5.0 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.17.9 // indirect + github.com/klauspost/compress v1.17.11 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -41,35 +42,35 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.20.4 // indirect + github.com/prometheus/client_golang v1.20.5 // indirect github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.59.1 // indirect + github.com/prometheus/common v0.60.1 // indirect github.com/prometheus/procfs v0.15.1 // indirect - github.com/stretchr/testify v1.9.0 // indirect + github.com/stretchr/testify v1.10.0 // indirect github.com/txix-open/bellows v1.2.0 // indirect - github.com/txix-open/etp/v3 v3.2.0 // indirect + github.com/txix-open/etp/v4 v4.0.1 // indirect github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - go.opentelemetry.io/otel v1.30.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.30.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.30.0 // indirect - go.opentelemetry.io/otel/metric v1.30.0 // indirect - go.opentelemetry.io/otel/sdk v1.30.0 // indirect - go.opentelemetry.io/otel/trace v1.30.0 // indirect + go.opentelemetry.io/otel v1.32.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.32.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0 // indirect + go.opentelemetry.io/otel/metric v1.32.0 // indirect + go.opentelemetry.io/otel/sdk v1.32.0 // indirect + go.opentelemetry.io/otel/trace v1.32.0 // indirect go.opentelemetry.io/proto/otlp v1.3.1 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/crypto v0.27.0 // indirect - golang.org/x/net v0.29.0 // indirect - golang.org/x/sys v0.25.0 // indirect - golang.org/x/text v0.18.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 // indirect - google.golang.org/grpc v1.67.0 // indirect - google.golang.org/protobuf v1.34.2 // indirect + golang.org/x/crypto v0.29.0 // indirect + golang.org/x/net v0.31.0 // indirect + golang.org/x/sys v0.27.0 // indirect + golang.org/x/text v0.20.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20241118233622-e639e219e697 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697 // indirect + google.golang.org/grpc v1.68.0 // indirect + google.golang.org/protobuf v1.35.2 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 374b7c0..d6cb2f8 100644 --- a/go.sum +++ b/go.sum @@ -21,14 +21,14 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= -github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= -github.com/getsentry/sentry-go v0.29.0 h1:YtWluuCFg9OfcqnaujpY918N/AhCCwarIDWOYSBAjCA= -github.com/getsentry/sentry-go v0.29.0/go.mod h1:jhPesDAL0Q0W2+2YEuVOvdWmVtdsr1+jtBrlDEVWwLY= +github.com/gabriel-vasile/mimetype v1.4.7 h1:SKFKl7kD0RiPdbht0s7hFtjl489WcQ1VyPW8ZzUMYCA= +github.com/gabriel-vasile/mimetype v1.4.7/go.mod h1:GDlAgAyIRT27BhFl53XNAFtfjzOkLaF35JdEG0P7LtU= +github.com/getsentry/sentry-go v0.29.1 h1:DyZuChN8Hz3ARxGVV8ePaNXh1dQ7d76AiB117xcREwA= +github.com/getsentry/sentry-go v0.29.1/go.mod h1:x3AtIzN01d6SiWkderzaH28Tm0lgkafpJ5Bm3li39O0= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-faker/faker/v4 v4.4.2 h1:96WeU9QKEqRUVYdjHquY2/5bAqmVM0IfGKHV5mbfqmQ= -github.com/go-faker/faker/v4 v4.4.2/go.mod h1:4K3v4AbKXYNHMQNaREMc9/kRB9j5JJzpFo6KHRvrcIw= +github.com/go-faker/faker/v4 v4.5.0 h1:ARzAY2XoOL9tOUK+KSecUQzyXQsUaZHefjyF8x6YFHc= +github.com/go-faker/faker/v4 v4.5.0/go.mod h1:p3oq1GRjG2PZ7yqeFFfQI20Xm61DoBDlCA8RiSyZ48M= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -50,6 +50,8 @@ github.com/go-redis/redis_rate/v10 v10.0.1 h1:calPxi7tVlxojKunJwQ72kwfozdy25RjA0 github.com/go-redis/redis_rate/v10 v10.0.1/go.mod h1:EMiuO9+cjRkR7UvdvwMO7vbgqJkltQHtwbdIQvaBKIU= github.com/go-redsync/redsync/v4 v4.13.0 h1:49X6GJfnbLGaIpBBREM/zA4uIMDXKAh1NDkvQ1EkZKA= github.com/go-redsync/redsync/v4 v4.13.0/go.mod h1:HMW4Q224GZQz6x1Xc7040Yfgacukdzu7ifTDAKiyErQ= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= @@ -57,8 +59,8 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 h1:TmHmbvxPmaegwhDubVz0lICL0J5Ka2vwTzhoePEXsGE= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0/go.mod h1:qztMSjm835F2bXf+5HKAPIS5qsmQDqZna/PgVt4rWtI= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -67,8 +69,8 @@ github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9 github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= -github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= +github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -94,12 +96,12 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.20.4 h1:Tgh3Yr67PaOv/uTqloMsCEdeuFTatm5zIq5+qNN23vI= -github.com/prometheus/client_golang v1.20.4/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= +github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= +github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJoX0= -github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0= +github.com/prometheus/common v0.60.1 h1:FUas6GcOw66yB/73KC+BOZoFJmbo/1pojoILArPAaSc= +github.com/prometheus/common v0.60.1/go.mod h1:h0LYf1R1deLSKtD4Vdg8gy4RuOvENW2J/h19V5NADQw= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= @@ -108,8 +110,8 @@ github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0 github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA= github.com/redis/rueidis v1.0.19 h1:s65oWtotzlIFN8eMPhyYwxlwLR1lUdhza2KtWprKYSo= github.com/redis/rueidis v1.0.19/go.mod h1:8B+r5wdnjwK3lTFml5VtxjzGOQAC+5UmujoD12pDrEo= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -118,18 +120,19 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 h1:QVqDTf3h2WHt08YuiTGPZLls0Wq99X9bWd0Q5ZSBesM= github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203/go.mod h1:oqN97ltKNihBbwlX8dLpwxCl3+HnXKV/R0e+sRLd9C8= github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY= github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o= -github.com/txix-open/etp/v3 v3.2.0 h1:EgTchT8VtCYV1iEo/y4jII3/NybrXiQDE0y6pmS350M= -github.com/txix-open/etp/v3 v3.2.0/go.mod h1:lgen0TJmiturgBhvlxH1/PQ7iLL/OebKbxPAQYkuKI0= +github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA= +github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8= github.com/txix-open/grmq v1.6.0 h1:V4QRb0sI2CMfdMaMsFGvGvUIDGad5vr3khNU7A3LlP8= github.com/txix-open/grmq v1.6.0/go.mod h1:s+NNNv42+32yLpjvl2tpqtyBbMB9e7kKFee3lfa/dyo= -github.com/txix-open/isp-kit v1.38.1 h1:IYsiW2xc06//xQsWcHX9A1GXCGTXQRXbUqotcxa6eDY= -github.com/txix-open/isp-kit v1.38.1/go.mod h1:uVn5y71Rg8jlFjFK3+QCh9uw1O7mcK+1grCNFZRWhME= +github.com/txix-open/isp-kit v1.41.1 h1:Ne+JwEJjYCFNVLKQho2xmDVpHY50jcgivulsiE3m83g= +github.com/txix-open/isp-kit v1.41.1/go.mod h1:I8qDM+HVuCJrzsvFcRBIyQ0wPvGC3Ua6YMYajKSlvT8= github.com/txix-open/jsonschema v1.2.0 h1:B8TrdSsPhDvYv67oi/LVqf7/+PuqFlMsNwUzGeHfl1s= github.com/txix-open/jsonschema v1.2.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To= @@ -143,18 +146,18 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -go.opentelemetry.io/otel v1.30.0 h1:F2t8sK4qf1fAmY9ua4ohFS/K+FUuOPemHUIXHtktrts= -go.opentelemetry.io/otel v1.30.0/go.mod h1:tFw4Br9b7fOS+uEao81PJjVMjW/5fvNCbpsDIXqP0pc= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.30.0 h1:lsInsfvhVIfOI6qHVyysXMNDnjO9Npvl7tlDPJFBVd4= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.30.0/go.mod h1:KQsVNh4OjgjTG0G6EiNi1jVpnaeeKsKMRwbLN+f1+8M= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.30.0 h1:umZgi92IyxfXd/l4kaDhnKgY8rnN/cZcF1LKc6I8OQ8= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.30.0/go.mod h1:4lVs6obhSVRb1EW5FhOuBTyiQhtRtAnnva9vD3yRfq8= -go.opentelemetry.io/otel/metric v1.30.0 h1:4xNulvn9gjzo4hjg+wzIKG7iNFEaBMX00Qd4QIZs7+w= -go.opentelemetry.io/otel/metric v1.30.0/go.mod h1:aXTfST94tswhWEb+5QjlSqG+cZlmyXy/u8jFpor3WqQ= -go.opentelemetry.io/otel/sdk v1.30.0 h1:cHdik6irO49R5IysVhdn8oaiR9m8XluDaJAs4DfOrYE= -go.opentelemetry.io/otel/sdk v1.30.0/go.mod h1:p14X4Ok8S+sygzblytT1nqG98QG2KYKv++HE0LY/mhg= -go.opentelemetry.io/otel/trace v1.30.0 h1:7UBkkYzeg3C7kQX8VAidWh2biiQbtAKjyIML8dQ9wmc= -go.opentelemetry.io/otel/trace v1.30.0/go.mod h1:5EyKqTzzmyqB9bwtCCq6pDLktPK6fmGf/Dph+8VI02o= +go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= +go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.32.0 h1:IJFEoHiytixx8cMiVAO+GmHR6Frwu+u5Ur8njpFO6Ac= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.32.0/go.mod h1:3rHrKNtLIoS0oZwkY2vxi+oJcwFRWdtUyRII+so45p8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0 h1:cMyu9O88joYEaI47CnQkxO1XZdpoTF9fEnW2duIddhw= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0/go.mod h1:6Am3rn7P9TVVeXYG+wtcGE7IE1tsQ+bP3AuWcKt/gOI= +go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= +go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= +go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= +go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= +go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= +go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -163,24 +166,26 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= -golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= -golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= -golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= -golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= -golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= -golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= -google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1 h1:hjSy6tcFQZ171igDaN5QHOw2n6vx40juYbC/x67CEhc= -google.golang.org/genproto/googleapis/api v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:qpvKtACPCQhAdu3PyQgV4l3LMXZEtft7y8QcarRsp9I= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 h1:pPJltXNxVzT4pK9yD8vR9X75DaWYYmLGMsEvBfFQZzQ= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= -google.golang.org/grpc v1.67.0 h1:IdH9y6PF5MPSdAntIcpjQ+tXO41pcQsfZV2RxtQgVcw= -google.golang.org/grpc v1.67.0/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA= -google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= -google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ= +golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg= +golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo= +golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM= +golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ= +golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= +golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= +golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= +golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= +golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +google.golang.org/genproto/googleapis/api v0.0.0-20241118233622-e639e219e697 h1:pgr/4QbFyktUv9CtQ/Fq4gzEE6/Xs7iCXbktaGzLHbQ= +google.golang.org/genproto/googleapis/api v0.0.0-20241118233622-e639e219e697/go.mod h1:+D9ySVjN8nY8YCVjc5O7PZDIdZporIDY3KaGfJunh88= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697 h1:LWZqQOEjDyONlF1H6afSWpAL/znlREo2tHfLoe+8LMA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU= +google.golang.org/grpc v1.68.0 h1:aHQeeJbo8zAkAa3pRzrVjZlbz6uSfeOXlJNQM0RAbz0= +google.golang.org/grpc v1.68.0/go.mod h1:fmSPC5AsjSBCK54MyHRx48kpOti1/jRfOlwEWywNjWA= +google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io= +google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/repository/rate_limiter.go b/repository/rate_limiter.go index 118db12..a44b5cc 100644 --- a/repository/rate_limiter.go +++ b/repository/rate_limiter.go @@ -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() +} diff --git a/routes/routes.go b/routes/routes.go index d4e6783..d10365a 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -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, }} } diff --git a/service/rate_limiter.go b/service/rate_limiter.go index eeb053e..bc999d0 100644 --- a/service/rate_limiter.go +++ b/service/rate_limiter.go @@ -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 +} diff --git a/tests/rate_limiter_test.go b/tests/rate_limiter_test.go index 75acaef..78c7cce 100644 --- a/tests/rate_limiter_test.go +++ b/tests/rate_limiter_test.go @@ -16,14 +16,22 @@ func TestRateLimiter(t *testing.T) { t.Parallel() tst, required := test.New(t) redis := NewRedis(tst) - r := repository.NewRateLimiter(tst.Logger(), redis, conf.Redis{Prefix: "test"}) + r := repository.NewRateLimiter(tst.Logger(), redis, conf.Remote{ + Redis: conf.Redis{Prefix: "test"}, + InMemLimiter: conf.InMemLimiter{ + ClearPeriodInSec: 10, + LastUseThresholdInSec: 10, + }, + }) + tst.T().Cleanup(r.Close) var ( maxRps = 5 key = "key" + ctx = context.Background() ) for i := range maxRps { - resp, err := r.Limit(context.Background(), key, maxRps) + resp, err := r.Limit(ctx, key, maxRps) required.NoError(err) exp := &domain.RateLimiterResponse{ Allow: true, @@ -33,7 +41,7 @@ func TestRateLimiter(t *testing.T) { required.EqualValues(exp, resp) } - resp, err := r.Limit(context.Background(), key, maxRps) + resp, err := r.Limit(ctx, key, maxRps) required.NoError(err) exp := &domain.RateLimiterResponse{ Allow: false, @@ -44,7 +52,7 @@ func TestRateLimiter(t *testing.T) { required.EqualValues(exp, resp) time.Sleep(time.Second) - resp, err = r.Limit(context.Background(), key, maxRps) + resp, err = r.Limit(ctx, key, maxRps) required.NoError(err) exp = &domain.RateLimiterResponse{ Allow: true, @@ -55,7 +63,7 @@ func TestRateLimiter(t *testing.T) { for range 1000 { key := fake.It[string]() - resp, err := r.Limit(context.Background(), key, 1) + resp, err := r.Limit(ctx, key, 1) required.NoError(err) exp := &domain.RateLimiterResponse{ Allow: true, @@ -65,3 +73,121 @@ func TestRateLimiter(t *testing.T) { required.EqualValues(exp, resp) } } + +func TestRateLimiterInMem(t *testing.T) { + t.Parallel() + tst, required := test.New(t) + r := repository.NewRateLimiter(tst.Logger(), nil, conf.Remote{ + InMemLimiter: conf.InMemLimiter{ + ClearPeriodInSec: 10, + LastUseThresholdInSec: 10, + }, + }) + tst.T().Cleanup(r.Close) + + var ( + maxRps = 5 + reqInterval = time.Second / time.Duration(maxRps) + key = "key" + ctx = context.Background() + ) + for i := range 2 * maxRps { + resp, err := r.LimitInMem(ctx, key, maxRps) + required.NoError(err) + expPassAfter := reqInterval * time.Duration(i) + required.True(resp.PassAfter <= expPassAfter) + } + + for range 1000 { + key := fake.It[string]() + resp, err := r.LimitInMem(ctx, key, 1) + required.NoError(err) + required.True(resp.PassAfter <= 0) + } +} + +func BenchmarkRateLimiter(b *testing.B) { + tst, _ := test.New(new(testing.T)) + redis := NewRedis(tst) + r := repository.NewRateLimiter(tst.Logger(), redis, conf.Remote{ + Redis: conf.Redis{Prefix: "test"}, + InMemLimiter: conf.InMemLimiter{ + ClearPeriodInSec: 10, + LastUseThresholdInSec: 10, + }, + }) + b.Cleanup(r.Close) + + var ( + maxRps = 10 + key = fake.It[string]() + ctx = context.Background() + ) + b.ResetTimer() + + b.Run("Limit", func(b *testing.B) { + for range b.N { + _, err := r.Limit(ctx, key, maxRps) + if err != nil { + b.Fatalf("unexpected error: %v", err) + } + } + }) + + b.Run("LimitInMem", func(b *testing.B) { + for range b.N { + _, err := r.LimitInMem(ctx, key, maxRps) + if err != nil { + b.Fatalf("unexpected error: %v", err) + } + } + }) +} + +// nolint:gocognit +func BenchmarkRateLimiter2(b *testing.B) { + tst, _ := test.New(new(testing.T)) + redis := NewRedis(tst) + r := repository.NewRateLimiter(tst.Logger(), redis, conf.Remote{ + Redis: conf.Redis{Prefix: "test"}, + InMemLimiter: conf.InMemLimiter{ + ClearPeriodInSec: 10, + LastUseThresholdInSec: 10, + }, + }) + b.Cleanup(r.Close) + + var ( + keys = fake.It[[]string](fake.MinSliceSize(100), fake.MaxSliceSize(100)) + ctx = context.Background() + ) + b.ResetTimer() + + b.Run("Limit", func(b *testing.B) { + for range b.N { + for i := range 100 { + maxRps := i + 1 + for _, key := range keys { + _, err := r.Limit(ctx, key, maxRps) + if err != nil { + b.Fatalf("unexpected error for maxRps %d and key %s: %v", maxRps, key, err) + } + } + } + } + }) + + b.Run("LimitInMem", func(b *testing.B) { + for range b.N { + for i := range 100 { + maxRps := i + 1 + for _, key := range keys { + _, err := r.LimitInMem(ctx, key, maxRps) + if err != nil { + b.Fatalf("unexpected error for maxRps %d and key %s: %v", maxRps, key, err) + } + } + } + } + }) +}