op.go 8.6 KB

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