op.go 8.2 KB

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