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 2 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
39 changes: 21 additions & 18 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
stopOnce sync.Once
done chan struct{} // closed when flushLoop has stopped
}

Expand Down Expand Up @@ -155,22 +156,24 @@ 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 {
// Critical section.
func() {
s.mu.Lock()
defer s.mu.Unlock()

if !s.initialized {
return
}

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

return s.Sync()
func (s *BufferedWriteSyncer) Stop() (err error) {
s.stopOnce.Do(func() {
// Critical section.
func() {
s.mu.Lock()
defer s.mu.Unlock()

if !s.initialized {
return
}

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

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