1 /*
2  * Copyright (C) 2018 The Android Open Source Project
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 HARDWARE_GOOGLE_PIXELSTATS_V1_0_RATELIMIT_H
18 #define HARDWARE_GOOGLE_PIXELSTATS_V1_0_RATELIMIT_H
19 
20 #include <utils/Timers.h>
21 
22 #include <map>
23 #include <mutex>
24 
25 namespace hardware {
26 namespace google {
27 namespace pixelstats {
28 namespace V1_0 {
29 namespace implementation {
30 
31 class RateLimiter {
32   public:
33     RateLimiter(int overall_limit = 0) { SetOverallDailyLimit(overall_limit); }
34 
35     // Returns true if you should rate limit the action reporting, false if not.
36     // limit: the number of times the action can occur within 24hrs.
37     bool RateLimit(int32_t action, int32_t limit);
38 
39     // Limit for all actions over a 24hr period.  0 disables overall limit.
40     void SetOverallDailyLimit(int32_t limit);
41 
42     // for tests only
43     void TurnBackHours(int32_t hours);
44 
45   private:
46     std::mutex lock_;
47     std::map<int, int> counts_; // action -> count of actions in a 24hr window.
48     int32_t overall_count_;
49     int32_t overall_limit_;
50     int64_t nsecs_at_rollover_;
51 };
52 
53 }  // namespace implementation
54 }  // namespace V1_0
55 }  // namespace pixelstats
56 }  // namespace google
57 }  // namespace hardware
58 
59 #endif // HARDWARE_GOOGLE_PIXELSTATS_V1_0_RATELIMIT_H
60 
61