Skip to content

Commit

Permalink
refactor(api): validating of target name in alone metrics (#1049)
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandrMatsko authored Jul 10, 2024
1 parent e719b3f commit 2ead98b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 6 additions & 3 deletions api/dto/triggers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ import (
metricSource "github.com/moira-alert/moira/metric_source"
)

var targetNameRegex = regexp.MustCompile("t(\\d+)")
var targetNameRegex = regexp.MustCompile("^t\\d+$")

// ErrBadAloneMetricName is used when any key in map TriggerModel.AloneMetric doesn't match targetNameRegex.
var ErrBadAloneMetricName = fmt.Errorf("alone metrics' target name must match the pattern: ^t\\d+$, for example: 't1'")

// TODO(litleleprikon): Remove after https://github.com/moira-alert/moira/issues/550 will be resolved.
var asteriskPattern = "*"
Expand Down Expand Up @@ -170,10 +173,10 @@ func (trigger *Trigger) Bind(request *http.Request) error {

for targetName := range trigger.AloneMetrics {
if !targetNameRegex.MatchString(targetName) {
return api.ErrInvalidRequestContent{ValidationError: fmt.Errorf("alone metrics target name should be in pattern: t\\d+")}
return api.ErrInvalidRequestContent{ValidationError: ErrBadAloneMetricName}
}

targetIndexStr := targetNameRegex.FindStringSubmatch(targetName)[1]
targetIndexStr := targetName[1:]
targetIndex, err := strconv.Atoi(targetIndexStr)
if err != nil {
return api.ErrInvalidRequestContent{ValidationError: fmt.Errorf("alone metrics target index should be valid number: %w", err)}
Expand Down
8 changes: 7 additions & 1 deletion api/dto/triggers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,13 @@ func TestTriggerValidation(t *testing.T) {
trigger.AloneMetrics = map[string]bool{"ttt": true}
tr := Trigger{trigger, throttling}
err := tr.Bind(request)
So(err, ShouldResemble, api.ErrInvalidRequestContent{ValidationError: fmt.Errorf("alone metrics target name should be in pattern: t\\d+")})
So(err, ShouldResemble, api.ErrInvalidRequestContent{ValidationError: ErrBadAloneMetricName})
})
Convey("have more than 1 metric name but only 1 need", func() {
trigger.AloneMetrics = map[string]bool{"t1 t2": true}
tr := Trigger{trigger, throttling}
err := tr.Bind(request)
So(err, ShouldResemble, api.ErrInvalidRequestContent{ValidationError: ErrBadAloneMetricName})
})
Convey("have target higher than total amount of targets", func() {
trigger.AloneMetrics = map[string]bool{"t3": true}
Expand Down

0 comments on commit 2ead98b

Please sign in to comment.