MSP-7967 add try_lock method

This commit is contained in:
Павел Комиссаров committed 2026-07-02 09:54:42 +03:00
1 parent 4a4969d9b9
commit 8221c78a5c
6 files changed
+147 -3

No files matched your search

+15
View File
@@ -10,6 +10,7 @@ import (
type LockerService interface { type LockerService interface {
Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) 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) 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) 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 // UnLock
// @Tags locker // @Tags locker
// @Summary снимаем лок со строки // @Summary снимаем лок со строки
+17
View File
@@ -77,6 +77,23 @@ func (l Locker) Lock(ctx context.Context, key string, ttl int) (*domain.LockResp
return &domain.LockResponse{LockKey: value}, nil 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) { func (l Locker) UnLock(ctx context.Context, key, lockKey string) (*domain.LockResponse, error) {
key = makeKey(l.prefix, key) key = makeKey(l.prefix, key)
+25 -1
View File
@@ -2,10 +2,12 @@ package routes
import ( import (
"github.com/txix-open/isp-kit/cluster" "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"
"github.com/txix-open/isp-kit/grpc/endpoint" "github.com/txix-open/isp-kit/grpc/endpoint"
"isp-lock-service/controller" "isp-lock-service/controller"
"isp-lock-service/docs"
) )
type Controllers struct { type Controllers struct {
@@ -15,7 +17,7 @@ type Controllers struct {
} }
func EndpointDescriptors() []cluster.EndpointDescriptor { func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{}) return concatDescriptors(endpointDescriptors(Controllers{}), commonEndpoints())
} }
func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux { 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) { for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
} }
for _, descriptor := range commonEndpoints() {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer return muxer
} }
@@ -32,6 +37,11 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
Inner: true, Inner: true,
UserAuthRequired: false, UserAuthRequired: false,
Handler: c.Locker.Lock, Handler: c.Locker.Lock,
}, {
Path: "isp-lock-service/try_lock",
Inner: true,
UserAuthRequired: false,
Handler: c.Locker.TryLock,
}, { }, {
Path: "isp-lock-service/unlock", Path: "isp-lock-service/unlock",
Inner: true, Inner: true,
@@ -64,3 +74,17 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
Handler: c.RateLimiter.LimitInMem, 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
}
+6
View File
@@ -10,6 +10,7 @@ import (
type LockerRepo interface { type LockerRepo interface {
Lock(ctx context.Context, key string, ttlInSec int) (*domain.LockResponse, error) 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) 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) 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) { func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) {
// nolint: wrapcheck // nolint: wrapcheck
return l.repo.UnLock(ctx, req.Key, req.LockKey) return l.repo.UnLock(ctx, req.Key, req.LockKey)
+1 -1
View File
@@ -137,7 +137,7 @@ func TestRateLimiterInMemInfiniteKey(t *testing.T) {
resp, err := r.LimitInMem(ctx, key, 1, true) resp, err := r.LimitInMem(ctx, key, 1, true)
required.NoError(err) required.NoError(err)
required.True(resp.PassAfter > 0) required.Positive(resp.PassAfter)
} }
func TestRateLimiterInMemLowRPSCase(t *testing.T) { func TestRateLimiterInMemLowRPSCase(t *testing.T) {
+83 -1
View File
@@ -2,6 +2,8 @@ package tests_test
import ( import (
"fmt" "fmt"
"sync"
"sync/atomic"
"testing" "testing"
"time" "time"
@@ -21,7 +23,7 @@ func NewRedis(test *test.Test) *redis.Client {
return redis.NewClient(&redis.Options{Addr: addr}) return redis.NewClient(&redis.Options{Addr: addr})
} }
func TestOne(t *testing.T) { func TestOneLock(t *testing.T) {
t.Parallel() t.Parallel()
tst, required := test.New(t) tst, required := test.New(t)
@@ -65,6 +67,86 @@ func TestOne(t *testing.T) {
required.NoError(err) 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) { func TestConcurrency(t *testing.T) {
t.Parallel() t.Parallel()
tst, required := test.New(t) tst, required := test.New(t)