proxygen
RateLimiter.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017-present Facebook, 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  */
17 
18 namespace folly {
19 namespace logging {
20 
22  auto ts = timestamp_.load();
23  auto now = clock::now().time_since_epoch().count();
24  if (now < (ts + interval_.count())) {
25  return false;
26  }
27 
28  if (!timestamp_.compare_exchange_strong(ts, now)) {
29  // We raced with another thread that reset the timestamp.
30  // We treat this as if we fell into the previous interval, and so we
31  // rate-limit ourself.
32  return false;
33  }
34 
35  if (ts == 0) {
36  // If we initialized timestamp_ for the very first time increment count_ by
37  // one instead of setting it to 0. Our original increment made it roll over
38  // to 0, so other threads may have already incremented it again and passed
39  // the check.
40  auto origCount = count_.fetch_add(1, std::memory_order_acq_rel);
41  // Check to see if other threads already hit the rate limit cap before we
42  // finished checkSlow().
43  return (origCount < maxPerInterval_);
44  }
45 
46  // In the future, if we wanted to return the number of dropped events we
47  // could use (count_.exchange(0) - maxPerInterval_) here.
48  count_.store(1, std::memory_order_release);
49  return true;
50 }
51 } // namespace logging
52 } // namespace folly
std::atomic< clock::rep > timestamp_
Definition: RateLimiter.h:64
const clock::time_point::duration interval_
Definition: RateLimiter.h:55
std::chrono::steady_clock::time_point now()
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
std::atomic< uint64_t > count_
Definition: RateLimiter.h:60
static time_point now() noexcept
Definition: Chrono.h:171