...

Source file src/go.etcd.io/etcd/client/v3/experimental/recipes/watch.go

Documentation: go.etcd.io/etcd/client/v3/experimental/recipes

     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  	"go.etcd.io/etcd/api/v3/mvccpb"
    21  	"go.etcd.io/etcd/client/v3"
    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  	ctx, cancel := context.WithCancel(context.Background())
    27  	defer cancel()
    28  	wc := c.Watch(ctx, key, clientv3.WithRev(rev))
    29  	if wc == nil {
    30  		return nil, ErrNoWatcher
    31  	}
    32  	return waitEvents(wc, evs), nil
    33  }
    34  
    35  func WaitPrefixEvents(c *clientv3.Client, prefix string, rev int64, evs []mvccpb.Event_EventType) (*clientv3.Event, error) {
    36  	ctx, cancel := context.WithCancel(context.Background())
    37  	defer cancel()
    38  	wc := c.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithRev(rev))
    39  	if wc == nil {
    40  		return nil, ErrNoWatcher
    41  	}
    42  	return waitEvents(wc, evs), nil
    43  }
    44  
    45  func waitEvents(wc clientv3.WatchChan, evs []mvccpb.Event_EventType) *clientv3.Event {
    46  	i := 0
    47  	for wresp := range wc {
    48  		for _, ev := range wresp.Events {
    49  			if ev.Type == evs[i] {
    50  				i++
    51  				if i == len(evs) {
    52  					return ev
    53  				}
    54  			}
    55  		}
    56  	}
    57  	return nil
    58  }
    59  

View as plain text