op.go 8.1 KB

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