diff --git a/controller/locker.go b/controller/locker.go index 2297c32..c2ed792 100644 --- a/controller/locker.go +++ b/controller/locker.go @@ -10,6 +10,7 @@ import ( type LockerService interface { Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) + TryLock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) } @@ -39,6 +40,20 @@ func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockR return l.s.Lock(ctx, req) } +// TryLock +// @Tags locker +// @Summary однократная попытка взять лок без ретраев +// @Description Пытаемся взять лок один раз. В отличие от Lock, не делает повторных попыток. При успехе возвращаем ключ для разблокировки. +// @Param key query string true "строка для лока" +// @Param ttlInSec query int true "число секунд после которых блокировка снимется автоматически" +// @Accept json +// @Produce json +// @Success 200 {object} domain.LockResponse +// @Router /api/isp-lock-service/try_lock [POST] +func (l Locker) TryLock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) { + return l.s.TryLock(ctx, req) +} + // UnLock // @Tags locker // @Summary снимаем лок со строки diff --git a/repository/locker.go b/repository/locker.go index 2c46cd2..07af7d9 100644 --- a/repository/locker.go +++ b/repository/locker.go @@ -77,6 +77,23 @@ func (l Locker) Lock(ctx context.Context, key string, ttl int) (*domain.LockResp return &domain.LockResponse{LockKey: value}, nil } +func (l Locker) TryLock(_ context.Context, key string, ttl int) (*domain.LockResponse, error) { + key = makeKey(l.prefix, key) + + mtx := l.cli.NewMutex(key, + redsync.WithExpiry(time.Duration(ttl)*time.Second), + ) + + err := mtx.TryLock() + if err != nil { + return nil, errors.WithMessagef(err, "fail lock. key=%s", key) + } + + value := mtx.Value() + + return &domain.LockResponse{LockKey: value}, nil +} + func (l Locker) UnLock(ctx context.Context, key, lockKey string) (*domain.LockResponse, error) { key = makeKey(l.prefix, key) diff --git a/routes/routes.go b/routes/routes.go index d10365a..812da46 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -2,10 +2,12 @@ package routes import ( "github.com/txix-open/isp-kit/cluster" + "github.com/txix-open/isp-kit/common_endpoints" "github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc/endpoint" "isp-lock-service/controller" + "isp-lock-service/docs" ) type Controllers struct { @@ -15,7 +17,7 @@ type Controllers struct { } func EndpointDescriptors() []cluster.EndpointDescriptor { - return endpointDescriptors(Controllers{}) + return concatDescriptors(endpointDescriptors(Controllers{}), commonEndpoints()) } func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux { @@ -23,6 +25,9 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux { for _, descriptor := range endpointDescriptors(c) { muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) } + for _, descriptor := range commonEndpoints() { + muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) + } return muxer } @@ -32,6 +37,11 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { Inner: true, UserAuthRequired: false, Handler: c.Locker.Lock, + }, { + Path: "isp-lock-service/try_lock", + Inner: true, + UserAuthRequired: false, + Handler: c.Locker.TryLock, }, { Path: "isp-lock-service/unlock", Inner: true, @@ -64,3 +74,17 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { Handler: c.RateLimiter.LimitInMem, }} } + +func commonEndpoints() []cluster.EndpointDescriptor { + return common_endpoints.CommonEndpoints("isp-lock-service", + common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson), + ) +} + +func concatDescriptors(descs ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { + result := make([]cluster.EndpointDescriptor, 0) + for _, desc := range descs { + result = append(result, desc...) + } + return result +} diff --git a/service/locker.go b/service/locker.go index ff1fb5b..db9947e 100644 --- a/service/locker.go +++ b/service/locker.go @@ -10,6 +10,7 @@ import ( type LockerRepo interface { Lock(ctx context.Context, key string, ttlInSec int) (*domain.LockResponse, error) + TryLock(ctx context.Context, key string, ttlInSec int) (*domain.LockResponse, error) UnLock(ctx context.Context, key, lockKey string) (*domain.LockResponse, error) } @@ -30,6 +31,11 @@ func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockR return l.repo.Lock(ctx, req.Key, req.TTLInSec) } +func (l Locker) TryLock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) { + // nolint: wrapcheck + return l.repo.TryLock(ctx, req.Key, req.TTLInSec) +} + func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) { // nolint: wrapcheck return l.repo.UnLock(ctx, req.Key, req.LockKey) diff --git a/tests/rate_limiter_test.go b/tests/rate_limiter_test.go index 8b7985e..9031b91 100644 --- a/tests/rate_limiter_test.go +++ b/tests/rate_limiter_test.go @@ -137,7 +137,7 @@ func TestRateLimiterInMemInfiniteKey(t *testing.T) { resp, err := r.LimitInMem(ctx, key, 1, true) required.NoError(err) - required.True(resp.PassAfter > 0) + required.Positive(resp.PassAfter) } func TestRateLimiterInMemLowRPSCase(t *testing.T) { diff --git a/tests/rc_test.go b/tests/rc_test.go index f492cb0..d804725 100644 --- a/tests/rc_test.go +++ b/tests/rc_test.go @@ -2,6 +2,8 @@ package tests_test import ( "fmt" + "sync" + "sync/atomic" "testing" "time" @@ -21,7 +23,7 @@ func NewRedis(test *test.Test) *redis.Client { return redis.NewClient(&redis.Options{Addr: addr}) } -func TestOne(t *testing.T) { +func TestOneLock(t *testing.T) { t.Parallel() tst, required := test.New(t) @@ -65,6 +67,86 @@ func TestOne(t *testing.T) { required.NoError(err) } +func TestOneTryLock(t *testing.T) { + t.Parallel() + + tst, required := test.New(t) + rcli := NewRedis(tst) + ctx := t.Context() + + r := repository.NewLocker(tst.Logger(), rcli, conf.Redis{Prefix: "testPrefix"}, conf.LockSettings{}) + + // success story + key := time.Now().String() + l, err := r.TryLock(ctx, key, 1) + required.NoError(err) + + _, err = r.UnLock(ctx, key, l.LockKey) + required.NoError(err) + + // second lock — no wait, immediate error on conflict + resp, err := r.TryLock(ctx, key, 1) + required.NoError(err) + + _, err = r.TryLock(ctx, key, 1) + required.Error(err) + if err != nil { + required.Error(err, "fail lock") + } + + _, err = r.UnLock(ctx, key, resp.LockKey) + required.NoError(err) +} + +func TestTryLockAfterTTL(t *testing.T) { + t.Parallel() + + tst, required := test.New(t) + rcli := NewRedis(tst) + ctx := t.Context() + + r := repository.NewLocker(tst.Logger(), rcli, conf.Redis{Prefix: "testPrefix"}, conf.LockSettings{}) + + key := time.Now().String() + _, err := r.TryLock(ctx, key, 1) + required.NoError(err) + + time.Sleep(1200 * time.Millisecond) + + l2, err := r.TryLock(ctx, key, 1) + required.NoError(err) + + _, err = r.UnLock(ctx, key, l2.LockKey) + required.NoError(err) +} + +func TestTryLockConcurrency(t *testing.T) { + t.Parallel() + tst, required := test.New(t) + redis := NewRedis(tst) + + r := repository.NewLocker(tst.Logger(), redis, conf.Redis{Prefix: "testPrefix"}, conf.LockSettings{}) + + var successCount atomic.Int64 + + group := new(sync.WaitGroup) + for range 10000 { + group.Add(1) + group.Go(func() { + defer group.Done() + resp, err := r.TryLock(t.Context(), "key", 5) + if err != nil { + return + } + successCount.Add(1) + _, err = r.UnLock(t.Context(), "key", resp.LockKey) + required.NoError(err) + }) + } + group.Wait() + required.Positive(successCount.Load()) +} + func TestConcurrency(t *testing.T) { t.Parallel() tst, required := test.New(t)