Skip to content

Commit

Permalink
zapcore: add stopped for Stop method called exactly once (#966)
Browse files Browse the repository at this point in the history
  • Loading branch information
zchee authored Jun 24, 2021
1 parent 0c42722 commit fb71758
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
20 changes: 16 additions & 4 deletions zapcore/buffered_write_syncer.go
Original file line number Diff line number Diff line change
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 {
err = s.Sync()
}

return err
}
8 changes: 8 additions & 0 deletions zapcore/buffered_write_syncer_test.go
Original file line number Diff line number Diff line change
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

0 comments on commit fb71758

Please sign in to comment.