2020-04-29 21:32:39 +00:00
|
|
|
// Package roughtime is a wrapper for a roughtime clock source.
|
2019-08-09 14:05:08 +00:00
|
|
|
package roughtime
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
rt "github.com/cloudflare/roughtime"
|
2019-08-19 16:13:05 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2019-08-09 14:05:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// offset is the difference between the system time and the time returned by
|
|
|
|
// the roughtime server
|
|
|
|
var offset time.Duration
|
|
|
|
|
2019-08-19 16:13:05 +00:00
|
|
|
var log = logrus.WithField("prefix", "roughtime")
|
|
|
|
|
2019-08-09 14:05:08 +00:00
|
|
|
func init() {
|
|
|
|
t0 := time.Now()
|
|
|
|
|
2019-09-30 20:30:45 +00:00
|
|
|
results := rt.Do(rt.Ecosystem, rt.DefaultQueryAttempts, rt.DefaultQueryTimeout, nil)
|
2019-08-09 14:05:08 +00:00
|
|
|
|
|
|
|
// Compute the average difference between the system's time and the
|
|
|
|
// Roughtime responses from the servers, rejecting responses whose radii
|
|
|
|
// are larger than 2 seconds.
|
|
|
|
var err error
|
|
|
|
offset, err = rt.AvgDeltaWithRadiusThresh(results, t0, 2*time.Second)
|
|
|
|
if err != nil {
|
2019-08-19 16:13:05 +00:00
|
|
|
log.WithError(err).Error("Failed to calculate roughtime offset")
|
2019-08-09 14:05:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Since returns the duration since t, based on the roughtime response
|
|
|
|
func Since(t time.Time) time.Duration {
|
2019-08-13 17:59:11 +00:00
|
|
|
return Now().Sub(t)
|
2019-08-09 14:05:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Until returns the duration until t, based on the roughtime response
|
|
|
|
func Until(t time.Time) time.Duration {
|
2019-08-13 17:59:11 +00:00
|
|
|
return t.Sub(Now())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now returns the current local time given the roughtime offset.
|
|
|
|
func Now() time.Time {
|
|
|
|
return time.Now().Add(offset)
|
2019-08-09 14:05:08 +00:00
|
|
|
}
|