op.go 16 KB

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