-
Notifications
You must be signed in to change notification settings - Fork 6
/
channel_peer.go
93 lines (84 loc) · 2.35 KB
/
channel_peer.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
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
package graft
import (
"errors"
)
type ChannelPeer struct {
requestVoteChan chan RequestVoteMessage
server *Server
voteResponseChan chan VoteResponseMessage
shutDownChan chan int
appendEntriesChan chan AppendEntriesMessage
appendEntriesResponseChan chan AppendEntriesResponseMessage
partitionChan chan bool
errorChan chan error
}
func NewChannelPeer(server *Server) ChannelPeer {
return ChannelPeer{
requestVoteChan: make(chan RequestVoteMessage),
server: server,
voteResponseChan: make(chan VoteResponseMessage),
shutDownChan: make(chan int),
appendEntriesChan: make(chan AppendEntriesMessage),
appendEntriesResponseChan: make(chan AppendEntriesResponseMessage),
partitionChan: make(chan bool),
errorChan: make(chan error),
}
}
func (peer ChannelPeer) ReceiveRequestVote(message RequestVoteMessage) (response VoteResponseMessage, err error) {
peer.requestVoteChan <- message
for {
select {
case response = <-peer.voteResponseChan:
err = nil
return
case err = <-peer.errorChan:
return
}
}
}
func (peer ChannelPeer) ReceiveAppendEntries(message AppendEntriesMessage) (response AppendEntriesResponseMessage, err error) {
peer.appendEntriesChan <- message
for {
select {
case response = <-peer.appendEntriesResponseChan:
return
case err = <-peer.errorChan:
return
}
}
}
func (peer ChannelPeer) Start() {
peer.server.Start()
go func(partitioned bool) {
for {
select {
case message := <-peer.requestVoteChan:
if partitioned {
peer.errorChan <- errors.New("Partitioned")
} else {
response, _ := peer.server.ReceiveRequestVote(message)
peer.voteResponseChan <- response
}
case message := <-peer.appendEntriesChan:
if partitioned != true {
response, _ := peer.server.ReceiveAppendEntries(message)
peer.appendEntriesResponseChan <- response
} else {
peer.errorChan <- errors.New("Partitioned")
}
case partitioned = <-peer.partitionChan:
case <-peer.shutDownChan:
return
}
}
}(false)
}
func (peer ChannelPeer) Partition() {
peer.partitionChan <- true
}
func (peer ChannelPeer) HealPartition() {
peer.partitionChan <- false
}
func (peer ChannelPeer) ShutDown() {
peer.shutDownChan <- 0
}