snapshot_recovery_response.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 SnapshotRecoveryResponse struct {
  10. Term uint64
  11. Success bool
  12. CommitIndex uint64
  13. }
  14. //------------------------------------------------------------------------------
  15. //
  16. // Constructors
  17. //
  18. //------------------------------------------------------------------------------
  19. // Creates a new Snapshot response.
  20. func newSnapshotRecoveryResponse(term uint64, success bool, commitIndex uint64) *SnapshotRecoveryResponse {
  21. return &SnapshotRecoveryResponse{
  22. Term: term,
  23. Success: success,
  24. CommitIndex: commitIndex,
  25. }
  26. }
  27. // Encodes the SnapshotRecoveryResponse to a buffer. Returns the number of bytes
  28. // written and any error that may have occurred.
  29. func (req *SnapshotRecoveryResponse) encode(w io.Writer) (int, error) {
  30. pb := &protobuf.ProtoSnapshotRecoveryResponse{
  31. Term: proto.Uint64(req.Term),
  32. Success: proto.Bool(req.Success),
  33. CommitIndex: proto.Uint64(req.CommitIndex),
  34. }
  35. p, err := proto.Marshal(pb)
  36. if err != nil {
  37. return -1, err
  38. }
  39. return w.Write(p)
  40. }
  41. // Decodes the SnapshotRecoveryResponse from a buffer. Returns the number of bytes read and
  42. // any error that occurs.
  43. func (req *SnapshotRecoveryResponse) decode(r io.Reader) (int, error) {
  44. data, err := ioutil.ReadAll(r)
  45. if err != nil {
  46. return 0, err
  47. }
  48. totalBytes := len(data)
  49. pb := &protobuf.ProtoSnapshotRecoveryResponse{}
  50. if err := proto.Unmarshal(data, pb); err != nil {
  51. return -1, err
  52. }
  53. req.Term = pb.GetTerm()
  54. req.Success = pb.GetSuccess()
  55. req.CommitIndex = pb.GetCommitIndex()
  56. return totalBytes, nil
  57. }