-
Notifications
You must be signed in to change notification settings - Fork 2
/
validate.go
104 lines (87 loc) · 2.4 KB
/
validate.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 main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"github.com/samber/lo"
)
type (
serviceConfig struct {
Dependencies struct {
EnvVars struct {
Required []dependency `json:"required"`
Optional []dependency `json:"optional"`
} `json:"env_vars"`
} `json:"dependencies"`
}
dependency struct {
dependencyInner
Partial bool `json:"-"`
}
dependencyInner struct {
Key string `json:"key"`
Regions []string `json:"regions"`
Products []string `json:"products"`
}
)
var ErrMissingEnvVars = errors.New("missing required environment variables")
// Required returns true if the dependency is required for the given region
func (d *dependency) Required(product, region string) bool {
return (d.Products == nil || lo.Contains(d.Products, product)) && (d.Regions == nil || lo.Contains(d.Regions, region))
}
// UnmarshalJSON handles the dependency being a string or an object
func (d *dependency) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err == nil {
d.Key = str
d.Partial = true
return nil
}
var dep dependencyInner
if err := json.Unmarshal(data, &dep); err != nil {
return fmt.Errorf("could not decode dependency: %w", err)
}
d.dependencyInner = dep
return nil
}
func validate(ctx context.Context, c *Config, e *EnvMap, l *slog.Logger) error {
if c.SkipValidation || c.Environment == "test" {
return nil
}
f, err := os.ReadFile(c.ServiceDefinition)
if os.IsNotExist(err) {
return nil
} else if err != nil {
return fmt.Errorf("could not read service definition: %w", err)
}
var cfg serviceConfig
if err := json.Unmarshal(f, &cfg); err != nil {
return fmt.Errorf("could not decode service definition: %w", err)
}
req := missing(cfg.Dependencies.EnvVars.Required, c, e)
opt := missing(cfg.Dependencies.EnvVars.Optional, c, e)
if len(opt) != 0 {
l.WarnContext(ctx, "Missing optional environment variables", "env_vars", opt)
}
if len(req) != 0 {
l.ErrorContext(ctx, "Missing required environment variables", "env_vars", req)
return fmt.Errorf("%w: %s", ErrMissingEnvVars, strings.Join(req, ", "))
}
return nil
}
func missing(deps []dependency, c *Config, e *EnvMap) []string {
res := []string{}
for _, d := range deps {
if !d.Required(c.Product, c.Region) {
continue
}
if v := os.Getenv(d.Key); v == "" && !e.Has(d.Key) {
res = append(res, d.Key)
}
}
return res
}