20,000 listings to a newcomer: 120 s (unfinished) -> 24 s. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
package p2p
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// A sync used to be cut off after a fixed two minutes, however well it was
|
|
// going: a newcomer catching up from a large region stopped half way and
|
|
// waited for the next anti-entropy round. Now it is cut off when it makes no
|
|
// progress for syncIdle, and in any case after syncMax.
|
|
const (
|
|
syncIdle = 2 * time.Minute
|
|
syncMax = 30 * time.Minute
|
|
)
|
|
|
|
type idleKey struct{}
|
|
|
|
// idleTimer ends a context after a period without progress.
|
|
type idleTimer struct {
|
|
mu sync.Mutex
|
|
timer *time.Timer
|
|
idle time.Duration
|
|
closed bool
|
|
}
|
|
|
|
func (t *idleTimer) touch() {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if !t.closed {
|
|
t.timer.Reset(t.idle)
|
|
}
|
|
}
|
|
|
|
// withIdleTimeout returns a context that ends after idle without a call to
|
|
// progress(ctx), or after max at the latest.
|
|
func withIdleTimeout(parent context.Context, idle, max time.Duration) (context.Context, context.CancelFunc) {
|
|
ctx, cancel := context.WithTimeout(parent, max)
|
|
t := &idleTimer{idle: idle}
|
|
t.timer = time.AfterFunc(idle, cancel)
|
|
ctx = context.WithValue(ctx, idleKey{}, t)
|
|
return ctx, func() {
|
|
t.mu.Lock()
|
|
t.closed = true
|
|
t.timer.Stop()
|
|
t.mu.Unlock()
|
|
cancel()
|
|
}
|
|
}
|
|
|
|
// progress tells ctx's idle timer that work is going on; for a context without
|
|
// one it does nothing.
|
|
func progress(ctx context.Context) {
|
|
if t, ok := ctx.Value(idleKey{}).(*idleTimer); ok {
|
|
t.touch()
|
|
}
|
|
}
|