userver: userver/components/component_context.hpp Source File
Loading...
Searching...
No Matches
component_context.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/components/component_context.hpp
4/// @brief @copybrief components::ComponentContext
5
6#include <stdexcept>
7#include <string_view>
8
9#include <userver/compiler/demangle.hpp>
10#include <userver/components/component_fwd.hpp>
11#include <userver/components/raw_component_base.hpp>
12#include <userver/engine/task/task_processor_fwd.hpp>
13#include <userver/utils/impl/internal_tag.hpp>
14#include <userver/utils/resource_scopes_fwd.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace engine::impl {
19class TaskContext;
20} // namespace engine::impl
21
22namespace components {
23
24namespace impl {
25
26class Manager;
27class ComponentContextImpl;
28class ComponentInfo;
29
30template <class T>
31constexpr auto NameFromComponentType() -> decltype(std::string_view{T::kName}) {
32 return T::kName;
33}
34
35template <class T, class... Args>
36constexpr auto NameFromComponentType(Args...) {
37 static_assert(
38 !sizeof(T),
39 "Component does not have a 'kName' member convertible to "
40 "std::string_view. You have to explicitly specify the name: "
41 "context.FindComponent<T>(name) or "
42 "context.FindComponentOptional<T>(name)."
43 );
44 return std::string_view{};
45}
46
47} // namespace impl
48
49/// @brief Exception that is thrown from
50/// components::ComponentContext::FindComponent() if a component load failed.
51class ComponentsLoadCancelledException : public std::runtime_error {
52public:
53 ComponentsLoadCancelledException();
54 explicit ComponentsLoadCancelledException(std::string_view message);
55};
56
57/// @brief Class to retrieve other components.
58///
59/// Only the const member functions of this class are meant for usage in
60/// component constructor (because of that this class is always passed as a
61/// const reference to the constructors).
62///
63/// @warning Don't store references to `ComponentContext` in your component!
64/// Lifetime of the passed `ComponentContext` ends as soon as
65/// the constructor ends.
66///
67/// For usage outside the component constructor see components::State.
68///
69/// @see @ref userver_components
70class ComponentContext final {
71public:
72 ComponentContext(ComponentContext&&) = delete;
73 ComponentContext& operator=(ComponentContext&&) = delete;
74
75 /// @brief Finds a component of type T with specified name (if any) and
76 /// returns the component after it was initialized.
77 ///
78 /// Can only be called from other component's constructor in a task where
79 /// that constructor was called.
80 /// May block and asynchronously wait for the creation of the requested
81 /// component.
82 /// @throw ComponentsLoadCancelledException if components loading was
83 /// cancelled due to errors in the creation of other component.
84 /// @throw std::runtime_error if component missing in `component_list` was
85 /// requested.
86 template <typename T>
87 T& FindComponent() const {
88 return FindComponent<T>(impl::NameFromComponentType<T>());
89 }
90
91 /// @overload T& FindComponent()
92 template <typename T>
93 T& FindComponent(std::string_view name) const {
94 if (!Contains(name)) {
95 ThrowNonRegisteredComponent(name, compiler::GetTypeName<T>());
96 }
97
98 auto* component_base = DoFindComponent(name);
99 T* ptr = dynamic_cast<T*>(component_base);
100 if (!ptr) {
101 ThrowComponentTypeMismatch(name, compiler::GetTypeName<T>(), component_base);
102 }
103
104 return *ptr;
105 }
106
107 template <typename T>
108 T& FindComponent(std::string_view /*name*/ = {}) {
109 return ReportMisuse<T>();
110 }
111
112 /// @brief If there's no component with specified type and name return
113 /// nullptr; otherwise behaves as FindComponent().
114 template <typename T>
116 return FindComponentOptional<T>(impl::NameFromComponentType<T>());
117 }
118
119 /// @overload T* FindComponentOptional()
120 template <typename T>
121 T* FindComponentOptional(std::string_view name) const {
122 if (!Contains(name)) {
123 return nullptr;
124 }
125 return dynamic_cast<T*>(DoFindComponent(name));
126 }
127
128 template <typename T>
129 T& FindComponentOptional(std::string_view /*name*/ = {}) {
130 return ReportMisuse<T>();
131 }
132
133 /// @brief Returns an engine::TaskProcessor with the specified name.
134 engine::TaskProcessor& GetTaskProcessor(std::string_view name) const;
135
136 template <typename T>
137 engine::TaskProcessor& GetTaskProcessor(const T&) {
138 return ReportMisuse<T>();
139 }
140
141 /// @brief Returns the current component name. This is helpful in cases
142 /// where multiple instances of the component class may be created using
143 /// `component_list.Append<T>("custom-name")` syntax.
144 ///
145 /// @warning The lifetime of the returned string ends as soon as
146 /// the current component's constructor completes. Store it
147 /// as an `std::string` if needed.
148 std::string_view GetComponentName() const;
149
150 /// @brief Returns the component's @ref utils::ResourceScopeStorage.
151 ///
152 /// See @ref resource_scopes_parameter "choosing scopes" before passing these scopes to another object.
153 utils::ResourceScopeStorage& Scopes() const;
154
155 /// @cond
156 // For internal use only.
157 ComponentContext(utils::impl::InternalTag, impl::ComponentContextImpl& impl, impl::ComponentInfo& component_info)
158 noexcept;
159
160 // For internal use only.
161 impl::ComponentContextImpl& GetImpl(utils::impl::InternalTag) const;
162
163 // For internal use only.
164 const impl::Manager& GetManager(utils::impl::InternalTag) const;
165 /// @endcond
166
167private:
168 /// @returns true if there is a component with the specified name and it
169 /// could be found via FindComponent()
170 bool Contains(std::string_view name) const noexcept;
171
172 template <typename T>
173 bool Contains(const T&) {
174 return ReportMisuse<T>();
175 }
176
177 template <class T>
178 decltype(auto) ReportMisuse() {
179 static_assert(
180 !sizeof(T),
181 "components::ComponentContext should be accepted by "
182 "a constant reference, i.e. "
183 "`MyComponent(const components::ComponentConfig& config, "
184 "const components::ComponentContext& context)`"
185 );
186 return 0;
187 }
188
189 [[noreturn]] void ThrowNonRegisteredComponent(std::string_view name, std::string_view type) const;
190
191 [[noreturn]] void ThrowComponentTypeMismatch(
192 std::string_view name,
193 std::string_view type,
194 RawComponentBase* component
195 ) const;
196
197 RawComponentBase* DoFindComponent(std::string_view name) const;
198
199 impl::ComponentContextImpl& impl_;
200 impl::ComponentInfo& component_info_;
201};
202
203} // namespace components
204
205USERVER_NAMESPACE_END