op.go 16 KB

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