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