event.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. type Event struct {
  15. Action string `json:"action"`
  16. Key string `json:"key, omitempty"`
  17. Dir bool `json:"dir,omitempty"`
  18. PrevValue string `json:"prevValue,omitempty"`
  19. Value string `json:"value,omitempty"`
  20. KVPairs kvPairs `json:"kvs,omitempty"`
  21. Expiration *time.Time `json:"expiration,omitempty"`
  22. TTL int64 `json:"ttl,omitempty"` // Time to live in second
  23. ModifiedIndex uint64 `json:"modifiedIndex"`
  24. }
  25. func newEvent(action string, key string, index uint64) *Event {
  26. return &Event{
  27. Action: action,
  28. Key: key,
  29. ModifiedIndex: index,
  30. }
  31. }
  32. func (e *Event) IsCreated() bool {
  33. if e.Action == Create {
  34. return true
  35. }
  36. if e.Action == Set && e.PrevValue == "" {
  37. return true
  38. }
  39. return false
  40. }
  41. func (e *Event) Index() uint64 {
  42. return e.ModifiedIndex
  43. }
  44. // Converts an event object into a response object.
  45. func (event *Event) Response() interface{} {
  46. if !event.Dir {
  47. response := &Response{
  48. Action: event.Action,
  49. Key: event.Key,
  50. Value: event.Value,
  51. PrevValue: event.PrevValue,
  52. Index: event.ModifiedIndex,
  53. TTL: event.TTL,
  54. Expiration: event.Expiration,
  55. }
  56. if response.Action == Set {
  57. if response.PrevValue == "" {
  58. response.NewKey = true
  59. }
  60. }
  61. if response.Action == CompareAndSwap || response.Action == Create {
  62. response.Action = "testAndSet"
  63. }
  64. return response
  65. } else {
  66. responses := make([]*Response, len(event.KVPairs))
  67. for i, kv := range event.KVPairs {
  68. responses[i] = &Response{
  69. Action: event.Action,
  70. Key: kv.Key,
  71. Value: kv.Value,
  72. Dir: kv.Dir,
  73. Index: event.ModifiedIndex,
  74. }
  75. }
  76. return responses
  77. }
  78. }