Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ottl truncate editor #23880

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .chloggen/add-ottl-truncate-editor.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Use this changelog template to create an entry for release notes.
# If your change doesn't affect end users, such as a test fix or a tooling change,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.

# 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. filelogreceiver)
component: pkg/ottl

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add truncate editor
jack-berg marked this conversation as resolved.
Show resolved Hide resolved

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [23847]

# (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:
15 changes: 15 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Available Editors:
- [replace_match](#replace_match)
- [replace_pattern](#replace_pattern)
- [set](#set)
- [truncate](#truncate)
- [truncate_all](#truncate_all)

### delete_key
Expand Down Expand Up @@ -252,6 +253,20 @@ Examples:

- `set(attributes["source"], trace_state["source"])`

### truncate

`truncate(target, limit)`

The `truncate` function truncates the string value such that the result is no longer than the limit.

`target` is a path expression to a telemetry field. `pattern` is a string following [filepath.Match syntax](https://pkg.go.dev/path/filepath#Match).

The `target` will be mutated such that the number of characters in it is less than or equal to the limit. Non-string values are ignored.

Examples:

- `truncate(body, 100)`

### truncate_all

`truncate_all(target, limit)`
Expand Down
48 changes: 48 additions & 0 deletions pkg/ottl/ottlfuncs/func_truncate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// 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"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

type TruncateArguments[K any] struct {
Target ottl.GetSetter[K] `ottlarg:"0"`
jack-berg marked this conversation as resolved.
Show resolved Hide resolved
Limit int64 `ottlarg:"1"`
}

func NewTruncateFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("truncate", &TruncateArguments[K]{}, createTruncateFunction[K])
}

func createTruncateFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*TruncateArguments[K])

if !ok {
return nil, fmt.Errorf("TruncateFactory args must be of type *TruncateArguments[K]")
}

return truncate(args.Target, args.Limit)
}

func truncate[K any](target ottl.GetSetter[K], limit int64) (ottl.ExprFunc[K], error) {
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
if limit < 0 {
return nil, fmt.Errorf("invalid limit for truncate function, %d cannot be negative", limit)
}
return func(ctx context.Context, tCtx K) (interface{}, error) {
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}
if valStr, ok := val.(string); ok {
if int64(len(valStr)) > limit {
return nil, target.Set(ctx, tCtx, valStr[:limit])
}
}
return nil, nil
}, nil
}
4 changes: 0 additions & 4 deletions pkg/ottl/ottlfuncs/func_truncate_all.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ func TruncateAll[K any](target ottl.PMapGetter[K], limit int64) (ottl.ExprFunc[K
return nil, fmt.Errorf("invalid limit for truncate_all function, %d cannot be negative", limit)
}
return func(ctx context.Context, tCtx K) (interface{}, error) {
if limit < 0 {
return nil, nil
}

val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
Expand Down
134 changes: 134 additions & 0 deletions pkg/ottl/ottlfuncs/func_truncate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/pdata/pcommon"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

func Test_truncate(t *testing.T) {
input := pcommon.NewValueStr("hello world")

target := &ottl.StandardGetSetter[pcommon.Value]{
Getter: func(ctx context.Context, tCtx pcommon.Value) (interface{}, error) {
return tCtx.Str(), nil
},
Setter: func(ctx context.Context, tCtx pcommon.Value, val interface{}) error {
tCtx.SetStr(val.(string))
return nil
},
}

tests := []struct {
name string
target ottl.GetSetter[pcommon.Value]
limit int64
want func(value pcommon.Value)
}{
{
name: "below limit",
target: target,
limit: 20,
want: func(expectedValue pcommon.Value) {
expectedValue.SetStr("hello world")
},
},
{
name: "above limit",
target: target,
limit: 10,
want: func(expectedValue pcommon.Value) {
expectedValue.SetStr("hello worl")
},
},
{
name: "at limit",
target: target,
limit: 11,
want: func(expectedValue pcommon.Value) {
expectedValue.SetStr("hello world")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
scenarioValue := pcommon.NewValueStr(input.Str())

exprFunc, err := truncate(tt.target, tt.limit)
assert.NoError(t, err)
result, err := exprFunc(nil, scenarioValue)
assert.NoError(t, err)
assert.Nil(t, result)

expected := pcommon.NewValueStr("")
tt.want(expected)

assert.Equal(t, expected, scenarioValue)
})
}
}

func Test_truncate_bad_input(t *testing.T) {
input := pcommon.NewValueInt(1)
target := &ottl.StandardGetSetter[interface{}]{
Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) {
return tCtx, nil
},
Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error {
t.Errorf("nothing should be set in this scenario")
return nil
},
}

exprFunc, err := truncate[interface{}](target, 10)
assert.NoError(t, err)

result, err := exprFunc(nil, input)
assert.NoError(t, err)
assert.Nil(t, result)

assert.Equal(t, pcommon.NewValueInt(1), input)
}

func Test_truncate_get_nil(t *testing.T) {
target := &ottl.StandardGetSetter[interface{}]{
Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) {
return tCtx, nil
},
Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error {
t.Errorf("nothing should be set in this scenario")
return nil
},
}

exprFunc, err := truncate[interface{}](target, 10)
assert.NoError(t, err)

result, err := exprFunc(nil, nil)
assert.NoError(t, err)
assert.Nil(t, result)
}

func Test_truncate_validation(t *testing.T) {
target := &ottl.StandardGetSetter[interface{}]{
Getter: func(ctx context.Context, tCtx interface{}) (interface{}, error) {
return tCtx, nil
},
Setter: func(ctx context.Context, tCtx interface{}, val interface{}) error {
t.Errorf("nothing should be set in this scenario")
return nil
},
}

_, err := truncate[interface{}](target, -1)
require.Error(t, err)
assert.ErrorContains(t, err, "invalid limit for truncate function, -1 cannot be negative")
}
1 change: 1 addition & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ func StandardFuncs[K any]() map[string]ottl.Factory[K] {
NewReplaceMatchFactory[K](),
NewReplacePatternFactory[K](),
NewSetFactory[K](),
NewTruncateFactory[K](),
NewTruncateAllFactory[K](),
}
f = append(f, converters[K]()...)
Expand Down