github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/state/lease/skew.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package lease
     5  
     6  import (
     7  	"time"
     8  )
     9  
    10  // Skew holds information about a remote writer's idea of the current time.
    11  type Skew struct {
    12  
    13  	// LastWrite is the most recent remote time known to have been written
    14  	// by the skewed writer.
    15  	LastWrite time.Time
    16  
    17  	// Beginning should be the latest known local time before LastWrite
    18  	// was read.
    19  	Beginning time.Time
    20  
    21  	// End should be the earliest known local time after LastWrite
    22  	// was read.
    23  	End time.Time
    24  }
    25  
    26  // Earliest returns the earliest local time after which we can be confident
    27  // that the remote writer will agree the supplied time is in the past.
    28  func (skew Skew) Earliest(remote time.Time) (local time.Time) {
    29  	if skew.isZero() {
    30  		return remote
    31  	}
    32  	delta := remote.Sub(skew.LastWrite)
    33  	return skew.Beginning.Add(delta)
    34  }
    35  
    36  // Latest returns the latest local time after which we can be confident that
    37  // the remote writer will agree the supplied time is in the past.
    38  func (skew Skew) Latest(remote time.Time) (local time.Time) {
    39  	if skew.isZero() {
    40  		return remote
    41  	}
    42  	delta := remote.Sub(skew.LastWrite)
    43  	return skew.End.Add(delta)
    44  }
    45  
    46  // isZero lets us shortcut Earliest and Latest when the skew represents a
    47  // perfect unskewed clock (such as for a local writer).
    48  func (skew Skew) isZero() bool {
    49  	return skew.LastWrite.IsZero() && skew.Beginning.IsZero() && skew.End.IsZero()
    50  }