Debian Codegraph @

config/configoptional/optional.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package configoptional // import "go.opentelemetry.io/collector/config/configoptional"
5
6 import (
7 "errors"
8 "fmt"
9 "reflect"
10 "strings"
11
12 "go.opentelemetry.io/collector/confmap"
13 "go.opentelemetry.io/collector/confmap/xconfmap"
14 "go.opentelemetry.io/collector/featuregate"
15 )
16
17 type flavor int
18
19 const (
20 noneFlavor flavor = 0
21 defaultFlavor flavor = 1
22 someFlavor flavor = 2
23 )
24
25 // Optional represents a value that may or may not be present.
26 // It supports two flavors for all types: Some(value) and None.
27 // It supports a third flavor for struct types: Default(defaultVal).
28 //
29 // For struct types, it supports unmarshaling from a configuration source.
30 // For struct types, it supports an 'enabled' field to explicitly disable a section.
31 // The zero value of Optional is None.
32 type Optional[T any] struct {
33 // value is the value of the Optional.
34 value T
35
36 // flavor indicates the flavor of the Optional.
37 // The zero value of flavor is noneFlavor.
38 flavor flavor
39 }
40
41 // deref a reflect.Type to its underlying type.
42 func deref(t reflect.Type) reflect.Type {
43 for t.Kind() == reflect.Ptr {
44 t = t.Elem()
45 }
46 return t
47 }
48
49 // assertStructKind checks if T can be dereferenced into a type with struct kind.
50 //
51 // We assert this because our unmarshaling logic currently only supports structs.
52 // This can be removed if we ever support scalar values.
53 func assertStructKind[T any]() error {
54 var instance T
55 t := deref(reflect.TypeOf(instance))
56 if t.Kind() != reflect.Struct {
57 return fmt.Errorf("configoptional: %q does not have a struct kind", t)
58 }
59
60 return nil
61 }
62
63 // assertNoEnabledField checks that a struct type
64 // does not have a field with a mapstructure tag "enabled".
65 //
66 // We assert this because we discussed an alternative design where we have an explicit
67 // "enabled" field in the struct to indicate if the struct is enabled or not.
68 // See https://github.com/open-telemetry/opentelemetry-collector/pull/13060.
69 // This can be removed if we ever support such a design (or if we just want to allow
70 // the "enabled" field in the struct).
71 func assertNoEnabledField[T any]() error {
72 var i T
73 t := deref(reflect.TypeOf(i))
74 if t.Kind() != reflect.Struct {
75 // Not a struct, no need to check for "enabled" field.
76 return nil
77 }
78
79 // Check if the struct has a field with the name "enabled".
80 for i := 0; i < t.NumField(); i++ {
81 field := t.Field(i)
82 mapstructureTags := strings.SplitN(field.Tag.Get("mapstructure"), ",", 2)
83 if len(mapstructureTags) > 0 && mapstructureTags[0] == "enabled" {
84 return errors.New("configoptional: underlying type cannot have a field with mapstructure tag 'enabled'")
85 }
86 }
87 return nil
88 }
89
90 // Some creates an Optional with a value and no factory.
91 //
92 // It panics if T has a field with the mapstructure tag "enabled".
93 func Some[T any](value T) Optional[T] {
94 if err := assertNoEnabledField[T](); err != nil {
95 panic(err)
96 }
97 return Optional[T]{value: value, flavor: someFlavor}
98 }
99
100 // Default creates an Optional with a default value for unmarshaling.
101 //
102 // It panics if
103 // - T is not a struct OR
104 // - T has a field with the mapstructure tag "enabled".
105 func Default[T any](value T) Optional[T] {
106 err := errors.Join(assertStructKind[T](), assertNoEnabledField[T]())
107 if err != nil {
108 panic(err)
109 }
110 return Optional[T]{value: value, flavor: defaultFlavor}
111 }
112
113 // None has no value. It has the same behavior as a nil pointer when unmarshaling.
114 //
115 // The zero value of Optional[T] is None[T]. Prefer using this constructor
116 // for validation.
117 //
118 // It panics if T has a field with the mapstructure tag "enabled".
119 func None[T any]() Optional[T] {
120 if err := assertNoEnabledField[T](); err != nil {
121 panic(err)
122 }
123 return Optional[T]{}
124 }
125
126 // HasValue checks if the Optional has a value.
127 func (o Optional[T]) HasValue() bool {
128 return o.flavor == someFlavor
129 }
130
131 // Get returns the value of the Optional.
132 // If the value is not present, it returns nil.
133 func (o *Optional[T]) Get() *T {
134 if !o.HasValue() {
135 return nil
136 }
137 return &o.value
138 }
139
140 // GetOrInsertDefault makes the Optional into a Some(val) and returns val.
141 //
142 // In particular, if it is Default(val) it turns it into Some(val)
143 // and if it is None[T]() it turns it into Some(zeroVal) where zeroVal is T's zero value.
144 // This method is useful for programmatic usage of an optional.
145 //
146 // It panics if
147 // - T is not a struct OR
148 // - T has a field with the mapstructure tag "enabled".
149 func (o *Optional[T]) GetOrInsertDefault() *T {
150 err := errors.Join(assertStructKind[T](), assertNoEnabledField[T]())
151 if err != nil {
152 panic(err)
153 }
154
155 if o.HasValue() {
156 return o.Get()
157 }
158
159 empty := confmap.NewFromStringMap(map[string]any{})
160 if err := empty.Unmarshal(o); err != nil {
161 // This should never happen, if it happens it is a bug, so this panic is not documented.
162 panic(fmt.Errorf("failed to unmarshal empty map into %T type: %w. Please report this bug", o.value, err))
163 }
164
165 return o.Get()
166 }
167
168 var _ confmap.Unmarshaler = (*Optional[any])(nil)
169
170 var (
171 addEnabledFieldFeatureGateID = "configoptional.AddEnabledField"
172 addEnabledFieldFeatureGate = featuregate.GlobalRegistry().MustRegister(
173 addEnabledFieldFeatureGateID,
174 featuregate.StageBeta,
175 featuregate.WithRegisterFromVersion("v0.138.0"),
176 featuregate.WithRegisterDescription("Allows optional fields to be toggled via an 'enabled' field."),
177 featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector/issues/14021"),
178 )
179 )
180
181 // Unmarshal the configuration into the Optional value.
182 //
183 // The behavior of this method depends on the state of the Optional:
184 // - None[T]: does nothing if the configuration is nil, otherwise it unmarshals into the zero value of T.
185 // - Some[T](val): equivalent to unmarshaling into a field of type T with value val.
186 // - Default[T](val), equivalent to unmarshaling into a field of type T with base value val,
187 // using val without overrides from the configuration if the configuration is nil.
188 //
189 // (Under the `configoptional.AddEnabledField` feature gate)
190 // If the configuration contains an 'enabled' field:
191 // - if enabled is true: the Optional becomes Some after unmarshaling.
192 // - if enabled is false: the Optional becomes None regardless of other configuration values.
193 //
194 // T must be derefenceable to a type with struct kind and not have an 'enabled' field.
195 // Scalar values are not supported.
196 func (o *Optional[T]) Unmarshal(conf *confmap.Conf) error {
197 if err := assertNoEnabledField[T](); err != nil {
198 return err
199 }
200
201 if o.flavor == noneFlavor && conf.ToStringMap() == nil {
202 // If the Optional is None and the configuration is nil, we do nothing.
203 // This replicates the behavior of unmarshaling into a field with a nil pointer.
204 return nil
205 }
206
207 isEnabled := true
208 if addEnabledFieldFeatureGate.IsEnabled() && conf.IsSet("enabled") {
209 enabled := conf.Get("enabled")
210 conf.Delete("enabled")
211 var ok bool
212 if isEnabled, ok = enabled.(bool); !ok {
213 return fmt.Errorf("unexpected type %T for 'enabled': got '%v' value expected 'true' or 'false'", enabled, enabled)
214 }
215 }
216
217 if err := conf.Unmarshal(&o.value); err != nil {
218 return err
219 }
220
221 if isEnabled {
222 o.flavor = someFlavor
223 } else {
224 o.flavor = noneFlavor
225 // override o.value with zero value.
226 var zero T
227 o.value = zero
228 }
229
230 return nil
231 }
232
233 var _ confmap.Marshaler = (*Optional[any])(nil)
234
235 // Marshal the Optional value into the configuration.
236 // If the Optional is None or Default, it does not marshal anything.
237 // If the Optional is Some, it marshals the value into the configuration.
238 //
239 // T must be derefenceable to a type with struct kind.
240 // Scalar values are not supported.
241 func (o Optional[T]) Marshal(conf *confmap.Conf) error {
242 if err := assertStructKind[T](); err != nil {
243 return err
244 }
245
246 if o.flavor == noneFlavor || o.flavor == defaultFlavor {
247 // Optional is None or Default, do not marshal anything.
248 return conf.Marshal(map[string]any(nil))
249 }
250
251 if err := conf.Marshal(o.value); err != nil {
252 return fmt.Errorf("configoptional: failed to marshal Optional value: %w", err)
253 }
254
255 return nil
256 }
257
258 var _ xconfmap.Validator = (*Optional[any])(nil)
259
260 // Validate implements [xconfmap.Validator]. This is required because the
261 // private fields in [xconfmap.Validator] can't be seen by the reflection used
262 // by [xconfmap.Validate], and therefore we have to continue the validation
263 // chain manually. This method isn't meant to be called directly, and should
264 // generally only be called by [xconfmap.Validate].
265 func (o *Optional[T]) Validate() error {
266 // When the flavor is None, the user has not passed this value,
267 // and therefore we should not validate it. The parent struct holding
268 // the Optional type can determine whether a None value is valid for
269 // a given config.
270 //
271 // If the flavor is still Default, then the user has not passed this
272 // value and we should also not validate it.
273 if o.flavor == noneFlavor || o.flavor == defaultFlavor {
274 return nil
275 }
276
277 // For the some flavor, validate the actual value.
278 return xconfmap.Validate(o.value)
279 }