github.com/m3db/m3@v1.5.0/src/cluster/mocks/blackhole_watcher.go (about)

     1  // Copyright (c) 2017 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package mocks
    22  
    23  import (
    24  	"sync"
    25  
    26  	clientv3 "go.etcd.io/etcd/client/v3"
    27  	"golang.org/x/net/context"
    28  )
    29  
    30  // watcher mocks an etcd client that just blackholes a few watch requests
    31  type watcher struct {
    32  	sync.Mutex
    33  
    34  	failed    int
    35  	failTotal int
    36  	c         *clientv3.Client
    37  	onFail    func()
    38  }
    39  
    40  // NewBlackholeWatcher returns a watcher that mimics blackholing
    41  func NewBlackholeWatcher(c *clientv3.Client, failTotal int, onFail func()) clientv3.Watcher {
    42  	return &watcher{
    43  		failed:    0,
    44  		failTotal: failTotal,
    45  		c:         c,
    46  		onFail:    onFail,
    47  	}
    48  }
    49  
    50  // Watch is implementing etcd clientv3 Watcher interface
    51  func (m *watcher) Watch(ctx context.Context, key string, opts ...clientv3.OpOption) clientv3.WatchChan {
    52  	m.Lock()
    53  
    54  	if m.failed < m.failTotal {
    55  		m.failed++
    56  		m.Unlock()
    57  
    58  		m.onFail()
    59  		return nil
    60  	}
    61  	m.Unlock()
    62  
    63  	return m.c.Watch(ctx, key, opts...)
    64  }
    65  
    66  // RequestProgress is implementing etcd clientv3 Watcher interface
    67  func (m *watcher) RequestProgress(ctx context.Context) error {
    68  	return nil
    69  }
    70  
    71  // Close is implementing etcd clientv3 Watcher interface
    72  func (m *watcher) Close() error {
    73  	return m.c.Close()
    74  }