/
data_source_updates_impl.go
389 lines (344 loc) · 11.5 KB
/
data_source_updates_impl.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package datasource
import (
"fmt"
"sync"
"time"
"gopkg.in/launchdarkly/go-sdk-common.v2/ldlog"
intf "gopkg.in/launchdarkly/go-server-sdk.v5/interfaces"
st "gopkg.in/launchdarkly/go-server-sdk.v5/interfaces/ldstoretypes"
"gopkg.in/launchdarkly/go-server-sdk.v5/internal"
"gopkg.in/launchdarkly/go-server-sdk.v5/internal/datakinds"
)
// DataSourceUpdatesImpl is the internal implementation of DataSourceUpdates. It is exported
// because the actual implementation type, rather than the interface, is required as a dependency
// of other SDK components.
type DataSourceUpdatesImpl struct { //nolint:golint // yes, we know the package name resembles the type name
store intf.DataStore
dataStoreStatusProvider intf.DataStoreStatusProvider
dataSourceStatusBroadcaster *internal.DataSourceStatusBroadcaster
flagChangeEventBroadcaster *internal.FlagChangeEventBroadcaster
dependencyTracker *dependencyTracker
outageTracker *outageTracker
loggers ldlog.Loggers
currentStatus intf.DataSourceStatus
lastStoreUpdateFailed bool
lock sync.Mutex
}
// NewDataSourceUpdatesImpl creates the internal implementation of DataSourceUpdates.
func NewDataSourceUpdatesImpl(
store intf.DataStore,
dataStoreStatusProvider intf.DataStoreStatusProvider,
dataSourceStatusBroadcaster *internal.DataSourceStatusBroadcaster,
flagChangeEventBroadcaster *internal.FlagChangeEventBroadcaster,
logDataSourceOutageAsErrorAfter time.Duration,
loggers ldlog.Loggers,
) *DataSourceUpdatesImpl {
return &DataSourceUpdatesImpl{
store: store,
dataStoreStatusProvider: dataStoreStatusProvider,
dataSourceStatusBroadcaster: dataSourceStatusBroadcaster,
flagChangeEventBroadcaster: flagChangeEventBroadcaster,
dependencyTracker: newDependencyTracker(),
outageTracker: newOutageTracker(logDataSourceOutageAsErrorAfter, loggers),
loggers: loggers,
currentStatus: intf.DataSourceStatus{
State: intf.DataSourceStateInitializing,
StateSince: time.Now(),
},
}
}
//nolint:golint,stylecheck // no doc comment for standard method
func (d *DataSourceUpdatesImpl) Init(allData []st.Collection) bool {
var oldData map[st.DataKind]map[string]st.ItemDescriptor
if d.flagChangeEventBroadcaster.HasListeners() {
// Query the existing data if any, so that after the update we can send events for whatever was changed
oldData = make(map[st.DataKind]map[string]st.ItemDescriptor)
for _, kind := range datakinds.AllDataKinds() {
if items, err := d.store.GetAll(kind); err == nil {
m := make(map[string]st.ItemDescriptor)
for _, item := range items {
m[item.Key] = item.Item
}
oldData[kind] = m
}
}
}
err := d.store.Init(sortCollectionsForDataStoreInit(allData))
updated := d.maybeUpdateError(err)
if updated {
// We must always update the dependency graph even if we don't currently have any event listeners, because if
// listeners are added later, we don't want to have to reread the whole data store to compute the graph
d.updateDependencyTrackerFromFullDataSet(allData)
// Now, if we previously queried the old data because someone is listening for flag change events, compare
// the versions of all items and generate events for those (and any other items that depend on them)
if oldData != nil {
d.sendChangeEvents(d.computeChangedItemsForFullDataSet(oldData, fullDataSetToMap(allData)))
}
}
return updated
}
//nolint:golint,stylecheck // no doc comment for standard method
func (d *DataSourceUpdatesImpl) Upsert(
kind st.DataKind,
key string,
item st.ItemDescriptor,
) bool {
updated, err := d.store.Upsert(kind, key, item)
didNotGetError := d.maybeUpdateError(err)
if updated {
d.dependencyTracker.updateDependenciesFrom(kind, key, item)
if d.flagChangeEventBroadcaster.HasListeners() {
affectedItems := make(kindAndKeySet)
d.dependencyTracker.addAffectedItems(affectedItems, kindAndKey{kind, key})
d.sendChangeEvents(affectedItems)
}
}
return didNotGetError
}
func (d *DataSourceUpdatesImpl) maybeUpdateError(err error) bool {
if err == nil {
d.lock.Lock()
defer d.lock.Unlock()
d.lastStoreUpdateFailed = false
return true
}
d.UpdateStatus(
intf.DataSourceStateInterrupted,
intf.DataSourceErrorInfo{
Kind: intf.DataSourceErrorKindStoreError,
Message: err.Error(),
Time: time.Now(),
},
)
shouldLog := false
d.lock.Lock()
shouldLog = !d.lastStoreUpdateFailed
d.lastStoreUpdateFailed = true
d.lock.Unlock()
if shouldLog {
d.loggers.Warnf("Unexpected data store error when trying to store an update received from the data source: %s", err)
}
return false
}
//nolint:golint,stylecheck // no doc comment for standard method
func (d *DataSourceUpdatesImpl) UpdateStatus(
newState intf.DataSourceState,
newError intf.DataSourceErrorInfo,
) {
if newState == "" {
return
}
if statusToBroadcast, changed := d.maybeUpdateStatus(newState, newError); changed {
d.dataSourceStatusBroadcaster.Broadcast(statusToBroadcast)
}
}
func (d *DataSourceUpdatesImpl) maybeUpdateStatus(
newState intf.DataSourceState,
newError intf.DataSourceErrorInfo,
) (intf.DataSourceStatus, bool) {
d.lock.Lock()
defer d.lock.Unlock()
oldStatus := d.currentStatus
if newState == intf.DataSourceStateInterrupted && oldStatus.State == intf.DataSourceStateInitializing {
newState = intf.DataSourceStateInitializing // see comment on DataSourceUpdates.UpdateStatus
}
if newState == oldStatus.State && newError.Kind == "" {
return intf.DataSourceStatus{}, false
}
stateSince := oldStatus.StateSince
if newState != oldStatus.State {
stateSince = time.Now()
}
lastError := oldStatus.LastError
if newError.Kind != "" {
lastError = newError
}
d.currentStatus = intf.DataSourceStatus{
State: newState,
StateSince: stateSince,
LastError: lastError,
}
d.outageTracker.trackDataSourceState(newState, newError)
return d.currentStatus, true
}
//nolint:golint,stylecheck // no doc comment for standard method
func (d *DataSourceUpdatesImpl) GetDataStoreStatusProvider() intf.DataStoreStatusProvider {
return d.dataStoreStatusProvider
}
// GetLastStatus is used internally by SDK components.
func (d *DataSourceUpdatesImpl) GetLastStatus() intf.DataSourceStatus {
d.lock.Lock()
defer d.lock.Unlock()
return d.currentStatus
}
func (d *DataSourceUpdatesImpl) waitFor(desiredState intf.DataSourceState, timeout time.Duration) bool {
d.lock.Lock()
if d.currentStatus.State == desiredState {
d.lock.Unlock()
return true
}
if d.currentStatus.State == intf.DataSourceStateOff {
d.lock.Unlock()
return false
}
statusCh := d.dataSourceStatusBroadcaster.AddListener()
defer d.dataSourceStatusBroadcaster.RemoveListener(statusCh)
d.lock.Unlock()
var deadline <-chan time.Time
if timeout > 0 {
deadline = time.After(timeout)
}
for {
select {
case newStatus := <-statusCh:
if newStatus.State == desiredState {
return true
}
if newStatus.State == intf.DataSourceStateOff {
return false
}
case <-deadline:
return false
}
}
}
func (d *DataSourceUpdatesImpl) sendChangeEvents(affectedItems kindAndKeySet) {
for item := range affectedItems {
if item.kind == datakinds.Features {
d.flagChangeEventBroadcaster.Broadcast(intf.FlagChangeEvent{Key: item.key})
}
}
}
func (d *DataSourceUpdatesImpl) updateDependencyTrackerFromFullDataSet(allData []st.Collection) {
d.dependencyTracker.reset()
for _, coll := range allData {
for _, item := range coll.Items {
d.dependencyTracker.updateDependenciesFrom(coll.Kind, item.Key, item.Item)
}
}
}
func fullDataSetToMap(allData []st.Collection) map[st.DataKind]map[string]st.ItemDescriptor {
ret := make(map[st.DataKind]map[string]st.ItemDescriptor, len(allData))
for _, coll := range allData {
m := make(map[string]st.ItemDescriptor, len(coll.Items))
for _, item := range coll.Items {
m[item.Key] = item.Item
}
ret[coll.Kind] = m
}
return ret
}
func (d *DataSourceUpdatesImpl) computeChangedItemsForFullDataSet(
oldDataMap map[st.DataKind]map[string]st.ItemDescriptor,
newDataMap map[st.DataKind]map[string]st.ItemDescriptor,
) kindAndKeySet {
affectedItems := make(kindAndKeySet)
for _, kind := range datakinds.AllDataKinds() {
oldItems := oldDataMap[kind]
newItems := newDataMap[kind]
allKeys := make([]string, 0, len(oldItems)+len(newItems))
for key := range oldItems {
allKeys = append(allKeys, key)
}
for key := range newItems {
if _, found := oldItems[key]; !found {
allKeys = append(allKeys, key)
}
}
for _, key := range allKeys {
oldItem, haveOld := oldItems[key]
newItem, haveNew := newItems[key]
if haveOld || haveNew {
if !haveOld || !haveNew || oldItem.Version < newItem.Version {
d.dependencyTracker.addAffectedItems(affectedItems, kindAndKey{kind, key})
}
}
}
}
return affectedItems
}
type outageTracker struct {
outageLoggingTimeout time.Duration
loggers ldlog.Loggers
inOutage bool
errorCounts map[intf.DataSourceErrorInfo]int
timeoutCloser chan struct{}
lock sync.Mutex
}
func newOutageTracker(outageLoggingTimeout time.Duration, loggers ldlog.Loggers) *outageTracker {
return &outageTracker{
outageLoggingTimeout: outageLoggingTimeout,
loggers: loggers,
}
}
func (o *outageTracker) trackDataSourceState(newState intf.DataSourceState, newError intf.DataSourceErrorInfo) {
if o.outageLoggingTimeout == 0 {
return
}
o.lock.Lock()
defer o.lock.Unlock()
if newState == intf.DataSourceStateInterrupted || newError.Kind != "" ||
(newState == intf.DataSourceStateInitializing && o.inOutage) {
// We are in a potentially recoverable outage. If that wasn't the case already, and if we've been
// configured with a timeout for logging the outage at a higher level, schedule that timeout.
if o.inOutage {
// We were already in one - just record this latest error for logging later.
o.recordError(newError)
} else {
// We weren't already in one, so set the timeout and start recording errors.
o.inOutage = true
o.errorCounts = make(map[intf.DataSourceErrorInfo]int)
o.recordError(newError)
o.timeoutCloser = make(chan struct{})
go o.awaitTimeout(o.timeoutCloser)
}
} else {
if o.timeoutCloser != nil {
close(o.timeoutCloser)
o.timeoutCloser = nil
}
o.inOutage = false
}
}
func (o *outageTracker) recordError(newError intf.DataSourceErrorInfo) {
// Accumulate how many times each kind of error has occurred during the outage - use just the basic
// properties as the key so the map won't expand indefinitely
basicErrorInfo := intf.DataSourceErrorInfo{Kind: newError.Kind, StatusCode: newError.StatusCode}
o.errorCounts[basicErrorInfo]++
}
func (o *outageTracker) awaitTimeout(closer chan struct{}) {
select {
case <-closer:
return
case <-time.After(o.outageLoggingTimeout):
break
}
o.lock.Lock()
if !o.inOutage {
// COVERAGE: there is no way to make this happen in unit tests; it is a very unlikely race condition
o.lock.Unlock()
return
}
errorsDesc := o.describeErrors()
o.timeoutCloser = nil
o.lock.Unlock()
o.loggers.Errorf(
"LaunchDarkly data source outage - updates have been unavailable for at least %s with the following errors: %s",
o.outageLoggingTimeout,
errorsDesc,
)
}
func (o *outageTracker) describeErrors() string {
ret := ""
for err, count := range o.errorCounts {
if ret != "" {
ret += ", "
}
times := "times"
if count == 1 {
times = "time"
}
ret += fmt.Sprintf("%s (%d %s)", err, count, times)
}
return ret
}