AsyncTimeout.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * Copyright 2014-present 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. #pragma once
  17. #include <folly/io/async/TimeoutManager.h>
  18. #include <folly/portability/Event.h>
  19. #include <boost/noncopyable.hpp>
  20. #include <memory>
  21. #include <utility>
  22. namespace folly {
  23. class EventBase;
  24. class RequestContext;
  25. class TimeoutManager;
  26. /**
  27. * AsyncTimeout is used to asynchronously wait for a timeout to occur.
  28. */
  29. class AsyncTimeout : private boost::noncopyable {
  30. public:
  31. typedef TimeoutManager::InternalEnum InternalEnum;
  32. /**
  33. * Create a new AsyncTimeout object, driven by the specified TimeoutManager.
  34. */
  35. explicit AsyncTimeout(TimeoutManager* timeoutManager);
  36. explicit AsyncTimeout(EventBase* eventBase);
  37. /**
  38. * Create a new internal AsyncTimeout object.
  39. *
  40. * Internal timeouts are like regular timeouts, but will not stop the
  41. * TimeoutManager loop from exiting if the only remaining events are internal
  42. * timeouts.
  43. *
  44. * This is useful for implementing fallback timeouts to abort the
  45. * TimeoutManager loop if the other events have not been processed within a
  46. * specified time period: if the event loop takes too long the timeout will
  47. * fire and can stop the event loop. However, if all other events complete,
  48. * the event loop will exit even though the internal timeout is still
  49. * installed.
  50. */
  51. AsyncTimeout(TimeoutManager* timeoutManager, InternalEnum internal);
  52. AsyncTimeout(EventBase* eventBase, InternalEnum internal);
  53. /**
  54. * Create a new AsyncTimeout object, not yet assigned to a TimeoutManager.
  55. *
  56. * attachEventBase() must be called prior to scheduling the timeout.
  57. */
  58. AsyncTimeout();
  59. /**
  60. * AsyncTimeout destructor.
  61. *
  62. * The timeout will be automatically cancelled if it is running.
  63. */
  64. virtual ~AsyncTimeout();
  65. /**
  66. * timeoutExpired() is invoked when the timeout period has expired.
  67. */
  68. virtual void timeoutExpired() noexcept = 0;
  69. /**
  70. * Schedule the timeout to fire in the specified number of milliseconds.
  71. *
  72. * After the specified number of milliseconds has elapsed, timeoutExpired()
  73. * will be invoked by the TimeoutManager's main loop.
  74. *
  75. * If the timeout is already running, it will be rescheduled with the
  76. * new timeout value.
  77. *
  78. * @param milliseconds The timeout duration, in milliseconds.
  79. *
  80. * @return Returns true if the timeout was successfully scheduled,
  81. * and false if an error occurred. After an error, the timeout is
  82. * always unscheduled, even if scheduleTimeout() was just
  83. * rescheduling an existing timeout.
  84. */
  85. bool scheduleTimeout(uint32_t milliseconds);
  86. bool scheduleTimeout(TimeoutManager::timeout_type timeout);
  87. /**
  88. * Cancel the timeout, if it is running.
  89. */
  90. void cancelTimeout();
  91. /**
  92. * Returns true if the timeout is currently scheduled.
  93. */
  94. bool isScheduled() const;
  95. /**
  96. * Attach the timeout to a TimeoutManager.
  97. *
  98. * This may only be called if the timeout is not currently attached to a
  99. * TimeoutManager (either by using the default constructor, or by calling
  100. * detachTimeoutManager()).
  101. *
  102. * This method must be invoked in the TimeoutManager's thread.
  103. *
  104. * The internal parameter specifies if this timeout should be treated as an
  105. * internal event. TimeoutManager::loop() will return when there are no more
  106. * non-internal events remaining.
  107. */
  108. void attachTimeoutManager(
  109. TimeoutManager* timeoutManager,
  110. InternalEnum internal = InternalEnum::NORMAL);
  111. void attachEventBase(
  112. EventBase* eventBase,
  113. InternalEnum internal = InternalEnum::NORMAL);
  114. /**
  115. * Detach the timeout from its TimeoutManager.
  116. *
  117. * This may only be called when the timeout is not running.
  118. * Once detached, the timeout may not be scheduled again until it is
  119. * re-attached to a EventBase by calling attachEventBase().
  120. *
  121. * This method must be called from the current TimeoutManager's thread.
  122. */
  123. void detachTimeoutManager();
  124. void detachEventBase();
  125. const TimeoutManager* getTimeoutManager() {
  126. return timeoutManager_;
  127. }
  128. /**
  129. * Returns the internal handle to the event
  130. */
  131. struct event* getEvent() {
  132. return &event_;
  133. }
  134. /**
  135. * Convenience function that wraps a function object as
  136. * an AsyncTimeout instance and returns the wrapper.
  137. *
  138. * Specially useful when using lambdas as AsyncTimeout
  139. * observers.
  140. *
  141. * Example:
  142. *
  143. * void foo(TimeoutManager &manager) {
  144. * std::atomic_bool done = false;
  145. *
  146. * auto observer = AsyncTimeout::make(manager, [&] {
  147. * std::cout << "hello, world!" << std::endl;
  148. * done = true;
  149. * });
  150. *
  151. * observer->scheduleTimeout(std::chrono::seconds(5));
  152. *
  153. * while (!done); // busy wait
  154. * }
  155. *
  156. * @author: Marcelo Juchem <marcelo@fb.com>
  157. */
  158. template <typename TCallback>
  159. static std::unique_ptr<AsyncTimeout> make(
  160. TimeoutManager& manager,
  161. TCallback&& callback);
  162. /**
  163. * Convenience function that wraps a function object as
  164. * an AsyncTimeout instance and returns the wrapper
  165. * after scheduling it using the given TimeoutManager.
  166. *
  167. * This is equivalent to calling `make_async_timeout`
  168. * followed by a `scheduleTimeout` on the resulting
  169. * wrapper.
  170. *
  171. * Specially useful when using lambdas as AsyncTimeout
  172. * observers.
  173. *
  174. * Example:
  175. *
  176. * void foo(TimeoutManager &manager) {
  177. * std::atomic_bool done = false;
  178. *
  179. * auto observer = AsyncTimeout::schedule(
  180. * std::chrono::seconds(5), manager, [&] {
  181. * std::cout << "hello, world!" << std::endl;
  182. * done = true;
  183. * }
  184. * );
  185. *
  186. * while (!done); // busy wait
  187. * }
  188. *
  189. * @author: Marcelo Juchem <marcelo@fb.com>
  190. */
  191. template <typename TCallback>
  192. static std::unique_ptr<AsyncTimeout> schedule(
  193. TimeoutManager::timeout_type timeout,
  194. TimeoutManager& manager,
  195. TCallback&& callback);
  196. private:
  197. static void libeventCallback(libevent_fd_t fd, short events, void* arg);
  198. struct event event_;
  199. /*
  200. * Store a pointer to the TimeoutManager. We only use this
  201. * for some assert() statements, to make sure that AsyncTimeout is always
  202. * used from the correct thread.
  203. */
  204. TimeoutManager* timeoutManager_;
  205. // Save the request context for when the timeout fires.
  206. std::shared_ptr<RequestContext> context_;
  207. };
  208. namespace detail {
  209. /**
  210. * Wraps a function object as an AsyncTimeout instance.
  211. *
  212. * @author: Marcelo Juchem <marcelo@fb.com>
  213. */
  214. template <typename TCallback>
  215. struct async_timeout_wrapper : public AsyncTimeout {
  216. template <typename UCallback>
  217. async_timeout_wrapper(TimeoutManager* manager, UCallback&& callback)
  218. : AsyncTimeout(manager), callback_(std::forward<UCallback>(callback)) {}
  219. void timeoutExpired() noexcept override {
  220. static_assert(
  221. noexcept(std::declval<TCallback>()()),
  222. "callback must be declared noexcept, e.g.: `[]() noexcept {}`");
  223. callback_();
  224. }
  225. private:
  226. TCallback callback_;
  227. };
  228. } // namespace detail
  229. template <typename TCallback>
  230. std::unique_ptr<AsyncTimeout> AsyncTimeout::make(
  231. TimeoutManager& manager,
  232. TCallback&& callback) {
  233. return std::unique_ptr<AsyncTimeout>(
  234. new detail::async_timeout_wrapper<typename std::decay<TCallback>::type>(
  235. std::addressof(manager), std::forward<TCallback>(callback)));
  236. }
  237. template <typename TCallback>
  238. std::unique_ptr<AsyncTimeout> AsyncTimeout::schedule(
  239. TimeoutManager::timeout_type timeout,
  240. TimeoutManager& manager,
  241. TCallback&& callback) {
  242. auto wrapper = AsyncTimeout::make(manager, std::forward<TCallback>(callback));
  243. wrapper->scheduleTimeout(timeout);
  244. return wrapper;
  245. }
  246. } // namespace folly