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

[ottl/pkg] Add support for locale in the Time converter #35107

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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
27 changes: 27 additions & 0 deletions .chloggen/ottl_time_func_locale_support.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# 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: Added support for locale in the Time converter

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

# (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:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [user]
17 changes: 17 additions & 0 deletions internal/coreinternal/timeutils/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package timeutils // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/timeutils"

import (
"errors"
"fmt"
"regexp"
"strings"
Expand Down Expand Up @@ -155,5 +156,21 @@ func ValidateGotime(layout string) error {
return nil
}

// ValidateLocale checks the given locale and returns an error if the language tag
// is not supported by the localized parser functions.
func ValidateLocale(locale string) error {
_, err := lunes.NewDefaultLocale(locale)
if err == nil {
return nil
}

var e *lunes.ErrUnsupportedLocale
if errors.As(err, &e) {
return fmt.Errorf("unsupported locale '%s', value must be a supported BCP 47 language tag", locale)
}

return fmt.Errorf("invalid locale '%s': %w", locale, err)
}

// Allows tests to override with deterministic value
var Now = time.Now
11 changes: 11 additions & 0 deletions internal/coreinternal/timeutils/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,14 @@ func TestParseLocalizedStrptimeInvalidType(t *testing.T) {
require.Error(t, err)
require.ErrorContains(t, err, "cannot be parsed as a time")
}

func TestValidateLocale(t *testing.T) {
require.NoError(t, ValidateLocale("es"))
require.NoError(t, ValidateLocale("en-US"))
require.NoError(t, ValidateLocale("ca-ES-valencia"))
}

func TestValidateLocaleUnsupported(t *testing.T) {
err := ValidateLocale("foo-bar")
require.ErrorContains(t, err, "unsupported locale 'foo-bar'")
}
15 changes: 13 additions & 2 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1455,11 +1455,11 @@ Examples:

### Time

`Time(target, format, Optional[location])`
`Time(target, format, Optional[location], Optional[locale])`

The `Time` Converter takes a string representation of a time and converts it to a Golang `time.Time`.

`target` is a string. `format` is a string, `location` is an optional string.
`target` is a string. `format` is a string, `location` is an optional string, `locale` is an optional string.

If either `target` or `format` are nil, an error is returned. The parser used is the parser at [internal/coreinternal/parser](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/internal/coreinternal/timeutils). If the `target` and `format` do not follow the parsing rules used by this parser, an error is returned.

Expand Down Expand Up @@ -1519,6 +1519,17 @@ Examples:
- `Time("2012-11-01T22:08:41+0000 EST", "%Y-%m-%dT%H:%M:%S%z %Z")`
- `Time("2023-05-26 12:34:56", "%Y-%m-%d %H:%M:%S", "America/New_York")`

`locale` specifies the input language of the `target` value. It is used to interpret timestamp values written in a specific language,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add something that conveys that when not set english is the local that gets used.

ensuring that the function can correctly parse the localized month names, day names, and periods of the day based on the provided language.

The value must be a well-formed BCP 47 language tag, and a known [CLDR](https://cldr.unicode.org) v45 locale.
If not supplied, English (`en`) is used.

Examples:

- `Time("mercoledì set 4 2024", "%A %h %e %Y", "", "it")`
- `Time("Febrero 25 lunes, 2002, 02:03:04 p.m.", "%B %d %A, %Y, %r", "America/New_York", "es-ES")`

### TraceID

`TraceID(bytes)`
Expand Down
22 changes: 19 additions & 3 deletions pkg/ottl/ottlfuncs/func_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-c
import (
"context"
"fmt"
"time"

"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/timeutils"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
Expand All @@ -15,6 +16,7 @@ type TimeArguments[K any] struct {
Time ottl.StringGetter[K]
Format string
Location ottl.Optional[string]
Locale ottl.Optional[string]
}

func NewTimeFactory[K any]() ottl.Factory[K] {
Expand All @@ -27,10 +29,10 @@ func createTimeFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ot
return nil, fmt.Errorf("TimeFactory args must be of type *TimeArguments[K]")
}

return Time(args.Time, args.Format, args.Location)
return Time(args.Time, args.Format, args.Location, args.Locale)
}

func Time[K any](inputTime ottl.StringGetter[K], format string, location ottl.Optional[string]) (ottl.ExprFunc[K], error) {
func Time[K any](inputTime ottl.StringGetter[K], format string, location ottl.Optional[string], locale ottl.Optional[string]) (ottl.ExprFunc[K], error) {
if format == "" {
return nil, fmt.Errorf("format cannot be nil")
}
Expand All @@ -45,6 +47,15 @@ func Time[K any](inputTime ottl.StringGetter[K], format string, location ottl.Op
return nil, err
}

var inputTimeLocale *string
if !locale.IsEmpty() {
l := locale.Get()
if err = timeutils.ValidateLocale(l); err != nil {
return nil, err
}
inputTimeLocale = &l
}

return func(ctx context.Context, tCtx K) (any, error) {
t, err := inputTime.Get(ctx, tCtx)
if err != nil {
Expand All @@ -53,7 +64,12 @@ func Time[K any](inputTime ottl.StringGetter[K], format string, location ottl.Op
if t == "" {
return nil, fmt.Errorf("time cannot be nil")
}
timestamp, err := timeutils.ParseStrptime(format, t, loc)
var timestamp time.Time
if inputTimeLocale != nil {
timestamp, err = timeutils.ParseLocalizedStrptime(format, t, loc, *inputTimeLocale)
} else {
timestamp, err = timeutils.ParseStrptime(format, t, loc)
}
if err != nil {
return nil, err
}
Expand Down
72 changes: 64 additions & 8 deletions pkg/ottl/ottlfuncs/func_time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func Test_Time(t *testing.T) {
format string
expected time.Time
location string
locale string
}{
{
name: "simple short form",
Expand Down Expand Up @@ -188,14 +189,52 @@ func Test_Time(t *testing.T) {
format: "%Y-%m-%dT%H:%M:%S %Z",
expected: time.Date(1986, 10, 01, 00, 17, 33, 00, time.FixedZone("MST", -7*60*60)),
},
{
name: "with locale",
time: &ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return "Febrero 25 lunes, 2002, 02:03:04 p.m.", nil
},
},
format: "%B %d %A, %Y, %r",
locale: "es-ES",
expected: time.Date(2002, 2, 25, 14, 03, 04, 0, time.Local),
},
{
name: "with locale - date only",
time: &ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return "mercoledì set 4 2024", nil
},
},
format: "%A %h %e %Y",
locale: "it",
expected: time.Date(2024, 9, 4, 0, 0, 0, 0, time.Local),
},
{
name: "with locale and location",
time: &ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return "Febrero 25 lunes, 2002, 02:03:04 p.m.", nil
},
},
format: "%B %d %A, %Y, %r",
location: "America/New_York",
locale: "es-ES",
expected: time.Date(2002, 2, 25, 14, 03, 04, 0, locationAmericaNewYork),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var locOptional ottl.Optional[string]
var locationOptional ottl.Optional[string]
if tt.location != "" {
locOptional = ottl.NewTestingOptional(tt.location)
locationOptional = ottl.NewTestingOptional(tt.location)
}
exprFunc, err := Time(tt.time, tt.format, locOptional)
var localeOptional ottl.Optional[string]
if tt.locale != "" {
localeOptional = ottl.NewTestingOptional(tt.locale)
}
exprFunc, err := Time(tt.time, tt.format, locationOptional, localeOptional)
assert.NoError(t, err)
result, err := exprFunc(nil, nil)
assert.NoError(t, err)
Expand Down Expand Up @@ -234,8 +273,9 @@ func Test_TimeError(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var locOptional ottl.Optional[string]
exprFunc, err := Time[any](tt.time, tt.format, locOptional)
var locationOptional ottl.Optional[string]
var localeOptional ottl.Optional[string]
exprFunc, err := Time[any](tt.time, tt.format, locationOptional, localeOptional)
require.NoError(t, err)
_, err = exprFunc(context.Background(), nil)
assert.ErrorContains(t, err, tt.expectedError)
Expand All @@ -250,6 +290,7 @@ func Test_TimeFormatError(t *testing.T) {
format string
expectedError string
location string
locale string
}{
{
name: "invalid short with no format",
Expand All @@ -272,14 +313,29 @@ func Test_TimeFormatError(t *testing.T) {
location: "Jupiter/Ganymede",
expectedError: "unknown time zone Jupiter/Ganymede",
},
{
name: "with unsupported locale",
time: &ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return "2023-05-26 12:34:56", nil
},
},
format: "%Y-%m-%d %H:%M:%S",
locale: "foo-bar",
expectedError: "unsupported locale 'foo-bar'",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var locOptional ottl.Optional[string]
var locationOptional ottl.Optional[string]
if tt.location != "" {
locOptional = ottl.NewTestingOptional(tt.location)
locationOptional = ottl.NewTestingOptional(tt.location)
}
var localeOptional ottl.Optional[string]
if tt.locale != "" {
localeOptional = ottl.NewTestingOptional(tt.locale)
}
_, err := Time[any](tt.time, tt.format, locOptional)
_, err := Time[any](tt.time, tt.format, locationOptional, localeOptional)
assert.ErrorContains(t, err, tt.expectedError)
})
}
Expand Down
Loading