Make HHWheelTimer take a TimeoutManager rather than EventBase
[folly.git] / folly / io / async / HHWheelTimer.h
1 /*
2  * Copyright 2015 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
17 #pragma once
18
19 #include <folly/Optional.h>
20 #include <folly/io/async/AsyncTimeout.h>
21 #include <folly/io/async/DelayedDestruction.h>
22
23 #include <boost/intrusive/list.hpp>
24 #include <glog/logging.h>
25
26 #include <chrono>
27 #include <cstddef>
28 #include <memory>
29 #include <list>
30
31 namespace folly {
32
33 /**
34  * Hashed Hierarchical Wheel Timer
35  *
36  * Comparison:
37  * AsyncTimeout - a single timeout.
38  * HHWheelTimer - a set of efficient timeouts with different interval,
39  *    but timeouts are not exact.
40  *
41  * All of the above are O(1) in insertion, tick update and cancel
42
43  * This implementation ticks once every 10ms.
44  * We model timers as the number of ticks until the next
45  * due event.  We allow 32-bits of space to track this
46  * due interval, and break that into 4 regions of 8 bits.
47  * Each region indexes into a bucket of 256 lists.
48  *
49  * Bucket 0 represents those events that are due the soonest.
50  * Each tick causes us to look at the next list in a bucket.
51  * The 0th list in a bucket is special; it means that it is time to
52  * flush the timers from the next higher bucket and schedule them
53  * into a different bucket.
54  *
55  * This technique results in a very cheap mechanism for
56  * maintaining time and timers, provided that we can maintain
57  * a consistent rate of ticks.
58  */
59 class HHWheelTimer : private folly::AsyncTimeout,
60                      public folly::DelayedDestruction {
61  public:
62   // This type has always been a misnomer, because it is not a unique pointer.
63   using UniquePtr = std::unique_ptr<HHWheelTimer, Destructor>;
64   using SharedPtr = IntrusivePtr<HHWheelTimer>;
65
66   template <typename... Args>
67   static UniquePtr newTimer(Args&&... args) {
68     return UniquePtr(new HHWheelTimer(std::forward<Args>(args)...));
69   }
70
71   /**
72    * A callback to be notified when a timeout has expired.
73    */
74   class Callback {
75    public:
76     Callback()
77       : wheel_(nullptr)
78       , expiration_(0) {}
79
80     virtual ~Callback();
81
82     /**
83      * timeoutExpired() is invoked when the timeout has expired.
84      */
85     virtual void timeoutExpired() noexcept = 0;
86
87     /// This callback was canceled. The default implementation is to just
88     /// proxy to `timeoutExpired` but if you care about the difference between
89     /// the timeout finishing or being canceled you can override this.
90     virtual void callbackCanceled() noexcept {
91       timeoutExpired();
92     }
93
94     /**
95      * Cancel the timeout, if it is running.
96      *
97      * If the timeout is not scheduled, cancelTimeout() does nothing.
98      */
99     void cancelTimeout() {
100       if (wheel_ == nullptr) {
101         // We're not scheduled, so there's nothing to do.
102         return;
103       }
104       cancelTimeoutImpl();
105     }
106
107     /**
108      * Return true if this timeout is currently scheduled, and false otherwise.
109      */
110     bool isScheduled() const {
111       return wheel_ != nullptr;
112     }
113
114    protected:
115     /**
116      * Don't override this unless you're doing a test. This is mainly here so
117      * that we can override it to simulate lag in steady_clock.
118      */
119     virtual std::chrono::milliseconds getCurTime() {
120       return std::chrono::duration_cast<std::chrono::milliseconds>(
121         std::chrono::steady_clock::now().time_since_epoch());
122     }
123
124    private:
125     // Get the time remaining until this timeout expires
126     std::chrono::milliseconds getTimeRemaining(
127           std::chrono::milliseconds now) const {
128       if (now >= expiration_) {
129         return std::chrono::milliseconds(0);
130       }
131       return expiration_ - now;
132     }
133
134     void setScheduled(HHWheelTimer* wheel,
135                       std::chrono::milliseconds);
136     void cancelTimeoutImpl();
137
138     HHWheelTimer* wheel_;
139     folly::Optional<DestructorGuard> wheelGuard_;
140     std::chrono::milliseconds expiration_;
141
142     typedef boost::intrusive::list_member_hook<
143       boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
144
145     ListHook hook_;
146
147     typedef boost::intrusive::list<
148       Callback,
149       boost::intrusive::member_hook<Callback, ListHook, &Callback::hook_>,
150       boost::intrusive::constant_time_size<false> > List;
151
152     std::shared_ptr<RequestContext> context_;
153
154     // Give HHWheelTimer direct access to our members so it can take care
155     // of scheduling/cancelling.
156     friend class HHWheelTimer;
157   };
158
159   /**
160    * Create a new HHWheelTimer with the specified interval and the
161    * default timeout value set.
162    *
163    * Objects created using this version of constructor can be used
164    * to schedule both variable interval timeouts using
165    * scheduleTimeout(callback, timeout) method, and default
166    * interval timeouts using scheduleTimeout(callback) method.
167    */
168   static int DEFAULT_TICK_INTERVAL;
169   explicit HHWheelTimer(
170       folly::TimeoutManager* timeoutManager,
171       std::chrono::milliseconds intervalMS =
172           std::chrono::milliseconds(DEFAULT_TICK_INTERVAL),
173       AsyncTimeout::InternalEnum internal = AsyncTimeout::InternalEnum::NORMAL,
174       std::chrono::milliseconds defaultTimeoutMS =
175           std::chrono::milliseconds(-1));
176
177   /**
178    * Destroy the HHWheelTimer.
179    *
180    * A HHWheelTimer should only be destroyed when there are no more
181    * callbacks pending in the set. (If it helps you may use cancelAll() to
182    * cancel all pending timeouts explicitly before calling this.)
183    */
184   virtual void destroy();
185
186   /**
187    * Cancel all outstanding timeouts
188    *
189    * @returns the number of timeouts that were cancelled.
190    */
191   size_t cancelAll();
192
193   /**
194    * Get the tick interval for this HHWheelTimer.
195    *
196    * Returns the tick interval in milliseconds.
197    */
198   std::chrono::milliseconds getTickInterval() const {
199     return interval_;
200   }
201
202   /**
203    * Get the default timeout interval for this HHWheelTimer.
204    *
205    * Returns the timeout interval in milliseconds.
206    */
207   std::chrono::milliseconds getDefaultTimeout() const {
208     return defaultTimeout_;
209   }
210
211   /**
212    * Schedule the specified Callback to be invoked after the
213    * specified timeout interval.
214    *
215    * If the callback is already scheduled, this cancels the existing timeout
216    * before scheduling the new timeout.
217    */
218   void scheduleTimeout(Callback* callback,
219                        std::chrono::milliseconds timeout);
220   void scheduleTimeoutImpl(Callback* callback,
221                        std::chrono::milliseconds timeout);
222
223   /**
224    * Schedule the specified Callback to be invoked after the
225    * fefault timeout interval.
226    *
227    * If the callback is already scheduled, this cancels the existing timeout
228    * before scheduling the new timeout.
229    *
230    * This method uses CHECK() to make sure that the default timeout was
231    * specified on the object initialization.
232    */
233   void scheduleTimeout(Callback* callback);
234
235   template <class F>
236   void scheduleTimeoutFn(F fn, std::chrono::milliseconds timeout) {
237     struct Wrapper : Callback {
238       Wrapper(F f) : fn_(std::move(f)) {}
239       void timeoutExpired() noexcept override {
240         try {
241           fn_();
242         } catch (std::exception const& e) {
243           LOG(ERROR) << "HHWheelTimer timeout callback threw an exception: "
244             << e.what();
245         } catch (...) {
246           LOG(ERROR) << "HHWheelTimer timeout callback threw a non-exception.";
247         }
248         delete this;
249       }
250       F fn_;
251     };
252     Wrapper* w = new Wrapper(std::move(fn));
253     scheduleTimeout(w, timeout);
254   }
255
256   /**
257    * Return the number of currently pending timeouts
258    */
259   uint64_t count() const {
260     return count_;
261   }
262
263   /**
264    * This turns on more exact timing.  By default the wheel timer
265    * increments its cached time only once everyN (default) ticks.
266    *
267    * With catchupEveryN at 1, timeouts will only be delayed until the
268    * next tick, at which point all overdue timeouts are called.  The
269    * wheel timer is approximately 2x slower with this set to 1.
270    *
271    * Load testing in opt mode showed skew was about 1% with no catchup.
272    */
273   void setCatchupEveryN(uint32_t everyN) {
274     catchupEveryN_ = everyN;
275   }
276
277   bool isDetachable() const {
278     return !folly::AsyncTimeout::isScheduled();
279   }
280
281   using folly::AsyncTimeout::attachEventBase;
282   using folly::AsyncTimeout::detachEventBase;
283   using folly::AsyncTimeout::getTimeoutManager;
284
285  protected:
286   /**
287    * Protected destructor.
288    *
289    * Use destroy() instead.  See the comments in DelayedDestruction for more
290    * details.
291    */
292   virtual ~HHWheelTimer();
293
294  private:
295   // Forbidden copy constructor and assignment operator
296   HHWheelTimer(HHWheelTimer const &) = delete;
297   HHWheelTimer& operator=(HHWheelTimer const &) = delete;
298
299   // Methods inherited from AsyncTimeout
300   virtual void timeoutExpired() noexcept;
301
302   std::chrono::milliseconds interval_;
303   std::chrono::milliseconds defaultTimeout_;
304
305   static constexpr int WHEEL_BUCKETS = 4;
306   static constexpr int WHEEL_BITS = 8;
307   static constexpr unsigned int WHEEL_SIZE = (1 << WHEEL_BITS);
308   static constexpr unsigned int WHEEL_MASK = (WHEEL_SIZE - 1);
309   static constexpr uint32_t LARGEST_SLOT = 0xffffffffUL;
310
311   typedef Callback::List CallbackList;
312   CallbackList buckets_[WHEEL_BUCKETS][WHEEL_SIZE];
313
314   int64_t timeToWheelTicks(std::chrono::milliseconds t) {
315     return t.count() / interval_.count();
316   }
317
318   bool cascadeTimers(int bucket, int tick);
319   int64_t nextTick_;
320   uint64_t count_;
321   std::chrono::milliseconds now_;
322
323   static constexpr uint32_t DEFAULT_CATCHUP_EVERY_N = 10;
324
325   uint32_t catchupEveryN_;
326   uint32_t expirationsSinceCatchup_;
327   bool processingCallbacksGuard_;
328 };
329
330 } // folly