]>
Commit | Line | Data |
---|---|---|
f67539c2 TL |
1 | /* |
2 | * Copyright (c) 2017 Uber Technologies, Inc. | |
3 | * | |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); | |
5 | * you may not use this file except in compliance with the License. | |
6 | * You may obtain a copy of the License at | |
7 | * | |
8 | * http://www.apache.org/licenses/LICENSE-2.0 | |
9 | * | |
10 | * Unless required by applicable law or agreed to in writing, software | |
11 | * distributed under the License is distributed on an "AS IS" BASIS, | |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
13 | * See the License for the specific language governing permissions and | |
14 | * limitations under the License. | |
15 | */ | |
16 | ||
17 | #ifndef JAEGERTRACING_UTILS_RATELIMITER_H | |
18 | #define JAEGERTRACING_UTILS_RATELIMITER_H | |
19 | ||
20 | #include <chrono> | |
21 | #include <mutex> | |
22 | ||
23 | namespace jaegertracing { | |
24 | namespace utils { | |
25 | ||
26 | template <typename ClockType = std::chrono::steady_clock> | |
27 | class RateLimiter { | |
28 | public: | |
29 | using Clock = ClockType; | |
30 | ||
31 | RateLimiter(double creditsPerSecond, double maxBalance) | |
32 | : _creditsPerSecond(creditsPerSecond) | |
33 | , _maxBalance(maxBalance) | |
34 | , _balance(_maxBalance) | |
35 | , _lastTick(Clock::now()) | |
36 | { | |
37 | } | |
38 | ||
39 | bool checkCredit(double itemCost) | |
40 | { | |
41 | std::lock_guard<std::mutex> lock(_mutex); | |
42 | const auto currentTime = Clock::now(); | |
43 | const auto elapsedTime = | |
44 | std::chrono::duration<double>(currentTime - _lastTick); | |
45 | _lastTick = currentTime; | |
46 | ||
47 | _balance += elapsedTime.count() * _creditsPerSecond; | |
48 | if (_balance > _maxBalance) { | |
49 | _balance = _maxBalance; | |
50 | } | |
51 | ||
52 | if (_balance >= itemCost) { | |
53 | _balance -= itemCost; | |
54 | return true; | |
55 | } | |
56 | ||
57 | return false; | |
58 | } | |
59 | ||
60 | private: | |
61 | double _creditsPerSecond; | |
62 | double _maxBalance; | |
63 | double _balance; | |
64 | typename Clock::time_point _lastTick; | |
65 | std::mutex _mutex; | |
66 | }; | |
67 | ||
68 | } // namespace utils | |
69 | } // namespace jaegertracing | |
70 | ||
71 | #endif // JAEGERTRACING_UTILS_RATELIMITER_H |