-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapter.go
94 lines (72 loc) · 1.97 KB
/
adapter.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package redigo
import (
"context"
"errors"
"time"
rsredigo "github.com/go-redsync/redsync/v4/redis/redigo"
"github.com/gomodule/redigo/redis"
"github.com/pwnedgod/wracha/adapter"
"github.com/pwnedgod/wracha/adapter/util/mutex"
"github.com/pwnedgod/wracha/adapter/util/mutex/redsync"
)
type redigoAdapter struct {
pool *redis.Pool
locker mutex.Locker
// Deprecated
multiMutex *mutex.MultiMutex
}
func NewAdapter(pool *redis.Pool) adapter.Adapter {
return &redigoAdapter{
pool: pool,
locker: redsync.NewLocker(rsredigo.NewPool(pool)),
multiMutex: mutex.NewMultiMutex(redsync.NewMutexFactory(rsredigo.NewPool(pool))),
}
}
func (a redigoAdapter) Exists(ctx context.Context, key string) (bool, error) {
conn := a.pool.Get()
defer a.pool.Close()
count, err := redis.Int64(conn.Do(CommandExists, key))
if err != nil {
return false, err
}
return count != 0, nil
}
func (a redigoAdapter) Get(ctx context.Context, key string) ([]byte, error) {
conn := a.pool.Get()
defer a.pool.Close()
data, err := redis.Bytes(conn.Do(CommandGet, key))
if err != nil {
if errors.Is(err, redis.ErrNil) {
err = adapter.ErrNotFound
}
return nil, err
}
return data, nil
}
func (a redigoAdapter) Set(ctx context.Context, key string, ttl time.Duration, value []byte) error {
args := []any{
key, value,
}
if ttl > 0 {
args = append(args, formatExpirationArgs(ttl)...)
}
conn := a.pool.Get()
defer a.pool.Close()
_, err := conn.Do(CommandSet, args...)
return err
}
func (a redigoAdapter) Delete(ctx context.Context, key string) error {
conn := a.pool.Get()
defer a.pool.Close()
_, err := conn.Do(CommandDel, key)
return err
}
func (a redigoAdapter) Lock(ctx context.Context, key string) error {
return a.multiMutex.Lock(ctx, key)
}
func (a redigoAdapter) Unlock(ctx context.Context, key string) error {
return a.multiMutex.Unlock(ctx, key)
}
func (a redigoAdapter) ObtainLock(ctx context.Context, key string) (adapter.Lock, error) {
return a.locker.Obtain(ctx, key)
}