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