op.go 15 KB

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