-
Notifications
You must be signed in to change notification settings - Fork 449
/
latency.go
56 lines (50 loc) · 1.07 KB
/
latency.go
1
2
3
4
5
6
7
8
9
10
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
48
49
50
51
52
53
54
55
56
package toxics
import (
"math/rand"
"time"
)
// The LatencyToxic passes data through with the a delay of latency +/- jitter added.
type LatencyToxic struct {
// Times in milliseconds
Latency int64 `json:"latency"`
Jitter int64 `json:"jitter"`
}
func (t *LatencyToxic) GetBufferSize() int {
return 1024
}
func (t *LatencyToxic) delay() time.Duration {
// Delay = t.Latency +/- t.Jitter
delay := t.Latency
jitter := t.Jitter
if jitter > 0 {
//#nosec
delay += rand.Int63n(jitter*2) - jitter
}
return time.Duration(delay) * time.Millisecond
}
func (t *LatencyToxic) Pipe(stub *ToxicStub) {
for {
select {
case <-stub.Interrupt:
return
case c := <-stub.Input:
if c == nil {
stub.Close()
return
}
sleep := t.delay() - time.Since(c.Timestamp)
select {
case <-time.After(sleep):
c.Timestamp = c.Timestamp.Add(sleep)
stub.Output <- c
case <-stub.Interrupt:
// Exit fast without applying latency.
stub.Output <- c // Don't drop any data on the floor
return
}
}
}
}
func init() {
Register("latency", new(LatencyToxic))
}