-
Notifications
You must be signed in to change notification settings - Fork 0
/
kv.go
319 lines (252 loc) · 7.86 KB
/
kv.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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package natty
import (
"context"
"regexp"
"sync"
"time"
"github.com/nats-io/nats.go"
"github.com/pkg/errors"
)
type KeyValueMap struct {
rwMutex *sync.RWMutex
// Key = bucket name, value = KeyValue
kvMap map[string]nats.KeyValue
}
func (n *Natty) Get(ctx context.Context, bucket string, key string) ([]byte, error) {
// NOTE: Context usage for K/V operations is not available in NATS (yet)
kv, err := n.getBucket(ctx, bucket, false, 0)
if err != nil {
if err == nats.ErrBucketNotFound {
return nil, nats.ErrKeyNotFound
}
return nil, errors.Wrap(err, "failed to get bucket")
}
kve, err := kv.Get(key)
if err != nil {
if err == nats.ErrKeyNotFound {
return nil, nats.ErrKeyNotFound
}
return nil, errors.Wrap(err, "unable to fetch key")
}
return kve.Value(), nil
}
// Put puts a key/val into a bucket and will create bucket if it doesn't already
// exit. TTL is optional - it will only be used if the bucket does not exist &
// only the first TTL will be used.
func (n *Natty) Put(ctx context.Context, bucket string, key string, data []byte, keyTTL ...time.Duration) error {
// NOTE: Context usage for K/V operations is not available in NATS (yet)
var ttl time.Duration
if len(keyTTL) > 0 {
ttl = keyTTL[0]
}
kv, err := n.getBucket(ctx, bucket, true, ttl)
if err != nil {
return errors.Wrap(err, "unable to fetch bucket")
}
if _, err := kv.Put(key, data); err != nil {
return errors.Wrap(err, "unable to put key")
}
return nil
}
// Create will add the key/value pair iff it does not exist; it will create
// the bucket if it does not already exist. TTL is optional - it will only be
// used if the bucket does not exist & only the first TTL will be used.
func (n *Natty) Create(ctx context.Context, bucket string, key string, data []byte, keyTTL ...time.Duration) error {
// NOTE: Context usage for K/V operations is not available in NATS (yet)
var ttl time.Duration
if len(keyTTL) > 0 {
ttl = keyTTL[0]
}
kv, err := n.getBucket(ctx, bucket, true, ttl)
if err != nil {
return errors.Wrap(err, "unable to fetch bucket")
}
if _, err := kv.Create(key, data); err != nil {
return errors.Wrap(err, "unable to put key")
}
return nil
}
func (n *Natty) Keys(ctx context.Context, bucket string) ([]string, error) {
kv, err := n.getBucket(ctx, bucket, false, 0)
if err != nil {
return nil, err
}
keys, err := kv.Keys(nats.Context(ctx))
if err != nil {
if err == nats.ErrNoKeysFound {
return make([]string, 0), nil
}
return nil, err
}
return keys, nil
}
func (n *Natty) Delete(ctx context.Context, bucket string, key string) error {
// NOTE: Context usage for K/V operations is not available in NATS (yet)
kv, err := n.getBucket(ctx, bucket, false, 0)
if err != nil {
if err == nats.ErrBucketNotFound {
return nil
}
return errors.Wrap(err, "unable to fetch bucket")
}
return kv.Purge(key)
}
func (n *Natty) DeleteBucket(_ context.Context, bucket string) error {
// Get rid of it locally (noop if doesn't exist)
n.kvMap.Delete(bucket)
if err := n.js.DeleteKeyValue(bucket); err != nil {
if err == nats.ErrStreamNotFound {
return nil
}
return errors.Wrap(err, "unable to delete bucket")
}
return nil
}
// CreateBucket creates a bucket; returns an error if it already exists.
// Context usage not supported by NATS kv (yet).
func (n *Natty) CreateBucket(_ context.Context, name string, ttl time.Duration, replicaCount int, description ...string) error {
if err := validateCreateBucket(name, ttl, replicaCount); err != nil {
return errors.Wrap(err, "unable to validate args")
}
cfg := &nats.KeyValueConfig{
Bucket: name,
TTL: ttl,
Replicas: replicaCount,
}
if len(description) > 0 {
cfg.Description = description[0]
}
kv, err := n.js.CreateKeyValue(cfg)
if err != nil {
return err
}
n.kvMap.Put(name, kv)
return nil
}
// Refresh will refresh the TTL of a key in a bucket. Since there is no built-in
// way to perform a refresh, we will first get the key and then attempt to update
// it referencing the revision ID we got.
func (n *Natty) Refresh(_ context.Context, bucket string, key string) error {
kv, err := n.getBucket(context.Background(), bucket, false, 0)
if err != nil {
return errors.Wrap(err, "unable to fetch bucket")
}
kve, err := kv.Get(key)
if err != nil {
if err == nats.ErrKeyNotFound {
return err
}
return errors.Wrap(err, "unable to fetch key")
}
if _, err := kv.Update(key, kve.Value(), kve.Revision()); err != nil {
return errors.Wrap(err, "unable to update key for refresh")
}
return nil
}
func validateCreateBucket(name string, _ time.Duration, replicaCount int) error {
if name == "" {
return errors.New("bucket name cannot be empty")
}
regex := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
if !regex.MatchString(name) {
return errors.New("bucket name can only contain alphanumeric, dash or underscore characters")
}
if replicaCount < 1 {
return errors.New("replicaCount must be greater than 0")
}
return nil
}
func (n *Natty) Status(ctx context.Context, bucket string) (nats.KeyValueStatus, error) {
kv, err := n.getBucket(ctx, bucket, false, 0)
if err != nil {
if err == nats.ErrBucketNotFound {
return nil, err
}
return nil, errors.Wrap(err, "unable to fetch bucket")
}
status, err := kv.Status()
if err != nil {
return nil, errors.Wrap(err, "unable to get bucket status")
}
return status, nil
}
// WatchKey returns an instance of nats.KeyWatcher for the given bucket
func (n *Natty) WatchKey(ctx context.Context, bucket, key string) (nats.KeyWatcher, error) {
b, err := n.getBucket(ctx, bucket, false, 0)
if err != nil {
return nil, errors.Wrapf(err, "unable to watch bucket '%s'", bucket)
}
watcher, err := b.Watch(key)
if err != nil {
return nil, errors.Wrapf(err, "unable to watch bucket '%s'", bucket)
}
return watcher, nil
}
// WatchBucket returns an instance of nats.KeyWatcher for the given bucket
func (n *Natty) WatchBucket(ctx context.Context, bucket string) (nats.KeyWatcher, error) {
b, err := n.getBucket(ctx, bucket, false, 0)
if err != nil {
return nil, errors.Wrapf(err, "unable to watch bucket '%s'", bucket)
}
watcher, err := b.WatchAll()
if err != nil {
return nil, errors.Wrapf(err, "unable to watch bucket '%s'", bucket)
}
return watcher, nil
}
// getBucket will either fetch a known bucket or create it if it doesn't exist
func (n *Natty) getBucket(_ context.Context, bucket string, create bool, ttl time.Duration) (nats.KeyValue, error) {
// NOTE: Context usage for K/V operations is not available in NATS (yet)
// Do we have this bucket locally?
kv, ok := n.kvMap.Get(bucket)
if ok {
return kv, nil
}
// Nope - try to get it from NATS
kv, err := n.js.KeyValue(bucket)
if err != nil {
// Is this a fatal error?
if err != nats.ErrBucketNotFound {
return nil, errors.Wrap(err, "key value fetch error in getBucket()")
}
}
// We either found the bucket or got a ErrBucketNotFound
if kv != nil {
n.kvMap.Put(bucket, kv)
return kv, nil
}
// Bucket was not found and we want to create
if kv == nil && create {
kv, err = n.js.CreateKeyValue(&nats.KeyValueConfig{
Bucket: bucket,
Description: "auto-created bucket via natty",
History: 5,
TTL: ttl,
})
if err != nil {
return nil, errors.Wrap(err, "bucket create error in getBucket()")
}
n.kvMap.Put(bucket, kv)
return kv, nil
}
// If we got here, we ran into a ErrBucketNotFound and we don't want to
// create a new bucket.
return nil, nats.ErrBucketNotFound
}
func (k *KeyValueMap) Get(key string) (nats.KeyValue, bool) {
k.rwMutex.RLock()
v, ok := k.kvMap[key]
k.rwMutex.RUnlock()
return v, ok
}
func (k *KeyValueMap) Put(key string, value nats.KeyValue) {
k.rwMutex.Lock()
k.kvMap[key] = value
k.rwMutex.Unlock()
}
// Delete functionality is not used because there is no way to list buckets in NATS
func (k *KeyValueMap) Delete(key string) {
k.rwMutex.Lock()
delete(k.kvMap, key)
k.rwMutex.Unlock()
}