github.com/kjdelisle/consul@v1.4.5/lib/rtt.go (about)

     1  package lib
     2  
     3  import (
     4  	"math"
     5  	"time"
     6  
     7  	"github.com/hashicorp/serf/coordinate"
     8  )
     9  
    10  // ComputeDistance returns the distance between the two network coordinates in
    11  // seconds. If either of the coordinates is nil then this will return positive
    12  // infinity.
    13  func ComputeDistance(a *coordinate.Coordinate, b *coordinate.Coordinate) float64 {
    14  	if a == nil || b == nil {
    15  		return math.Inf(1.0)
    16  	}
    17  
    18  	return a.DistanceTo(b).Seconds()
    19  }
    20  
    21  // CoordinateSet holds all the coordinates for a given node, indexed by network
    22  // segment name.
    23  type CoordinateSet map[string]*coordinate.Coordinate
    24  
    25  // Intersect tries to return a pair of coordinates which are compatible with the
    26  // current set and a given set. We employ some special knowledge about network
    27  // segments to avoid doing a full intersection, since this is in several hot
    28  // paths. This might return nil for either coordinate in the output pair if an
    29  // intersection cannot be found. The ComputeDistance function above is designed
    30  // to deal with that.
    31  func (cs CoordinateSet) Intersect(other CoordinateSet) (*coordinate.Coordinate, *coordinate.Coordinate) {
    32  	// Use the empty segment by default.
    33  	segment := ""
    34  
    35  	// If we have a single segment, then let our segment take priority since
    36  	// we are possibly a client. Any node with more than one segment can only
    37  	// be a server, which means it should be in all segments.
    38  	if len(cs) == 1 {
    39  		for s := range cs {
    40  			segment = s
    41  		}
    42  	}
    43  
    44  	// Likewise for the other set.
    45  	if len(other) == 1 {
    46  		for s := range other {
    47  			segment = s
    48  		}
    49  	}
    50  
    51  	return cs[segment], other[segment]
    52  }
    53  
    54  // GenerateCoordinate creates a new coordinate with the given distance from the
    55  // origin. This should only be used for tests.
    56  func GenerateCoordinate(rtt time.Duration) *coordinate.Coordinate {
    57  	coord := coordinate.NewCoordinate(coordinate.DefaultConfig())
    58  	coord.Vec[0] = rtt.Seconds()
    59  	coord.Height = 0
    60  	return coord
    61  }