userver: userver/utils/resource_scopes.hpp Source File
Loading...
Searching...
No Matches
resource_scopes.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/resource_scopes.hpp
4/// @brief @copybrief utils::ResourceScopeStorage
5
6#include <concepts>
7#include <cstdint>
8#include <memory>
9#include <optional>
10#include <type_traits>
11#include <utility>
12#include <vector>
13
14#include <userver/compiler/impl/lifetime.hpp>
15#include <userver/components/component_fwd.hpp>
16#include <userver/utils/assert.hpp>
17#include <userver/utils/impl/internal_tag.hpp>
18#include <userver/utils/move_only_function.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22namespace utils {
23
24namespace impl {
25class ScopeBase {
26public:
27 virtual ~ScopeBase() = default;
28
29 virtual void AfterConstruction() = 0;
30};
31
32template <typename Handle>
33class Scope final : public ScopeBase {
34public:
35 using AfterConstructionCallback = utils::move_only_function<Handle()>;
36
37 explicit Scope(AfterConstructionCallback after_construction)
38 : after_construction_(std::move(after_construction))
39 {}
40
41 void AfterConstruction() override { before_destruction_.emplace(after_construction_()); }
42
43private:
44 AfterConstructionCallback after_construction_;
45 std::optional<Handle> before_destruction_;
46};
47
48template <>
49class Scope<void> final : public ScopeBase {
50public:
51 using AfterConstructionCallback = utils::move_only_function<void()>;
52
53 explicit Scope(AfterConstructionCallback after_construction)
54 : after_construction_(std::move(after_construction))
55 {}
56
57 void AfterConstruction() override { after_construction_(); }
58
59private:
60 AfterConstructionCallback after_construction_;
61};
62
63/// @brief An object of ScopePtr defines actions to do after
64/// a component is constructed and just before it is destroyed.
65///
66/// @see @ref components::ComponentContext::Scopes
67using ScopePtr = std::unique_ptr<impl::ScopeBase>;
68
69} // namespace impl
70
71/// @brief Explicit opt-in to managing resource-scope lifetime manually.
72/// Prefer @ref utils::WithResourceScopes, @ref utils::MakeWithResourceScopes or
73/// @ref utils::MakeUniqueWithResourceScopes instead.
74struct UnsafeManualResourceScopes final {
75 constexpr explicit UnsafeManualResourceScopes() noexcept = default;
76};
77
78/// @brief Runs resource setup after object construction and cleanup before object destruction.
79///
80/// During construction, use @ref utils::ResourceScopeStorage::Register to queue setup functions. The component system
81/// or scope wrapper calls @ref utils::ResourceScopeStorage::AfterConstruction after all constructors, including derived
82/// constructors, finish. It calls @ref utils::ResourceScopeStorage::BeforeDestruction to destroy the returned RAII
83/// handles before the object's destructor starts.
84///
85/// See @ref resource_scopes_parameter "choosing scopes" for ownership and wrapper selection, and
86/// @ref resource_scopes_register "using Register directly" for custom resources.
87///
88/// @snippet core/src/components/resource_scopes_test.cpp ResourceScopeStorage - HappyPathOrder
89class ResourceScopeStorage final {
90public:
91 /// @brief Constructs an empty storage.
92 ///
93 /// Prefer a scope wrapper, including in tests; see @ref resource_scopes_parameter "choosing scopes".
94 explicit ResourceScopeStorage(UnsafeManualResourceScopes) noexcept {}
95
96 ResourceScopeStorage(ResourceScopeStorage&& other) noexcept = default;
97 ResourceScopeStorage& operator=(ResourceScopeStorage&& other) noexcept = default;
98
99 /// @brief Registers a functor to register some resource that will be
100 /// called after the component is successfully created (including all
101 /// class descendants) or after the component creation is emulated in
102 /// unit tests. The functor must return a RAII-style handle object
103 /// that unregisters the previously registered resource. The returned handle's
104 /// destructor is called just before the component destructor is called.
105 ///
106 /// During construction the callback is queued and runs from @ref AfterConstruction.
107 /// If @ref Register is called from another scope's opening callback, or after
108 /// @ref AfterConstruction has completed, the new scope is opened immediately.
109 /// Its destructor runs in reverse opening-completion order.
110 ///
111 /// @note A queued callback is not called if the component is not created OR
112 /// any previously registered callback throws an exception.
113 /// @note if you don't have an existing RAII-ish class, but still want
114 /// to do a cleanup, you might want to use @ref utils::FastScopeGuard
115 /// to wrap the cleanup function.
116 ///
117 /// See @ref resource_scopes_parameter "where to obtain this storage" and
118 /// @ref resource_scopes_register "using Register directly" for custom resource lifetimes.
119 template <std::invocable<> AfterConstructionCallback>
120 void Register(AfterConstructionCallback after_construction)
121 {
122 Register(utils::impl::InternalTag{}, Priority{0}, std::move(after_construction));
123 }
124
125 /// @cond
126 // For internal use only.
127 // Lower values run earlier in AfterConstruction and later in BeforeDestruction.
128 using Priority = std::int32_t;
129
130 template <std::invocable<> AfterConstructionCallback>
131 void Register(utils::impl::InternalTag, Priority priority, AfterConstructionCallback after_construction)
132 {
133 using Handle = std::invoke_result_t<AfterConstructionCallback>;
134 auto scope = std::make_unique<impl::Scope<Handle>>(std::move(after_construction));
135 DoRegister(std::move(scope), priority);
136 }
137 /// @endcond
138
139 /// @brief Call all registered functors.
140 ///
141 /// If a functor throws, already constructed resources are unregistered via
142 /// @ref BeforeDestruction and the exception is rethrown.
144
145 /// @brief Unregister all previously registered resources.
146 ///
147 /// Also drops factories that have not run @ref AfterConstruction yet,
148 /// so captured RAII handles unregister immediately.
149 void BeforeDestruction() noexcept;
150
151private:
152 enum class State {
153 kConstruction,
154 kAfterConstruction,
155 kReady,
156 kBeforeDestruction,
157 kDestruction,
158 };
159
160 struct ScopeWithPriority {
161 Priority priority{0};
162 impl::ScopePtr scope;
163 };
164
165 void DoRegister(impl::ScopePtr resource_scope, Priority priority);
166 void OpenAndKeep(impl::ScopePtr resource_scope);
167 void OpenAndClose(impl::ScopePtr resource_scope);
168 static void SortByPriority(std::vector<ScopeWithPriority>& scopes) noexcept;
169
170 std::vector<ScopeWithPriority> registered_scopes_;
171 std::vector<impl::ScopePtr> initialized_scopes_;
172 State state_{State::kConstruction};
173};
174
175/// @brief A wrapper that provides @ref utils::ResourceScopeStorage for the wrapped object.
176///
177/// The wrapped object is passed `utils::ResourceScopeStorage&` as the first argument to the constructor.
178/// Prefer this over storing @ref ResourceScopeStorage as a field of the wrapped object itself.
179/// Use @ref MakeWithResourceScopes when the caller needs a `std::shared_ptr` to the wrapped object.
180template <typename Wrapped>
181class WithResourceScopes final {
182public:
183 /// @brief Constructs the wrapped object and passes the embedded @ref utils::ResourceScopeStorage to it
184 /// as the first argument.
185 template <typename... Args>
186 explicit WithResourceScopes(std::in_place_t, Args&&... args)
187 : wrapped_(resource_scope_storage_, std::forward<Args>(args)...)
188 {
189 resource_scope_storage_.AfterConstruction();
190 }
191
192 // Not movable: scopes pin a reference to the wrapped object.
193 WithResourceScopes(WithResourceScopes&&) = delete;
194 WithResourceScopes& operator=(WithResourceScopes&&) = delete;
195
196 ~WithResourceScopes() { resource_scope_storage_.BeforeDestruction(); }
197
198 /// @brief Returns the wrapped object.
199 Wrapped& operator*() & noexcept USERVER_IMPL_LIFETIME_BOUND { return wrapped_; }
200 /// @overload
201 const Wrapped& operator*() const& noexcept USERVER_IMPL_LIFETIME_BOUND { return wrapped_; }
202
203 /// @brief Returns the wrapped object.
204 Wrapped* operator->() noexcept USERVER_IMPL_LIFETIME_BOUND { return &wrapped_; }
205 /// @overload
206 const Wrapped* operator->() const noexcept USERVER_IMPL_LIFETIME_BOUND { return &wrapped_; }
207
208private:
209 ResourceScopeStorage resource_scope_storage_{UnsafeManualResourceScopes{}};
210 Wrapped wrapped_;
211};
212
213/// @brief Constructs @ref WithResourceScopes and returns an aliasing `std::shared_ptr` to the wrapped object.
214///
215/// The returned pointer shares ownership of the wrapper. @ref WithResourceScopes is not movable
216/// and stays at a stable heap address, so scoped registrations remain valid for the lifetime
217/// of any copy of the `shared_ptr`.
218///
219/// @snippet core/src/components/resource_scopes_test.cpp MakeWithResourceScopes
220template <typename Wrapped, typename... Args>
221std::shared_ptr<Wrapped> MakeWithResourceScopes(Args&&... args) {
222 auto holder = std::make_shared<WithResourceScopes<Wrapped>>(std::in_place, std::forward<Args>(args)...);
223 auto* const wrapped = std::addressof(**holder);
224 return std::shared_ptr<Wrapped>(std::move(holder), wrapped);
225}
226
227namespace impl {
228
229struct ResourceScopeStorageHolder {
230 ResourceScopeStorage scopes{UnsafeManualResourceScopes{}};
231};
232
233template <typename Wrapped>
234// NOLINTNEXTLINE(fuchsia-multiple-inheritance)
235class UniqueWithResourceScopes final : private ResourceScopeStorageHolder, public Wrapped {
236public:
237 template <typename... Args>
238 explicit UniqueWithResourceScopes(Args&&... args)
239 : Wrapped(ResourceScopeStorageHolder::scopes, std::forward<Args>(args)...)
240 {
241 ResourceScopeStorageHolder::scopes.AfterConstruction();
242 }
243
244 UniqueWithResourceScopes(UniqueWithResourceScopes&&) = delete;
245 UniqueWithResourceScopes& operator=(UniqueWithResourceScopes&&) = delete;
246
247 ~UniqueWithResourceScopes() override { ResourceScopeStorageHolder::scopes.BeforeDestruction(); }
248};
249
250} // namespace impl
251
252/// @brief Constructs an object with resource scopes and returns an owning `std::unique_ptr` to it.
253///
254/// The constructor of `Wrapped` receives @ref utils::ResourceScopeStorage as its first argument,
255/// followed by the forwarded arguments. `Wrapped` must not be `final` and must have a public virtual destructor:
256/// an internal derived wrapper closes the scopes before the destructor of `Wrapped` runs, including when
257/// deleted through a pointer to a base class of `Wrapped`.
258///
259/// Scopes open after the constructor of `Wrapped` completes. If that constructor throws, queued scopes are not
260/// opened. If opening a scope throws, already opened scopes close before `Wrapped` is destroyed.
261/// Use @ref utils::WithResourceScopes or @ref utils::MakeWithResourceScopes for final types.
262///
263/// @snippet core/src/components/resource_scopes_test.cpp MakeUniqueWithResourceScopesSnippet
264template <typename Wrapped, typename... Args>
265std::unique_ptr<Wrapped> MakeUniqueWithResourceScopes(Args&&... args) {
266 static_assert(
267 !std::is_final_v<Wrapped>,
268 "utils::MakeUniqueWithResourceScopes<T> requires a non-final T; use utils::WithResourceScopes or "
269 "utils::MakeWithResourceScopes for final types"
270 );
271 static_assert(
272 std::has_virtual_destructor_v<Wrapped>,
273 "utils::MakeUniqueWithResourceScopes<T> requires T to have a virtual destructor for deletion through "
274 "std::unique_ptr<T>"
275 );
276 if constexpr (!std::is_final_v<Wrapped> && std::has_virtual_destructor_v<Wrapped>) {
277 return std::make_unique<impl::UniqueWithResourceScopes<Wrapped>>(std::forward<Args>(args)...);
278 } else {
279 return nullptr;
280 }
281}
282
283ResourceScopeStorage&
284LocateDependency(components::WithType<ResourceScopeStorage>, const components::ComponentConfig& config, const components::ComponentContext&);
285
286} // namespace utils
287
288USERVER_NAMESPACE_END