-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathfunc_truncate_all.go
58 lines (47 loc) · 1.58 KB
/
func_truncate_all.go
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
// 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"
"fmt"
"go.opentelemetry.io/collector/pdata/pcommon"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)
type TruncateAllArguments[K any] struct {
Target ottl.PMapGetter[K]
Limit int64
}
func NewTruncateAllFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("truncate_all", &TruncateAllArguments[K]{}, createTruncateAllFunction[K])
}
func createTruncateAllFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*TruncateAllArguments[K])
if !ok {
return nil, fmt.Errorf("TruncateAllFactory args must be of type *TruncateAllArguments[K]")
}
return TruncateAll(args.Target, args.Limit)
}
func TruncateAll[K any](target ottl.PMapGetter[K], limit int64) (ottl.ExprFunc[K], error) {
if limit < 0 {
return nil, fmt.Errorf("invalid limit for truncate_all function, %d cannot be negative", limit)
}
return func(ctx context.Context, tCtx K) (any, error) {
if limit < 0 {
return nil, nil
}
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}
val.Range(func(_ string, value pcommon.Value) bool {
stringVal := value.Str()
if int64(len(stringVal)) > limit {
value.SetStr(stringVal[:limit])
}
return true
})
// TODO: Write log when truncation is performed
// https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/9730
return nil, nil
}, nil
}