-
Notifications
You must be signed in to change notification settings - Fork 5
/
sync.go
126 lines (115 loc) · 2.59 KB
/
sync.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
package featureprobe
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
)
type Synchronizer struct {
auth string
togglesUrl string
RefreshInterval time.Duration
repository *Repository
httpClient http.Client
mu sync.Mutex
startOnce sync.Once
stopOnce sync.Once
setInitializedOnce sync.Once
isInitialized bool
stopChan chan struct{}
ticker *time.Ticker
enablePolling bool
}
func NewSynchronizer(url string, RefreshInterval time.Duration, auth string, repo *Repository) Synchronizer {
return Synchronizer{
auth: auth,
togglesUrl: url,
RefreshInterval: RefreshInterval,
httpClient: newHttpClient(RefreshInterval),
repository: repo,
stopChan: make(chan struct{}),
enablePolling: true,
}
}
func NewCustomRepoSynchronizer(repo *Repository) Synchronizer {
return Synchronizer{
repository: repo,
stopChan: make(chan struct{}),
enablePolling: false,
}
}
func (s *Synchronizer) Start(ready chan<- struct{}) {
var readyOnce sync.Once
notifyReady := func() {
readyOnce.Do(func() {
close(ready)
})
}
if !s.enablePolling {
s.isInitialized = true
notifyReady()
return
}
s.startOnce.Do(func() {
s.ticker = time.NewTicker(s.RefreshInterval)
go func() {
for {
select {
case <-s.stopChan:
return
case <-s.ticker.C:
err := s.FetchRemoteRepo()
if err == nil {
s.setInitializedOnce.Do(func() {
// first sync success
s.isInitialized = true
notifyReady()
})
}
}
}
}()
})
}
// Initialized return false means not successfully fetch remote resource
func (s *Synchronizer) Initialized() bool {
return s.isInitialized
}
func (s *Synchronizer) Stop() {
if s.stopChan != nil {
s.stopOnce.Do(func() {
close(s.stopChan)
s.isInitialized = false
})
}
}
// FetchRemoteRepo fetch remote repo and update local repo
func (s *Synchronizer) FetchRemoteRepo() error {
req, err := http.NewRequest(http.MethodGet, s.togglesUrl, nil)
if err != nil {
fmt.Printf("%s\n", err)
return err
}
req.Header.Add("Authorization", s.auth)
req.Header.Add("User-Agent", USER_AGENT)
s.mu.Lock()
resp, err := s.httpClient.Do(req)
s.mu.Unlock()
if err != nil {
fmt.Printf("%s\n", err)
return err
}
defer resp.Body.Close()
bodyBytes, _ := ioutil.ReadAll(resp.Body)
s.mu.Lock()
repoData := RepositoryData{}
err = json.Unmarshal(bodyBytes, &repoData)
s.repository.flush(repoData)
s.mu.Unlock()
if err != nil {
fmt.Printf("%s\n", err)
}
return err
}