go.etcd.io/etcd@v3.3.27+incompatible/contrib/recipes/client.go (about) 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 15 package recipe 16 17 import ( 18 "context" 19 "errors" 20 21 v3 "github.com/coreos/etcd/clientv3" 22 spb "github.com/coreos/etcd/mvcc/mvccpb" 23 ) 24 25 var ( 26 ErrKeyExists = errors.New("key already exists") 27 ErrWaitMismatch = errors.New("unexpected wait result") 28 ErrTooManyClients = errors.New("too many clients") 29 ErrNoWatcher = errors.New("no watcher channel") 30 ) 31 32 // deleteRevKey deletes a key by revision, returning false if key is missing 33 func deleteRevKey(kv v3.KV, key string, rev int64) (bool, error) { 34 cmp := v3.Compare(v3.ModRevision(key), "=", rev) 35 req := v3.OpDelete(key) 36 txnresp, err := kv.Txn(context.TODO()).If(cmp).Then(req).Commit() 37 if err != nil { 38 return false, err 39 } else if !txnresp.Succeeded { 40 return false, nil 41 } 42 return true, nil 43 } 44 45 func claimFirstKey(kv v3.KV, kvs []*spb.KeyValue) (*spb.KeyValue, error) { 46 for _, k := range kvs { 47 ok, err := deleteRevKey(kv, string(k.Key), k.ModRevision) 48 if err != nil { 49 return nil, err 50 } else if ok { 51 return k, nil 52 } 53 } 54 return nil, nil 55 }