Fix RequestContext held too long issue in EventBase
[folly.git] / folly / ScopeGuard.h
1 /*
2  * Copyright 2017 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 <cstddef>
20 #include <functional>
21 #include <new>
22 #include <type_traits>
23 #include <utility>
24
25 #include <folly/Portability.h>
26 #include <folly/Preprocessor.h>
27 #include <folly/detail/UncaughtExceptionCounter.h>
28
29 namespace folly {
30
31 /**
32  * ScopeGuard is a general implementation of the "Initialization is
33  * Resource Acquisition" idiom.  Basically, it guarantees that a function
34  * is executed upon leaving the currrent scope unless otherwise told.
35  *
36  * The makeGuard() function is used to create a new ScopeGuard object.
37  * It can be instantiated with a lambda function, a std::function<void()>,
38  * a functor, or a void(*)() function pointer.
39  *
40  *
41  * Usage example: Add a friend to memory if and only if it is also added
42  * to the db.
43  *
44  * void User::addFriend(User& newFriend) {
45  *   // add the friend to memory
46  *   friends_.push_back(&newFriend);
47  *
48  *   // If the db insertion that follows fails, we should
49  *   // remove it from memory.
50  *   // (You could also declare this as "auto guard = makeGuard(...)")
51  *   ScopeGuard guard = makeGuard([&] { friends_.pop_back(); });
52  *
53  *   // this will throw an exception upon error, which
54  *   // makes the ScopeGuard execute UserCont::pop_back()
55  *   // once the Guard's destructor is called.
56  *   db_->addFriend(GetName(), newFriend.GetName());
57  *
58  *   // an exception was not thrown, so don't execute
59  *   // the Guard.
60  *   guard.dismiss();
61  * }
62  *
63  * Examine ScopeGuardTest.cpp for some more sample usage.
64  *
65  * Stolen from:
66  *   Andrei's and Petru Marginean's CUJ article:
67  *     http://drdobbs.com/184403758
68  *   and the loki library:
69  *     http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
70  *   and triendl.kj article:
71  *     http://www.codeproject.com/KB/cpp/scope_guard.aspx
72  */
73 class ScopeGuardImplBase {
74  public:
75   void dismiss() noexcept {
76     dismissed_ = true;
77   }
78
79   template <typename T>
80   FOLLY_ALWAYS_INLINE static void runAndWarnAboutToCrashOnException(
81       T& function) noexcept {
82     try {
83       function();
84     } catch (...) {
85       warnAboutToCrash();
86       std::terminate();
87     }
88   }
89
90  protected:
91   ScopeGuardImplBase() noexcept : dismissed_(false) {}
92
93   static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
94     return ScopeGuardImplBase{};
95   }
96
97   template <typename T>
98   static const T& asConst(const T& t) noexcept {
99     return t;
100   }
101
102   bool dismissed_;
103
104  private:
105   static void warnAboutToCrash() noexcept;
106 };
107
108 template <typename FunctionType>
109 class ScopeGuardImpl : public ScopeGuardImplBase {
110  public:
111   explicit ScopeGuardImpl(FunctionType& fn) noexcept(
112       std::is_nothrow_copy_constructible<FunctionType>::value)
113       : ScopeGuardImpl(
114             asConst(fn),
115             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
116                          &fn)) {}
117
118   explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
119       std::is_nothrow_copy_constructible<FunctionType>::value)
120       : ScopeGuardImpl(
121             fn,
122             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
123                          &fn)) {}
124
125   explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
126       std::is_nothrow_move_constructible<FunctionType>::value)
127       : ScopeGuardImpl(
128             std::move_if_noexcept(fn),
129             makeFailsafe(std::is_nothrow_move_constructible<FunctionType>{},
130                          &fn)) {}
131
132   ScopeGuardImpl(ScopeGuardImpl&& other) noexcept(
133       std::is_nothrow_move_constructible<FunctionType>::value)
134       : function_(std::move_if_noexcept(other.function_)) {
135     // If the above line attempts a copy and the copy throws, other is
136     // left owning the cleanup action and will execute it (or not) depending
137     // on the value of other.dismissed_. The following lines only execute
138     // if the move/copy succeeded, in which case *this assumes ownership of
139     // the cleanup action and dismisses other.
140     dismissed_ = other.dismissed_;
141     other.dismissed_ = true;
142   }
143
144   ~ScopeGuardImpl() noexcept {
145     if (!dismissed_) {
146       execute();
147     }
148   }
149
150  private:
151   static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
152     return makeEmptyScopeGuard();
153   }
154
155   template <typename Fn>
156   static auto makeFailsafe(std::false_type, Fn* fn) noexcept
157       -> ScopeGuardImpl<decltype(std::ref(*fn))> {
158     return ScopeGuardImpl<decltype(std::ref(*fn))>{std::ref(*fn)};
159   }
160
161   template <typename Fn>
162   explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
163       : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
164     failsafe.dismiss();
165   }
166
167   void* operator new(std::size_t) = delete;
168
169   void execute() noexcept {
170     runAndWarnAboutToCrashOnException(function_);
171   }
172
173   FunctionType function_;
174 };
175
176 template <typename FunctionType>
177 ScopeGuardImpl<typename std::decay<FunctionType>::type>
178 makeGuard(FunctionType&& fn) noexcept(
179     std::is_nothrow_constructible<typename std::decay<FunctionType>::type,
180                                   FunctionType>::value) {
181   return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
182       std::forward<FunctionType>(fn));
183 }
184
185 /**
186  * This is largely unneeded if you just use auto for your guards.
187  */
188 typedef ScopeGuardImplBase&& ScopeGuard;
189
190 namespace detail {
191
192 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
193     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
194     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
195
196 /**
197  * ScopeGuard used for executing a function when leaving the current scope
198  * depending on the presence of a new uncaught exception.
199  *
200  * If the executeOnException template parameter is true, the function is
201  * executed if a new uncaught exception is present at the end of the scope.
202  * If the parameter is false, then the function is executed if no new uncaught
203  * exceptions are present at the end of the scope.
204  *
205  * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
206  */
207 template <typename FunctionType, bool executeOnException>
208 class ScopeGuardForNewException {
209  public:
210   explicit ScopeGuardForNewException(const FunctionType& fn)
211       : function_(fn) {
212   }
213
214   explicit ScopeGuardForNewException(FunctionType&& fn)
215       : function_(std::move(fn)) {
216   }
217
218   ScopeGuardForNewException(ScopeGuardForNewException&& other)
219       : function_(std::move(other.function_))
220       , exceptionCounter_(std::move(other.exceptionCounter_)) {
221   }
222
223   ~ScopeGuardForNewException() noexcept(executeOnException) {
224     if (executeOnException == exceptionCounter_.isNewUncaughtException()) {
225       if (executeOnException) {
226         ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
227       } else {
228         function_();
229       }
230     }
231   }
232
233  private:
234   ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
235
236   void* operator new(std::size_t) = delete;
237
238   FunctionType function_;
239   UncaughtExceptionCounter exceptionCounter_;
240 };
241
242 /**
243  * Internal use for the macro SCOPE_FAIL below
244  */
245 enum class ScopeGuardOnFail {};
246
247 template <typename FunctionType>
248 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
249 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
250   return
251       ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
252       std::forward<FunctionType>(fn));
253 }
254
255 /**
256  * Internal use for the macro SCOPE_SUCCESS below
257  */
258 enum class ScopeGuardOnSuccess {};
259
260 template <typename FunctionType>
261 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
262 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
263   return
264       ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
265       std::forward<FunctionType>(fn));
266 }
267
268 #endif // native uncaught_exception() supported
269
270 /**
271  * Internal use for the macro SCOPE_EXIT below
272  */
273 enum class ScopeGuardOnExit {};
274
275 template <typename FunctionType>
276 ScopeGuardImpl<typename std::decay<FunctionType>::type>
277 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
278   return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
279       std::forward<FunctionType>(fn));
280 }
281 } // namespace detail
282
283 } // namespace folly
284
285 #define SCOPE_EXIT \
286   auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
287   = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
288
289 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
290     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
291     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
292 #define SCOPE_FAIL \
293   auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
294   = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
295
296 #define SCOPE_SUCCESS \
297   auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
298   = ::folly::detail::ScopeGuardOnSuccess() + [&]()
299 #endif // native uncaught_exception() supported