Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/flow/tracing/internal/jaegerremote/utils/rate_limiter.go
4096 views
1
// Copyright The OpenTelemetry Authors
2
// Copyright (c) 2021 The Jaeger Authors.
3
// Copyright (c) 2017 Uber Technologies, Inc.
4
//
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
//
9
// http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing, software
12
// distributed under the License is distributed on an "AS IS" BASIS,
13
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
// See the License for the specific language governing permissions and
15
// limitations under the License.
16
17
//nolint:all
18
package utils
19
20
import (
21
"sync"
22
"time"
23
)
24
25
// RateLimiter is a filter used to check if a message that is worth itemCost units is within the rate limits.
26
//
27
28
// RateLimiter is a rate limiter based on leaky bucket algorithm, formulated in terms of a
29
// credits balance that is replenished every time CheckCredit() method is called (tick) by the amount proportional
30
// to the time elapsed since the last tick, up to max of creditsPerSecond. A call to CheckCredit() takes a cost
31
// of an item we want to pay with the balance. If the balance exceeds the cost of the item, the item is "purchased"
32
// and the balance reduced, indicated by returned value of true. Otherwise the balance is unchanged and return false.
33
//
34
// This can be used to limit a rate of messages emitted by a service by instantiating the Rate Limiter with the
35
// max number of messages a service is allowed to emit per second, and calling CheckCredit(1.0) for each message
36
// to determine if the message is within the rate limit.
37
//
38
// It can also be used to limit the rate of traffic in bytes, by setting creditsPerSecond to desired throughput
39
// as bytes/second, and calling CheckCredit() with the actual message size.
40
type RateLimiter struct {
41
lock sync.Mutex
42
43
creditsPerSecond float64
44
balance float64
45
maxBalance float64
46
lastTick time.Time
47
48
timeNow func() time.Time
49
}
50
51
// NewRateLimiter creates a new RateLimiter.
52
func NewRateLimiter(creditsPerSecond, maxBalance float64) *RateLimiter {
53
return &RateLimiter{
54
creditsPerSecond: creditsPerSecond,
55
balance: maxBalance,
56
maxBalance: maxBalance,
57
lastTick: time.Now(),
58
timeNow: time.Now,
59
}
60
}
61
62
// CheckCredit tries to reduce the current balance by itemCost provided that the current balance
63
// is not lest than itemCost.
64
func (rl *RateLimiter) CheckCredit(itemCost float64) bool {
65
rl.lock.Lock()
66
defer rl.lock.Unlock()
67
68
// if we have enough credits to pay for current item, then reduce balance and allow
69
if rl.balance >= itemCost {
70
rl.balance -= itemCost
71
return true
72
}
73
// otherwise check if balance can be increased due to time elapsed, and try again
74
rl.updateBalance()
75
if rl.balance >= itemCost {
76
rl.balance -= itemCost
77
return true
78
}
79
return false
80
}
81
82
// updateBalance recalculates current balance based on time elapsed. Must be called while holding a lock.
83
func (rl *RateLimiter) updateBalance() {
84
// calculate how much time passed since the last tick, and update current tick
85
currentTime := rl.timeNow()
86
elapsedTime := currentTime.Sub(rl.lastTick)
87
rl.lastTick = currentTime
88
// calculate how much credit have we accumulated since the last tick
89
rl.balance += elapsedTime.Seconds() * rl.creditsPerSecond
90
if rl.balance > rl.maxBalance {
91
rl.balance = rl.maxBalance
92
}
93
}
94
95
// Update changes the main parameters of the rate limiter in-place, while retaining
96
// the current accumulated balance (pro-rated to the new maxBalance value). Using this method
97
// instead of creating a new rate limiter helps to avoid thundering herd when sampling
98
// strategies are updated.
99
func (rl *RateLimiter) Update(creditsPerSecond, maxBalance float64) {
100
rl.lock.Lock()
101
defer rl.lock.Unlock()
102
103
rl.updateBalance() // get up-to-date balance
104
rl.balance = rl.balance * maxBalance / rl.maxBalance
105
rl.creditsPerSecond = creditsPerSecond
106
rl.maxBalance = maxBalance
107
}
108
109