Expressions: Use enumerations rather than strings (#83741)

This commit is contained in:
Ryan McKinley
2024-03-01 19:38:32 +02:00
committed by GitHub
parent c59ebfc60f
commit 5f6bf93dd5
9 changed files with 77 additions and 41 deletions
+18 -10
View File
@@ -18,23 +18,31 @@ import (
type ThresholdCommand struct {
ReferenceVar string
RefID string
ThresholdFunc string
ThresholdFunc ThresholdType
Conditions []float64
Invert bool
}
// +enum
type ThresholdType string
const (
ThresholdIsAbove = "gt"
ThresholdIsBelow = "lt"
ThresholdIsWithinRange = "within_range"
ThresholdIsOutsideRange = "outside_range"
ThresholdIsAbove ThresholdType = "gt"
ThresholdIsBelow ThresholdType = "lt"
ThresholdIsWithinRange ThresholdType = "within_range"
ThresholdIsOutsideRange ThresholdType = "outside_range"
)
var (
supportedThresholdFuncs = []string{ThresholdIsAbove, ThresholdIsBelow, ThresholdIsWithinRange, ThresholdIsOutsideRange}
supportedThresholdFuncs = []string{
string(ThresholdIsAbove),
string(ThresholdIsBelow),
string(ThresholdIsWithinRange),
string(ThresholdIsOutsideRange),
}
)
func NewThresholdCommand(refID, referenceVar, thresholdFunc string, conditions []float64) (*ThresholdCommand, error) {
func NewThresholdCommand(refID, referenceVar string, thresholdFunc ThresholdType, conditions []float64) (*ThresholdCommand, error) {
switch thresholdFunc {
case ThresholdIsOutsideRange, ThresholdIsWithinRange:
if len(conditions) < 2 {
@@ -57,8 +65,8 @@ func NewThresholdCommand(refID, referenceVar, thresholdFunc string, conditions [
}
type ConditionEvalJSON struct {
Params []float64 `json:"params"`
Type string `json:"type"` // e.g. "gt"
Params []float64 `json:"params"`
Type ThresholdType `json:"type"` // e.g. "gt"
}
// UnmarshalResampleCommand creates a ResampleCMD from Grafana's frontend query.
@@ -121,7 +129,7 @@ func (tc *ThresholdCommand) Execute(ctx context.Context, now time.Time, vars mat
}
// createMathExpression converts all the info we have about a "threshold" expression in to a Math expression
func createMathExpression(referenceVar string, thresholdFunc string, args []float64, invert bool) (string, error) {
func createMathExpression(referenceVar string, thresholdFunc ThresholdType, args []float64, invert bool) (string, error) {
var exp string
switch thresholdFunc {
case ThresholdIsAbove: