Debian Codegraph @

samplers/jaegerremote/internal/ratelimiter/rate_limiter.go

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