diff --git a/.chloggen/enhance-fromraw.yaml b/.chloggen/enhance-fromraw.yaml new file mode 100644 index 00000000000..aa7eb66a3be --- /dev/null +++ b/.chloggen/enhance-fromraw.yaml @@ -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: pdata + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: Enhance FromRaw method to support slices of supported types and custom types that are maps + +# One or more tracking issues or pull requests related to the change +issues: [] + +# (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: [] diff --git a/pdata/pcommon/value.go b/pdata/pcommon/value.go index ad16e6173a5..04acc2921f4 100644 --- a/pdata/pcommon/value.go +++ b/pdata/pcommon/value.go @@ -8,7 +8,9 @@ import ( "encoding/json" "fmt" "math" + "reflect" "strconv" + "time" "go.opentelemetry.io/collector/pdata/internal" otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" @@ -186,16 +188,42 @@ func (v Value) FromRaw(iv any) error { v.SetBool(tv) case []byte: v.SetEmptyBytes().FromRaw(tv) + case time.Time: + v.SetStr(tv.UTC().Format("2006-01-02T15:04:05.000Z")) case map[string]any: return v.SetEmptyMap().FromRaw(tv) case []any: return v.SetEmptySlice().FromRaw(tv) default: - return fmt.Errorf("", tv) + return v.handleDefaultCase(iv) } return nil } +func (v Value) handleDefaultCase(iv any) error { + ref := reflect.ValueOf(iv) + switch ref.Kind() { + case reflect.Map: + // we handle a special case where the user might've defined a custom type, but internally + // it's a map[string]any{}. + if ref.CanConvert(reflect.TypeOf(map[string]any{})) { + updated := ref.Convert(reflect.TypeOf(map[string]any{})).Interface() + return v.FromRaw(updated) + } + case reflect.Array, reflect.Slice: + s := make([]any, ref.Len()) + for i := 0; i < ref.Len(); i++ { + s[i] = ref.Index(i).Interface() + } + + // if the underlying type of our slice is supported, then the following will succeed. + // or else, it will fail with "" in subsequent call + return v.SetEmptySlice().FromRaw(s) + + } + return fmt.Errorf("", iv) +} + // Type returns the type of the value for this Value. // Calling this function on zero-initialized Value will cause a panic. func (v Value) Type() ValueType {