event.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package store
  2. import (
  3. "time"
  4. )
  5. const (
  6. Get = "get"
  7. Create = "create"
  8. Update = "update"
  9. Delete = "delete"
  10. TestAndSet = "testAndSet"
  11. Expire = "expire"
  12. )
  13. const (
  14. UndefIndex = 0
  15. UndefTerm = 0
  16. )
  17. type Event struct {
  18. Action string `json:"action"`
  19. Key string `json:"key, omitempty"`
  20. Dir bool `json:"dir,omitempty"`
  21. PrevValue string `json:"prevValue,omitempty"`
  22. Value string `json:"value,omitempty"`
  23. KVPairs kvPairs `json:"kvs,omitempty"`
  24. Expiration *time.Time `json:"expiration,omitempty"`
  25. TTL int64 `json:"ttl,omitempty"` // Time to live in second
  26. // The command index of the raft machine when the command is executed
  27. Index uint64 `json:"index"`
  28. Term uint64 `json:"term"`
  29. }
  30. func newEvent(action string, key string, index uint64, term uint64) *Event {
  31. return &Event{
  32. Action: action,
  33. Key: key,
  34. Index: index,
  35. Term: term,
  36. }
  37. }
  38. // Converts an event object into a response object.
  39. func (event *Event) Response() interface{} {
  40. if !event.Dir {
  41. response := &Response{
  42. Action: event.Action,
  43. Key: event.Key,
  44. Value: event.Value,
  45. PrevValue: event.PrevValue,
  46. Index: event.Index,
  47. TTL: event.TTL,
  48. Expiration: event.Expiration,
  49. }
  50. if response.Action == Create || response.Action == Update {
  51. response.Action = "set"
  52. if response.PrevValue == "" {
  53. response.NewKey = true
  54. }
  55. }
  56. return response
  57. } else {
  58. responses := make([]*Response, len(event.KVPairs))
  59. for i, kv := range event.KVPairs {
  60. responses[i] = &Response{
  61. Action: event.Action,
  62. Key: kv.Key,
  63. Value: kv.Value,
  64. Dir: kv.Dir,
  65. Index: event.Index,
  66. }
  67. }
  68. return responses
  69. }
  70. }