Skip to content

Commit

Permalink
[otelconsumer]: Add support for conversion of type any (#42849)
Browse files Browse the repository at this point in the history
* [otelconsumer]: Add support for conversion of type any

* fix lint

* update test

* add lint
  • Loading branch information
khushijain21 authored Mar 4, 2025
1 parent e8360e3 commit 02fc9c5
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
46 changes: 46 additions & 0 deletions libbeat/otelbeat/otelmap/otelmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,55 @@ func FromMapstr(m mapstr.M) pcommon.Map {
newVal := dest.AppendEmpty()
newVal.SetStr(i.UTC().Format("2006-01-02T15:04:05.000Z"))
}
case []any:
dest := out.PutEmptySlice(k)
convertValue(v.([]interface{}), dest)
default:
out.PutStr(k, fmt.Sprintf("unknown type: %T", x))
}
}
return out
}

// convertValue converts a slice of any[] to pcommon.Value
func convertValue(v []any, dest pcommon.Slice) {
// Handling the most common types without reflect is a small perf win.
for _, i := range v {
newValue := dest.AppendEmpty()
switch val := i.(type) {
case bool:
newValue.SetBool(val)
case string:
newValue.SetStr(val)
case int:
newValue.SetInt(int64(val))
case int8:
newValue.SetInt(int64(val))
case int16:
newValue.SetInt(int64(val))
case int32:
newValue.SetInt(int64(val))
case int64:
newValue.SetInt(val)
case uint:
newValue.SetInt(int64(val))
case uint8:
newValue.SetInt(int64(val))
case uint16:
newValue.SetInt(int64(val))
case uint32:
newValue.SetInt(int64(val))
case uint64:
newValue.SetInt(int64(val))
case float32:
newValue.SetDouble(float64(val))
case float64:
newValue.SetDouble(val)
case time.Time:
newValue.SetStr(val.UTC().Format("2006-01-02T15:04:05.000Z"))
default:
newValue.SetStr(fmt.Sprintf("unknown type: %T", val))
}

}
}
19 changes: 19 additions & 0 deletions libbeat/otelbeat/otelmap/otelmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,25 @@ func TestFromMapstrSliceInt(t *testing.T) {
assert.Equal(t, want, got)
}

func TestFromMapstrSliceAny(t *testing.T) {
inputSlice := []any{42, "forty-three", true}
inputMap := mapstr.M{
"slice": inputSlice,
}
want := pcommon.NewMap()
sliceOfInt := want.PutEmptySlice("slice")

val := sliceOfInt.AppendEmpty()
val.SetInt(int64(inputSlice[0].(int)))
val = sliceOfInt.AppendEmpty()
val.SetStr(inputSlice[1].(string))
val = sliceOfInt.AppendEmpty()
val.SetBool(inputSlice[2].(bool))

got := FromMapstr(inputMap)
assert.Equal(t, want, got)
}

func TestFromMapstrDouble(t *testing.T) {
tests := map[string]struct {
mapstr_val interface{}
Expand Down

0 comments on commit 02fc9c5

Please sign in to comment.