summaryrefslogtreecommitdiff
path: root/plugins/redis/kv.go
blob: 320b744379836e64f2f947173d367f6b998d4910 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package redis

import (
	"context"
	"strings"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/spiral/errors"
	"github.com/spiral/roadrunner/v2/plugins/config"
	"github.com/spiral/roadrunner/v2/plugins/kv"
	"github.com/spiral/roadrunner/v2/plugins/logger"
	kvv1 "github.com/spiral/roadrunner/v2/proto/kv/v1beta"
	"github.com/spiral/roadrunner/v2/utils"
)

type Driver struct {
	universalClient redis.UniversalClient
	log             logger.Logger
	cfg             *Config
}

func NewRedisDriver(log logger.Logger, key string, cfgPlugin config.Configurer) (kv.Storage, error) {
	const op = errors.Op("new_boltdb_driver")

	d := &Driver{
		log: log,
	}

	// will be different for every connected driver
	err := cfgPlugin.UnmarshalKey(key, &d.cfg)
	if err != nil {
		return nil, errors.E(op, err)
	}

	d.cfg.InitDefaults()
	d.log = log

	d.universalClient = redis.NewUniversalClient(&redis.UniversalOptions{
		Addrs:              d.cfg.Addrs,
		DB:                 d.cfg.DB,
		Username:           d.cfg.Username,
		Password:           d.cfg.Password,
		SentinelPassword:   d.cfg.SentinelPassword,
		MaxRetries:         d.cfg.MaxRetries,
		MinRetryBackoff:    d.cfg.MaxRetryBackoff,
		MaxRetryBackoff:    d.cfg.MaxRetryBackoff,
		DialTimeout:        d.cfg.DialTimeout,
		ReadTimeout:        d.cfg.ReadTimeout,
		WriteTimeout:       d.cfg.WriteTimeout,
		PoolSize:           d.cfg.PoolSize,
		MinIdleConns:       d.cfg.MinIdleConns,
		MaxConnAge:         d.cfg.MaxConnAge,
		PoolTimeout:        d.cfg.PoolTimeout,
		IdleTimeout:        d.cfg.IdleTimeout,
		IdleCheckFrequency: d.cfg.IdleCheckFreq,
		ReadOnly:           d.cfg.ReadOnly,
		RouteByLatency:     d.cfg.RouteByLatency,
		RouteRandomly:      d.cfg.RouteRandomly,
		MasterName:         d.cfg.MasterName,
	})

	return d, nil
}

// Has checks if value exists.
func (d *Driver) Has(keys ...string) (map[string]bool, error) {
	const op = errors.Op("redis_driver_has")
	if keys == nil {
		return nil, errors.E(op, errors.NoKeys)
	}

	m := make(map[string]bool, len(keys))
	for _, key := range keys {
		keyTrimmed := strings.TrimSpace(key)
		if keyTrimmed == "" {
			return nil, errors.E(op, errors.EmptyKey)
		}

		exist, err := d.universalClient.Exists(context.Background(), key).Result()
		if err != nil {
			return nil, err
		}
		if exist == 1 {
			m[key] = true
		}
	}
	return m, nil
}

// Get loads key content into slice.
func (d *Driver) Get(key string) ([]byte, error) {
	const op = errors.Op("redis_driver_get")
	// to get cases like "  "
	keyTrimmed := strings.TrimSpace(key)
	if keyTrimmed == "" {
		return nil, errors.E(op, errors.EmptyKey)
	}
	return d.universalClient.Get(context.Background(), key).Bytes()
}

// MGet loads content of multiple values (some values might be skipped).
// https://redis.io/commands/mget
// Returns slice with the interfaces with values
func (d *Driver) MGet(keys ...string) (map[string][]byte, error) {
	const op = errors.Op("redis_driver_mget")
	if keys == nil {
		return nil, errors.E(op, errors.NoKeys)
	}

	// should not be empty keys
	for _, key := range keys {
		keyTrimmed := strings.TrimSpace(key)
		if keyTrimmed == "" {
			return nil, errors.E(op, errors.EmptyKey)
		}
	}

	m := make(map[string][]byte, len(keys))

	for _, k := range keys {
		cmd := d.universalClient.Get(context.Background(), k)
		if cmd.Err() != nil {
			if cmd.Err() == redis.Nil {
				continue
			}
			return nil, errors.E(op, cmd.Err())
		}

		m[k] = utils.AsBytes(cmd.Val())
	}

	return m, nil
}

// Set sets value with the TTL in seconds
// https://redis.io/commands/set
// Redis `SET key value [expiration]` command.
//
// Use expiration for `SETEX`-like behavior.
// Zero expiration means the key has no expiration time.
func (d *Driver) Set(items ...*kvv1.Item) error {
	const op = errors.Op("redis_driver_set")
	if items == nil {
		return errors.E(op, errors.NoKeys)
	}
	now := time.Now()
	for _, item := range items {
		if item == nil {
			return errors.E(op, errors.EmptyKey)
		}

		if item.Timeout == "" {
			err := d.universalClient.Set(context.Background(), item.Key, item.Value, 0).Err()
			if err != nil {
				return err
			}
		} else {
			t, err := time.Parse(time.RFC3339, item.Timeout)
			if err != nil {
				return err
			}
			err = d.universalClient.Set(context.Background(), item.Key, item.Value, t.Sub(now)).Err()
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// Delete one or multiple keys.
func (d *Driver) Delete(keys ...string) error {
	const op = errors.Op("redis_driver_delete")
	if keys == nil {
		return errors.E(op, errors.NoKeys)
	}

	// should not be empty keys
	for _, key := range keys {
		keyTrimmed := strings.TrimSpace(key)
		if keyTrimmed == "" {
			return errors.E(op, errors.EmptyKey)
		}
	}
	return d.universalClient.Del(context.Background(), keys...).Err()
}

// MExpire https://redis.io/commands/expire
// timeout in RFC3339
func (d *Driver) MExpire(items ...*kvv1.Item) error {
	const op = errors.Op("redis_driver_mexpire")
	now := time.Now()
	for _, item := range items {
		if item == nil {
			continue
		}
		if item.Timeout == "" || strings.TrimSpace(item.Key) == "" {
			return errors.E(op, errors.Str("should set timeout and at least one key"))
		}

		t, err := time.Parse(time.RFC3339, item.Timeout)
		if err != nil {
			return err
		}

		// t guessed to be in future
		// for Redis we use t.Sub, it will result in seconds, like 4.2s
		d.universalClient.Expire(context.Background(), item.Key, t.Sub(now))
	}

	return nil
}

// TTL https://redis.io/commands/ttl
// return time in seconds (float64) for a given keys
func (d *Driver) TTL(keys ...string) (map[string]string, error) {
	const op = errors.Op("redis_driver_ttl")
	if keys == nil {
		return nil, errors.E(op, errors.NoKeys)
	}

	// should not be empty keys
	for _, key := range keys {
		keyTrimmed := strings.TrimSpace(key)
		if keyTrimmed == "" {
			return nil, errors.E(op, errors.EmptyKey)
		}
	}

	m := make(map[string]string, len(keys))

	for _, key := range keys {
		duration, err := d.universalClient.TTL(context.Background(), key).Result()
		if err != nil {
			return nil, err
		}

		m[key] = duration.String()
	}
	return m, nil
}