influxdb/append_entries_response.go

71 lines
1.7 KiB
Go
Raw Normal View History

package raft
import (
2013-07-18 16:26:31 +00:00
"code.google.com/p/goprotobuf/proto"
"github.com/goraft/raft/protobuf"
"io"
2013-07-18 16:26:31 +00:00
"io/ioutil"
)
// The response returned from a server appending entries to the log.
type AppendEntriesResponse struct {
Term uint64
// the current index of the server
Index uint64
Success bool
CommitIndex uint64
peer string
append bool
}
// Creates a new AppendEntries response.
func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse {
return &AppendEntriesResponse{
Term: term,
Success: success,
Index: index,
CommitIndex: commitIndex,
}
}
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) {
2013-07-18 16:26:31 +00:00
pb := &protobuf.ProtoAppendEntriesResponse{
Term: proto.Uint64(resp.Term),
Index: proto.Uint64(resp.Index),
CommitIndex: proto.Uint64(resp.CommitIndex),
Success: proto.Bool(resp.Success),
}
p, err := proto.Marshal(pb)
2013-07-18 16:26:31 +00:00
if err != nil {
return -1, err
}
return w.Write(p)
}
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-18 16:26:31 +00:00
totalBytes := len(data)
pb := &protobuf.ProtoAppendEntriesResponse{}
if err := proto.Unmarshal(data, pb); err != nil {
2013-07-18 16:26:31 +00:00
return -1, err
}
2013-07-18 16:26:31 +00:00
resp.Term = pb.GetTerm()
resp.Index = pb.GetIndex()
resp.CommitIndex = pb.GetCommitIndex()
resp.Success = pb.GetSuccess()
2013-07-18 16:26:31 +00:00
return totalBytes, nil
}