-
Notifications
You must be signed in to change notification settings - Fork 27
/
main.go
183 lines (148 loc) · 4.47 KB
/
main.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
package main
import (
"context"
"fmt"
"log"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/beatlabs/harvester"
harvesterconfig "github.com/beatlabs/harvester/config"
harvestersync "github.com/beatlabs/harvester/sync"
"github.com/hashicorp/consul/api"
"github.com/redis/go-redis/v9"
)
const (
consulAddress = "127.0.0.1:8500"
consulDC = ""
consulToken = ""
)
type config struct {
// IndexName demonstrates only seed.
IndexName harvestersync.String `seed:"customers-v1"`
// CacheRetention demonstrates seed and env var.
CacheRetention harvestersync.Int64 `seed:"43200" env:"ENV_CACHE_RETENTION_SECONDS"`
// LogLevel demonstrates seed and flag.
LogLevel harvestersync.String `seed:"DEBUG" flag:"loglevel"`
// OpeningBalance demonstrates seed, env var and redis.
OpeningBalance harvestersync.Float64 `seed:"0.0" redis:"opening-balance"`
// AccessToken demonstrates seed and consul for a secret.
AccessToken harvestersync.Secret `seed:"defaultaccesstoken" consul:"harvester/example/accesstoken"`
// Email demonstrates seed for a custom type.
Email Email `seed:"[email protected]"`
}
func (c *config) String() string {
return fmt.Sprintf("config: IndexName: %s CacheRetention: %d LogLevel: %s OpeningBalance: %f AccessToken: %s Email: %s",
c.IndexName.Get(), c.CacheRetention.Get(), c.LogLevel.Get(), c.OpeningBalance.Get(), c.AccessToken.Get(),
c.Email.String())
}
func main() {
ctx, cnl := context.WithCancel(context.Background())
defer cnl()
setEnvVarCacheRetention()
seedConsulAccessToken("currentaccesstoken")
setRedisOpeningBalance(ctx, "1000")
cfg := config{}
chNotify := make(chan harvesterconfig.ChangeNotification)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for change := range chNotify {
log.Printf("notification: " + change.String())
}
wg.Done()
}()
redisClient := createRedisClient()
h, err := harvester.New(&cfg, chNotify,
harvester.WithConsulSeed(consulAddress, consulDC, consulToken, 0),
harvester.WithConsulMonitor(consulAddress, consulDC, consulToken, 0),
harvester.WithRedisSeed(redisClient),
harvester.WithRedisMonitor(redisClient, 200*time.Millisecond),
)
if err != nil {
log.Fatalf("failed to create harvester: %v", err)
}
err = h.Harvest(ctx)
if err != nil {
log.Fatalf("failed to harvest configuration: %v", err)
}
log.Println(cfg.String())
seedConsulAccessToken("newtaccesstoken")
setRedisOpeningBalance(ctx, "2000")
time.Sleep(1 * time.Second) // Wait for the data to be updated async...
log.Println(cfg.String())
}
func setEnvVarCacheRetention() {
err := os.Setenv("ENV_CACHE_RETENTION_SECONDS", "86400")
if err != nil {
log.Fatalf("failed to set env var: %v", err)
}
}
func seedConsulAccessToken(accessToken string) {
cl, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatalf("failed to create consul client: %v", err)
}
p := &api.KVPair{Key: "harvester/example/accesstoken", Value: []byte(accessToken)}
_, err = cl.KV().Put(p, nil)
if err != nil {
log.Fatalf("failed to put key value pair to consul: %v", err)
}
}
func setRedisOpeningBalance(ctx context.Context, amount string) error {
_, err := createRedisClient().Set(ctx, "opening-balance", amount, 0).Result()
if err != nil {
return err
}
return nil
}
func createRedisClient() *redis.Client {
return redis.NewClient(&redis.Options{})
}
// regex to validate an email value.
const emailPattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
// Email represents a custom config structure.
type Email struct {
m sync.RWMutex
v string
name string
domain string
}
// SetString performs basic validation and sets a config value from string typed value.
func (t *Email) SetString(v string) error {
re := regexp.MustCompile(emailPattern)
if !re.MatchString(v) {
return fmt.Errorf("%s is not a valid email address", v)
}
t.m.Lock()
defer t.m.Unlock()
t.v = v
parts := strings.Split(v, "@")
t.name = parts[0]
t.domain = parts[1]
return nil
}
// Get returns the stored value.
func (t *Email) Get() string {
t.m.RLock()
defer t.m.RUnlock()
return t.v
}
// GetName returns name part of the stored email.
func (t *Email) GetName() string {
t.m.RLock()
defer t.m.RUnlock()
return t.name
}
// GetDomain returns domain part of the stored email.
func (t *Email) GetDomain() string {
t.m.RLock()
defer t.m.RUnlock()
return t.domain
}
// String represents golang Stringer interface.
func (t *Email) String() string {
return t.Get()
}