op.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. minModRev int64
  38. maxModRev int64
  39. minCreateRev int64
  40. maxCreateRev int64
  41. // for range, watch
  42. rev int64
  43. // for watch, put, delete
  44. prevKV bool
  45. // progressNotify is for progress updates.
  46. progressNotify bool
  47. // createdNotify is for created event
  48. createdNotify bool
  49. // filters for watchers
  50. filterPut bool
  51. filterDelete bool
  52. // for put
  53. val []byte
  54. leaseID LeaseID
  55. }
  56. func (op Op) toRangeRequest() *pb.RangeRequest {
  57. if op.t != tRange {
  58. panic("op.t != tRange")
  59. }
  60. r := &pb.RangeRequest{
  61. Key: op.key,
  62. RangeEnd: op.end,
  63. Limit: op.limit,
  64. Revision: op.rev,
  65. Serializable: op.serializable,
  66. KeysOnly: op.keysOnly,
  67. CountOnly: op.countOnly,
  68. MinModRevision: op.minModRev,
  69. MaxModRevision: op.maxModRev,
  70. MinCreateRevision: op.minCreateRev,
  71. MaxCreateRevision: op.maxCreateRev,
  72. }
  73. if op.sort != nil {
  74. r.SortOrder = pb.RangeRequest_SortOrder(op.sort.Order)
  75. r.SortTarget = pb.RangeRequest_SortTarget(op.sort.Target)
  76. }
  77. return r
  78. }
  79. func (op Op) toRequestOp() *pb.RequestOp {
  80. switch op.t {
  81. case tRange:
  82. return &pb.RequestOp{Request: &pb.RequestOp_RequestRange{RequestRange: op.toRangeRequest()}}
  83. case tPut:
  84. r := &pb.PutRequest{Key: op.key, Value: op.val, Lease: int64(op.leaseID), PrevKv: op.prevKV}
  85. return &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: r}}
  86. case tDeleteRange:
  87. r := &pb.DeleteRangeRequest{Key: op.key, RangeEnd: op.end, PrevKv: op.prevKV}
  88. return &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{RequestDeleteRange: r}}
  89. default:
  90. panic("Unknown Op")
  91. }
  92. }
  93. func (op Op) isWrite() bool {
  94. return op.t != tRange
  95. }
  96. func OpGet(key string, opts ...OpOption) Op {
  97. ret := Op{t: tRange, key: []byte(key)}
  98. ret.applyOpts(opts)
  99. return ret
  100. }
  101. func OpDelete(key string, opts ...OpOption) Op {
  102. ret := Op{t: tDeleteRange, key: []byte(key)}
  103. ret.applyOpts(opts)
  104. switch {
  105. case ret.leaseID != 0:
  106. panic("unexpected lease in delete")
  107. case ret.limit != 0:
  108. panic("unexpected limit in delete")
  109. case ret.rev != 0:
  110. panic("unexpected revision in delete")
  111. case ret.sort != nil:
  112. panic("unexpected sort in delete")
  113. case ret.serializable:
  114. panic("unexpected serializable in delete")
  115. case ret.countOnly:
  116. panic("unexpected countOnly in delete")
  117. case ret.minModRev != 0, ret.maxModRev != 0:
  118. panic("unexpected mod revision filter in delete")
  119. case ret.minCreateRev != 0, ret.maxCreateRev != 0:
  120. panic("unexpected create revision filter in delete")
  121. case ret.filterDelete, ret.filterPut:
  122. panic("unexpected filter in delete")
  123. case ret.createdNotify:
  124. panic("unexpected createdNotify in delete")
  125. }
  126. return ret
  127. }
  128. func OpPut(key, val string, opts ...OpOption) Op {
  129. ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
  130. ret.applyOpts(opts)
  131. switch {
  132. case ret.end != nil:
  133. panic("unexpected range in put")
  134. case ret.limit != 0:
  135. panic("unexpected limit in put")
  136. case ret.rev != 0:
  137. panic("unexpected revision in put")
  138. case ret.sort != nil:
  139. panic("unexpected sort in put")
  140. case ret.serializable:
  141. panic("unexpected serializable in put")
  142. case ret.countOnly:
  143. panic("unexpected countOnly in put")
  144. case ret.minModRev != 0, ret.maxModRev != 0:
  145. panic("unexpected mod revision filter in put")
  146. case ret.minCreateRev != 0, ret.maxCreateRev != 0:
  147. panic("unexpected create revision filter in put")
  148. case ret.filterDelete, ret.filterPut:
  149. panic("unexpected filter in put")
  150. case ret.createdNotify:
  151. panic("unexpected createdNotify in put")
  152. }
  153. return ret
  154. }
  155. func opWatch(key string, opts ...OpOption) Op {
  156. ret := Op{t: tRange, key: []byte(key)}
  157. ret.applyOpts(opts)
  158. switch {
  159. case ret.leaseID != 0:
  160. panic("unexpected lease in watch")
  161. case ret.limit != 0:
  162. panic("unexpected limit in watch")
  163. case ret.sort != nil:
  164. panic("unexpected sort in watch")
  165. case ret.serializable:
  166. panic("unexpected serializable in watch")
  167. case ret.countOnly:
  168. panic("unexpected countOnly in watch")
  169. case ret.minModRev != 0, ret.maxModRev != 0:
  170. panic("unexpected mod revision filter in watch")
  171. case ret.minCreateRev != 0, ret.maxCreateRev != 0:
  172. panic("unexpected create revision filter in watch")
  173. }
  174. return ret
  175. }
  176. func (op *Op) applyOpts(opts []OpOption) {
  177. for _, opt := range opts {
  178. opt(op)
  179. }
  180. }
  181. // OpOption configures Operations like Get, Put, Delete.
  182. type OpOption func(*Op)
  183. // WithLease attaches a lease ID to a key in 'Put' request.
  184. func WithLease(leaseID LeaseID) OpOption {
  185. return func(op *Op) { op.leaseID = leaseID }
  186. }
  187. // WithLimit limits the number of results to return from 'Get' request.
  188. func WithLimit(n int64) OpOption { return func(op *Op) { op.limit = n } }
  189. // WithRev specifies the store revision for 'Get' request.
  190. // Or the start revision of 'Watch' request.
  191. func WithRev(rev int64) OpOption { return func(op *Op) { op.rev = rev } }
  192. // WithSort specifies the ordering in 'Get' request. It requires
  193. // 'WithRange' and/or 'WithPrefix' to be specified too.
  194. // 'target' specifies the target to sort by: key, version, revisions, value.
  195. // 'order' can be either 'SortNone', 'SortAscend', 'SortDescend'.
  196. func WithSort(target SortTarget, order SortOrder) OpOption {
  197. return func(op *Op) {
  198. if target == SortByKey && order == SortAscend {
  199. // If order != SortNone, server fetches the entire key-space,
  200. // and then applies the sort and limit, if provided.
  201. // Since current mvcc.Range implementation returns results
  202. // sorted by keys in lexicographically ascending order,
  203. // client should ignore SortOrder if the target is SortByKey.
  204. order = SortNone
  205. }
  206. op.sort = &SortOption{target, order}
  207. }
  208. }
  209. // GetPrefixRangeEnd gets the range end of the prefix.
  210. // 'Get(foo, WithPrefix())' is equal to 'Get(foo, WithRange(GetPrefixRangeEnd(foo))'.
  211. func GetPrefixRangeEnd(prefix string) string {
  212. return string(getPrefix([]byte(prefix)))
  213. }
  214. func getPrefix(key []byte) []byte {
  215. end := make([]byte, len(key))
  216. copy(end, key)
  217. for i := len(end) - 1; i >= 0; i-- {
  218. if end[i] < 0xff {
  219. end[i] = end[i] + 1
  220. end = end[:i+1]
  221. return end
  222. }
  223. }
  224. // next prefix does not exist (e.g., 0xffff);
  225. // default to WithFromKey policy
  226. return noPrefixEnd
  227. }
  228. // WithPrefix enables 'Get', 'Delete', or 'Watch' requests to operate
  229. // on the keys with matching prefix. For example, 'Get(foo, WithPrefix())'
  230. // can return 'foo1', 'foo2', and so on.
  231. func WithPrefix() OpOption {
  232. return func(op *Op) {
  233. op.end = getPrefix(op.key)
  234. }
  235. }
  236. // WithRange specifies the range of 'Get', 'Delete', 'Watch' requests.
  237. // For example, 'Get' requests with 'WithRange(end)' returns
  238. // the keys in the range [key, end).
  239. // endKey must be lexicographically greater than start key.
  240. func WithRange(endKey string) OpOption {
  241. return func(op *Op) { op.end = []byte(endKey) }
  242. }
  243. // WithFromKey specifies the range of 'Get', 'Delete', 'Watch' requests
  244. // to be equal or greater than the key in the argument.
  245. func WithFromKey() OpOption { return WithRange("\x00") }
  246. // WithSerializable makes 'Get' request serializable. By default,
  247. // it's linearizable. Serializable requests are better for lower latency
  248. // requirement.
  249. func WithSerializable() OpOption {
  250. return func(op *Op) { op.serializable = true }
  251. }
  252. // WithKeysOnly makes the 'Get' request return only the keys and the corresponding
  253. // values will be omitted.
  254. func WithKeysOnly() OpOption {
  255. return func(op *Op) { op.keysOnly = true }
  256. }
  257. // WithCountOnly makes the 'Get' request return only the count of keys.
  258. func WithCountOnly() OpOption {
  259. return func(op *Op) { op.countOnly = true }
  260. }
  261. // WithMinModRev filters out keys for Get with modification revisions less than the given revision.
  262. func WithMinModRev(rev int64) OpOption { return func(op *Op) { op.minModRev = rev } }
  263. // WithMaxModRev filters out keys for Get with modification revisions greater than the given revision.
  264. func WithMaxModRev(rev int64) OpOption { return func(op *Op) { op.maxModRev = rev } }
  265. // WithMinCreateRev filters out keys for Get with creation revisions less than the given revision.
  266. func WithMinCreateRev(rev int64) OpOption { return func(op *Op) { op.minCreateRev = rev } }
  267. // WithMaxCreateRev filters out keys for Get with creation revisions greater than the given revision.
  268. func WithMaxCreateRev(rev int64) OpOption { return func(op *Op) { op.maxCreateRev = rev } }
  269. // WithFirstCreate gets the key with the oldest creation revision in the request range.
  270. func WithFirstCreate() []OpOption { return withTop(SortByCreateRevision, SortAscend) }
  271. // WithLastCreate gets the key with the latest creation revision in the request range.
  272. func WithLastCreate() []OpOption { return withTop(SortByCreateRevision, SortDescend) }
  273. // WithFirstKey gets the lexically first key in the request range.
  274. func WithFirstKey() []OpOption { return withTop(SortByKey, SortAscend) }
  275. // WithLastKey gets the lexically last key in the request range.
  276. func WithLastKey() []OpOption { return withTop(SortByKey, SortDescend) }
  277. // WithFirstRev gets the key with the oldest modification revision in the request range.
  278. func WithFirstRev() []OpOption { return withTop(SortByModRevision, SortAscend) }
  279. // WithLastRev gets the key with the latest modification revision in the request range.
  280. func WithLastRev() []OpOption { return withTop(SortByModRevision, SortDescend) }
  281. // withTop gets the first key over the get's prefix given a sort order
  282. func withTop(target SortTarget, order SortOrder) []OpOption {
  283. return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
  284. }
  285. // WithProgressNotify makes watch server send periodic progress updates
  286. // every 10 minutes when there is no incoming events.
  287. // Progress updates have zero events in WatchResponse.
  288. func WithProgressNotify() OpOption {
  289. return func(op *Op) {
  290. op.progressNotify = true
  291. }
  292. }
  293. // WithCreatedNotify makes watch server sends the created event.
  294. func WithCreatedNotify() OpOption {
  295. return func(op *Op) {
  296. op.createdNotify = true
  297. }
  298. }
  299. // WithFilterPut discards PUT events from the watcher.
  300. func WithFilterPut() OpOption {
  301. return func(op *Op) { op.filterPut = true }
  302. }
  303. // WithFilterDelete discards DELETE events from the watcher.
  304. func WithFilterDelete() OpOption {
  305. return func(op *Op) { op.filterDelete = true }
  306. }
  307. // WithPrevKV gets the previous key-value pair before the event happens. If the previous KV is already compacted,
  308. // nothing will be returned.
  309. func WithPrevKV() OpOption {
  310. return func(op *Op) {
  311. op.prevKV = true
  312. }
  313. }
  314. // LeaseOp represents an Operation that lease can execute.
  315. type LeaseOp struct {
  316. id LeaseID
  317. // for TimeToLive
  318. attachedKeys bool
  319. }
  320. // LeaseOption configures lease operations.
  321. type LeaseOption func(*LeaseOp)
  322. func (op *LeaseOp) applyOpts(opts []LeaseOption) {
  323. for _, opt := range opts {
  324. opt(op)
  325. }
  326. }
  327. // WithAttachedKeys requests lease timetolive API to return
  328. // attached keys of given lease ID.
  329. func WithAttachedKeys() LeaseOption {
  330. return func(op *LeaseOp) { op.attachedKeys = true }
  331. }
  332. func toLeaseTimeToLiveRequest(id LeaseID, opts ...LeaseOption) *pb.LeaseTimeToLiveRequest {
  333. ret := &LeaseOp{id: id}
  334. ret.applyOpts(opts)
  335. return &pb.LeaseTimeToLiveRequest{ID: int64(id), Keys: ret.attachedKeys}
  336. }