-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathfunc_when.go
More file actions
67 lines (55 loc) · 1.73 KB
/
Copy pathfunc_when.go
File metadata and controls
67 lines (55 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs"
import (
"context"
"errors"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs/internal/funcutil"
)
type WhenArguments[K any] struct {
Condition ottl.LambdaExpression[K]
TrueValue ottl.Getter[K]
FalseValue ottl.Getter[K]
}
func NewWhenFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("When", &WhenArguments[K]{}, createWhenFunction[K])
}
func createWhenFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*WhenArguments[K])
if !ok {
return nil, errors.New("WhenFactory args must be of type *WhenArguments[K]")
}
return whenFunction(&args.Condition, args.TrueValue, args.FalseValue), nil
}
func whenFunction[K any](condition *ottl.LambdaExpression[K], trueValueGetter, falseValueGetter ottl.Getter[K]) ottl.ExprFunc[K] {
var trueValue any
var falseValue any
if tv, ok := ottl.GetLiteralValue(trueValueGetter); ok {
trueValue = tv
}
if fv, ok := ottl.GetLiteralValue(falseValueGetter); ok {
falseValue = fv
}
return func(ctx context.Context, tCtx K) (any, error) {
lb, err := condition.Activate(ctx, 0)
if err != nil {
return nil, err
}
defer lb.Close()
match, err := funcutil.EvaluateLambdaActivation[K, bool](tCtx, lb)
if err != nil {
return nil, err
}
if match {
if trueValue != nil {
return trueValue, nil
}
return trueValueGetter.Get(ctx, tCtx)
}
if falseValue != nil {
return falseValue, nil
}
return falseValueGetter.Get(ctx, tCtx)
}
}