github.com/anycable/anycable-go@v1.5.1/utils/utils.go (about)

     1  package utils
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"math"
     7  	"math/rand"
     8  	"os"
     9  	"time"
    10  
    11  	"github.com/mattn/go-isatty"
    12  )
    13  
    14  // IsTTY returns true if program is running with TTY
    15  func IsTTY() bool {
    16  	return isatty.IsTerminal(os.Stdout.Fd())
    17  }
    18  
    19  func ToJSON[T any](val T) []byte {
    20  	jsonStr, err := json.Marshal(&val)
    21  	if err != nil {
    22  		panic(fmt.Sprintf("😲 Failed to build JSON for %v: %v", val, err))
    23  	}
    24  	return jsonStr
    25  }
    26  
    27  func Keys[T any](val map[string]T) []string {
    28  	var res = make([]string, len(val))
    29  
    30  	i := 0
    31  
    32  	for k := range val {
    33  		res[i] = k
    34  		i++
    35  	}
    36  
    37  	return res
    38  }
    39  
    40  // NextRetry returns a cooldown duration before next attempt using
    41  // a simple exponential backoff
    42  func NextRetry(step int) time.Duration {
    43  	if step == 0 {
    44  		return 250 * time.Millisecond
    45  	}
    46  
    47  	left := math.Pow(2, float64(step))
    48  	right := 2 * left
    49  
    50  	secs := left + (right-left)*rand.Float64() // nolint:gosec
    51  	return time.Duration(secs) * time.Second
    52  }