|
| 1 | +// Copyright The OpenTelemetry Authors |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs" |
| 5 | + |
| 6 | +import ( |
| 7 | + "cmp" |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "slices" |
| 11 | + "strconv" |
| 12 | + |
| 13 | + "go.opentelemetry.io/collector/pdata/pcommon" |
| 14 | + |
| 15 | + "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + sortAsc = "asc" |
| 20 | + sortDesc = "desc" |
| 21 | +) |
| 22 | + |
| 23 | +type SortArguments[K any] struct { |
| 24 | + Target ottl.Getter[K] |
| 25 | + Order ottl.Optional[string] |
| 26 | +} |
| 27 | + |
| 28 | +func NewSortFactory[K any]() ottl.Factory[K] { |
| 29 | + return ottl.NewFactory("Sort", &SortArguments[K]{}, createSortFunction[K]) |
| 30 | +} |
| 31 | + |
| 32 | +func createSortFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) { |
| 33 | + args, ok := oArgs.(*SortArguments[K]) |
| 34 | + |
| 35 | + if !ok { |
| 36 | + return nil, fmt.Errorf("SortFactory args must be of type *SortArguments[K]") |
| 37 | + } |
| 38 | + |
| 39 | + order := sortAsc |
| 40 | + if !args.Order.IsEmpty() { |
| 41 | + o := args.Order.Get() |
| 42 | + switch o { |
| 43 | + case sortAsc, sortDesc: |
| 44 | + order = o |
| 45 | + default: |
| 46 | + return nil, fmt.Errorf("invalid arguments: %s. Order should be either \"%s\" or \"%s\"", o, sortAsc, sortDesc) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return sort(args.Target, order), nil |
| 51 | +} |
| 52 | + |
| 53 | +func sort[K any](target ottl.Getter[K], order string) ottl.ExprFunc[K] { |
| 54 | + return func(ctx context.Context, tCtx K) (any, error) { |
| 55 | + val, err := target.Get(ctx, tCtx) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + |
| 60 | + switch v := val.(type) { |
| 61 | + case pcommon.Slice: |
| 62 | + return sortSlice(v, order) |
| 63 | + case pcommon.Value: |
| 64 | + if v.Type() == pcommon.ValueTypeSlice { |
| 65 | + return sortSlice(v.Slice(), order) |
| 66 | + } |
| 67 | + return nil, fmt.Errorf("sort with unsupported type: '%s'. Target is not a list", v.Type().String()) |
| 68 | + case []any: |
| 69 | + // handle Sort([1,2,3]) |
| 70 | + slice := pcommon.NewValueSlice().SetEmptySlice() |
| 71 | + if err := slice.FromRaw(v); err != nil { |
| 72 | + return nil, fmt.Errorf("sort with unsupported type: '%T'. Target is not a list of primitive types; %w", v, err) |
| 73 | + } |
| 74 | + return sortSlice(slice, order) |
| 75 | + case []string: |
| 76 | + dup := makeCopy(v) |
| 77 | + return sortTypedSlice(dup, order), nil |
| 78 | + case []int64: |
| 79 | + dup := makeCopy(v) |
| 80 | + return sortTypedSlice(dup, order), nil |
| 81 | + case []float64: |
| 82 | + dup := makeCopy(v) |
| 83 | + return sortTypedSlice(dup, order), nil |
| 84 | + case []bool: |
| 85 | + var strings []string |
| 86 | + for _, b := range v { |
| 87 | + strings = append(strings, strconv.FormatBool(b)) |
| 88 | + } |
| 89 | + |
| 90 | + sortTypedSlice(strings, order) |
| 91 | + |
| 92 | + bools := make([]bool, len(strings)) |
| 93 | + for i, s := range strings { |
| 94 | + boolValue, _ := strconv.ParseBool(s) |
| 95 | + bools[i] = boolValue |
| 96 | + } |
| 97 | + return bools, nil |
| 98 | + default: |
| 99 | + return nil, fmt.Errorf("sort with unsupported type: '%T'. Target is not a list", v) |
| 100 | + } |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +// sortSlice sorts a pcommon.Slice based on the specified order. |
| 105 | +// It gets the common type for all elements in the slice and converts all elements to this common type, creating a new copy |
| 106 | +// Parameters: |
| 107 | +// - slice: The pcommon.Slice to be sorted |
| 108 | +// - order: The sort order. "asc" for ascending, "desc" for descending |
| 109 | +// |
| 110 | +// Returns: |
| 111 | +// - A sorted slice as []any or the original pcommon.Slice |
| 112 | +// - An error if an unsupported type is encountered |
| 113 | +func sortSlice(slice pcommon.Slice, order string) (any, error) { |
| 114 | + length := slice.Len() |
| 115 | + if length == 0 { |
| 116 | + return slice, nil |
| 117 | + } |
| 118 | + |
| 119 | + commonType, ok := findCommonValueType(slice) |
| 120 | + if !ok { |
| 121 | + return slice, nil |
| 122 | + } |
| 123 | + |
| 124 | + switch commonType { |
| 125 | + case pcommon.ValueTypeInt: |
| 126 | + arr := makeConvertedCopy(slice, func(idx int) int64 { |
| 127 | + return slice.At(idx).Int() |
| 128 | + }) |
| 129 | + return sortConvertedSlice(arr, order), nil |
| 130 | + case pcommon.ValueTypeDouble: |
| 131 | + arr := makeConvertedCopy(slice, func(idx int) float64 { |
| 132 | + s := slice.At(idx) |
| 133 | + if s.Type() == pcommon.ValueTypeInt { |
| 134 | + return float64(s.Int()) |
| 135 | + } |
| 136 | + |
| 137 | + return s.Double() |
| 138 | + }) |
| 139 | + return sortConvertedSlice(arr, order), nil |
| 140 | + case pcommon.ValueTypeStr: |
| 141 | + arr := makeConvertedCopy(slice, func(idx int) string { |
| 142 | + return slice.At(idx).AsString() |
| 143 | + }) |
| 144 | + return sortConvertedSlice(arr, order), nil |
| 145 | + default: |
| 146 | + return nil, fmt.Errorf("sort with unsupported type: '%T'", commonType) |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +type targetType interface { |
| 151 | + ~int64 | ~float64 | ~string |
| 152 | +} |
| 153 | + |
| 154 | +// findCommonValueType determines the most appropriate common type for all elements in a pcommon.Slice. |
| 155 | +// It returns two values: |
| 156 | +// - A pcommon.ValueType representing the desired common type for all elements. |
| 157 | +// Mixed Numeric types return ValueTypeDouble. Integer type returns ValueTypeInt. Double type returns ValueTypeDouble. |
| 158 | +// String, Bool, Empty and mixed of the mentioned types return ValueTypeStr, as they require string conversion for comparison. |
| 159 | +// - A boolean indicating whether a common type could be determined (true) or not (false). |
| 160 | +// returns false for ValueTypeMap, ValueTypeSlice and ValueTypeBytes. They are unsupported types for sort. |
| 161 | +func findCommonValueType(slice pcommon.Slice) (pcommon.ValueType, bool) { |
| 162 | + length := slice.Len() |
| 163 | + if length == 0 { |
| 164 | + return pcommon.ValueTypeEmpty, false |
| 165 | + } |
| 166 | + |
| 167 | + wantType := slice.At(0).Type() |
| 168 | + wantStr := false |
| 169 | + wantDouble := false |
| 170 | + |
| 171 | + for i := 0; i < length; i++ { |
| 172 | + value := slice.At(i) |
| 173 | + currType := value.Type() |
| 174 | + |
| 175 | + switch currType { |
| 176 | + case pcommon.ValueTypeInt: |
| 177 | + if wantType == pcommon.ValueTypeDouble { |
| 178 | + wantDouble = true |
| 179 | + } |
| 180 | + case pcommon.ValueTypeDouble: |
| 181 | + if wantType == pcommon.ValueTypeInt { |
| 182 | + wantDouble = true |
| 183 | + } |
| 184 | + case pcommon.ValueTypeStr, pcommon.ValueTypeBool, pcommon.ValueTypeEmpty: |
| 185 | + wantStr = true |
| 186 | + default: |
| 187 | + return pcommon.ValueTypeEmpty, false |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + if wantStr { |
| 192 | + wantType = pcommon.ValueTypeStr |
| 193 | + } else if wantDouble { |
| 194 | + wantType = pcommon.ValueTypeDouble |
| 195 | + } |
| 196 | + |
| 197 | + return wantType, true |
| 198 | +} |
| 199 | + |
| 200 | +func makeCopy[T targetType](src []T) []T { |
| 201 | + dup := make([]T, len(src)) |
| 202 | + copy(dup, src) |
| 203 | + return dup |
| 204 | +} |
| 205 | + |
| 206 | +func sortTypedSlice[T targetType](arr []T, order string) []T { |
| 207 | + if len(arr) == 0 { |
| 208 | + return arr |
| 209 | + } |
| 210 | + |
| 211 | + slices.SortFunc(arr, func(a, b T) int { |
| 212 | + if order == sortDesc { |
| 213 | + return cmp.Compare(b, a) |
| 214 | + } |
| 215 | + return cmp.Compare(a, b) |
| 216 | + }) |
| 217 | + |
| 218 | + return arr |
| 219 | +} |
| 220 | + |
| 221 | +type convertedValue[T targetType] struct { |
| 222 | + value T |
| 223 | + originalValue any |
| 224 | +} |
| 225 | + |
| 226 | +func makeConvertedCopy[T targetType](slice pcommon.Slice, converter func(idx int) T) []convertedValue[T] { |
| 227 | + length := slice.Len() |
| 228 | + var out []convertedValue[T] |
| 229 | + for i := 0; i < length; i++ { |
| 230 | + cv := convertedValue[T]{ |
| 231 | + value: converter(i), |
| 232 | + originalValue: slice.At(i).AsRaw(), |
| 233 | + } |
| 234 | + out = append(out, cv) |
| 235 | + } |
| 236 | + return out |
| 237 | +} |
| 238 | + |
| 239 | +func sortConvertedSlice[T targetType](cvs []convertedValue[T], order string) []any { |
| 240 | + slices.SortFunc(cvs, func(a, b convertedValue[T]) int { |
| 241 | + if order == sortDesc { |
| 242 | + return cmp.Compare(b.value, a.value) |
| 243 | + } |
| 244 | + return cmp.Compare(a.value, b.value) |
| 245 | + }) |
| 246 | + |
| 247 | + var out []any |
| 248 | + for _, cv := range cvs { |
| 249 | + out = append(out, cv.originalValue) |
| 250 | + } |
| 251 | + |
| 252 | + return out |
| 253 | +} |
0 commit comments