-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.go
95 lines (78 loc) · 1.89 KB
/
models.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
94
95
package models
import (
"bytes"
"encoding/gob"
)
//RequestType defines the kind of request received
//by the RaftServer, it can be one of 'AppendEntry'
// 'RequestVote' or 'ClientCommand'
//go:generate stringer -type=RequestType
type RequestType int
const (
AppendEntry RequestType = iota
RequestVote
ClientCommand
)
type Request struct {
RequestType RequestType
Payload []byte
}
type RequestConverter interface {
ToRequest() (Request, error)
}
type AppendEntryPayload struct {
Term uint64
LeaderId string
PrevLogIndex uint64
PrevLogTerm uint64
Entries []byte
LeaderCommit uint64
}
func (aep *AppendEntryPayload) ToRequest() (Request, error) {
return toRequestPayload(AppendEntry, aep)
}
type RequestVotePayload struct {
Term uint64
CandidateId string
LastLogIndex uint64
LastLogTerm uint64
}
func (rvp *RequestVotePayload) ToRequest() (Request, error) {
return toRequestPayload(RequestVote, rvp)
}
type ClientCommandPayload struct {
ClientCommand []byte
}
func (ccp *ClientCommandPayload) ToRequest() (Request, error) {
return toRequestPayload(ClientCommand, ccp)
}
type AppendEntryResponse struct {
Term uint64
Success bool
}
func (aer *AppendEntryResponse) FromPayload(payload []byte) error {
decoder := gob.NewDecoder(bytes.NewBuffer(payload))
return decoder.Decode(aer)
}
type RequestVoteResponse struct {
Term uint64
VoteGranted bool
}
func (rvr *RequestVoteResponse) FromPayload(payload []byte) error {
decoder := gob.NewDecoder(bytes.NewBuffer(payload))
return decoder.Decode(rvr)
}
type Response struct {
Payload []byte
}
func toRequestPayload(requestType RequestType, payload interface{}) (Request, error) {
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
if err := encoder.Encode(payload); err != nil {
return Request{}, err
}
return Request{
RequestType: requestType,
Payload: buffer.Bytes(),
}, nil
}