Skip to content

Commit

Permalink
Replace clock mocking library (#5017)
Browse files Browse the repository at this point in the history
## Motivation
`github.com/benbjohnson/clock` has been archived a while ago. This PR replaces the outdated dependency with `github.com/jonboulle/clockwork`.

## Changes
- Replace uses of `github.com/benbjohnson/clock` with `github.com/jonboulle/clockwork`

## Test Plan
existing tests pass

## TODO
<!-- This section should be removed when all items are complete -->
- [x] Explain motivation or link existing issue(s)
- [x] Test changes and document test plan
- [x] Update documentation as needed
- [x] Update [changelog](../CHANGELOG.md) as needed
  • Loading branch information
fasmat committed Sep 15, 2023
1 parent 055f185 commit 306c43a
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 38 deletions.
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ go 1.21
require (
cloud.google.com/go/storage v1.33.0
github.com/ALTree/bigfloat v0.2.0
github.com/benbjohnson/clock v1.3.5
github.com/chaos-mesh/chaos-mesh/api v0.0.0-20230912033821-30d9600a7db0
github.com/cosmos/btcutil v1.0.5
github.com/go-llsqlite/crawshaw v0.0.0-20230910110433-7e901377eb6c
Expand All @@ -21,6 +20,7 @@ require (
github.com/hashicorp/golang-lru/v2 v2.0.6
github.com/ipfs/go-ds-leveldb v0.5.0
github.com/ipfs/go-log/v2 v2.5.1
github.com/jonboulle/clockwork v0.2.2
github.com/libp2p/go-libp2p v0.31.0
github.com/libp2p/go-libp2p-kad-dht v0.25.1
github.com/libp2p/go-libp2p-pubsub v0.9.3
Expand Down Expand Up @@ -68,6 +68,7 @@ require (
cloud.google.com/go/compute/metadata v0.2.3 // indirect
cloud.google.com/go/iam v1.1.1 // indirect
github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 // indirect
github.com/benbjohnson/clock v1.3.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/c0mm4nd/go-ripemd v0.0.0-20200326052756-bd1759ad7d10 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,8 @@ github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ=
github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
Expand Down
12 changes: 6 additions & 6 deletions hare3/hare.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"sync"
"time"

"github.com/benbjohnson/clock"
"github.com/jonboulle/clockwork"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
Expand Down Expand Up @@ -100,7 +100,7 @@ type WeakCoinOutput struct {

type Opt func(*Hare)

func WithWallclock(clock clock.Clock) Opt {
func WithWallclock(clock clockwork.Clock) Opt {
return func(hr *Hare) {
hr.wallclock = clock
}
Expand Down Expand Up @@ -153,7 +153,7 @@ func New(

config: DefaultConfig(),
log: zap.NewNop(),
wallclock: clock.New(),
wallclock: clockwork.NewRealClock(),

nodeclock: nodeclock,
pubsub: pubsub,
Expand Down Expand Up @@ -188,7 +188,7 @@ type Hare struct {
// options
config Config
log *zap.Logger
wallclock clock.Clock
wallclock clockwork.Clock

// dependencies
nodeclock nodeclock
Expand Down Expand Up @@ -370,7 +370,7 @@ func (h *Hare) run(layer types.LayerID, beacon types.Beacon, proto *protocol) er
h.log.Debug("active in preround", zap.Uint32("lid", layer.Uint32()))
// initial set is not needed if node is not active in preround
select {
case <-h.wallclock.After(h.wallclock.Until(walltime)):
case <-h.wallclock.After(walltime.Sub(h.wallclock.Now())):
case <-h.ctx.Done():
return h.ctx.Err()
}
Expand All @@ -385,7 +385,7 @@ func (h *Hare) run(layer types.LayerID, beacon types.Beacon, proto *protocol) er
result := false
for {
select {
case <-h.wallclock.After(h.wallclock.Until(walltime)):
case <-h.wallclock.After(walltime.Sub(h.wallclock.Now())):
h.log.Debug("execute round",
zap.Uint32("lid", layer.Uint32()),
zap.Uint8("iter", proto.Iter), zap.Stringer("round", proto.Round),
Expand Down
15 changes: 7 additions & 8 deletions hare3/hare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"testing"
"time"

"github.com/benbjohnson/clock"
"github.com/jonboulle/clockwork"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -109,7 +109,7 @@ type node struct {
t *tester

i int
clock *clock.Mock
clock clockwork.FakeClock
nclock *testNodeClock
signer *signing.EdSigner
vrfsigner *signing.VRFSigner
Expand All @@ -126,8 +126,7 @@ type node struct {
}

func (n *node) withClock() *node {
n.clock = clock.NewMock()
n.clock.Set(n.t.start)
n.clock = clockwork.NewFakeClockAt(n.t.start)
return n
}

Expand Down Expand Up @@ -410,7 +409,7 @@ func (cl *lockstepCluster) movePreround(layer types.LayerID) {
Add(cl.t.cfg.PreroundDelay)
for _, n := range cl.nodes {
n.nclock.StartLayer(layer)
n.clock.Set(cl.timestamp)
n.clock.Advance(cl.timestamp.Sub(n.clock.Now()))
}
send := 0
for _, n := range cl.nodes {
Expand All @@ -430,7 +429,7 @@ func (cl *lockstepCluster) moveRound() {
cl.timestamp = cl.timestamp.Add(cl.t.cfg.RoundDuration)
send := 0
for _, n := range cl.nodes {
n.clock.Set(cl.timestamp)
n.clock.Advance(cl.timestamp.Sub(n.clock.Now()))
}
for _, n := range cl.nodes {
if n.tracer.waitEligibility() != nil {
Expand Down Expand Up @@ -627,9 +626,9 @@ func TestHandler(t *testing.T) {
n.mpublisher.EXPECT().Publish(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
layer := tst.genesis + 1
n.nclock.StartLayer(layer)
n.clock.Set(tst.start.
n.clock.Advance((tst.start.
Add(tst.layerDuration * time.Duration(layer)).
Add(tst.cfg.PreroundDelay))
Add(tst.cfg.PreroundDelay)).Sub(n.clock.Now()))
elig := n.tracer.waitEligibility()
t.Run("malformed", func(t *testing.T) {
require.ErrorIs(t, n.hare.Handler(context.Background(), "", []byte("malformed")),
Expand Down
10 changes: 5 additions & 5 deletions timesync/clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"sync"
"time"

"github.com/benbjohnson/clock"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/errgroup"

Expand All @@ -25,7 +25,7 @@ var tickDistance = metrics.NewHistogramWithBuckets(
type NodeClock struct {
LayerConverter // layer conversions provider

clock clock.Clock // provides the time
clock clockwork.Clock // provides the time
genesis time.Time
tickInterval time.Duration

Expand All @@ -44,7 +44,7 @@ type NodeClock struct {
// NewClock return TimeClock struct that notifies tickInterval has passed.
func NewClock(opts ...OptionFunc) (*NodeClock, error) {
cfg := &option{
clock: clock.New(),
clock: clockwork.NewRealClock(),
}
for _, opt := range opts {
opt(cfg)
Expand Down Expand Up @@ -81,15 +81,15 @@ func (t *NodeClock) startClock() error {
log.Duration("tick_interval", t.tickInterval),
)

ticker := t.clock.Ticker(t.tickInterval)
ticker := t.clock.NewTicker(t.tickInterval)
for {
currLayer := t.TimeToLayer(t.clock.Now())
t.log.With().Debug("global clock going to sleep before next tick",
log.Stringer("curr_layer", currLayer),
)

select {
case <-ticker.C:
case <-ticker.Chan():
case <-t.stop:
t.log.Info("stopping global clock")
ticker.Stop()
Expand Down
6 changes: 3 additions & 3 deletions timesync/clock_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import (
"fmt"
"time"

"github.com/benbjohnson/clock"
"github.com/jonboulle/clockwork"

"github.com/spacemeshos/go-spacemesh/log"
)

type option struct {
clock clock.Clock
clock clockwork.Clock
genesisTime time.Time
layerDuration time.Duration
tickInterval time.Duration
Expand Down Expand Up @@ -44,7 +44,7 @@ func (o *option) validate() error {
type OptionFunc func(*option) error

// withClock specifies which clock the NodeClock should use. Defaults to the real clock.
func withClock(clock clock.Clock) OptionFunc {
func withClock(clock clockwork.Clock) OptionFunc {
return func(opts *option) error {
opts.clock = clock
return nil
Expand Down
27 changes: 12 additions & 15 deletions timesync/clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"testing"
"time"

"github.com/benbjohnson/clock"
"github.com/jonboulle/clockwork"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
Expand Down Expand Up @@ -189,8 +189,7 @@ func Test_NodeClock_Await_WithClockMovingBackwards(t *testing.T) {
layerDuration := 100 * time.Millisecond
tickInterval := 10 * time.Millisecond

mClock := clock.NewMock()
mClock.Set(now)
mClock := clockwork.NewFakeClockAt(now)

clock, err := NewClock(
withClock(mClock),
Expand All @@ -213,7 +212,7 @@ func Test_NodeClock_Await_WithClockMovingBackwards(t *testing.T) {
}

// move the clock backwards by a layer
mClock.Set(now.Add(-2 * layerDuration))
mClock.Advance(-2 * layerDuration)
ch := clock.AwaitLayer(types.LayerID(9))

select {
Expand All @@ -223,7 +222,8 @@ func Test_NodeClock_Await_WithClockMovingBackwards(t *testing.T) {
}

// continue clock forward in time
mClock.Add(3 * layerDuration)
mClock.Advance(3 * layerDuration)
clock.tick()

select {
case <-ch:
Expand All @@ -238,8 +238,7 @@ func Test_NodeClock_NonMonotonicTick_Forward(t *testing.T) {
layerDuration := 100 * time.Millisecond
tickInterval := 10 * time.Millisecond

mClock := clock.NewMock()
mClock.Set(genesis.Add(5 * layerDuration))
mClock := clockwork.NewFakeClockAt(genesis.Add(5 * layerDuration))

clock, err := NewClock(
withClock(mClock),
Expand All @@ -261,7 +260,7 @@ func Test_NodeClock_NonMonotonicTick_Forward(t *testing.T) {
}

// hibernate for 5 layers (clock jumps forward)
mClock.Add(5 * layerDuration)
mClock.Advance(5 * layerDuration)

select {
case <-ch:
Expand All @@ -277,8 +276,7 @@ func Test_NodeClock_NonMonotonicTick_Backward(t *testing.T) {
layerDuration := 10 * time.Millisecond
tickInterval := 1 * time.Millisecond

mClock := clock.NewMock()
mClock.Set(genesis.Add(5 * layerDuration))
mClock := clockwork.NewFakeClockAt(genesis.Add(5 * layerDuration))

clock, err := NewClock(
withClock(mClock),
Expand All @@ -304,7 +302,7 @@ func Test_NodeClock_NonMonotonicTick_Backward(t *testing.T) {
}

// simulate time passing
mClock.Add(1 * layerDuration)
mClock.Advance(1 * layerDuration)

select {
case <-ch6:
Expand All @@ -321,7 +319,7 @@ func Test_NodeClock_NonMonotonicTick_Backward(t *testing.T) {
}

// NTP corrects time backwards
mClock.Add(-1 * layerDuration)
mClock.Advance(-1 * layerDuration)
ch6 = clock.AwaitLayer(types.LayerID(6))

select {
Expand All @@ -335,7 +333,7 @@ func Test_NodeClock_NonMonotonicTick_Backward(t *testing.T) {
}

// simulate time passing
mClock.Add(2 * layerDuration)
mClock.Advance(2 * layerDuration)

select {
case <-ch6:
Expand Down Expand Up @@ -374,8 +372,7 @@ func Fuzz_NodeClock_CurrentLayer(f *testing.F) {
layerTime := time.Duration(layerSecs) * time.Second
tickInterval := layerTime / 10

mClock := clock.NewMock()
mClock.Set(nowTime)
mClock := clockwork.NewFakeClockAt(nowTime)

clock, err := NewClock(
withClock(mClock),
Expand Down

0 comments on commit 306c43a

Please sign in to comment.