op.go 13 KB

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