go.etcd.io/etcd@v3.3.27+incompatible/contrib/recipes/watch.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  
    20  	"github.com/coreos/etcd/clientv3"
    21  	"github.com/coreos/etcd/mvcc/mvccpb"
    22  )
    23  
    24  // WaitEvents waits on a key until it observes the given events and returns the final one.
    25  func WaitEvents(c *clientv3.Client, key string, rev int64, evs []mvccpb.Event_EventType) (*clientv3.Event, error) {
    26  	wc := c.Watch(context.Background(), key, clientv3.WithRev(rev))
    27  	if wc == nil {
    28  		return nil, ErrNoWatcher
    29  	}
    30  	return waitEvents(wc, evs), nil
    31  }
    32  
    33  func WaitPrefixEvents(c *clientv3.Client, prefix string, rev int64, evs []mvccpb.Event_EventType) (*clientv3.Event, error) {
    34  	wc := c.Watch(context.Background(), prefix, clientv3.WithPrefix(), clientv3.WithRev(rev))
    35  	if wc == nil {
    36  		return nil, ErrNoWatcher
    37  	}
    38  	return waitEvents(wc, evs), nil
    39  }
    40  
    41  func waitEvents(wc clientv3.WatchChan, evs []mvccpb.Event_EventType) *clientv3.Event {
    42  	i := 0
    43  	for wresp := range wc {
    44  		for _, ev := range wresp.Events {
    45  			if ev.Type == evs[i] {
    46  				i++
    47  				if i == len(evs) {
    48  					return ev
    49  				}
    50  			}
    51  		}
    52  	}
    53  	return nil
    54  }