delay.go 1.91 KB
Newer Older
1 2 3
package delay

import (
4
	"math/rand"
5 6 7 8
	"sync"
	"time"
)

9 10
var sharedRNG = rand.New(rand.NewSource(time.Now().UnixNano()))

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// Delay makes it easy to add (threadsafe) configurable delays to other
// objects.
type D interface {
	Set(time.Duration) time.Duration
	Wait()
	Get() time.Duration
}

// Fixed returns a delay with fixed latency
func Fixed(t time.Duration) D {
	return &delay{t: t}
}

type delay struct {
	l sync.RWMutex
	t time.Duration
}

func (d *delay) Set(t time.Duration) time.Duration {
	d.l.Lock()
	defer d.l.Unlock()
	prev := d.t
	d.t = t
	return prev
}

func (d *delay) Wait() {
	d.l.RLock()
	defer d.l.RUnlock()
	time.Sleep(d.t)
}

func (d *delay) Get() time.Duration {
	d.l.Lock()
	defer d.l.Unlock()
	return d.t
}
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

// VariableNormal is a delay following a normal distribution
// Notice that to implement the D interface Set can only change the mean delay
// the standard deviation is set only at initialization
func VariableNormal(t, std time.Duration, rng *rand.Rand) D {
	if rng == nil {
		rng = sharedRNG
	}

	v := &variableNormal{
		std: std,
		rng: rng,
	}
	v.t = t
	return v
}

type variableNormal struct {
	delay
	std time.Duration
	rng *rand.Rand
}

func (d *variableNormal) Wait() {
	d.l.RLock()
	defer d.l.RUnlock()
	randomDelay := time.Duration(d.rng.NormFloat64() * float64(d.std))
	time.Sleep(randomDelay + d.t)
}

// VariableUniform is a delay following a uniform distribution
// Notice that to implement the D interface Set can only change the minimum delay
// the delta is set only at initialization
func VariableUniform(t, d time.Duration, rng *rand.Rand) D {
	if rng == nil {
		rng = sharedRNG
	}

	v := &variableUniform{
		d:   d,
		rng: rng,
	}
	v.t = t
	return v
}

type variableUniform struct {
	delay
	d   time.Duration // max delta
	rng *rand.Rand
}

func (d *variableUniform) Wait() {
	d.l.RLock()
	defer d.l.RUnlock()
	randomDelay := time.Duration(d.rng.Float64() * float64(d.d))
	time.Sleep(randomDelay + d.t)
}