event.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package store
  2. const (
  3. Get = "get"
  4. Create = "create"
  5. Set = "set"
  6. Update = "update"
  7. Delete = "delete"
  8. CompareAndSwap = "compareAndSwap"
  9. CompareAndDelete = "compareAndDelete"
  10. Expire = "expire"
  11. )
  12. type Event struct {
  13. Action string `json:"action"`
  14. Node *NodeExtern `json:"node,omitempty"`
  15. PrevNode *NodeExtern `json:"prevNode,omitempty"`
  16. }
  17. func newEvent(action string, key string, modifiedIndex, createdIndex uint64) *Event {
  18. n := &NodeExtern{
  19. Key: key,
  20. ModifiedIndex: modifiedIndex,
  21. CreatedIndex: createdIndex,
  22. }
  23. return &Event{
  24. Action: action,
  25. Node: n,
  26. }
  27. }
  28. func (e *Event) IsCreated() bool {
  29. if e.Action == Create {
  30. return true
  31. }
  32. if e.Action == Set && e.PrevNode == nil {
  33. return true
  34. }
  35. return false
  36. }
  37. func (e *Event) Index() uint64 {
  38. return e.Node.ModifiedIndex
  39. }
  40. // Converts an event object into a response object.
  41. func (event *Event) Response(currentIndex uint64) interface{} {
  42. if !event.Node.Dir {
  43. response := &Response{
  44. Action: event.Action,
  45. Key: event.Node.Key,
  46. Value: event.Node.Value,
  47. Index: event.Node.ModifiedIndex,
  48. TTL: event.Node.TTL,
  49. Expiration: event.Node.Expiration,
  50. }
  51. if event.PrevNode != nil {
  52. response.PrevValue = event.PrevNode.Value
  53. }
  54. if currentIndex != 0 {
  55. response.Index = currentIndex
  56. }
  57. if response.Action == Set {
  58. if response.PrevValue == nil {
  59. response.NewKey = true
  60. }
  61. }
  62. if response.Action == CompareAndSwap || response.Action == Create {
  63. response.Action = "testAndSet"
  64. }
  65. return response
  66. } else {
  67. responses := make([]*Response, len(event.Node.Nodes))
  68. for i, node := range event.Node.Nodes {
  69. responses[i] = &Response{
  70. Action: event.Action,
  71. Key: node.Key,
  72. Value: node.Value,
  73. Dir: node.Dir,
  74. Index: node.ModifiedIndex,
  75. }
  76. if currentIndex != 0 {
  77. responses[i].Index = currentIndex
  78. }
  79. }
  80. return responses
  81. }
  82. }