Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[confmap] Automatically invoke Validate() during Conf.Unmarshal #12031

Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .chloggen/tyler.confmap-configvalidator.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
component: confmap

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add ability for confmap to invoke `ConfigValidator.Validate` as part of `conf.Unmarshal`.

# One or more tracking issues or pull requests related to the change
issues: [12031]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [api]
95 changes: 93 additions & 2 deletions confmap/confmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"github.com/knadh/koanf/maps"
"github.com/knadh/koanf/providers/confmap"
"github.com/knadh/koanf/v2"
"go.uber.org/multierr"

encoder "go.opentelemetry.io/collector/confmap/internal/mapstructure"
)
Expand Down Expand Up @@ -59,7 +60,8 @@
}

type unmarshalOption struct {
ignoreUnused bool
ignoreUnused bool
invokeValidate bool
}

// WithIgnoreUnused sets an option to ignore errors if existing
Expand All @@ -71,20 +73,109 @@
})
}

// WithInvokeValidate sets an option to invoke the Validate method
// of unmarshalled types that implement ConfigValidator.
// When used, config validation with be executed automatically
// as part of unmarshalling.
func WithInvokeValidate() UnmarshalOption {
return unmarshalOptionFunc(func(uo *unmarshalOption) {
uo.invokeValidate = true
})
}

type unmarshalOptionFunc func(*unmarshalOption)

func (fn unmarshalOptionFunc) apply(set *unmarshalOption) {
fn(set)
}

// ConfigValidator defines an optional interface for configurations to implement to do validation.
type ConfigValidator interface {
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
// Validate the configuration and returns an error if invalid.
Validate() error
}

// As interface types are only used for static typing, a common idiom to find the reflection Type
// for an interface type Foo is to use a *Foo value.
var configValidatorType = reflect.TypeOf((*ConfigValidator)(nil)).Elem()

func validate(v reflect.Value) error {
// Validate the value itself.
k := v.Kind()
switch k {
case reflect.Invalid:
return nil

Check warning on line 107 in confmap/confmap.go

View check run for this annotation

Codecov / codecov/patch

confmap/confmap.go#L106-L107

Added lines #L106 - L107 were not covered by tests
case reflect.Ptr, reflect.Interface:
return validate(v.Elem())
case reflect.Struct:
var errs error
errs = multierr.Append(errs, callValidateIfPossible(v))
// Reflect on the pointed data and check each of its fields.
for i := 0; i < v.NumField(); i++ {
if !v.Type().Field(i).IsExported() {
continue

Check warning on line 116 in confmap/confmap.go

View check run for this annotation

Codecov / codecov/patch

confmap/confmap.go#L116

Added line #L116 was not covered by tests
}
errs = multierr.Append(errs, validate(v.Field(i)))
}
return errs
case reflect.Slice, reflect.Array:
var errs error
errs = multierr.Append(errs, callValidateIfPossible(v))
// Reflect on the pointed data and check each of its fields.
for i := 0; i < v.Len(); i++ {
errs = multierr.Append(errs, validate(v.Index(i)))
}
return errs
case reflect.Map:
var errs error
errs = multierr.Append(errs, callValidateIfPossible(v))
iter := v.MapRange()
for iter.Next() {
errs = multierr.Append(errs, validate(iter.Key()))
errs = multierr.Append(errs, validate(iter.Value()))
}
return errs
default:
return callValidateIfPossible(v)
}
}

func callValidateIfPossible(v reflect.Value) error {
// If the value type implements ConfigValidator just call Validate
if v.Type().Implements(configValidatorType) {
return v.Interface().(ConfigValidator).Validate()
}

Check warning on line 147 in confmap/confmap.go

View check run for this annotation

Codecov / codecov/patch

confmap/confmap.go#L146-L147

Added lines #L146 - L147 were not covered by tests

// If the pointer type implements ConfigValidator call Validate on the pointer to the current value.
if reflect.PointerTo(v.Type()).Implements(configValidatorType) {
// If not addressable, then create a new *V pointer and set the value to current v.
if !v.CanAddr() {
pv := reflect.New(reflect.PointerTo(v.Type()).Elem())
pv.Elem().Set(v)
v = pv.Elem()
}
return v.Addr().Interface().(ConfigValidator).Validate()
}

return nil
}

// Unmarshal unmarshalls the config into a struct using the given options.
// Tags on the fields of the structure must be properly set.
func (l *Conf) Unmarshal(result any, opts ...UnmarshalOption) error {
set := unmarshalOption{}
for _, opt := range opts {
opt.apply(&set)
}
return decodeConfig(l, result, !set.ignoreUnused, l.skipTopLevelUnmarshaler)
err := decodeConfig(l, result, !set.ignoreUnused, l.skipTopLevelUnmarshaler)
if err != nil {
return err
}

if set.invokeValidate {
return validate(reflect.ValueOf(result))
}
return nil
}

type marshalOption struct{}
Expand Down
105 changes: 105 additions & 0 deletions confmap/confmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -964,3 +964,108 @@ func TestStringyTypes(t *testing.T) {
assert.Equal(t, tt.isStringy, isStringyStructure(to))
}
}

type validateConfig struct {
String string `mapstructure:"string"`
Nested nestedValidateConfig `mapstructure:"nested"`
SliceNested []nestedValidateConfig `mapstructure:"slice"`
MapNested map[string]nestedValidateConfig `mapstructure:"map"`
}

func (c *validateConfig) Validate() error {
if c.String == "error" {
return errors.New("error in validateConfig because String")
}
return nil
}

type nestedValidateConfig struct {
String string `mapstructure:"string"`
}

func (c *nestedValidateConfig) Validate() error {
if c.String == "error" {
return errors.New("error in nestedValidateConfig because String")
}
return nil
}

func TestUnmarshalInvokesValidate(t *testing.T) {
tests := []struct {
name string
input map[string]any
err error
}{
{
name: "Validation passes",
input: map[string]any{
"string": "value",
"nested": nestedValidateConfig{
String: "value",
},
"slice": []nestedValidateConfig{
{
String: "value",
},
},
"map": map[string]nestedValidateConfig{
"key": {
String: "value",
},
},
},
err: nil,
},
{
name: "Validation fails because String",
input: map[string]any{
"string": "error",
},
err: errors.New("error in validateConfig because String"),
},
{
name: "Validation fails because nested String",
input: map[string]any{
"nested": nestedValidateConfig{
String: "error",
},
},
err: errors.New("error in nestedValidateConfig because String"),
},
{
name: "Validation fails because nested slice String",
input: map[string]any{
"slice": []nestedValidateConfig{
{
String: "error",
},
},
},
err: errors.New("error in nestedValidateConfig because String"),
},
{
name: "Validation fails because nested map String",
input: map[string]any{
"map": map[string]nestedValidateConfig{
"key": {
String: "error",
},
},
},
err: errors.New("error in nestedValidateConfig because String"),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conf := NewFromStringMap(tt.input)
c := &validateConfig{}
err := conf.Unmarshal(c, WithInvokeValidate())
if tt.err == nil {
require.NoError(t, err)
} else {
require.Equal(t, tt.err, err)
}
})
}
}
Loading