-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel.go
66 lines (58 loc) · 1.5 KB
/
channel.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
57
58
59
60
61
62
63
64
65
66
package paxos
import (
"fmt"
"math/rand"
"time"
)
// The supervisor is not currently being used.
type ChannelSupervisor struct{}
func NewChannelSupervisor() *ChannelSupervisor {
return &ChannelSupervisor{}
}
// Channel defines an non-FIFO, lossy channel. Specifically, messages sent through a Channel could
// be delayed, re-ordered, or lost. The "lossy-ness" of the channel can be configured.
type Channel struct {
s *ChannelSupervisor
rand *rand.Rand
read chan Msg
write chan Msg
dropRate float64
log bool
}
// NewChannel creates a new channel. DropRate should be a number between 0 and 1 (inclusive): it
// determines what percentage of messages on the channel will be dropped. If log is true, any
// messages sent via the channel will be logged.
func (s *ChannelSupervisor) NewChannel(dropRate float64, log bool) *Channel {
return &Channel{
s: s,
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
read: make(chan Msg, 10),
write: make(chan Msg, 10),
dropRate: dropRate,
log: log,
}
}
func (c *Channel) Read() <-chan Msg {
return c.read
}
func (c *Channel) Write() chan<- Msg {
return c.write
}
func (c *Channel) Run() {
for {
select {
case in := <-c.write:
time.Sleep(time.Duration(c.rand.Intn(20)) * time.Millisecond)
if c.rand.Float64() > c.dropRate {
if c.log {
fmt.Printf("SENT: %s\n", MsgToString(in))
}
c.read <- in
} else {
if c.log {
fmt.Printf("\tNOT SENT: %s\n", MsgToString(in))
}
}
}
}
}