github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/go-themis/oracle/oracles/remote.go (about)

     1  package oracles
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/insionng/yougam/libraries/juju/errors"
     7  	"github.com/insionng/yougam/libraries/ngaut/tso/client"
     8  	"github.com/insionng/yougam/libraries/pingcap/go-themis/oracle"
     9  )
    10  
    11  const maxRetryCnt = 3
    12  
    13  var _ oracle.Oracle = &remoteOracle{}
    14  
    15  // remoteOracle is an oracle that use a remote data source.
    16  type remoteOracle struct {
    17  	c *client.Client
    18  }
    19  
    20  // NewRemoteOracle creates an oracle that use a remote data source.
    21  // Refer https://yougam/libraries/ngaut/tso for more details.
    22  func NewRemoteOracle(zks, path string) oracle.Oracle {
    23  	return &remoteOracle{
    24  		c: client.NewClient(&client.Conf{
    25  			ZKAddr:   zks,
    26  			RootPath: path,
    27  		}),
    28  	}
    29  }
    30  
    31  func (t *remoteOracle) IsExpired(lockTs uint64, TTL uint64) bool {
    32  	beginMs := lockTs >> epochShiftBits
    33  	// TODO records the local wall time when getting beginMs from TSO
    34  	return uint64(time.Now().UnixNano()/int64(time.Millisecond)) >= (beginMs + TTL)
    35  }
    36  
    37  // GetTimestamp gets timestamp from remote data source.
    38  func (t *remoteOracle) GetTimestamp() (uint64, error) {
    39  	var err error
    40  	for i := 0; i < maxRetryCnt; i++ {
    41  		ts, e := t.c.GoGetTimestamp().GetTS()
    42  		if e == nil {
    43  			return uint64((ts.Physical << epochShiftBits) + ts.Logical), nil
    44  		}
    45  		err = errors.Trace(e)
    46  	}
    47  	return 0, err
    48  }