source: filezilla/trunk/fuentes/src/engine/ratelimiter.h @ 130

Last change on this file since 130 was 130, checked in by jrpelegrina, 4 years ago

First release to xenial

File size: 1.7 KB
Line 
1#ifndef __RATELIMITER_H__
2#define __RATELIMITER_H__
3
4#include <option_change_event_handler.h>
5
6class COptionsBase;
7
8class CRateLimiterObject;
9
10// This class implements a simple rate limiter based on the Token Bucket algorithm.
11class CRateLimiter final : protected CEventHandler, COptionChangeEventHandler
12{
13public:
14        CRateLimiter(CEventLoop& loop, COptionsBase& options);
15        ~CRateLimiter();
16
17        enum rate_direction
18        {
19                inbound,
20                outbound
21        };
22
23        void AddObject(CRateLimiterObject* pObject);
24        void RemoveObject(CRateLimiterObject* pObject);
25
26protected:
27        int64_t GetLimit(rate_direction direction) const;
28
29        int GetBucketSize() const;
30
31        std::list<CRateLimiterObject*> m_objectList;
32        std::list<CRateLimiterObject*> m_wakeupList[2];
33
34        timer_id m_timer{};
35
36        int64_t m_tokenDebt[2];
37
38        COptionsBase& options_;
39
40        void WakeupWaitingObjects(scoped_lock & l);
41
42        void OnOptionsChanged(changed_options_t const& options);
43
44        void operator()(CEventBase const& ev);
45        void OnTimer(timer_id id);
46        void OnRateChanged();
47
48        mutex sync_;
49};
50
51struct ratelimit_changed_event_type{};
52typedef CEvent<ratelimit_changed_event_type> CRateLimitChangedEvent;
53
54class CRateLimiterObject
55{
56        friend class CRateLimiter;
57
58public:
59        CRateLimiterObject();
60        virtual ~CRateLimiterObject() {}
61        int64_t GetAvailableBytes(CRateLimiter::rate_direction direction) const { return m_bytesAvailable[direction]; }
62
63        bool IsWaiting(CRateLimiter::rate_direction direction) const;
64
65protected:
66        void UpdateUsage(CRateLimiter::rate_direction direction, int usedBytes);
67        void Wait(CRateLimiter::rate_direction direction);
68
69        virtual void OnRateAvailable(CRateLimiter::rate_direction) {}
70
71private:
72        bool m_waiting[2];
73        int64_t m_bytesAvailable[2];
74};
75
76#endif //__RATELIMITER_H__
Note: See TracBrowser for help on using the repository browser.