This repository has been archived by the owner on Oct 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
polling.go
117 lines (101 loc) · 2.55 KB
/
polling.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
package ldclient
import (
"sync"
"time"
)
type pollingProcessor struct {
store FeatureStore
requestor *requestor
config Config
setInitializedOnce sync.Once
isInitialized bool
quit chan struct{}
closeOnce sync.Once
}
func newPollingProcessor(config Config, requestor *requestor) *pollingProcessor {
pp := &pollingProcessor{
store: config.FeatureStore,
requestor: requestor,
config: config,
quit: make(chan struct{}),
}
return pp
}
func (pp *pollingProcessor) Start(closeWhenReady chan<- struct{}) {
pp.config.Logger.Printf("Starting LaunchDarkly polling processor with interval: %+v", pp.config.PollInterval)
ticker := newTickerWithInitialTick(pp.config.PollInterval)
go func() {
defer ticker.Stop()
var readyOnce sync.Once
notifyReady := func() {
readyOnce.Do(func() {
close(closeWhenReady)
})
}
// Ensure we stop waiting for initialization if we exit, even if initialization fails
defer notifyReady()
for {
select {
case <-pp.quit:
pp.config.Logger.Printf("Polling Processor closed.")
return
case <-ticker.C:
if err := pp.poll(); err != nil {
pp.config.Logger.Printf("ERROR: Error when requesting feature updates: %+v", err)
if hse, ok := err.(HttpStatusError); ok {
pp.config.Logger.Printf("ERROR: %s", httpErrorMessage(hse.Code, "polling request", "will retry"))
if !isHTTPErrorRecoverable(hse.Code) {
notifyReady()
return
}
}
continue
}
pp.setInitializedOnce.Do(func() {
pp.isInitialized = true
notifyReady()
})
}
}
}()
}
func (pp *pollingProcessor) poll() error {
allData, cached, err := pp.requestor.requestAll()
if err != nil {
return err
}
// We initialize the store only if the request wasn't cached
if !cached {
return pp.store.Init(MakeAllVersionedDataMap(allData.Flags, allData.Segments))
}
return nil
}
func (pp *pollingProcessor) Close() error {
pp.closeOnce.Do(func() {
pp.config.Logger.Printf("Closing Polling Processor")
close(pp.quit)
})
return nil
}
func (pp *pollingProcessor) Initialized() bool {
return pp.isInitialized
}
type tickerWithInitialTick struct {
*time.Ticker
C <-chan time.Time
}
func newTickerWithInitialTick(interval time.Duration) *tickerWithInitialTick {
c := make(chan time.Time)
ticker := time.NewTicker(interval)
t := &tickerWithInitialTick{
C: c,
Ticker: ticker,
}
go func() {
c <- time.Now() // Ensure we do an initial poll immediately
for tt := range ticker.C {
c <- tt
}
}()
return t
}