event.go 2.0 KB

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