-
Notifications
You must be signed in to change notification settings - Fork 55
/
repository.go
228 lines (193 loc) · 5.29 KB
/
repository.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
package unleash
import (
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"net/url"
"sync"
"time"
"github.com/Unleash/unleash-client-go/v4/api"
)
var SEGMENT_CLIENT_SPEC_VERSION = "4.3.1"
type repository struct {
repositoryChannels
sync.RWMutex
options repositoryOptions
etag string
close chan struct{}
closed chan struct{}
ctx context.Context
cancel func()
isReady bool
refreshTicker *time.Ticker
segments map[int][]api.Constraint
errors float64
maxSkips float64
skips float64
}
func newRepository(options repositoryOptions, channels repositoryChannels) *repository {
repo := &repository{
options: options,
repositoryChannels: channels,
close: make(chan struct{}),
closed: make(chan struct{}),
refreshTicker: time.NewTicker(options.refreshInterval),
segments: map[int][]api.Constraint{},
errors: 0,
maxSkips: 10,
skips: 0,
}
ctx, cancel := context.WithCancel(context.Background())
repo.ctx = ctx
repo.cancel = cancel
if options.httpClient == nil {
repo.options.httpClient = http.DefaultClient
}
if options.storage == nil {
repo.options.storage = &DefaultStorage{}
}
repo.options.storage.Init(options.backupPath, options.appName)
go repo.sync()
return repo
}
func (r *repository) fetchAndReportError() {
err := r.fetch()
if err != nil {
if urlErr, ok := err.(*url.Error); !(ok && urlErr.Err == context.Canceled) {
r.err(err)
}
}
if !r.isReady && err == nil {
r.isReady = true
r.ready <- true
}
}
func (r *repository) sync() {
r.fetchAndReportError()
for {
select {
case <-r.close:
if err := r.options.storage.Persist(); err != nil {
r.err(err)
}
close(r.closed)
return
case <-r.refreshTicker.C:
if r.skips == 0 {
r.fetchAndReportError()
} else {
r.decrementSkips()
}
}
}
}
func (r *repository) backoff() {
r.errors = math.Min(r.maxSkips, r.errors+1)
r.skips = r.errors
}
func (r *repository) successfulFetch() {
r.errors = math.Max(0, r.errors-1)
r.skips = r.errors
}
func (r *repository) decrementSkips() {
r.skips = math.Max(0, r.skips-1)
}
func (r *repository) configurationError() {
r.errors = r.maxSkips
r.skips = r.errors
}
func (r *repository) fetch() error {
u, _ := r.options.url.Parse(getFetchURLPath(r.options.projectName))
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return err
}
req = req.WithContext(r.ctx)
req.Header.Add("UNLEASH-APPNAME", r.options.appName)
req.Header.Add("UNLEASH-INSTANCEID", r.options.instanceId)
req.Header.Add("User-Agent", r.options.appName)
// Needs to reference a version of the client specifications that include
// global segments
req.Header.Add("Unleash-Client-Spec", SEGMENT_CLIENT_SPEC_VERSION)
for k, v := range r.options.customHeaders {
req.Header[k] = v
}
if r.etag != "" {
req.Header.Add("If-None-Match", r.etag)
}
resp, err := r.options.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotModified {
return nil
}
if err := r.statusIsOK(resp); err != nil {
return err
}
var featureResp api.FeatureResponse
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&featureResp); err != nil {
return err
}
r.Lock()
r.etag = resp.Header.Get("Etag")
r.segments = featureResp.SegmentsMap()
r.options.storage.Reset(featureResp.FeatureMap(), true)
r.successfulFetch()
r.Unlock()
return nil
}
func (r *repository) statusIsOK(resp *http.Response) error {
s := resp.StatusCode
if http.StatusOK <= s && s < http.StatusMultipleChoices {
return nil
} else if s == http.StatusUnauthorized || s == http.StatusForbidden || s == http.StatusNotFound {
r.configurationError()
return fmt.Errorf("%s %s returned status code %d your SDK is most likely misconfigured, backing off to maximum (%f times our interval)", resp.Request.Method, resp.Request.URL, s, r.maxSkips)
} else if s == http.StatusTooManyRequests || s >= http.StatusInternalServerError {
r.backoff()
return fmt.Errorf("%s %s returned status code %d, backing off (%f times our interval)", resp.Request.Method, resp.Request.URL, s, r.errors)
}
return fmt.Errorf("%s %s returned status code %d", resp.Request.Method, resp.Request.URL, s)
}
func (r *repository) getToggle(key string) *api.Feature {
r.RLock()
defer r.RUnlock()
if toggle, found := r.options.storage.Get(key); found {
if feature, ok := toggle.(api.Feature); ok {
return &feature
}
}
return nil
}
func (r *repository) resolveSegmentConstraints(strategy api.Strategy) ([]api.Constraint, error) {
segmentConstraints := []api.Constraint{}
for _, segmentId := range strategy.Segments {
if resolvedConstraints, ok := r.segments[segmentId]; ok {
segmentConstraints = append(segmentConstraints, resolvedConstraints...)
} else {
return segmentConstraints, fmt.Errorf("segment does not exist")
}
}
return segmentConstraints, nil
}
func (r *repository) list() []api.Feature {
r.RLock()
defer r.RUnlock()
var features []api.Feature
for _, feature := range r.options.storage.List() {
features = append(features, feature.(api.Feature))
}
return features
}
func (r *repository) Close() error {
close(r.close)
r.cancel()
<-r.closed
r.refreshTicker.Stop()
return nil
}