- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / policy / cloud / rate_limiter.h
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef CHROME_BROWSER_POLICY_CLOUD_RATE_LIMITER_H_
6 #define CHROME_BROWSER_POLICY_CLOUD_RATE_LIMITER_H_
7
8 #include <queue>
9
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/cancelable_callback.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/threading/non_thread_safe.h"
16 #include "base/time/time.h"
17
18 namespace base {
19 class SequencedTaskRunner;
20 class TickClock;
21 }
22
23 namespace policy {
24
25 // A simple class to limit the rate at which a callback is invoked.
26 class RateLimiter : public base::NonThreadSafe {
27  public:
28   // Will limit invocations of |callback| to |max_requests| per |duration|.
29   // |task_runner| is used to post delayed tasks, and |clock| is used to
30   // measure elapsed time.
31   RateLimiter(size_t max_requests,
32               const base::TimeDelta& duration,
33               const base::Closure& callback,
34               scoped_refptr<base::SequencedTaskRunner> task_runner,
35               scoped_ptr<base::TickClock> clock);
36   ~RateLimiter();
37
38   // Posts a request to invoke |callback_|. It is invoked immediately if the
39   // rate in the preceding |duration_| period is within the limit, otherwise
40   // the callback will be invoked later, ensuring the allowed rate is not
41   // exceeded.
42   void PostRequest();
43
44  private:
45   const size_t max_requests_;
46   const base::TimeDelta duration_;
47   base::Closure callback_;
48   scoped_refptr<base::SequencedTaskRunner> task_runner_;
49   scoped_ptr<base::TickClock> clock_;
50
51   std::queue<base::TimeTicks> invocation_times_;
52   base::CancelableClosure delayed_callback_;
53
54   DISALLOW_COPY_AND_ASSIGN(RateLimiter);
55 };
56
57 }  // namespace policy
58
59 #endif  // CHROME_BROWSER_POLICY_CLOUD_RATE_LIMITER_H_