-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathristretto_backend.go
111 lines (99 loc) · 2.19 KB
/
ristretto_backend.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
package mwcache
import (
"errors"
"fmt"
"reflect"
"strconv"
"github.com/dgraph-io/ristretto"
"github.com/stoewer/go-strcase"
)
type RistrettoBackend struct {
cache *ristretto.Cache
}
func newRistrettoBackend(rawOptions map[string]string) (*RistrettoBackend, error) {
opt, err := parseRistrettoOptions(rawOptions)
if err != nil {
return nil, err
}
cache, err := ristretto.NewCache(opt)
if err != nil {
return nil, err
}
return &RistrettoBackend{cache}, nil
}
// TODO
func ValidateRistrettoConfig(rawOptions map[string]string) error {
optionReflect := reflect.ValueOf(ristretto.Config{})
for k := range rawOptions {
k = strcase.UpperCamelCase(k)
if !optionReflect.FieldByName(k).IsValid() {
return fmt.Errorf("Unknown config: " + k)
}
}
return nil
}
// TODO
func parseRistrettoOptions(rawOptions map[string]string) (*ristretto.Config, error) {
c := ristretto.Config{}
optionsReflect := reflect.ValueOf(&c)
for k, strV := range rawOptions {
k = strcase.UpperCamelCase(k)
field := optionsReflect.Elem().FieldByName(k)
switch field.Type().String() {
case "string":
field.SetString(strV)
case "bool":
v, err := strconv.ParseBool(strV)
if err != nil {
return nil, err
}
field.SetBool(v)
case "int":
v, err := strconv.ParseInt(strV, 10, 64)
if err != nil {
return nil, err
}
field.SetInt(v)
case "int32":
v, err := strconv.ParseInt(strV, 10, 64)
if err != nil {
return nil, err
}
field.SetInt(v)
case "int64":
v, err := strconv.ParseInt(strV, 10, 64)
if err != nil {
return nil, err
}
field.SetInt(v)
case "float64":
v, err := strconv.ParseFloat(strV, 64)
if err != nil {
return nil, err
}
field.SetFloat(v)
}
}
return &c, nil
}
func (m *RistrettoBackend) put(key string, val string) error {
if ok := m.cache.Set(key, val, 1); !ok {
return errors.New("Set was dropped")
}
return nil
}
func (m *RistrettoBackend) get(key string) (string, error) {
val, ok := m.cache.Get(key)
if !ok {
return "", ErrKeyNotFound
}
return val.(string), nil
}
func (m *RistrettoBackend) delete(key string) error {
m.cache.Del(key)
return nil
}
// Interface guards
var (
_ Backend = (*RistrettoBackend)(nil)
)