op.go 14 KB

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