-
Notifications
You must be signed in to change notification settings - Fork 137
/
flag.go
324 lines (294 loc) · 7.44 KB
/
flag.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
320
321
322
323
324
package feature
import (
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"net/url"
"strings"
"time"
"github.com/cozy/cozy-stack/model/instance"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/couchdb"
"github.com/cozy/cozy-stack/pkg/prefixer"
)
// Flags is a struct for a set of feature flags.
type Flags struct {
DocID string
DocRev string
M map[string]interface{}
Sources []*Flags
}
// ID is part of the couchdb.Document interface
func (f *Flags) ID() string { return f.DocID }
// Rev is part of the couchdb.Document interface
func (f *Flags) Rev() string { return f.DocRev }
// DocType is part of the couchdb.Document interface
func (f *Flags) DocType() string { return consts.Settings }
// SetID is part of the couchdb.Document interface
func (f *Flags) SetID(id string) { f.DocID = id }
// SetRev is part of the couchdb.Document interface
func (f *Flags) SetRev(rev string) { f.DocRev = rev }
// Clone is part of the couchdb.Document interface
func (f *Flags) Clone() couchdb.Doc {
clone := Flags{DocID: f.DocID, DocRev: f.DocRev}
clone.M = make(map[string]interface{})
for k, v := range f.M {
clone.M[k] = v
}
return &clone
}
// MarshalJSON is used for marshalling to JSON.
func (f *Flags) MarshalJSON() ([]byte, error) {
return json.Marshal(f.M)
}
// UnmarshalJSON is used to parse JSON.
func (f *Flags) UnmarshalJSON(bytes []byte) error {
err := json.Unmarshal(bytes, &f.M)
if err != nil {
return err
}
if id, ok := f.M["_id"].(string); ok {
f.SetID(id)
delete(f.M, "_id")
}
if rev, ok := f.M["_rev"].(string); ok {
f.SetRev(rev)
delete(f.M, "_rev")
}
return nil
}
func (f *Flags) GetList(name string) ([]interface{}, error) {
if f.M[name] == nil {
return []interface{}{}, nil
}
value, ok := f.M[name].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Flag %s is not a list flag", name)
}
list, ok := value["list"].([]interface{})
if !ok {
return nil, fmt.Errorf("Flag %s is not a list flag", name)
}
return list, nil
}
func (f *Flags) HasListItem(name, item string) (bool, error) {
list, err := f.GetList(name)
if err != nil {
return false, err
}
for _, i := range list {
if i == item {
return true, nil
}
}
return false, nil
}
// GetFlags returns the list of feature flags for the given instance.
func GetFlags(inst *instance.Instance) (*Flags, error) {
sources := make([]*Flags, 0)
m := make(map[string]interface{})
flags := &Flags{
DocID: consts.FlagsSettingsID,
M: m,
Sources: sources,
}
flags.addInstanceFlags(inst)
if err := flags.addManager(inst); err != nil {
inst.Logger().WithNamespace("flags").
Warnf("Cannot get the flags from the manager: %s", err)
}
if err := flags.addConfig(inst); err != nil {
inst.Logger().WithNamespace("flags").
Warnf("Cannot get the flags from the config: %s", err)
}
if err := flags.addContext(inst); err != nil {
inst.Logger().WithNamespace("flags").
Warnf("Cannot get the flags from the context: %s", err)
}
if err := flags.addDefaults(inst); err != nil {
inst.Logger().WithNamespace("flags").
Warnf("Cannot get the flags from the defaults: %s", err)
}
return flags, nil
}
func (f *Flags) addInstanceFlags(inst *instance.Instance) {
if len(inst.FeatureFlags) == 0 {
return
}
m := make(map[string]interface{})
for k, v := range inst.FeatureFlags {
m[k] = v
}
flags := &Flags{
DocID: consts.InstanceFlagsSettingsID,
M: m,
}
f.Sources = append(f.Sources, flags)
for k, v := range flags.M {
if _, ok := f.M[k]; !ok {
f.M[k] = v
}
}
}
func (f *Flags) addManager(inst *instance.Instance) error {
if len(inst.FeatureSets) == 0 {
return nil
}
m, err := getFlagsFromManager(inst)
if err != nil || len(m) == 0 {
return err
}
flags := &Flags{
DocID: consts.ManagerFlagsSettingsID,
M: m,
}
f.Sources = append(f.Sources, flags)
for k, v := range flags.M {
if _, ok := f.M[k]; !ok {
f.M[k] = v
}
}
return nil
}
var (
cacheDuration = 12 * time.Hour
errInvalidResponse = errors.New("Invalid response from the manager")
)
func getFlagsFromManager(inst *instance.Instance) (map[string]interface{}, error) {
cache := config.GetConfig().CacheStorage
cacheKey := fmt.Sprintf("flags:%s:%v", inst.ContextName, inst.FeatureSets)
var flags map[string]interface{}
if buf, ok := cache.Get(cacheKey); ok {
if err := json.Unmarshal(buf, &flags); err == nil {
return flags, nil
}
}
client := instance.APIManagerClient(inst)
if client == nil {
return flags, nil
}
query := url.Values{
"sets": {strings.Join(inst.FeatureSets, ",")},
"context": {inst.ContextName},
}.Encode()
data, err := client.Get(fmt.Sprintf("/api/v1/features?%s", query))
if err != nil {
return nil, err
}
var ok bool
if flags, ok = data["flags"].(map[string]interface{}); !ok {
return nil, errInvalidResponse
}
if buf, err := json.Marshal(flags); err == nil {
cache.Set(cacheKey, buf, cacheDuration)
}
return flags, nil
}
func (f *Flags) addConfig(inst *instance.Instance) error {
ctx, ok := inst.SettingsContext()
if !ok {
return nil
}
normalized := make(map[string]interface{})
if m, ok := ctx["features"].(map[string]interface{}); ok {
for k, v := range m {
normalized[k] = v
}
} else if items, ok := ctx["features"].([]interface{}); ok {
for _, item := range items {
if m, ok := item.(map[string]interface{}); ok && len(m) == 1 {
for k, v := range m {
normalized[k] = v
}
} else {
normalized[fmt.Sprintf("%v", item)] = true
}
}
} else {
return nil
}
ctxFlags := &Flags{
DocID: consts.ConfigFlagsSettingsID,
M: normalized,
}
f.Sources = append(f.Sources, ctxFlags)
for k, v := range ctxFlags.M {
if _, ok := f.M[k]; !ok {
f.M[k] = v
}
}
return nil
}
func (f *Flags) addContext(inst *instance.Instance) error {
id := fmt.Sprintf("%s.%s", consts.ContextFlagsSettingsID, inst.ContextName)
var context Flags
err := couchdb.GetDoc(prefixer.GlobalPrefixer, consts.Settings, id, &context)
if couchdb.IsNotFoundError(err) {
return nil
} else if err != nil {
return err
}
if len(context.M) == 0 {
return nil
}
context.SetID(consts.ContextFlagsSettingsID)
f.Sources = append(f.Sources, &context)
for k, v := range context.M {
if _, ok := f.M[k]; !ok {
if value := applyRatio(inst, k, v); value != nil {
f.M[k] = value
}
}
}
return nil
}
const maxUint32 = 1<<32 - 1
func applyRatio(inst *instance.Instance, key string, data interface{}) interface{} {
items, ok := data.([]interface{})
if !ok || len(items) == 0 {
return nil
}
sum := crc32.ChecksumIEEE([]byte(fmt.Sprintf("%s:%s", inst.DocID, key)))
for i := range items {
item, ok := items[i].(map[string]interface{})
if !ok {
continue
}
ratio, ok := item["ratio"].(float64)
if !ok || ratio == 0.0 {
continue
}
if ratio == 1.0 {
return item["value"]
}
computed := uint32(ratio * maxUint32)
if computed >= sum {
return item["value"]
}
sum -= computed
}
return nil
}
func (f *Flags) addDefaults(inst *instance.Instance) error {
var defaults Flags
err := couchdb.GetDoc(prefixer.GlobalPrefixer, consts.Settings, consts.DefaultFlagsSettingsID, &defaults)
if couchdb.IsNotFoundError(err) {
return nil
} else if err != nil {
return err
}
if len(defaults.M) == 0 {
return nil
}
defaults.SetID(consts.DefaultFlagsSettingsID)
f.Sources = append(f.Sources, &defaults)
for k, v := range defaults.M {
if _, ok := f.M[k]; !ok {
f.M[k] = v
}
}
return nil
}
var _ couchdb.Doc = &Flags{}