Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
steps:
- uses: actions/setup-go@v5
with:
go-version: stable
go-version: oldstable
- uses: actions/checkout@v4
- name: golangci-lint
uses: golangci/golangci-lint-action@v9.2.0
Expand Down
167 changes: 131 additions & 36 deletions throttle.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import (
"context"
"errors"
"fmt"
"runtime"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -80,8 +82,10 @@
}

type throttle struct {
sem chan struct{} // Semaphore channel for concurrency limit.
blocked int64 // Number of blocked slots in semaphore.
sem chan struct{} // Semaphore channel for concurrency limit.
capacity int64 // Size of semaphore.
blocked int64 // Number of blocked slots in semaphore.
adj sync.Mutex // Serializes concurrency adjustments.

latency *dynhist.Collector // Latency histogram collector for percentile calculation.
hCycles int64 // Number of healthy cycles passed since last perf adjustment.
Expand Down Expand Up @@ -121,13 +125,17 @@
}

if t.cfg.MaxConcurrency != 0 {
t.sem = make(chan struct{}, t.cfg.MaxConcurrency)
t.capacity = t.cfg.MaxConcurrency
t.sem = make(chan struct{}, t.capacity)

if t.cfg.InitialConcurrency != 0 {
t.blocked = t.cfg.MaxConcurrency - t.cfg.InitialConcurrency
for i := 0; i < int(t.blocked); i++ {
t.sem <- struct{}{}
}
initial := t.cfg.InitialConcurrency
if initial == 0 {
initial = t.cfg.MaxConcurrency
}

t.blocked = t.capacity - initial
for i := 0; i < int(t.blocked); i++ {
t.sem <- struct{}{}
}
}

Expand Down Expand Up @@ -273,23 +281,21 @@
newConcurrency := int64(0)

if t.sem != nil {
blocked := atomic.LoadInt64(&t.blocked)
active := t.cfg.MaxConcurrency - blocked
lim := t.limits()

t.adj.Lock()

active := t.capacity - atomic.LoadInt64(&t.blocked)
delta := int64(float64(active) * t.cfg.StepFracConcurrency)

if active-delta <= t.cfg.MinConcurrency {
delta = active - t.cfg.MinConcurrency
if active-delta <= lim.MinConcurrency {
delta = max(active-lim.MinConcurrency, 0)
}

newConcurrency = active - delta

if delta > 0 {
for i := 0; i < int(delta); i++ {
t.sem <- struct{}{}
}

atomic.AddInt64(&t.blocked, delta)
}
t.block(delta)
t.adj.Unlock()
}

if t.rlExists {
Expand All @@ -312,29 +318,24 @@
newConcurrency := int64(0)

if t.sem != nil {
blocked := atomic.LoadInt64(&t.blocked)
if blocked != 0 {
active := t.cfg.MaxConcurrency - blocked
delta := int64(float64(active) * t.cfg.StepFracConcurrency)
lim := t.limits()

if delta < 1 {
delta = 1
}
t.adj.Lock()

active := t.capacity - atomic.LoadInt64(&t.blocked)
if active < lim.MaxConcurrency {
delta := max(int64(float64(active)*t.cfg.StepFracConcurrency), 1)

if active+delta >= t.cfg.MaxConcurrency {
delta = t.cfg.MaxConcurrency - active
if active+delta >= lim.MaxConcurrency {
delta = lim.MaxConcurrency - active
}

newConcurrency = active + delta

if delta != 0 {
for i := 0; i < int(delta); i++ {
<-t.sem
}

atomic.AddInt64(&t.blocked, -delta)
}
t.block(-delta)
}

t.adj.Unlock()
}

if t.rlExists {
Expand All @@ -346,6 +347,100 @@
}
}

// block removes delta slots from the active pool, negative delta returns slots back, t.adj must be held.
func (t *throttle) block(delta int64) {
for i := int64(0); i < delta; i++ {
t.sem <- struct{}{}
}

for i := int64(0); i > delta; i-- {
<-t.sem
}

atomic.AddInt64(&t.blocked, delta)
}

// ErrInvalidLimits is returned by SetLimits for inconsistent or out of range limits.
var ErrInvalidLimits = errors.New("invalid limits")

// Limits are bounds of rate and concurrency that can be changed in runtime.
type Limits struct {
MinRate rate.Limit
MaxRate rate.Limit
MinConcurrency int64
MaxConcurrency int64
}

// Limits returns current bounds.
func (t *Throttle) Limits() Limits {
return t.limits()
}

func (t *throttle) limits() Limits {
t.mu.RLock()
defer t.mu.RUnlock()

return Limits{
MinRate: t.cfg.MinRate,
MaxRate: t.cfg.MaxRate,
MinConcurrency: t.cfg.MinConcurrency,
MaxConcurrency: t.cfg.MaxConcurrency,
}
}

// SetLimits changes bounds of rate and concurrency, current rate is clamped immediately.
//
// Concurrency is adjusted in background, as removing slots has to wait for operations in progress to finish.
// MaxConcurrency can not exceed the value of Config.MaxConcurrency that Throttle was created with.
// Rate bounds are ignored if rate limiting was not enabled with Config.MaxRate.
func (t *Throttle) SetLimits(l Limits) error {
if t.sem != nil && (l.MinConcurrency < 0 || l.MinConcurrency > l.MaxConcurrency || l.MaxConcurrency > t.capacity) {
return fmt.Errorf("%w: concurrency want 0 <= min <= max <= %d, got min %d, max %d",
ErrInvalidLimits, t.capacity, l.MinConcurrency, l.MaxConcurrency)
}

if t.rlExists && (l.MinRate <= 0 || l.MinRate > l.MaxRate) {
return fmt.Errorf("%w: rate want 0 < min <= max, got min %v, max %v", ErrInvalidLimits, l.MinRate, l.MaxRate)
}

t.mu.Lock()

if t.sem != nil {
t.cfg.MinConcurrency, t.cfg.MaxConcurrency = l.MinConcurrency, l.MaxConcurrency
}

if t.rlExists {
t.cfg.MinRate, t.cfg.MaxRate = l.MinRate, l.MaxRate

if cur := t.rl.Limit(); cur > l.MaxRate || cur < l.MinRate {
t.rl = rate.NewLimiter(min(max(cur, l.MinRate), l.MaxRate), 1)
}

Check notice on line 417 in throttle.go

View workflow job for this annotation

GitHub Actions / test (stable)

1 statement(s) are not covered by tests.
}

t.mu.Unlock()

if t.sem != nil {
go t.enforceConcurrency(l)
}

return nil
}

// enforceConcurrency brings active concurrency in bounds.
func (t *throttle) enforceConcurrency(l Limits) {
t.adj.Lock()
defer t.adj.Unlock()

active := t.capacity - atomic.LoadInt64(&t.blocked)

switch {
case active > l.MaxConcurrency:
t.block(active - l.MaxConcurrency)
case active < l.MinConcurrency:
t.block(active - l.MinConcurrency)
}
}

func (t *throttle) updateRateLimiter(slower bool) rate.Limit {
t.mu.Lock()
defer t.mu.Unlock()
Expand Down Expand Up @@ -392,7 +487,7 @@

// Concurrency returns the number of available slots in the semaphore.
func (t *Throttle) Concurrency() int64 {
return t.cfg.MaxConcurrency - atomic.LoadInt64(&t.blocked)
return t.capacity - atomic.LoadInt64(&t.blocked)
}

// FailedPercent returns the fraction of failed operations of a healthy system, in percents.
Expand Down
29 changes: 29 additions & 0 deletions throttle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,32 @@ func TestThrottle_FailedPercentZeroTotal(t *testing.T) {

assert.Equal(t, 0.0, s.FailedPercent())
}

func TestThrottle_SetLimits(t *testing.T) {
th := throttle.NewThrottle(func(cfg *throttle.Config) {
cfg.Interval = time.Hour
cfg.MinConcurrency = 2
cfg.MaxConcurrency = 20
cfg.InitialConcurrency = 10
cfg.MinRate = 10
cfg.MaxRate = 100
})

assert.Equal(t, int64(10), th.Concurrency())

// Out of bounds.
require.ErrorIs(t, th.SetLimits(throttle.Limits{MinRate: 10, MaxRate: 100, MinConcurrency: 2, MaxConcurrency: 21}), throttle.ErrInvalidLimits)
require.ErrorIs(t, th.SetLimits(throttle.Limits{MinRate: 200, MaxRate: 100, MinConcurrency: 2, MaxConcurrency: 10}), throttle.ErrInvalidLimits)

// Lower the max, concurrency follows in background.
l := throttle.Limits{MinRate: 10, MaxRate: 100, MinConcurrency: 2, MaxConcurrency: 4}
require.NoError(t, th.SetLimits(l))
assert.Equal(t, l, th.Limits())
assert.Eventually(t, func() bool { return th.Concurrency() == 4 }, time.Second, time.Millisecond)

// Raise the min above current.
l.MinConcurrency = 6
l.MaxConcurrency = 20
require.NoError(t, th.SetLimits(l))
assert.Eventually(t, func() bool { return th.Concurrency() == 6 }, time.Second, time.Millisecond)
}
Loading