-
Notifications
You must be signed in to change notification settings - Fork 3
/
store_redis.go
86 lines (68 loc) · 1.81 KB
/
store_redis.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
package session
import (
"context"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"github.com/nais/wonderwall/pkg/metrics"
)
type redisSessionStore struct {
client redis.Cmdable
}
var _ Store = &redisSessionStore{}
func NewRedis(client redis.Cmdable) Store {
return &redisSessionStore{
client: client,
}
}
func (s *redisSessionStore) Read(ctx context.Context, key string) (*EncryptedData, error) {
encryptedData := &EncryptedData{}
err := metrics.ObserveRedisLatency(metrics.RedisOperationRead, func() error {
return s.client.Get(ctx, key).Scan(encryptedData)
})
if err == nil {
return encryptedData, nil
}
if errors.Is(err, redis.Nil) {
return nil, fmt.Errorf("%w: %w", ErrNotFound, err)
}
return nil, err
}
func (s *redisSessionStore) Write(ctx context.Context, key string, value *EncryptedData, expiration time.Duration) error {
err := metrics.ObserveRedisLatency(metrics.RedisOperationWrite, func() error {
return s.client.Set(ctx, key, value, expiration).Err()
})
if err != nil {
return err
}
return nil
}
func (s *redisSessionStore) Delete(ctx context.Context, keys ...string) error {
err := metrics.ObserveRedisLatency(metrics.RedisOperationDelete, func() error {
return s.client.Del(ctx, keys...).Err()
})
if err == nil {
return nil
}
if errors.Is(err, redis.Nil) {
return fmt.Errorf("%w: %w", ErrNotFound, err)
}
return err
}
func (s *redisSessionStore) Update(ctx context.Context, key string, value *EncryptedData) error {
_, err := s.Read(ctx, key)
if err != nil {
return err
}
err = metrics.ObserveRedisLatency(metrics.RedisOperationUpdate, func() error {
return s.client.Set(ctx, key, value, redis.KeepTTL).Err()
})
if err != nil {
return err
}
return nil
}
func (s *redisSessionStore) MakeLock(key string) Lock {
return NewRedisLock(s.client, key)
}