|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "reflect" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/go-playground/validator/v10" |
| 12 | + "gopkg.in/yaml.v3" |
| 13 | +) |
| 14 | + |
| 15 | +// FileConfig represents the top-level YAML configuration file. |
| 16 | +type FileConfig struct { |
| 17 | + WorkerID string `yaml:"worker_id"` |
| 18 | + Cleanup *bool `yaml:"cleanup"` |
| 19 | + Backend BackendConfig `yaml:"backend"` |
| 20 | +} |
| 21 | + |
| 22 | +// BackendConfig contains the backend selection. |
| 23 | +// At most one backend field may be non-nil; configuring multiple backends simultaneously is an error. |
| 24 | +type BackendConfig struct { |
| 25 | + Docker *DockerConfig `yaml:"docker"` |
| 26 | +} |
| 27 | + |
| 28 | +// DockerConfig holds Docker-backend-specific configuration. |
| 29 | +type DockerConfig struct { |
| 30 | + Volumes []string `yaml:"volumes"` |
| 31 | + Environment []EnvEntry `yaml:"environment" validate:"dive"` |
| 32 | +} |
| 33 | + |
| 34 | +// EnvEntry represents a single environment variable in the config file. |
| 35 | +// If Value is nil, the variable is inherited from the host process environment. |
| 36 | +type EnvEntry struct { |
| 37 | + Name string `yaml:"name" validate:"required,no_whitespace"` |
| 38 | + Value *string `yaml:"value"` |
| 39 | +} |
| 40 | + |
| 41 | +// configValidator is the package-level validator instance, initialized once. |
| 42 | +var configValidator = newConfigValidator() |
| 43 | + |
| 44 | +func newConfigValidator() *validator.Validate { |
| 45 | + v := validator.New() |
| 46 | + |
| 47 | + // no_whitespace rejects strings that contain spaces or tabs. |
| 48 | + _ = v.RegisterValidation("no_whitespace", func(fl validator.FieldLevel) bool { |
| 49 | + return !strings.ContainsAny(fl.Field().String(), " \t") |
| 50 | + }) |
| 51 | + |
| 52 | + // Struct-level validator for BackendConfig: at most one backend field may be non-nil. |
| 53 | + // Uses reflection so that future backend fields are automatically covered. |
| 54 | + v.RegisterStructValidation(func(sl validator.StructLevel) { |
| 55 | + cfg := sl.Current() |
| 56 | + configured := 0 |
| 57 | + for i := 0; i < cfg.NumField(); i++ { |
| 58 | + if cfg.Field(i).Kind() == reflect.Ptr && !cfg.Field(i).IsNil() { |
| 59 | + configured++ |
| 60 | + } |
| 61 | + } |
| 62 | + if configured > 1 { |
| 63 | + sl.ReportError(sl.Current().Interface(), "Backend", "Backend", "only_one_backend", "") |
| 64 | + } |
| 65 | + }, BackendConfig{}) |
| 66 | + |
| 67 | + return v |
| 68 | +} |
| 69 | + |
| 70 | +// Load reads and validates a YAML config file. |
| 71 | +func Load(path string) (*FileConfig, error) { |
| 72 | + data, err := os.ReadFile(path) |
| 73 | + if err != nil { |
| 74 | + return nil, fmt.Errorf("failed to read config file: %w", err) |
| 75 | + } |
| 76 | + |
| 77 | + var cfg FileConfig |
| 78 | + decoder := yaml.NewDecoder(bytes.NewReader(data)) |
| 79 | + decoder.KnownFields(true) |
| 80 | + if err := decoder.Decode(&cfg); err != nil { |
| 81 | + return nil, fmt.Errorf("failed to parse config file: %w", err) |
| 82 | + } |
| 83 | + |
| 84 | + if err := configValidator.Struct(cfg); err != nil { |
| 85 | + return nil, fmt.Errorf("invalid config: %w", formatValidationErrors(err)) |
| 86 | + } |
| 87 | + |
| 88 | + return &cfg, nil |
| 89 | +} |
| 90 | + |
| 91 | +// formatValidationErrors converts validator.ValidationErrors into a human-readable error. |
| 92 | +func formatValidationErrors(err error) error { |
| 93 | + var validationErrors validator.ValidationErrors |
| 94 | + if !errors.As(err, &validationErrors) { |
| 95 | + return err |
| 96 | + } |
| 97 | + |
| 98 | + msgs := make([]string, 0, len(validationErrors)) |
| 99 | + for _, e := range validationErrors { |
| 100 | + switch e.Tag() { |
| 101 | + case "required": |
| 102 | + msgs = append(msgs, fmt.Sprintf("%s is required", e.Namespace())) |
| 103 | + case "no_whitespace": |
| 104 | + msgs = append(msgs, fmt.Sprintf("%s must not contain whitespace", e.Namespace())) |
| 105 | + case "only_one_backend": |
| 106 | + msgs = append(msgs, "at most one backend may be configured") |
| 107 | + default: |
| 108 | + msgs = append(msgs, fmt.Sprintf("%s failed validation %q", e.Namespace(), e.Tag())) |
| 109 | + } |
| 110 | + } |
| 111 | + return fmt.Errorf("%s", strings.Join(msgs, "; ")) |
| 112 | +} |
| 113 | + |
| 114 | +// ResolveEnv converts environment entries to a map, resolving host-inherited values. |
| 115 | +func ResolveEnv(entries []EnvEntry) map[string]string { |
| 116 | + result := make(map[string]string, len(entries)) |
| 117 | + for _, entry := range entries { |
| 118 | + if entry.Value != nil { |
| 119 | + result[entry.Name] = *entry.Value |
| 120 | + } else { |
| 121 | + result[entry.Name] = os.Getenv(entry.Name) |
| 122 | + } |
| 123 | + } |
| 124 | + return result |
| 125 | +} |
0 commit comments