2023-02-25 03:33:38 +00:00
|
|
|
package internal
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"math"
|
|
|
|
|
"math/rand"
|
2023-03-07 16:24:46 +00:00
|
|
|
"regexp"
|
2023-02-25 03:33:38 +00:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
2023-03-21 16:54:08 +00:00
|
|
|
type contextKey struct{}
|
|
|
|
|
|
2023-02-25 03:33:38 +00:00
|
|
|
const (
|
|
|
|
|
JobStatusNew = "new"
|
|
|
|
|
JobStatusProcessed = "processed"
|
|
|
|
|
JobStatusFailed = "failed"
|
|
|
|
|
)
|
|
|
|
|
|
2023-03-21 16:54:08 +00:00
|
|
|
var JobCtxVarKey contextKey
|
|
|
|
|
|
2023-02-25 03:33:38 +00:00
|
|
|
// CalculateBackoff calculates the number of seconds to back off before the next retry
|
|
|
|
|
// this formula is unabashedly taken from Sidekiq because it is good.
|
|
|
|
|
func CalculateBackoff(retryCount int) time.Time {
|
|
|
|
|
const backoffExponent = 4
|
|
|
|
|
const maxInt = 30
|
|
|
|
|
p := int(math.Round(math.Pow(float64(retryCount), backoffExponent)))
|
2023-08-27 08:31:52 +00:00
|
|
|
return time.Now().UTC().Add(time.Duration(p+15+RandInt(maxInt)*retryCount+1) * time.Second)
|
2023-02-25 03:33:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RandInt returns a random integer up to max
|
|
|
|
|
func RandInt(max int) int {
|
2023-08-29 09:25:14 +00:00
|
|
|
r := rand.New(rand.NewSource(time.Now().UnixNano())) // nolint: gosec
|
|
|
|
|
return r.Intn(max)
|
2023-02-25 03:33:38 +00:00
|
|
|
}
|
|
|
|
|
|
2023-03-07 16:24:46 +00:00
|
|
|
// StripNonAlphanum strips nonalphanumeric/non underscore characters from a string and returns a new one
|
2023-02-25 03:33:38 +00:00
|
|
|
func StripNonAlphanum(s string) string {
|
2023-03-07 16:24:46 +00:00
|
|
|
re := regexp.MustCompile(`[^a-zA-Z0-9_]`)
|
|
|
|
|
return re.ReplaceAllString(s, "")
|
2023-02-25 03:33:38 +00:00
|
|
|
}
|