github.com/thanos-io/thanos@v0.32.5/internal/cortex/util/validation/notifications_limit_flag.go (about)

     1  // Copyright (c) The Cortex Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package validation
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  
    10  	"github.com/pkg/errors"
    11  	"golang.org/x/exp/slices"
    12  )
    13  
    14  var allowedIntegrationNames = []string{
    15  	"webhook", "email", "pagerduty", "opsgenie", "wechat", "slack", "victorops", "pushover", "sns",
    16  }
    17  
    18  type NotificationRateLimitMap map[string]float64
    19  
    20  // String implements flag.Value
    21  func (m NotificationRateLimitMap) String() string {
    22  	out, err := json.Marshal(map[string]float64(m))
    23  	if err != nil {
    24  		return fmt.Sprintf("failed to marshal: %v", err)
    25  	}
    26  	return string(out)
    27  }
    28  
    29  // Set implements flag.Value
    30  func (m NotificationRateLimitMap) Set(s string) error {
    31  	newMap := map[string]float64{}
    32  	return m.updateMap(json.Unmarshal([]byte(s), &newMap), newMap)
    33  }
    34  
    35  // UnmarshalYAML implements yaml.Unmarshaler.
    36  func (m NotificationRateLimitMap) UnmarshalYAML(unmarshal func(interface{}) error) error {
    37  	newMap := map[string]float64{}
    38  	return m.updateMap(unmarshal(newMap), newMap)
    39  }
    40  
    41  func (m NotificationRateLimitMap) updateMap(unmarshalErr error, newMap map[string]float64) error {
    42  	if unmarshalErr != nil {
    43  		return unmarshalErr
    44  	}
    45  
    46  	for k, v := range newMap {
    47  		if !slices.Contains(allowedIntegrationNames, k) {
    48  			return errors.Errorf("unknown integration name: %s", k)
    49  		}
    50  		m[k] = v
    51  	}
    52  	return nil
    53  }
    54  
    55  // MarshalYAML implements yaml.Marshaler.
    56  func (m NotificationRateLimitMap) MarshalYAML() (interface{}, error) {
    57  	return map[string]float64(m), nil
    58  }