logging: fix compiler compatibility for one more constexpr function
[folly.git] / folly / experimental / logging / RateLimiter.cpp
1 /*
2  * Copyright 2004-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  */
16 #include <folly/experimental/logging/RateLimiter.h>
17
18 namespace folly {
19 namespace logging {
20 IntervalRateLimiter::IntervalRateLimiter(
21     uint64_t maxPerInterval,
22     std::chrono::steady_clock::duration interval)
23     : maxPerInterval_{maxPerInterval},
24       interval_{interval},
25       timestamp_{std::chrono::steady_clock::now().time_since_epoch().count()} {}
26
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())) {
31     return false;
32   }
33
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.
38     return false;
39   }
40
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);
44   return true;
45 }
46 }
47 }