op.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2016 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package clientv3
  15. import (
  16. "reflect"
  17. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  18. "github.com/coreos/etcd/lease"
  19. )
  20. type opType int
  21. const (
  22. // A default Op has opType 0, which is invalid.
  23. tRange opType = iota + 1
  24. tPut
  25. tDeleteRange
  26. )
  27. // Op represents an Operation that kv can execute.
  28. type Op struct {
  29. t opType
  30. key []byte
  31. end []byte
  32. // for range
  33. limit int64
  34. sort *SortOption
  35. serializable bool
  36. // for range, watch
  37. rev int64
  38. // for put
  39. val []byte
  40. leaseID lease.LeaseID
  41. }
  42. func (op Op) toRequestUnion() *pb.RequestUnion {
  43. switch op.t {
  44. case tRange:
  45. r := &pb.RangeRequest{Key: op.key, RangeEnd: op.end, Limit: op.limit, Revision: op.rev}
  46. if op.sort != nil {
  47. r.SortOrder = pb.RangeRequest_SortOrder(op.sort.Order)
  48. r.SortTarget = pb.RangeRequest_SortTarget(op.sort.Target)
  49. }
  50. return &pb.RequestUnion{Request: &pb.RequestUnion_RequestRange{RequestRange: r}}
  51. case tPut:
  52. r := &pb.PutRequest{Key: op.key, Value: op.val, Lease: int64(op.leaseID)}
  53. return &pb.RequestUnion{Request: &pb.RequestUnion_RequestPut{RequestPut: r}}
  54. case tDeleteRange:
  55. r := &pb.DeleteRangeRequest{Key: op.key, RangeEnd: op.end}
  56. return &pb.RequestUnion{Request: &pb.RequestUnion_RequestDeleteRange{RequestDeleteRange: r}}
  57. default:
  58. panic("Unknown Op")
  59. }
  60. }
  61. func (op Op) toWatchRequest() *watchRequest {
  62. switch op.t {
  63. case tRange:
  64. key := string(op.key)
  65. prefix := ""
  66. if op.end != nil {
  67. prefix = key
  68. key = ""
  69. }
  70. wr := &watchRequest{
  71. key: key,
  72. prefix: prefix,
  73. rev: op.rev,
  74. }
  75. return wr
  76. default:
  77. panic("Only for tRange")
  78. }
  79. }
  80. func (op Op) isWrite() bool {
  81. return op.t != tRange
  82. }
  83. func OpGet(key string, opts ...OpOption) Op {
  84. ret := Op{t: tRange, key: []byte(key)}
  85. ret.applyOpts(opts)
  86. return ret
  87. }
  88. func OpDelete(key string, opts ...OpOption) Op {
  89. ret := Op{t: tDeleteRange, key: []byte(key)}
  90. ret.applyOpts(opts)
  91. switch {
  92. case ret.leaseID != 0:
  93. panic("unexpected lease in delete")
  94. case ret.limit != 0:
  95. panic("unexpected limit in delete")
  96. case ret.rev != 0:
  97. panic("unexpected revision in delete")
  98. case ret.sort != nil:
  99. panic("unexpected sort in delete")
  100. case ret.serializable != false:
  101. panic("unexpected serializable in delete")
  102. }
  103. return ret
  104. }
  105. func OpPut(key, val string, opts ...OpOption) Op {
  106. ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
  107. ret.applyOpts(opts)
  108. switch {
  109. case ret.end != nil:
  110. panic("unexpected range in put")
  111. case ret.limit != 0:
  112. panic("unexpected limit in put")
  113. case ret.rev != 0:
  114. panic("unexpected revision in put")
  115. case ret.sort != nil:
  116. panic("unexpected sort in put")
  117. case ret.serializable != false:
  118. panic("unexpected serializable in delete")
  119. }
  120. return ret
  121. }
  122. func opWatch(key string, opts ...OpOption) Op {
  123. ret := Op{t: tRange, key: []byte(key)}
  124. ret.applyOpts(opts)
  125. switch {
  126. case ret.end != nil && !reflect.DeepEqual(ret.end, getPrefix(ret.key)):
  127. panic("only supports single keys or prefixes")
  128. case ret.leaseID != 0:
  129. panic("unexpected lease in watch")
  130. case ret.limit != 0:
  131. panic("unexpected limit in watch")
  132. case ret.sort != nil:
  133. panic("unexpected sort in watch")
  134. case ret.serializable != false:
  135. panic("unexpected serializable in watch")
  136. }
  137. return ret
  138. }
  139. func (op *Op) applyOpts(opts []OpOption) {
  140. for _, opt := range opts {
  141. opt(op)
  142. }
  143. }
  144. // OpOption configures Operations like Get, Put, Delete.
  145. type OpOption func(*Op)
  146. // WithLease attaches a lease ID to a key in 'Put' request.
  147. func WithLease(leaseID lease.LeaseID) OpOption {
  148. return func(op *Op) { op.leaseID = leaseID }
  149. }
  150. // WithLimit limits the number of results to return from 'Get' request.
  151. func WithLimit(n int64) OpOption { return func(op *Op) { op.limit = n } }
  152. // WithRev specifies the store revision for 'Get' request.
  153. // Or the start revision of 'Watch' request.
  154. func WithRev(rev int64) OpOption { return func(op *Op) { op.rev = rev } }
  155. // WithSort specifies the ordering in 'Get' request. It requires
  156. // 'WithRange' and/or 'WithPrefix' to be specified too.
  157. // 'target' specifies the target to sort by: key, version, revisions, value.
  158. // 'order' can be either 'SortNone', 'SortAscend', 'SortDescend'.
  159. func WithSort(target SortTarget, order SortOrder) OpOption {
  160. return func(op *Op) {
  161. op.sort = &SortOption{target, order}
  162. }
  163. }
  164. func getPrefix(key []byte) []byte {
  165. end := make([]byte, len(key))
  166. copy(end, key)
  167. for i := len(end) - 1; i >= 0; i-- {
  168. if end[i] < 0xff {
  169. end[i] = end[i] + 1
  170. end = end[:i+1]
  171. return end
  172. }
  173. }
  174. // next prefix does not exist (e.g., 0xffff);
  175. // default to WithFromKey policy
  176. end = []byte{0}
  177. return end
  178. }
  179. // WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate
  180. // on the keys with matching prefix. For example, 'Get(foo, WithPrefix())'
  181. // can return 'foo1', 'foo2', and so on.
  182. func WithPrefix() OpOption {
  183. return func(op *Op) {
  184. op.end = getPrefix(op.key)
  185. }
  186. }
  187. // WithRange specifies the range of 'Get' or 'Delete' requests.
  188. // For example, 'Get' requests with 'WithRange(end)' returns
  189. // the keys in the range [key, end).
  190. func WithRange(endKey string) OpOption {
  191. return func(op *Op) { op.end = []byte(endKey) }
  192. }
  193. // WithFromKey specifies the range of 'Get' or 'Delete' requests
  194. // to be equal or greater than they key in the argument.
  195. func WithFromKey() OpOption { return WithRange("\x00") }
  196. // WithSerializable makes 'Get' request serializable. By default,
  197. // it's linearizable. Serializable requests are better for lower latency
  198. // requirement.
  199. func WithSerializable() OpOption {
  200. return func(op *Op) { op.serializable = true }
  201. }
  202. // WithFirstCreate gets the key with the oldest creation revision in the request range.
  203. func WithFirstCreate() []OpOption { return withTop(SortByCreatedRev, SortAscend) }
  204. // WithLastCreate gets the key with the latest creation revision in the request range.
  205. func WithLastCreate() []OpOption { return withTop(SortByCreatedRev, SortDescend) }
  206. // WithFirstKey gets the lexically first key in the request range.
  207. func WithFirstKey() []OpOption { return withTop(SortByKey, SortAscend) }
  208. // WithLastKey gets the lexically last key in the request range.
  209. func WithLastKey() []OpOption { return withTop(SortByKey, SortDescend) }
  210. // WithFirstRev gets the key with the oldest modification revision in the request range.
  211. func WithFirstRev() []OpOption { return withTop(SortByModifiedRev, SortAscend) }
  212. // WithLastRev gets the key with the latest modification revision in the request range.
  213. func WithLastRev() []OpOption { return withTop(SortByModifiedRev, SortDescend) }
  214. // withTop gets the first key over the get's prefix given a sort order
  215. func withTop(target SortTarget, order SortOrder) []OpOption {
  216. return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
  217. }