EventTokenBucket.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim:set ts=2 sw=2 sts=2 et cindent: */
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #ifndef NetEventTokenBucket_h__
  7. #define NetEventTokenBucket_h__
  8. #include "ARefBase.h"
  9. #include "nsCOMPtr.h"
  10. #include "nsDeque.h"
  11. #include "nsITimer.h"
  12. #include "mozilla/TimeStamp.h"
  13. class nsICancelable;
  14. namespace mozilla {
  15. namespace net {
  16. /* A token bucket is used to govern the maximum rate a series of events
  17. can be executed at. For instance if your event was "eat a piece of cake"
  18. then a token bucket configured to allow "1 piece per day" would spread
  19. the eating of a 8 piece cake over 8 days even if you tried to eat the
  20. whole thing up front. In a practical sense it 'costs' 1 token to execute
  21. an event and tokens are 'earned' at a particular rate as time goes by.
  22. The token bucket can be perfectly smooth or allow a configurable amount of
  23. burstiness. A bursty token bucket allows you to save up unused credits, while
  24. a perfectly smooth one would not. A smooth "1 per day" cake token bucket
  25. would require 9 days to eat that cake if you skipped a slice on day 4
  26. (use the token or lose it), while a token bucket configured with a burst
  27. of 2 would just let you eat 2 slices on day 5 (the credits for day 4 and day
  28. 5) and finish the cake in the usual 8 days.
  29. EventTokenBucket(hz=20, burst=5) creates a token bucket with the following properties:
  30. + events from an infinite stream will be admitted 20 times per second (i.e.
  31. hz=20 means 1 event per 50 ms). Timers will be used to space things evenly down to
  32. 5ms gaps (i.e. up to 200hz). Token buckets with rates greater than 200hz will admit
  33. multiple events with 5ms gaps between them. 10000hz is the maximum rate and 1hz is
  34. the minimum rate.
  35. + The burst size controls the limit of 'credits' that a token bucket can accumulate
  36. when idle. For our (20,5) example each event requires 50ms of credit (again, 20hz = 50ms
  37. per event). a burst size of 5 means that the token bucket can accumulate a
  38. maximum of 250ms (5 * 50ms) for this bucket. If no events have been admitted for the
  39. last full second the bucket can still only accumulate 250ms of credit - but that credit
  40. means that 5 events can be admitted without delay. A burst size of 1 is the minimum.
  41. The EventTokenBucket is created with maximum credits already applied, but they
  42. can be cleared with the ClearCredits() method. The maximum burst size is
  43. 15 minutes worth of events.
  44. + An event is submitted to the token bucket asynchronously through SubmitEvent().
  45. The OnTokenBucketAdmitted() method of the submitted event is used as a callback
  46. when the event is ready to run. A cancelable event is returned to the SubmitEvent() caller
  47. for use in the case they do not wish to wait for the callback.
  48. */
  49. class EventTokenBucket;
  50. class ATokenBucketEvent
  51. {
  52. public:
  53. virtual void OnTokenBucketAdmitted() = 0;
  54. };
  55. class TokenBucketCancelable;
  56. class EventTokenBucket : public nsITimerCallback, public ARefBase
  57. {
  58. public:
  59. NS_DECL_THREADSAFE_ISUPPORTS
  60. NS_DECL_NSITIMERCALLBACK
  61. // This should be constructed on the main thread
  62. EventTokenBucket(uint32_t eventsPerSecond, uint32_t burstSize);
  63. // These public methods are all meant to be called from the socket thread
  64. void ClearCredits();
  65. uint32_t BurstEventsAvailable();
  66. uint32_t QueuedEvents();
  67. // a paused token bucket will not process any events, but it will accumulate
  68. // credits. ClearCredits can be used before unpausing if desired.
  69. void Pause();
  70. void UnPause();
  71. void Stop();
  72. // The returned cancelable event can only be canceled from the socket thread
  73. nsresult SubmitEvent(ATokenBucketEvent *event, nsICancelable **cancelable);
  74. private:
  75. virtual ~EventTokenBucket();
  76. void CleanupTimers();
  77. friend class RunNotifyEvent;
  78. friend class SetTimerEvent;
  79. bool TryImmediateDispatch(TokenBucketCancelable *event);
  80. void SetRate(uint32_t eventsPerSecond, uint32_t burstSize);
  81. void DispatchEvents();
  82. void UpdateTimer();
  83. void UpdateCredits();
  84. const static uint64_t kUsecPerSec = 1000000;
  85. const static uint64_t kUsecPerMsec = 1000;
  86. const static uint64_t kMaxHz = 10000;
  87. uint64_t mUnitCost; // usec of credit needed for 1 event (from eventsPerSecond)
  88. uint64_t mMaxCredit; // usec mCredit limit (from busrtSize)
  89. uint64_t mCredit; // usec of accumulated credit.
  90. bool mPaused;
  91. bool mStopped;
  92. nsDeque mEvents;
  93. bool mTimerArmed;
  94. TimeStamp mLastUpdate;
  95. // The timer is created on the main thread, but is armed and executes Notify()
  96. // callbacks on the socket thread in order to maintain low latency of event
  97. // delivery.
  98. nsCOMPtr<nsITimer> mTimer;
  99. #ifdef XP_WIN
  100. // Windows timers are 15ms granularity by default. When we have active events
  101. // that need to be dispatched at 50ms or less granularity we change the OS
  102. // granularity to 1ms. 90 seconds after that need has elapsed we will change it
  103. // back
  104. const static uint64_t kCostFineGrainThreshold = 50 * kUsecPerMsec;
  105. void FineGrainTimers(); // get 1ms granularity
  106. void NormalTimers(); // reset to default granularity
  107. void WantNormalTimers(); // reset after 90 seconds if not needed in interim
  108. void FineGrainResetTimerNotify(); // delayed callback to reset
  109. TimeStamp mLastFineGrainTimerUse;
  110. bool mFineGrainTimerInUse;
  111. bool mFineGrainResetTimerArmed;
  112. nsCOMPtr<nsITimer> mFineGrainResetTimer;
  113. #endif
  114. };
  115. } // namespace net
  116. } // namespace mozilla
  117. #endif