github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/retry/setup.go (about)

     1  package retry
     2  
     3  import (
     4  	"errors"
     5  	"strconv"
     6  	"time"
     7  
     8  	"github.com/asaskevich/govalidator"
     9  
    10  	"github.com/hellofresh/janus/pkg/plugin"
    11  	"github.com/hellofresh/janus/pkg/proxy"
    12  )
    13  
    14  const (
    15  	strNull = "null"
    16  )
    17  
    18  type (
    19  	// Config represents the Body Limit configuration
    20  	Config struct {
    21  		Attempts  int      `json:"attempts"`
    22  		Backoff   Duration `json:"backoff"`
    23  		Predicate string   `json:"predicate"`
    24  	}
    25  
    26  	// Duration is a wrapper for time.Duration so we can use human readable configs
    27  	Duration time.Duration
    28  )
    29  
    30  // MarshalJSON is the implementation of the MarshalJSON interface
    31  func (d *Duration) MarshalJSON() ([]byte, error) {
    32  	s := (*time.Duration)(d).String()
    33  	s = strconv.Quote(s)
    34  
    35  	return []byte(s), nil
    36  }
    37  
    38  // UnmarshalJSON is the implementation of the UnmarshalJSON interface
    39  func (d *Duration) UnmarshalJSON(data []byte) error {
    40  	s := string(data)
    41  	if s == strNull {
    42  		return errors.New("invalid time duration")
    43  	}
    44  
    45  	s, err := strconv.Unquote(s)
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	t, err := time.ParseDuration(s)
    51  	if err != nil {
    52  		return err
    53  	}
    54  
    55  	*d = Duration(t)
    56  	return nil
    57  }
    58  
    59  func init() {
    60  	plugin.RegisterPlugin("retry", plugin.Plugin{
    61  		Action:   setupRetry,
    62  		Validate: validateConfig,
    63  	})
    64  }
    65  
    66  func setupRetry(def *proxy.RouterDefinition, rawConfig plugin.Config) error {
    67  	var config Config
    68  	err := plugin.Decode(rawConfig, &config)
    69  	if err != nil {
    70  		return err
    71  	}
    72  
    73  	def.AddMiddleware(NewRetryMiddleware(config))
    74  	return nil
    75  }
    76  
    77  func validateConfig(rawConfig plugin.Config) (bool, error) {
    78  	var config Config
    79  	err := plugin.Decode(rawConfig, &config)
    80  	if err != nil {
    81  		return false, err
    82  	}
    83  
    84  	return govalidator.ValidateStruct(config)
    85  }