event.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // Converts an event object into a response object.
  40. func (event *Event) Response() interface{} {
  41. if !event.Dir {
  42. response := &Response{
  43. Action: event.Action,
  44. Key: event.Key,
  45. Value: event.Value,
  46. PrevValue: event.PrevValue,
  47. Index: event.Index,
  48. TTL: event.TTL,
  49. Expiration: event.Expiration,
  50. }
  51. if response.Action == Create || response.Action == Set {
  52. response.Action = "set"
  53. if response.PrevValue == "" {
  54. response.NewKey = true
  55. }
  56. }
  57. return response
  58. } else {
  59. responses := make([]*Response, len(event.KVPairs))
  60. for i, kv := range event.KVPairs {
  61. responses[i] = &Response{
  62. Action: event.Action,
  63. Key: kv.Key,
  64. Value: kv.Value,
  65. Dir: kv.Dir,
  66. Index: event.Index,
  67. }
  68. }
  69. return responses
  70. }
  71. }