Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NewTicker to the Clock Interface #948

Merged
merged 9 commits into from May 25, 2021
15 changes: 10 additions & 5 deletions clock.go
Expand Up @@ -20,13 +20,14 @@

package zap

import "time"
import (
"time"

"go.uber.org/zap/zapcore"
)

// Clock is a source of time for logged entries.
type Clock interface {
// Now returns the current local time.
Now() time.Time
}
type Clock = zapcore.Clock

// systemClock implements default Clock that uses system time.
type systemClock struct{}
Expand All @@ -36,3 +37,7 @@ var _systemClock Clock = systemClock{}
func (systemClock) Now() time.Time {
return time.Now()
}

moisesvega marked this conversation as resolved.
Show resolved Hide resolved
func (systemClock) NewTicker(duration time.Duration) *time.Ticker {
return time.NewTicker(duration)
}
3 changes: 3 additions & 0 deletions clock_test.go
Expand Up @@ -32,6 +32,9 @@ import (
type constantClock time.Time

func (c constantClock) Now() time.Time { return time.Time(c) }
func (c constantClock) NewTicker(d time.Duration) *time.Ticker {
return &time.Ticker{}
}

func TestWithClock(t *testing.T) {
date := time.Date(2077, 1, 23, 10, 15, 13, 441, time.UTC)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -3,6 +3,7 @@ module go.uber.org/zap
go 1.13

require (
github.com/benbjohnson/clock v1.1.0 // indirect
github.com/pkg/errors v0.8.1
github.com/stretchr/testify v1.7.0
go.uber.org/atomic v1.7.0
Expand Down
3 changes: 3 additions & 0 deletions go.sum
@@ -1,10 +1,13 @@
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
Expand Down
34 changes: 34 additions & 0 deletions zapcore/clock.go
@@ -0,0 +1,34 @@
// Copyright (c) 2021 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zapcore

import (
"time"
)

// Clock is a source of time for logged entries.
type Clock interface {
// Now returns the current local time.
Now() time.Time
// NewTicker returns *time.Ticker that holds a channel
// that delivers ``ticks'' of a clock.
moisesvega marked this conversation as resolved.
Show resolved Hide resolved
NewTicker(time.Duration) *time.Ticker
moisesvega marked this conversation as resolved.
Show resolved Hide resolved
}
61 changes: 61 additions & 0 deletions zapcore/clock_test.go
@@ -0,0 +1,61 @@
// Copyright (c) 2021 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zapcore

import (
"sync/atomic"
"testing"
"time"

"github.com/benbjohnson/clock"
"github.com/stretchr/testify/assert"
)

type controlledClock struct {
mockClock *clock.Mock
}

func (c *controlledClock) Now() time.Time {
return c.mockClock.Now()
}

func (c *controlledClock) NewTicker(d time.Duration) *time.Ticker {
return &time.Ticker{C: c.mockClock.Ticker(d).C}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works but we can shorten this by embedding clock.Mock and only overriding NewTicker:

type controlledClock struct{
  *clock.Mock
}

func newControlledClock() *controlledClock

func (*controlledClock) NewTicker(...) *time.Ticker

}

func TestMockClock(t *testing.T) {
var n int32
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of using sync/atomic, we should use go.uber.org/atomic here.

var n atomic.Int32

// ...

<-ticker.C
n.Inc()

// ...

assert.Equal(t, 42, n.Load())

See also https://github.com/uber-go/guide/blob/master/style.md#use-gouberorgatomic

ctrlMock := &controlledClock{mockClock: clock.NewMock()}

// Create a channel to increment every microsecond.
go func() {
ticker := ctrlMock.NewTicker(1 * time.Microsecond)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

code style: can be just time.Microsecond instead of 1 * time.Microsecond.

for {
<-ticker.C
atomic.AddInt32(&n, 1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a goroutine leak. If we use go.uber.org/goleak here (which we do in #782).
We need to create a second quit channel that this selects on.

for {
  select {
  case <-quit:
    ticker.Stop()
    return
    
  case <-ticker.C:
    // ...
  }
}

This might also have to use a second channel to indicate that the goroutine has finished to wait for it to exit.

done := make(chan struct{})
go func() {
    defer close(done)
    // ...
}()
defer func() { <-done }() // wait for end

}
}()
time.Sleep(1 * time.Microsecond)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be necessary. My guess is that it's to wait for the ticker to start up.
We can probably get rid of this by starting the ticker right above the go func(), or as an argument to go func.

go func(ticker *time.Ticker) {
  // ...
}(ctrlMock.NewTicker(..))


// Move clock forward.
ctrlMock.mockClock.Add(10 * time.Microsecond)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we embed clock.MockClock inside ctrlMock as suggested above, this .mockClock can be dropped.

assert.Equal(t, atomic.LoadInt32(&n), int32(10))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For assert.Equal, the arguments are (expected, got), not (got, expected).

}