2013-07-17 13:45:53 +00:00
|
|
|
package raft
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
2013-07-18 16:26:31 +00:00
|
|
|
"io/ioutil"
|
2014-01-11 12:35:09 +00:00
|
|
|
|
|
|
|
"code.google.com/p/gogoprotobuf/proto"
|
|
|
|
"github.com/goraft/raft/protobuf"
|
2013-07-17 13:45:53 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// The response returned from a server appending entries to the log.
|
|
|
|
type AppendEntriesResponse struct {
|
2014-01-12 07:40:55 +00:00
|
|
|
pb *protobuf.ProtoAppendEntriesResponse
|
|
|
|
peer string
|
|
|
|
append bool
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Creates a new AppendEntries response.
|
|
|
|
func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse {
|
2014-01-12 07:40:55 +00:00
|
|
|
pb := &protobuf.ProtoAppendEntriesResponse{
|
|
|
|
Term: proto.Uint64(term),
|
|
|
|
Index: proto.Uint64(index),
|
|
|
|
Success: proto.Bool(success),
|
|
|
|
CommitIndex: proto.Uint64(commitIndex),
|
|
|
|
}
|
|
|
|
|
2013-07-17 13:45:53 +00:00
|
|
|
return &AppendEntriesResponse{
|
2014-01-12 07:40:55 +00:00
|
|
|
pb: pb,
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-12 07:40:55 +00:00
|
|
|
func (aer *AppendEntriesResponse) Index() uint64 {
|
|
|
|
return aer.pb.GetIndex()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (aer *AppendEntriesResponse) CommitIndex() uint64 {
|
|
|
|
return aer.pb.GetCommitIndex()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (aer *AppendEntriesResponse) Term() uint64 {
|
|
|
|
return aer.pb.GetTerm()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (aer *AppendEntriesResponse) Success() bool {
|
|
|
|
return aer.pb.GetSuccess()
|
|
|
|
}
|
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
// Encodes the AppendEntriesResponse to a buffer. Returns the number of bytes
|
|
|
|
// written and any error that may have occurred.
|
2013-09-19 01:07:12 +00:00
|
|
|
func (resp *AppendEntriesResponse) Encode(w io.Writer) (int, error) {
|
2014-01-12 07:40:55 +00:00
|
|
|
b, err := proto.Marshal(resp.pb)
|
2013-07-18 16:26:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return -1, err
|
|
|
|
}
|
|
|
|
|
2014-01-12 07:40:55 +00:00
|
|
|
return w.Write(b)
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
2013-07-18 16:26:31 +00:00
|
|
|
// Decodes the AppendEntriesResponse from a buffer. Returns the number of bytes read and
|
|
|
|
// any error that occurs.
|
2013-09-19 01:07:12 +00:00
|
|
|
func (resp *AppendEntriesResponse) Decode(r io.Reader) (int, error) {
|
2013-07-18 16:26:31 +00:00
|
|
|
data, err := ioutil.ReadAll(r)
|
|
|
|
if err != nil {
|
|
|
|
return -1, err
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
2014-01-12 07:40:55 +00:00
|
|
|
resp.pb = new(protobuf.ProtoAppendEntriesResponse)
|
|
|
|
if err := proto.Unmarshal(data, resp.pb); err != nil {
|
2013-07-18 16:26:31 +00:00
|
|
|
return -1, err
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|
|
|
|
|
2014-01-12 07:40:55 +00:00
|
|
|
return len(data), nil
|
2013-07-17 13:45:53 +00:00
|
|
|
}
|