-
Notifications
You must be signed in to change notification settings - Fork 187
/
cache.go
99 lines (84 loc) · 2.66 KB
/
cache.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
package config
import (
"encoding/json"
"time"
"github.com/spf13/viper"
)
// CacheConfig contains fields, which enable and configure
// Flipt's various caching mechanisms.
//
// Currently, flipt support in-memory and redis backed caching.
type CacheConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"`
TTL time.Duration `json:"ttl,omitempty" mapstructure:"ttl"`
Backend CacheBackend `json:"backend,omitempty" mapstructure:"backend"`
Memory MemoryCacheConfig `json:"memory,omitempty" mapstructure:"memory"`
Redis RedisCacheConfig `json:"redis,omitempty" mapstructure:"redis"`
}
func (c *CacheConfig) setDefaults(v *viper.Viper) (warnings []string) {
v.SetDefault("cache", map[string]any{
"enabled": false,
"backend": CacheMemory,
"ttl": 1 * time.Minute,
"redis": map[string]any{
"host": "localhost",
"port": 6379,
"password": "",
"db": 0,
},
"memory": map[string]any{
"enabled": false, // deprecated (see below)
"eviction_interval": 5 * time.Minute,
},
})
if v.GetBool("cache.memory.enabled") {
warnings = append(warnings, deprecatedMsgMemoryEnabled)
// forcibly set top-level `enabled` to true
v.Set("cache.enabled", true)
// ensure ttl is mapped to the value at memory.expiration
v.RegisterAlias("cache.ttl", "cache.memory.expiration")
// ensure ttl default is set
v.SetDefault("cache.memory.expiration", 1*time.Minute)
}
if v.IsSet("cache.memory.expiration") {
warnings = append(warnings, deprecatedMsgMemoryExpiration)
}
return
}
// CacheBackend is either memory or redis
type CacheBackend uint8
func (c CacheBackend) String() string {
return cacheBackendToString[c]
}
func (c CacheBackend) MarshalJSON() ([]byte, error) {
return json.Marshal(c.String())
}
const (
_ CacheBackend = iota
// CacheMemory ...
CacheMemory
// CacheRedis ...
CacheRedis
)
var (
cacheBackendToString = map[CacheBackend]string{
CacheMemory: "memory",
CacheRedis: "redis",
}
stringToCacheBackend = map[string]CacheBackend{
"memory": CacheMemory,
"redis": CacheRedis,
}
)
// MemoryCacheConfig contains fields, which configure in-memory caching.
type MemoryCacheConfig struct {
EvictionInterval time.Duration `json:"evictionInterval,omitempty" mapstructure:"eviction_interval"`
}
// RedisCacheConfig contains fields, which configure the connection
// credentials for redis backed caching.
type RedisCacheConfig struct {
Host string `json:"host,omitempty" mapstructure:"host"`
Port int `json:"port,omitempty" mapstructure:"port"`
Password string `json:"password,omitempty" mapstructure:"password"`
DB int `json:"db,omitempty" mapstructure:"db"`
}