2 * Copyright 2004-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #include <folly/experimental/logging/RateLimiter.h>
20 IntervalRateLimiter::IntervalRateLimiter(
21 uint64_t maxPerInterval,
22 std::chrono::steady_clock::duration interval)
23 : maxPerInterval_{maxPerInterval},
25 timestamp_{std::chrono::steady_clock::now().time_since_epoch().count()} {}
27 bool IntervalRateLimiter::checkSlow() {
28 auto ts = timestamp_.load();
29 auto now = std::chrono::steady_clock::now().time_since_epoch().count();
30 if (now < (ts + interval_.count())) {
34 if (!timestamp_.compare_exchange_strong(ts, now)) {
35 // We raced with another thread that reset the timestamp.
36 // We treat this as if we fell into the previous interval, and so we
37 // rate-limit ourself.
41 // In the future, if we wanted to return the number of dropped events we
42 // could use (count_.exchange(0) - maxPerInterval_) here.
43 count_.store(1, std::memory_order_release);
46 } // namespace logging