Skip to content

Commit

Permalink
Implement random sleep durations
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Ellis (OpenFaaS Ltd) <[email protected]>
  • Loading branch information
alexellis committed Dec 12, 2024
1 parent 977e64b commit dab6684
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions sleep/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,44 @@ package function
import (
"fmt"
"log"
"math/rand"
"os"
"time"
)

var r *rand.Rand

func init() {

r = rand.New(rand.NewSource(time.Now().Unix()))
}

// Handle a serverless request
// 1. When no headers are given, sleep for the environment variable: sleep_duration.
// 2. When an X-Sleep header is given, sleep for that amount of time.
// 3. When the X-Min-Sleep and X-Max-Sleep headers are given, sleep for a random amount
// of time between those two figures
func Handle(req []byte) string {

if minV, ok := os.LookupEnv("Http_X_Min_Sleep"); ok && len(minV) > 0 {
if maxV, ok := os.LookupEnv("Http_X_Max_Sleep"); ok && len(maxV) > 0 {
minSleep, _ := time.ParseDuration(minV)
maxSleep, _ := time.ParseDuration(maxV)

minMs := minSleep.Milliseconds()
maxMs := maxSleep.Milliseconds()

randMs := r.Int63n(maxMs-minMs) + minMs

sleepDuration, _ := time.ParseDuration(fmt.Sprintf("%dms", randMs))

log.Printf("Start sleep for: %fs\n", sleepDuration.Seconds())
time.Sleep(sleepDuration)
log.Printf("Sleep done for: %fs\n", sleepDuration.Seconds())
return fmt.Sprintf("Slept for: %fs", sleepDuration.Seconds())
}
}

sleepDuration := time.Second * 2

if val, ok := os.LookupEnv("Http_X_Sleep"); ok && len(val) > 0 {
Expand Down

0 comments on commit dab6684

Please sign in to comment.