-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdatasource_poll.go
104 lines (88 loc) · 1.89 KB
/
datasource_poll.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
package growthbook
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
)
type PollDataSource struct {
client *Client
logger *slog.Logger
interval time.Duration
cancel context.CancelFunc
ready bool
etag string
}
func WithPollDataSource(interval time.Duration) ClientOption {
return func(c *Client) error {
c.data.dataSource = newPollDataSource(c, interval)
return nil
}
}
func newPollDataSource(client *Client, interval time.Duration) *PollDataSource {
return &PollDataSource{
client: client,
interval: interval,
logger: client.logger.With("source", "Growthbook polling datasource"),
}
}
func (ds *PollDataSource) Start(ctx context.Context) error {
ds.logger.Info("Starting")
ctx, cancel := context.WithCancel(ctx)
ds.cancel = cancel
err := ds.loadData(ctx)
if err != nil {
return err
}
ds.logger.Info("First load finished")
ds.ready = true
go ds.startPolling(ctx)
ds.logger.Info("Started")
return nil
}
func (ds *PollDataSource) Close() error {
if !ds.ready {
return fmt.Errorf("Datasource is not ready")
}
ds.logger.Info("Closing")
ds.cancel()
return nil
}
func (ds *PollDataSource) startPolling(ctx context.Context) {
for {
timer := time.NewTimer(ds.interval)
select {
case <-ctx.Done():
ds.ready = false
ds.logger.Info("Finished polling due to context")
return
case <-timer.C:
err := ds.loadData(ctx)
if err != nil {
ds.logger.Error("Error loading features", "error", err)
}
if errors.Is(err, context.Canceled) {
ds.logger.Info("Finished polling due to context")
return
}
}
}
}
func (ds *PollDataSource) loadData(ctx context.Context) error {
resp, err := ds.client.CallFeatureApi(ctx, ds.etag)
if err != nil {
return err
}
if resp.Etag != "" {
ds.etag = resp.Etag
}
if resp.Features == nil {
return nil
}
err = ds.client.UpdateFromApiResponse(resp)
if err != nil {
return err
}
return nil
}