github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/closedts/provider/testutils/clock.go (about)

     1  // Copyright 2018 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package testutils
    12  
    13  import (
    14  	"github.com/cockroachdb/cockroach/pkg/kv/kvserver/closedts/ctpb"
    15  	"github.com/cockroachdb/cockroach/pkg/roachpb"
    16  	"github.com/cockroachdb/cockroach/pkg/util/hlc"
    17  	"github.com/cockroachdb/cockroach/pkg/util/stop"
    18  	"github.com/cockroachdb/errors"
    19  )
    20  
    21  // A TestClock provides a blocking LiveClockFn that can be triggered
    22  // at will.
    23  type TestClock struct {
    24  	stopper *stop.Stopper
    25  	ch      chan tick
    26  }
    27  
    28  // NewTestClock sets up a test clock that returns errors once the
    29  // Stopper starts quiescing.
    30  func NewTestClock(stopper *stop.Stopper) *TestClock {
    31  	t := &TestClock{
    32  		stopper: stopper,
    33  		ch:      make(chan tick),
    34  	}
    35  	return t
    36  }
    37  
    38  type tick struct {
    39  	liveNow   hlc.Timestamp
    40  	liveEpoch ctpb.Epoch
    41  	err       error
    42  }
    43  
    44  // Tick is called by tests to manually emit a single clock tick. The tick
    45  // will only returned to a single caller of LiveNow().
    46  func (c *TestClock) Tick(liveNow hlc.Timestamp, liveEpoch ctpb.Epoch, err error) {
    47  	c.ch <- tick{liveNow, liveEpoch, err}
    48  }
    49  
    50  // LiveNow implements closedts.LiveClockFn.
    51  func (c *TestClock) LiveNow(roachpb.NodeID) (liveNow hlc.Timestamp, liveEpoch ctpb.Epoch, _ error) {
    52  	select {
    53  	case r := <-c.ch:
    54  		return r.liveNow, r.liveEpoch, r.err
    55  	case <-c.stopper.ShouldQuiesce():
    56  		return hlc.Timestamp{}, 0, errors.New("quiescing")
    57  	}
    58  }