append_entries_response.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package raft
  2. import (
  3. "code.google.com/p/goprotobuf/proto"
  4. "github.com/benbjohnson/go-raft/protobuf"
  5. "io"
  6. "io/ioutil"
  7. )
  8. // The response returned from a server appending entries to the log.
  9. type AppendEntriesResponse struct {
  10. Term uint64
  11. // the current index of the server
  12. Index uint64
  13. Success bool
  14. CommitIndex uint64
  15. peer string
  16. append bool
  17. }
  18. // Creates a new AppendEntries response.
  19. func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse {
  20. return &AppendEntriesResponse{
  21. Term: term,
  22. Success: success,
  23. Index: index,
  24. CommitIndex: commitIndex,
  25. }
  26. }
  27. // Encodes the AppendEntriesResponse to a buffer. Returns the number of bytes
  28. // written and any error that may have occurred.
  29. func (resp *AppendEntriesResponse) encode(w io.Writer) (int, error) {
  30. pb := &protobuf.ProtoAppendEntriesResponse{
  31. Term: proto.Uint64(resp.Term),
  32. Index: proto.Uint64(resp.Index),
  33. CommitIndex: proto.Uint64(resp.CommitIndex),
  34. Success: proto.Bool(resp.Success),
  35. }
  36. p, err := proto.Marshal(pb)
  37. if err != nil {
  38. return -1, err
  39. }
  40. return w.Write(p)
  41. }
  42. // Decodes the AppendEntriesResponse from a buffer. Returns the number of bytes read and
  43. // any error that occurs.
  44. func (resp *AppendEntriesResponse) decode(r io.Reader) (int, error) {
  45. data, err := ioutil.ReadAll(r)
  46. if err != nil {
  47. return -1, err
  48. }
  49. totalBytes := len(data)
  50. pb := &protobuf.ProtoAppendEntriesResponse{}
  51. if err := proto.Unmarshal(data, pb); err != nil {
  52. return -1, err
  53. }
  54. resp.Term = pb.GetTerm()
  55. resp.Index = pb.GetIndex()
  56. resp.CommitIndex = pb.GetCommitIndex()
  57. resp.Success = pb.GetSuccess()
  58. return totalBytes, nil
  59. }