-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.go
More file actions
396 lines (320 loc) · 11.7 KB
/
Copy pathconfig.go
File metadata and controls
396 lines (320 loc) · 11.7 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package aastro
import (
"errors"
"fmt"
"io"
"os"
"reflect"
"regexp"
"strings"
"time"
"github.com/creasty/defaults"
"github.com/go-playground/validator/v10"
"gopkg.in/yaml.v3"
)
type Config struct {
Schema string `yaml:"schema" validate:"required,oneof=v1"`
Debug bool `yaml:"debug"`
Gateway GatewayConfig `yaml:"gateway" validate:"required"`
}
func (c *Config) Marshal() ([]byte, error) {
return yaml.Marshal(c)
}
func (c *Config) WriteTo(w io.Writer) (int64, error) {
data, err := c.Marshal()
if err != nil {
return 0, fmt.Errorf("marshal config: %w", err)
}
n, err := w.Write(data)
return int64(n), err
}
type GatewayConfig struct {
Service ServiceConfig `yaml:"service"`
Server ServerConfig `yaml:"server" validate:"required"`
Admin AdminConfig `yaml:"admin" validate:"required"`
Observability ObservabilityConfig `yaml:"observability"`
Routing RoutingConfig `yaml:"routing" validate:"required"`
}
type ServiceConfig struct {
Name string `yaml:"name" default:"aastro"`
}
type ServerConfig struct {
Port int `yaml:"port" validate:"required,min=1,max=65535"`
Timeout time.Duration `yaml:"timeout" default:"5s"`
HeaderTimeout time.Duration `yaml:"header_timeout" default:"5s"`
TLS ServerTLSConfig `yaml:"tls"`
}
type AdminConfig struct {
Port int `yaml:"port" validate:"required,min=1,max=65535"`
BindAddr string `yaml:"bind_addr" default:"127.0.0.1"`
Timeout time.Duration `yaml:"timeout" default:"5m"`
HeaderTimeout time.Duration `yaml:"header_timeout" default:"5s"`
EnablePprof bool `yaml:"enable_pprof" default:"false"`
}
type ObservabilityConfig struct {
Tracing TracingConfig `yaml:"tracing"`
Metrics MetricsConfig `yaml:"metrics"`
}
type MetricsConfig struct {
Enabled bool `yaml:"enabled"`
Exporter string `yaml:"exporter" validate:"required_if=Enabled true,omitempty,oneof=otlp prometheus"`
OTLP OTLPConfig `yaml:"otlp"`
}
type TracingConfig struct {
Enabled bool `yaml:"enabled"`
Exporter string `yaml:"exporter" validate:"required_if=Enabled true,omitempty,oneof=otlp"`
SamplingRatio float64 `yaml:"sampling_ratio" default:"1.0" validate:"min=0,max=1"`
OTLP OTLPConfig `yaml:"otlp"`
}
type OTLPConfig struct {
Endpoint string `yaml:"endpoint"`
Insecure bool `yaml:"insecure"`
Interval time.Duration `yaml:"interval"`
}
type ServerTLSConfig struct {
Enabled bool `yaml:"enabled"`
CertFile string `yaml:"cert_file" validate:"required_if=Enabled true"`
KeyFile string `yaml:"key_file" validate:"required_if=Enabled true"`
MinVersion string `yaml:"min_version" default:"1.2" validate:"omitempty,oneof=1.2 1.3"`
ClientAuth string `yaml:"client_auth" default:"none" validate:"omitempty,oneof=require optional none"`
ClientCAFile string `yaml:"client_ca_file" validate:"required_unless=ClientAuth none"`
}
type RoutingConfig struct {
RateLimiter RateLimiterConfig `yaml:"rate_limiter" validate:"omitempty"`
TrustedProxies []string `yaml:"trusted_proxies"`
Flows []FlowConfig `yaml:"flows" validate:"min=1,dive,required"`
}
type RateLimiterConfig struct {
Enabled bool `yaml:"enabled"`
Config map[string]interface{} `yaml:"config" validate:"required"`
}
type FlowConfig struct {
Path string `yaml:"path" validate:"required,startswith=/"`
Method string `yaml:"method" validate:"required,oneof=GET POST PUT PATCH DELETE HEAD OPTIONS QUERY"`
Streaming bool `yaml:"streaming"`
// Aggregation is required only for flows with more than one upstream -
// a single-upstream flow is proxied directly and never aggregates
// (enforced in validateFlows, since that depends on len(Upstreams)).
Aggregation *AggregationConfig `yaml:"aggregation"`
Upstreams []UpstreamConfig `yaml:"upstreams" validate:"required,min=1,dive,required"`
Plugins []PluginConfig `yaml:"plugins" validate:"omitempty,dive"`
Middlewares []MiddlewareConfig `yaml:"middlewares" validate:"omitempty,dive"`
}
type AggregationConfig struct {
BestEffort bool `yaml:"best_effort"`
Strategy string `yaml:"strategy" validate:"required,oneof=array merge namespace"`
OnConflict *OnConflictConfig `yaml:"on_conflict" validate:"required_if=Strategy merge"`
}
type OnConflictConfig struct {
Policy string `yaml:"policy" validate:"oneof=overwrite error first prefer"`
Upstream string `yaml:"prefer_upstream" validate:"required_if=Policy prefer"`
}
type UpstreamConfig struct {
Name string `yaml:"name" validate:"required"`
Hosts AddrList `yaml:"hosts" validate:"min=1,dive"`
Path string `yaml:"path"`
Method string `yaml:"method"`
Timeout time.Duration `yaml:"timeout" default:"3s"`
ForwardHeaders []string `yaml:"forward_headers"`
ForwardQueries []string `yaml:"forward_queries"`
ForwardParams []string `yaml:"forward_params"`
Policy PolicyConfig `yaml:"policy"`
Transport TransportConfig `yaml:"transport"`
TLS TLSConfig `yaml:"tls"`
}
type TLSConfig struct {
Enabled bool `yaml:"enabled"`
CertFile string `yaml:"cert_file" validate:"required_with=KeyFile"`
KeyFile string `yaml:"key_file" validate:"required_with=CertFile"`
CAFile string `yaml:"ca_file"`
ServerName string `yaml:"server_name"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
MinVersion string `yaml:"min_version" default:"1.2" validate:"omitempty,oneof=1.2 1.3"`
}
type TransportConfig struct {
MaxIdleConns int `yaml:"max_idle_conns" default:"100"`
MaxIdleConnsPerHost int `yaml:"max_idle_conns_per_host" default:"50"`
IdleConnTimeout time.Duration `yaml:"idle_conn_timeout" default:"90s"`
}
type PluginConfig struct {
Name string `yaml:"name" validate:"required"`
Source string `yaml:"source" validate:"required,oneof=builtin file"`
Path string `yaml:"path" validate:"required_if=Source file"`
Config map[string]interface{} `yaml:"config"`
}
type MiddlewareConfig struct {
Name string `yaml:"name" validate:"required"`
Source string `yaml:"source" validate:"required,oneof=builtin file"`
Path string `yaml:"path" validate:"required_if=Source file,omitempty"`
Config map[string]interface{} `yaml:"config"`
}
type PolicyConfig struct {
HeaderBlacklist []string `yaml:"header_blacklist"`
RequireBody bool `yaml:"require_body"`
MaxResponseBodySize int64 `yaml:"max_response_body_size"`
FollowRedirects bool `yaml:"follow_redirects"`
RetryConfig RetryConfig `yaml:"retry"`
CircuitBreakerConfig CircuitBreakerConfig `yaml:"circuit_breaker"`
LoadBalancingConfig LoadBalancingConfig `yaml:"load_balancing"`
}
type RetryConfig struct {
MaxRetries int `yaml:"max_retries"`
RetryOnStatuses []int `yaml:"retry_on_statuses"`
BackoffDelay time.Duration `yaml:"backoff_delay"`
}
type CircuitBreakerConfig struct {
Enabled bool `yaml:"enabled"`
MaxFailures int `yaml:"max_failures"`
ResetTimeout time.Duration `yaml:"reset_timeout"`
}
type LoadBalancingConfig struct {
Mode string `yaml:"mode"`
}
type AddrList []string
func (a *AddrList) UnmarshalYAML(value *yaml.Node) error {
switch value.Kind {
case yaml.ScalarNode:
var addr string
if err := value.Decode(&addr); err != nil {
return err
}
*a = []string{addr}
return nil
case yaml.SequenceNode:
var addrs []string
if err := value.Decode(&addrs); err != nil {
return err
}
*a = addrs
return nil
case yaml.DocumentNode, yaml.MappingNode, yaml.AliasNode:
return fmt.Errorf("expects a string or sequence, got %v", value.Kind)
default:
return fmt.Errorf("unexpected yaml node kind for AddrList: %v", value.Kind)
}
}
// LoadConfig reads, parses, applies defaults, validates, and returns the config.
func LoadConfig(path string) (Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return Config{}, fmt.Errorf("cannot read configuration file: %w", err)
}
var cfg Config
if err = yaml.Unmarshal(data, &cfg); err != nil {
return Config{}, fmt.Errorf("cannot parse configuration file: %w", err)
}
if err = ValidateConfig(&cfg); err != nil {
return Config{}, err
}
return cfg, nil
}
func DefaultUpstreamConfig() UpstreamConfig {
var u UpstreamConfig
_ = defaults.Set(&u)
return u
}
func ValidateConfig(cfg *Config) error {
if err := defaults.Set(cfg); err != nil {
return fmt.Errorf("cannot apply configuration defaults: %w", err)
}
v := newValidator()
if err := v.Struct(cfg); err != nil {
return fmt.Errorf("invalid configuration:\n%w", formatValidationError(err))
}
if cfg.Gateway.Server.Port == cfg.Gateway.Admin.Port {
return errors.New("server.port and admin.port must differ")
}
if err := validateFlows(*cfg); err != nil {
return fmt.Errorf("invalid flow configuration: %w", err)
}
return nil
}
func newValidator() *validator.Validate {
v := validator.New()
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := fld.Tag.Get("yaml")
if name == "" || name == "-" {
return strings.ToLower(fld.Name)
}
return strings.ToLower(strings.Split(name, ",")[0])
})
return v
}
var pathParamPattern = regexp.MustCompile(`\{([^}]+)\}`)
func validateFlows(cfg Config) error {
for _, f := range cfg.Gateway.Routing.Flows {
flowParams := extractPathParams(f.Path)
for _, u := range f.Upstreams {
if err := validateUpstreamParams(u, flowParams, f.Path); err != nil {
return err
}
}
if f.Streaming && len(f.Upstreams) > 1 {
return fmt.Errorf("flow %q: streaming flow must have only one upstream", f.Path)
}
if !f.Streaming && len(f.Upstreams) > 1 && f.Aggregation == nil {
return fmt.Errorf("flow %q: aggregation is required for flows with more than one upstream", f.Path)
}
}
return nil
}
func extractPathParams(path string) map[string]struct{} {
params := make(map[string]struct{})
for _, match := range pathParamPattern.FindAllStringSubmatch(path, -1) {
params[match[1]] = struct{}{}
}
return params
}
func validateUpstreamParams(u UpstreamConfig, flowParams map[string]struct{}, flowPath string) error {
for _, match := range pathParamPattern.FindAllStringSubmatch(u.Path, -1) {
if _, ok := flowParams[match[1]]; !ok {
return fmt.Errorf(
"upstream %q: path param '{%s}' not declared in flow path %q",
u.Name, match[1], flowPath,
)
}
}
for _, param := range u.ForwardParams {
if param == "*" {
continue
}
if _, ok := flowParams[param]; !ok {
return fmt.Errorf(
"upstream %q: forward_param %q not declared in flow path %q",
u.Name, param, flowPath,
)
}
}
return nil
}
func formatValidationError(err error) error {
var ves validator.ValidationErrors
if !errors.As(err, &ves) {
return err
}
messages := make([]string, 0, len(ves))
for _, fe := range ves {
path := strings.TrimPrefix(fe.Namespace(), "Config.")
messages = append(messages, fmt.Sprintf(" %s: %s", path, validationMessage(fe)))
}
return errors.New(strings.Join(messages, "\n"))
}
func validationMessage(fe validator.FieldError) string {
switch fe.Tag() {
case "required":
return "field is required"
case "min":
return fmt.Sprintf("must have at least %s item(s)", fe.Param())
case "oneof":
return fmt.Sprintf("must be one of [%s]", fe.Param())
case "hosts":
return "must be a valid URL"
case "required_if":
if fe.Field() == "path" {
return "is required when source is 'file'"
}
return fe.Error()
default:
return fmt.Sprintf("validation failed on %q", fe.Tag())
}
}