From 9e994624b709400d9a068f0e9d9b2c0edc71a0be Mon Sep 17 00:00:00 2001 From: Leonid Nikolaev Date: Wed, 1 Feb 2023 12:48:18 +0300 Subject: [PATCH] MSP-1388 [ref] repository/locker.go --- repository/locker.go | 77 ++++++++++++++++---------------------------- service/locker.go | 8 ++--- tests/rc_test.go | 26 +++++++-------- 3 files changed, 43 insertions(+), 68 deletions(-) diff --git a/repository/locker.go b/repository/locker.go index 89d0def..57cc589 100644 --- a/repository/locker.go +++ b/repository/locker.go @@ -3,6 +3,7 @@ package repository import ( "context" "fmt" + "strconv" "time" "isp-lock-service/conf" @@ -47,21 +48,40 @@ func NewLocker(logger log.Logger, cfg conf.Remote) Locker { } } -func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) { +func (l Locker) Lock(ctx context.Context, key string, ttl int) (*domain.LockResponse, error) { l.logger.Debug(ctx, "call repo.Lock") - val, err := l.RCLock(req.Key, time.Duration(req.TTLInSec)*time.Second) - if err != nil { - return nil, errors.WithMessage(err, "ошибка в lock") + + key = makeKey(l.prefix, key) + + l.logger.Debug(context.Background(), "пробуем залочить "+key+" на "+strconv.Itoa(ttl)+" сек.") + + mtx := l.cli.NewMutex(key, redsync.WithExpiry(time.Duration(ttl)*time.Second)) + + if err := mtx.Lock(); err != nil { + return nil, errors.WithMessagef(err, "fail lock. key=%s", key) } - return &domain.LockResponse{LockKey: val}, nil + + value := mtx.Value() + l.logger.Debug(context.Background(), "ключ для разблокировки "+value) + + return &domain.LockResponse{LockKey: value}, nil } -func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) { +func (l Locker) UnLock(ctx context.Context, key, lockKey string) (*domain.LockResponse, error) { l.logger.Debug(ctx, "call repo.UnLock") - _, err := l.RCUnLock(req.Key, req.LockKey) + + key = makeKey(l.prefix, key) + + l.logger.Debug(context.Background(), "пробуем разлочить "+key+"+"+lockKey) + + ok, err := l.cli.NewMutex(key, redsync.WithValue(lockKey)).Unlock() + + l.logger.Debug(context.Background(), fmt.Sprint("ok=", ok)) + if err != nil { - return &domain.LockResponse{}, errors.WithMessage(err, "ошибка в unlock") + return nil, errors.WithMessagef(err, "fail unlock. key=%s", key) } + return &domain.LockResponse{}, nil } @@ -69,47 +89,6 @@ func makeKey(prefix, key string) string { return prefix + "::" + key } -// RCLock - функция установки лока по ключу -// -// key - суффикс ключа -// ttl - время жизни ключа -// -// Возвращает ключ для разблокировки -func (rc *Locker) RCLock(key string, ttl time.Duration) (string, error) { - key = makeKey(rc.prefix, key) - - rc.logger.Debug(context.Background(), "пробуем залочить "+key+" на "+ttl.String()) - - mtx := rc.cli.NewMutex(key, redsync.WithExpiry(ttl)) - - if err := mtx.Lock(); err != nil { - // nolint: wrapcheck - return "", err - } - - value := mtx.Value() - rc.logger.Debug(context.Background(), "ключ для разблокировки "+value) - - return value, nil -} - -// RCUnLock - функция снятия лока по ключу -// -// key - суффикс ключа -// lockKey - ключ, полученный в ответе из функции Lock -func (rc *Locker) RCUnLock(key, lockKey string) (bool, error) { - key = makeKey(rc.prefix, key) - - rc.logger.Debug(context.Background(), "пробуем разлочить "+key+"+"+lockKey) - - ok, err := rc.cli.NewMutex(key, redsync.WithValue(lockKey)).Unlock() - - rc.logger.Debug(context.Background(), fmt.Sprint("ok=", ok)) - - // nolint: wrapcheck - return ok, err -} - func NewLockerWithClient(prefix string, l log.Logger, cli *goredislib.Client) (*Locker, error) { rc := redsync.New(goredis.NewPool(cli)) diff --git a/service/locker.go b/service/locker.go index 1dfbee1..462b73a 100644 --- a/service/locker.go +++ b/service/locker.go @@ -9,8 +9,8 @@ import ( ) type LockerRepo interface { - Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) - UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) + Lock(ctx context.Context, key string, ttlInSec int) (*domain.LockResponse, error) + UnLock(ctx context.Context, key, lockKey string) (*domain.LockResponse, error) } type Locker struct { @@ -21,13 +21,13 @@ type Locker struct { func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) { l.logger.Debug(ctx, "call srv.Lock") // nolint: wrapcheck - return l.repo.Lock(ctx, req) + return l.repo.Lock(ctx, req.Key, req.TTLInSec) } func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) { l.logger.Debug(ctx, "call srv.UnLock") // nolint: wrapcheck - return l.repo.UnLock(ctx, req) + return l.repo.UnLock(ctx, req.Key, req.LockKey) } func NewLocker(logger log.Logger, repo LockerRepo) Locker { diff --git a/tests/rc_test.go b/tests/rc_test.go index 8a27613..ee695f5 100644 --- a/tests/rc_test.go +++ b/tests/rc_test.go @@ -1,6 +1,7 @@ package tests_test import ( + "context" "fmt" "testing" "time" @@ -8,7 +9,6 @@ import ( "isp-lock-service/repository" "github.com/go-redis/redis/v8" - "github.com/go-redsync/redsync/v4" "github.com/integration-system/isp-kit/test" ) @@ -23,46 +23,42 @@ func NewRedis(test *test.Test) *redis.Client { func TestOne(t *testing.T) { tst, required := test.New(t) rcli := NewRedis(tst) + ctx := context.Background() r, err := repository.NewLockerWithClient("testPrefix", tst.Logger(), rcli) required.NoError(err) // success story key := time.Now().String() - l, err := r.RCLock(key, time.Second) + l, err := r.Lock(ctx, key, 1) required.NoError(err) - _, err = r.RCUnLock(key, l) + _, err = r.UnLock(ctx, key, l.LockKey) required.NoError(err) // look at wait - _, err = r.RCLock(key, time.Second) + _, err = r.Lock(ctx, key, 1) required.NoError(err) n := time.Now() - _, err = r.RCLock(key, time.Second) + _, err = r.Lock(ctx, key, 1) required.NoError(err) diff := time.Since(n) - if diff < time.Second { - t.Error("#2.3::error with second lock::", diff.String()) - } + required.Greater(diff, time.Second) // look at error - l, err = r.RCLock(key, 10*time.Second) + l, err = r.Lock(ctx, key, 10) required.NoError(err) - _, err = r.RCLock(key, time.Second) + _, err = r.Lock(ctx, key, 1) required.Error(err) if err != nil { - // nolint: errorlint - if _, ok := err.(redsync.ErrTaken); !ok { - t.Error("#3.3::", err) - } + required.Error(err, "fail lock") } - _, err = r.RCUnLock(key, l) + _, err = r.UnLock(ctx, key, l.LockKey) required.NoError(err) }