/
store_ristretto.go
79 lines (65 loc) · 1.87 KB
/
store_ristretto.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
package libcache
import (
"context"
"errors"
"fmt"
"time"
"github.com/dgraph-io/ristretto"
)
// ristrettoStore is a store for Ristretto (memory) library.
type ristrettoStore struct {
client *ristretto.Cache
options *Options
}
// newRistretto creates a new store to Ristretto (memory) library instance.
func newRistretto(client *ristretto.Cache, options ...Option) *ristrettoStore {
return &ristrettoStore{
client: client,
options: applyOptions(options...),
}
}
// Get returns data stored from a given key.
func (s *ristrettoStore) Get(_ context.Context, key any) (any, error) {
var err error
s.client.Wait()
value, exists := s.client.Get(key)
if !exists {
err = newNotFound(errors.New("value not found in Ristretto store"))
}
return value, err
}
// GetWithTTL returns data stored from a given key and its corresponding TTL.
func (s *ristrettoStore) GetWithTTL(ctx context.Context, key any) (any, time.Duration, error) {
s.client.Wait()
value, err := s.Get(ctx, key)
if err != nil {
return nil, 0, err
}
ttl, exist := s.client.GetTTL(key)
if !exist {
ttl = time.Duration(0)
}
return value, ttl, err
}
// Set defines data in Ristretto memoey cache for given key identifier.
func (s *ristrettoStore) Set(_ context.Context, key any, value any, options ...Option) error {
opts := applyOptionsWithDefault(s.options, options...)
var err error
if set := s.client.SetWithTTL(key, value, opts.Cost, opts.Expiration); !set {
err = fmt.Errorf("an error has occurred while setting value '%v' on key '%v'", value, key)
}
if err != nil {
return err
}
return nil
}
// Delete removes data in Ristretto memoey cache for given key identifier.
func (s *ristrettoStore) Delete(_ context.Context, key any) error {
s.client.Del(key)
return nil
}
// Clear resets all data in the store.
func (s *ristrettoStore) Clear(_ context.Context) error {
s.client.Clear()
return nil
}