-
Notifications
You must be signed in to change notification settings - Fork 8
/
config.go
102 lines (93 loc) · 2.37 KB
/
config.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
package dispatch
import (
"github.com/viant/bqtail/base"
"github.com/viant/bqtail/dispatch/config"
"time"
"context"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/viant/afs"
"os"
"strings"
)
//Config represents dispatchBqEvents config
type Config struct {
base.Config
config.Ruleset
TimeToLiveInMin int
MaxConcurrentSQL int
MaxConcurrentLoad int
}
//TimeToLive returns time to live
func (c *Config) TimeToLive() time.Duration {
if c.TimeToLiveInMin == 0 {
c.TimeToLiveInMin = 1
}
return time.Minute*time.Duration(c.TimeToLiveInMin) - (5 * time.Second)
}
//Init initialises config
func (c *Config) Init(ctx context.Context, fs afs.Service) error {
err := c.Config.Init(ctx)
if err != nil {
return err
}
if c.TimeToLiveInMin == 0 {
c.TimeToLiveInMin = 1
}
return c.Ruleset.Init(ctx, fs, c.ProjectID)
}
//ReloadIfNeeded reloads rules if needed
func (c *Config) ReloadIfNeeded(ctx context.Context, fs afs.Service) error {
_, err := c.Ruleset.ReloadIfNeeded(ctx, fs)
return err
}
//NewConfigFromEnv creates config from env
func NewConfigFromEnv(ctx context.Context, key string) (*Config, error) {
if key == "" {
return nil, errors.New("os env cfg key was empty")
}
data := os.Getenv(key)
if data == "" {
return nil, fmt.Errorf("env.%v was empty", key)
}
cfg := &Config{}
err := json.NewDecoder(strings.NewReader(data)).Decode(cfg)
if err != nil {
return nil, errors.Wrapf(err, "failed to decode config: %s", data)
}
if err = cfg.Init(ctx, afs.New()); err != nil {
return nil, err
}
err = cfg.Config.Validate()
return cfg, err
}
//NewConfigFromURL creates new config from URL
func NewConfigFromURL(ctx context.Context, URL string) (*Config, error) {
storageService := afs.New()
data, err := storageService.DownloadWithURL(ctx, URL)
if err != nil {
return nil, err
}
cfg := &Config{}
err = json.Unmarshal(data, cfg)
if err != nil {
return nil, errors.Wrapf(err, "failed to decode config: %s", URL)
}
if err = cfg.Init(ctx, afs.New()); err != nil {
return cfg, err
}
err = cfg.Config.Validate()
return cfg, err
}
//NewConfig creates a new config from env (json or URL)
func NewConfig(ctx context.Context, key string) (*Config, error) {
if key == "" {
return nil, fmt.Errorf("config key was empty")
}
value := os.Getenv(key)
if json.Valid([]byte(value)) {
return NewConfigFromEnv(ctx, key)
}
return NewConfigFromURL(ctx, value)
}