forked from DevCycleHQ/go-server-sdk
/
configmanager.go
198 lines (169 loc) · 4.63 KB
/
configmanager.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
package devcycle
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync/atomic"
"time"
"github.com/BIwashi/go-server-sdk/v2/util"
)
const CONFIG_RETRIES = 1
type ConfigReceiver interface {
StoreConfig([]byte, string) error
}
type EnvironmentConfigManager struct {
sdkKey string
rawConfig []byte
configETag string
localBucketing ConfigReceiver
firstLoad bool
context context.Context
stopPolling context.CancelFunc
httpClient *http.Client
cfg *HTTPConfiguration
hasConfig atomic.Bool
ticker *time.Ticker
}
func NewEnvironmentConfigManager(
sdkKey string,
localBucketing ConfigReceiver,
options *Options,
cfg *HTTPConfiguration,
) (e *EnvironmentConfigManager) {
configManager := &EnvironmentConfigManager{
sdkKey: sdkKey,
localBucketing: localBucketing,
cfg: cfg,
httpClient: &http.Client{
// Set an explicit timeout so that we don't wait forever on a request
// Use the configurable timeout because fetching the first config can block SDK initialization.
Timeout: options.RequestTimeout,
},
hasConfig: atomic.Bool{},
firstLoad: true,
}
configManager.context, configManager.stopPolling = context.WithCancel(context.Background())
return configManager
}
func (e *EnvironmentConfigManager) StartPolling(
interval time.Duration,
) {
e.ticker = time.NewTicker(interval)
go func() {
for {
select {
case <-e.context.Done():
util.Warnf("Stopping config polling.")
e.ticker.Stop()
return
case <-e.ticker.C:
err := e.fetchConfig(CONFIG_RETRIES)
if err != nil {
util.Warnf("Error fetching config: %s\n", err)
}
}
}
}()
}
func (e *EnvironmentConfigManager) initialFetch() error {
return e.fetchConfig(CONFIG_RETRIES)
}
func (e *EnvironmentConfigManager) fetchConfig(numRetriesRemaining int) (err error) {
defer func() {
if r := recover(); r != nil {
// get the stack trace and potentially log it here
err = fmt.Errorf("recovered from panic in fetchConfig: %v", r)
}
}()
req, err := http.NewRequest("GET", e.getConfigURL(), nil)
if err != nil {
return err
}
if e.configETag != "" {
req.Header.Set("If-None-Match", e.configETag)
}
resp, err := e.httpClient.Do(req)
if err != nil {
if numRetriesRemaining > 0 {
util.Warnf("Retrying config fetch %d more times. Error: %s", numRetriesRemaining, err)
return e.fetchConfig(numRetriesRemaining - 1)
}
return err
}
defer resp.Body.Close()
switch statusCode := resp.StatusCode; {
case statusCode == http.StatusOK:
return e.setConfigFromResponse(resp)
case statusCode == http.StatusNotModified:
return nil
case statusCode == http.StatusForbidden:
e.stopPolling()
return fmt.Errorf("invalid SDK key. Aborting config polling")
case statusCode >= 500:
// Retryable Errors. Continue polling.
util.Warnf("Config fetch failed. Status:" + resp.Status)
default:
err = fmt.Errorf("Unexpected response code: %d\n"+
"Body: %s\n"+
"URL: %s\n"+
"Headers: %s\n"+
"Could not download configuration. Using cached version if available %s\n",
resp.StatusCode, resp.Body, e.getConfigURL(), resp.Header, resp.Header.Get("ETag"))
}
if numRetriesRemaining > 0 {
util.Warnf("Retrying config fetch %d more times. Status: %s", numRetriesRemaining, resp.Status)
return e.fetchConfig(numRetriesRemaining - 1)
}
return err
}
func (e *EnvironmentConfigManager) setConfigFromResponse(response *http.Response) error {
config, err := io.ReadAll(response.Body)
if err != nil {
return err
}
var prettyJSON bytes.Buffer
error := json.Indent(&prettyJSON, config, "", " ")
if error != nil {
fmt.Printf("JSON parse error: %s", error)
} else {
fmt.Printf("body: %s\n", prettyJSON.String())
}
// Check
valid := json.Valid(config)
if !valid {
return fmt.Errorf("invalid JSON data received for config")
}
e.configETag = response.Header.Get("Etag")
err = e.setConfig(config, e.configETag)
if err != nil {
return err
}
util.Infof("Config set. ETag: %s\n", e.configETag)
if e.firstLoad {
e.firstLoad = false
util.Infof("DevCycle SDK Initialized.")
}
return nil
}
func (e *EnvironmentConfigManager) setConfig(config []byte, eTag string) error {
err := e.localBucketing.StoreConfig(config, eTag)
if err != nil {
return err
}
e.rawConfig = config
e.hasConfig.Store(true)
return nil
}
func (e *EnvironmentConfigManager) getConfigURL() string {
configBasePath := e.cfg.ConfigCDNBasePath
return fmt.Sprintf("%s/config/v1/server/%s.json", configBasePath, e.sdkKey)
}
func (e *EnvironmentConfigManager) HasConfig() bool {
return e.hasConfig.Load()
}
func (e *EnvironmentConfigManager) Close() {
e.stopPolling()
}