github.com/kula/etcd@v0.2.1-0.20131226070625-e96234382ac0/store/event.go (about)

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