Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ func LockWithTimeoutAction(ws zapcore.WriteSyncer, timeout int, action string) z
r := &lockWithTimeoutWrapper{
ws: ws,
lock: make(chan struct{}, 1),
t: time.NewTicker(time.Second),
timeout: timeout,
timeoutAction: normalizeTimeoutAction(action),
}
Expand All @@ -146,7 +145,6 @@ func LockWithTimeoutAction(ws zapcore.WriteSyncer, timeout int, action string) z
type lockWithTimeoutWrapper struct {
ws zapcore.WriteSyncer
lock chan struct{}
t *time.Ticker
timeout int
timeoutAction string
timedOut atomic.Bool
Expand All @@ -173,16 +171,25 @@ func (s *lockWithTimeoutWrapper) getLockOrBlock() bool {
}
}

for i := 0; i < s.timeout; {
select {
case s.lock <- struct{}{}:
s.timedOut.Store(false)
return true
case <-s.t.C:
i++
}
select {
case s.lock <- struct{}{}:
s.timedOut.Store(false)
return true
default:
}

// Each caller waits on its own timer. A ticker shared by all waiters would
// deliver each tick to only one of them, stretching the wait to roughly
// timeout * waiters.
timer := time.NewTimer(time.Duration(s.timeout) * time.Second)
defer timer.Stop()
select {
case s.lock <- struct{}{}:
s.timedOut.Store(false)
return true
case <-timer.C:
return false
}
return false
}

func (s *lockWithTimeoutWrapper) unlock() {
Expand Down
30 changes: 30 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"bufio"
"bytes"
"net/url"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -178,6 +179,35 @@ func TestTimeoutActionDiscard(t *testing.T) {
require.Contains(t, blocking.String(), "written")
}

func TestTimeoutNotScaledByWaiters(t *testing.T) {
const waiters = 8
for _, action := range []string{LogTimeoutActionDiscard, LogTimeoutActionPanic} {
t.Run(action, func(t *testing.T) {
blocking := newBlockingOnceWriteSyncer()
ws := LockWithTimeoutAction(blocking, 1, action)
go func() { _, _ = ws.Write([]byte("first")) }()
<-blocking.started

// All waiters queue up behind the stuck write at the same time. Each
// of them must give up after its own timeout, not after
// timeout * waiters.
start := time.Now()
var wg sync.WaitGroup
for range waiters {
wg.Add(1)
go func() {
defer wg.Done()
defer func() { _ = recover() }()
_, _ = ws.Write([]byte("blocked"))
}()
}
wg.Wait()
require.Less(t, time.Since(start), 3*time.Second)
close(blocking.release)
})
}
}

type hang struct{}

func (_ hang) Write(_ []byte) (int, error) {
Expand Down
Loading