event.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. }
  16. func newEvent(action string, key string, modifiedIndex, createdIndex uint64) *Event {
  17. n := &NodeExtern{
  18. Key: key,
  19. ModifiedIndex: modifiedIndex,
  20. CreatedIndex: createdIndex,
  21. }
  22. return &Event{
  23. Action: action,
  24. Node: n,
  25. }
  26. }
  27. func (e *Event) IsCreated() bool {
  28. if e.Action == Create {
  29. return true
  30. }
  31. if e.Action == Set && e.Node.PrevValue == "" {
  32. return true
  33. }
  34. return false
  35. }
  36. func (e *Event) Index() uint64 {
  37. return e.Node.ModifiedIndex
  38. }
  39. // Converts an event object into a response object.
  40. func (event *Event) Response(currentIndex uint64) interface{} {
  41. if !event.Node.Dir {
  42. response := &Response{
  43. Action: event.Action,
  44. Key: event.Node.Key,
  45. Value: event.Node.Value,
  46. PrevValue: event.Node.PrevValue,
  47. Index: event.Node.ModifiedIndex,
  48. TTL: event.Node.TTL,
  49. Expiration: event.Node.Expiration,
  50. }
  51. if currentIndex != 0 {
  52. response.Index = currentIndex
  53. }
  54. if response.Action == Set {
  55. if response.PrevValue == "" {
  56. response.NewKey = true
  57. }
  58. }
  59. if response.Action == CompareAndSwap || response.Action == Create {
  60. response.Action = "testAndSet"
  61. }
  62. return response
  63. } else {
  64. responses := make([]*Response, len(event.Node.Nodes))
  65. for i, node := range event.Node.Nodes {
  66. responses[i] = &Response{
  67. Action: event.Action,
  68. Key: node.Key,
  69. Value: node.Value,
  70. Dir: node.Dir,
  71. Index: node.ModifiedIndex,
  72. }
  73. if currentIndex != 0 {
  74. responses[i].Index = currentIndex
  75. }
  76. }
  77. return responses
  78. }
  79. }