/
redis_persistence.go
65 lines (50 loc) · 1.42 KB
/
redis_persistence.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package mocks
import (
"github.com/brienze1/crypto-robot-validator/internal/validator/integration/exceptions"
"github.com/brienze1/crypto-robot-validator/pkg/custom_error"
)
type redisPersistence struct {
LockCounter int
LockError error
UnlockCounter int
UnlockError error
lock map[string]string
}
func RedisPersistence() *redisPersistence {
return &redisPersistence{
lock: make(map[string]string),
}
}
func (r *redisPersistence) Lock(key string) custom_error.BaseErrorAdapter {
r.LockCounter++
if r.LockError != nil {
return exceptions.RedisPersistenceLockError(r.LockError, "Lock error", false)
}
if _, isLocked := r.lock[key]; isLocked {
return exceptions.RedisPersistenceLockError(r.LockError, "key is already locked", true)
}
r.lock[key] = key
return nil
}
func (r *redisPersistence) Unlock(key string) custom_error.BaseErrorAdapter {
r.UnlockCounter++
if r.UnlockError != nil {
return exceptions.RedisPersistenceLockError(r.UnlockError, "Unlock error", true)
}
if _, isLocked := r.lock[key]; !isLocked {
return exceptions.RedisPersistenceLockError(r.LockError, "key is already unlocked", true)
}
delete(r.lock, key)
return nil
}
func (r *redisPersistence) IsLocked(key string) bool {
_, isLocked := r.lock[key]
return isLocked
}
func (r *redisPersistence) Reset() {
r.LockCounter = 0
r.LockError = nil
r.UnlockCounter = 0
r.UnlockError = nil
r.lock = make(map[string]string)
}