op.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright 2016 The etcd Authors
  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 pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  16. type opType int
  17. const (
  18. // A default Op has opType 0, which is invalid.
  19. tRange opType = iota + 1
  20. tPut
  21. tDeleteRange
  22. )
  23. var (
  24. noPrefixEnd = []byte{0}
  25. )
  26. // Op represents an Operation that kv can execute.
  27. type Op struct {
  28. t opType
  29. key []byte
  30. end []byte
  31. // for range
  32. limit int64
  33. sort *SortOption
  34. serializable bool
  35. keysOnly bool
  36. countOnly bool
  37. // for range, watch
  38. rev int64
  39. // for watch, put, delete
  40. prevKV bool
  41. // progressNotify is for progress updates.
  42. progressNotify bool
  43. // createdNotify is for created event
  44. createdNotify bool
  45. // filters for watchers
  46. filterPut bool
  47. filterDelete bool
  48. // for put
  49. val []byte
  50. leaseID LeaseID
  51. }
  52. func (op Op) toRequestOp() *pb.RequestOp {
  53. switch op.t {
  54. case tRange:
  55. r := &pb.RangeRequest{
  56. Key: op.key,
  57. RangeEnd: op.end,
  58. Limit: op.limit,
  59. Revision: op.rev,
  60. Serializable: op.serializable,
  61. KeysOnly: op.keysOnly,
  62. CountOnly: op.countOnly,
  63. }
  64. if op.sort != nil {
  65. r.SortOrder = pb.RangeRequest_SortOrder(op.sort.Order)
  66. r.SortTarget = pb.RangeRequest_SortTarget(op.sort.Target)
  67. }
  68. return &pb.RequestOp{Request: &pb.RequestOp_RequestRange{RequestRange: r}}
  69. case tPut:
  70. r := &pb.PutRequest{Key: op.key, Value: op.val, Lease: int64(op.leaseID), PrevKv: op.prevKV}
  71. return &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: r}}
  72. case tDeleteRange:
  73. r := &pb.DeleteRangeRequest{Key: op.key, RangeEnd: op.end, PrevKv: op.prevKV}
  74. return &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{RequestDeleteRange: r}}
  75. default:
  76. panic("Unknown Op")
  77. }
  78. }
  79. func (op Op) isWrite() bool {
  80. return op.t != tRange
  81. }
  82. func OpGet(key string, opts ...OpOption) Op {
  83. ret := Op{t: tRange, key: []byte(key)}
  84. ret.applyOpts(opts)
  85. return ret
  86. }
  87. func OpDelete(key string, opts ...OpOption) Op {
  88. ret := Op{t: tDeleteRange, key: []byte(key)}
  89. ret.applyOpts(opts)
  90. switch {
  91. case ret.leaseID != 0:
  92. panic("unexpected lease in delete")
  93. case ret.limit != 0:
  94. panic("unexpected limit in delete")
  95. case ret.rev != 0:
  96. panic("unexpected revision in delete")
  97. case ret.sort != nil:
  98. panic("unexpected sort in delete")
  99. case ret.serializable:
  100. panic("unexpected serializable in delete")
  101. case ret.countOnly:
  102. panic("unexpected countOnly in delete")
  103. case ret.filterDelete, ret.filterPut:
  104. panic("unexpected filter in delete")
  105. case ret.createdNotify:
  106. panic("unexpected createdNotify in delete")
  107. }
  108. return ret
  109. }
  110. func OpPut(key, val string, opts ...OpOption) Op {
  111. ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
  112. ret.applyOpts(opts)
  113. switch {
  114. case ret.end != nil:
  115. panic("unexpected range in put")
  116. case ret.limit != 0:
  117. panic("unexpected limit in put")
  118. case ret.rev != 0:
  119. panic("unexpected revision in put")
  120. case ret.sort != nil:
  121. panic("unexpected sort in put")
  122. case ret.serializable:
  123. panic("unexpected serializable in put")
  124. case ret.countOnly:
  125. panic("unexpected countOnly in put")
  126. case ret.filterDelete, ret.filterPut:
  127. panic("unexpected filter in put")
  128. case ret.createdNotify:
  129. panic("unexpected createdNotify in put")
  130. }
  131. return ret
  132. }
  133. func opWatch(key string, opts ...OpOption) Op {
  134. ret := Op{t: tRange, key: []byte(key)}
  135. ret.applyOpts(opts)
  136. switch {
  137. case ret.leaseID != 0:
  138. panic("unexpected lease in watch")
  139. case ret.limit != 0:
  140. panic("unexpected limit in watch")
  141. case ret.sort != nil:
  142. panic("unexpected sort in watch")
  143. case ret.serializable:
  144. panic("unexpected serializable in watch")
  145. case ret.countOnly:
  146. panic("unexpected countOnly in watch")
  147. }
  148. return ret
  149. }
  150. func (op *Op) applyOpts(opts []OpOption) {
  151. for _, opt := range opts {
  152. opt(op)
  153. }
  154. }
  155. // OpOption configures Operations like Get, Put, Delete.
  156. type OpOption func(*Op)
  157. // WithLease attaches a lease ID to a key in 'Put' request.
  158. func WithLease(leaseID LeaseID) OpOption {
  159. return func(op *Op) { op.leaseID = leaseID }
  160. }
  161. // WithLimit limits the number of results to return from 'Get' request.
  162. func WithLimit(n int64) OpOption { return func(op *Op) { op.limit = n } }
  163. // WithRev specifies the store revision for 'Get' request.
  164. // Or the start revision of 'Watch' request.
  165. func WithRev(rev int64) OpOption { return func(op *Op) { op.rev = rev } }
  166. // WithSort specifies the ordering in 'Get' request. It requires
  167. // 'WithRange' and/or 'WithPrefix' to be specified too.
  168. // 'target' specifies the target to sort by: key, version, revisions, value.
  169. // 'order' can be either 'SortNone', 'SortAscend', 'SortDescend'.
  170. func WithSort(target SortTarget, order SortOrder) OpOption {
  171. return func(op *Op) {
  172. op.sort = &SortOption{target, order}
  173. }
  174. }
  175. // GetPrefixRangeEnd gets the range end of the prefix.
  176. // 'Get(foo, WithPrefix())' is equal to 'Get(foo, WithRange(GetPrefixRangeEnd(foo))'.
  177. func GetPrefixRangeEnd(prefix string) string {
  178. return string(getPrefix([]byte(prefix)))
  179. }
  180. func getPrefix(key []byte) []byte {
  181. end := make([]byte, len(key))
  182. copy(end, key)
  183. for i := len(end) - 1; i >= 0; i-- {
  184. if end[i] < 0xff {
  185. end[i] = end[i] + 1
  186. end = end[:i+1]
  187. return end
  188. }
  189. }
  190. // next prefix does not exist (e.g., 0xffff);
  191. // default to WithFromKey policy
  192. return noPrefixEnd
  193. }
  194. // WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate
  195. // on the keys with matching prefix. For example, 'Get(foo, WithPrefix())'
  196. // can return 'foo1', 'foo2', and so on.
  197. func WithPrefix() OpOption {
  198. return func(op *Op) {
  199. op.end = getPrefix(op.key)
  200. }
  201. }
  202. // WithRange specifies the range of 'Get' or 'Delete' requests.
  203. // For example, 'Get' requests with 'WithRange(end)' returns
  204. // the keys in the range [key, end).
  205. func WithRange(endKey string) OpOption {
  206. return func(op *Op) { op.end = []byte(endKey) }
  207. }
  208. // WithFromKey specifies the range of 'Get' or 'Delete' requests
  209. // to be equal or greater than the key in the argument.
  210. func WithFromKey() OpOption { return WithRange("\x00") }
  211. // WithSerializable makes 'Get' request serializable. By default,
  212. // it's linearizable. Serializable requests are better for lower latency
  213. // requirement.
  214. func WithSerializable() OpOption {
  215. return func(op *Op) { op.serializable = true }
  216. }
  217. // WithKeysOnly makes the 'Get' request return only the keys and the corresponding
  218. // values will be omitted.
  219. func WithKeysOnly() OpOption {
  220. return func(op *Op) { op.keysOnly = true }
  221. }
  222. // WithCountOnly makes the 'Get' request return only the count of keys.
  223. func WithCountOnly() OpOption {
  224. return func(op *Op) { op.countOnly = true }
  225. }
  226. // WithFirstCreate gets the key with the oldest creation revision in the request range.
  227. func WithFirstCreate() []OpOption { return withTop(SortByCreateRevision, SortAscend) }
  228. // WithLastCreate gets the key with the latest creation revision in the request range.
  229. func WithLastCreate() []OpOption { return withTop(SortByCreateRevision, SortDescend) }
  230. // WithFirstKey gets the lexically first key in the request range.
  231. func WithFirstKey() []OpOption { return withTop(SortByKey, SortAscend) }
  232. // WithLastKey gets the lexically last key in the request range.
  233. func WithLastKey() []OpOption { return withTop(SortByKey, SortDescend) }
  234. // WithFirstRev gets the key with the oldest modification revision in the request range.
  235. func WithFirstRev() []OpOption { return withTop(SortByModRevision, SortAscend) }
  236. // WithLastRev gets the key with the latest modification revision in the request range.
  237. func WithLastRev() []OpOption { return withTop(SortByModRevision, SortDescend) }
  238. // withTop gets the first key over the get's prefix given a sort order
  239. func withTop(target SortTarget, order SortOrder) []OpOption {
  240. return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
  241. }
  242. // WithProgressNotify makes watch server send periodic progress updates.
  243. // Progress updates have zero events in WatchResponse.
  244. func WithProgressNotify() OpOption {
  245. return func(op *Op) {
  246. op.progressNotify = true
  247. }
  248. }
  249. // WithCreatedNotify makes watch server sends the created event.
  250. func WithCreatedNotify() OpOption {
  251. return func(op *Op) {
  252. op.createdNotify = true
  253. }
  254. }
  255. // WithFilterPut discards PUT events from the watcher.
  256. func WithFilterPut() OpOption {
  257. return func(op *Op) { op.filterPut = true }
  258. }
  259. // WithFilterDelete discards DELETE events from the watcher.
  260. func WithFilterDelete() OpOption {
  261. return func(op *Op) { op.filterDelete = true }
  262. }
  263. // WithPrevKV gets the previous key-value pair before the event happens. If the previous KV is already compacted,
  264. // nothing will be returned.
  265. func WithPrevKV() OpOption {
  266. return func(op *Op) {
  267. op.prevKV = true
  268. }
  269. }