- newPacer(perSecond, now, sleep): strictly spaced slots, no burst, safe for concurrent callers - Wait reserves the next slot under a mutex and sleeps outside it - a cancelled caller gives its slot back when it is the last one; a cancelled context returns at once - a rate that is zero, negative, NaN or infinite means no pacer; a very low rate is capped at one interval of a year - tests with an injected clock and sleep
81 lines
2 KiB
Go
81 lines
2 KiB
Go
package queue
|
|
|
|
import (
|
|
"context"
|
|
"math"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// maxInterval caps the spacing of a very low rate, so the arithmetic on time never overflows.
|
|
const maxInterval = 365 * 24 * time.Hour
|
|
|
|
// pacer spaces the start of sends: at most one every interval, with no burst. Relays such as
|
|
// Amazon SES refuse mail sent faster than their rate.
|
|
type pacer struct {
|
|
interval time.Duration
|
|
now func() time.Time
|
|
sleep func(ctx context.Context, d time.Duration) error
|
|
|
|
mu sync.Mutex
|
|
next time.Time // the first free slot
|
|
}
|
|
|
|
// newPacer returns a pacer for perSecond sends per second. It returns nil, which never waits, when
|
|
// perSecond is not a positive finite number: the rate is unlimited.
|
|
func newPacer(perSecond float64, now func() time.Time, sleep func(ctx context.Context, d time.Duration) error) *pacer {
|
|
if !(perSecond > 0) || math.IsInf(perSecond, 0) {
|
|
return nil
|
|
}
|
|
interval := maxInterval
|
|
if f := float64(time.Second) / perSecond; f < float64(maxInterval) {
|
|
interval = time.Duration(f)
|
|
}
|
|
return &pacer{interval: interval, now: now, sleep: sleep}
|
|
}
|
|
|
|
// Wait blocks until the caller's slot. Each caller reserves the next free slot under the lock and
|
|
// sleeps outside it. A cancelled context returns its error at once; a slot reserved by a caller
|
|
// that gives up is released when no later caller has reserved after it.
|
|
func (p *pacer) Wait(ctx context.Context) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if p == nil {
|
|
return nil
|
|
}
|
|
p.mu.Lock()
|
|
now := p.now()
|
|
slot := p.next
|
|
if slot.Before(now) {
|
|
slot = now
|
|
}
|
|
p.next = slot.Add(p.interval)
|
|
p.mu.Unlock()
|
|
|
|
d := slot.Sub(now)
|
|
if d <= 0 {
|
|
return nil
|
|
}
|
|
if err := p.sleep(ctx, d); err != nil {
|
|
p.mu.Lock()
|
|
if p.next.Equal(slot.Add(p.interval)) {
|
|
p.next = slot
|
|
}
|
|
p.mu.Unlock()
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sleepCtx sleeps for d, or until ctx is done.
|
|
func sleepCtx(ctx context.Context, d time.Duration) error {
|
|
t := time.NewTimer(d)
|
|
defer t.Stop()
|
|
select {
|
|
case <-t.C:
|
|
return nil
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|