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

zapcore: add stopped for Stop method called exactly once #966

Merged
merged 4 commits into from Jun 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 16 additions & 4 deletions zapcore/buffered_write_syncer.go
Expand Up @@ -74,6 +74,7 @@ type BufferedWriteSyncer struct {
writer *bufio.Writer
ticker *time.Ticker
stop chan struct{} // closed when flushLoop should stop
stopped bool // whether Stop() has run
done chan struct{} // closed when flushLoop has stopped
}

Expand Down Expand Up @@ -155,9 +156,9 @@ func (s *BufferedWriteSyncer) flushLoop() {

// Stop closes the buffer, cleans up background goroutines, and flushes
// remaining unwritten data.
//
// This must be called exactly once.
func (s *BufferedWriteSyncer) Stop() error {
func (s *BufferedWriteSyncer) Stop() (err error) {
var stopped bool

// Critical section.
func() {
s.mu.Lock()
Expand All @@ -167,10 +168,21 @@ func (s *BufferedWriteSyncer) Stop() error {
return
}

stopped = s.stopped
if stopped {
return
}
s.stopped = true

s.ticker.Stop()
close(s.stop) // tell flushLoop to stop
<-s.done // and wait until it has
}()

return s.Sync()
// Don't call Sync on consecutive Stops.
if !stopped {
prashantv marked this conversation as resolved.
Show resolved Hide resolved
err = s.Sync()
}

return err
}
8 changes: 8 additions & 0 deletions zapcore/buffered_write_syncer_test.go
Expand Up @@ -53,6 +53,14 @@ func TestBufferWriter(t *testing.T) {
assert.Equal(t, "foo", buf.String(), "Unexpected log string")
})

t.Run("stop twice", func(t *testing.T) {
ws := &BufferedWriteSyncer{WS: &ztest.FailWriter{}}
_, err := ws.Write([]byte("foo"))
require.NoError(t, err, "Unexpected error writing to WriteSyncer.")
assert.Error(t, ws.Stop(), "Expected stop to fail.")
assert.NoError(t, ws.Stop(), "Expected stop to not fail.")
})

t.Run("wrap twice", func(t *testing.T) {
buf := &bytes.Buffer{}
bufsync := &BufferedWriteSyncer{WS: AddSync(buf)}
Expand Down