userver: userver/server/request/request_context.hpp Source File
Loading...
Searching...
No Matches
request_context.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/server/request/request_context.hpp
4/// @brief @copybrief server::request::RequestContext
5
6#include <stdexcept>
7#include <string>
8#include <string_view>
9#include <type_traits>
10
11#include <userver/dynamic_config/fwd.hpp>
12#include <userver/server/request/storage_context.hpp>
13#include <userver/utils/any_movable.hpp>
14#include <userver/utils/fast_pimpl.hpp>
15#include <userver/utils/statistics/labels.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace server::request {
20
21namespace impl {
22class InternalRequestContext;
23}
24
25/// @brief Stores request-specific data during request processing.
26///
27/// For example: you can store some data in `HandleRequestThrow()` method
28/// and access this data in `GetResponseDataForLogging()` method.
29///
30/// Use typed tags to store and retrieve per-request custom data.
31///
32/// The context can be used to pass data between middleware, authentication
33/// checkers, handlers, and logging hooks.
34///
35/// ## Example usage:
36///
37/// Define a shared tag in a header:
38/// @snippet samples/postgres_auth/auth_bearer.hpp request context tag
39///
40/// Store the value in an authentication checker:
41/// @snippet samples/postgres_auth/auth_bearer.cpp request context store
42///
43/// Read it in a handler:
44/// @snippet samples/postgres_auth/postgres_service.cpp request context read
45class RequestContext final {
46public:
47 RequestContext();
48
49 RequestContext(RequestContext&&) noexcept;
50
51 RequestContext(const RequestContext&) = delete;
52
53 ~RequestContext();
54
55 /// @brief Returns the dynamic config snapshot captured at the start of HTTP request processing.
56 ///
57 /// The snapshot is available in the initial section of HTTP middlewares (before the `Next()` call), and in request
58 /// logging hooks. It is reset before calling a streaming handler. For non-streaming HTTP handlers, the snapshot is
59 /// available for the entire duration of request handling, including response logging hooks. For WebSocket handlers,
60 /// it is available during the HTTP handshake and reset before calling `Handle()`.
61 ///
62 /// @throws std::logic_error if the snapshot has not been initialized or has already been reset.
63 const dynamic_config::Snapshot& GetInitialDynamicConfig() const USERVER_IMPL_LIFETIME_BOUND;
64
65 /// @brief Stores data under the tag if no value was previously stored.
66 /// @returns Reference to the stored data.
67 /// @throws std::runtime_error if data for the tag is already stored.
68 template <typename Data>
69 Data& SetData(const utils::AnyStorageDataTag<StorageContext, Data>& tag, Data data) USERVER_IMPL_LIFETIME_BOUND;
70
71 /// @brief Emplaces data under the tag if no value was previously stored.
72 /// @returns Reference to the stored data.
73 /// @throws std::runtime_error if data for the tag is already stored.
74 template <typename Data, typename... Args>
75 Data& EmplaceData(const utils::AnyStorageDataTag<StorageContext, Data>& tag, Args&&... args)
76 USERVER_IMPL_LIFETIME_BOUND;
77
78 /// @returns Stored data for the tag.
79 /// @throws std::runtime_error if no data was stored.
80 template <typename Data>
81 Data& GetData(const utils::AnyStorageDataTag<StorageContext, Data>& tag) USERVER_IMPL_LIFETIME_BOUND;
82
83 /// @returns Read-only access to stored data for the tag.
84 /// @throws std::runtime_error if no data was stored.
85 template <typename Data>
86 const Data& GetData(const utils::AnyStorageDataTag<StorageContext, Data>& tag) const USERVER_IMPL_LIFETIME_BOUND;
87
88 /// @returns Pointer to stored data for the tag or nullptr if absent.
89 template <typename Data>
90 Data* GetDataOptional(const utils::AnyStorageDataTag<StorageContext, Data>& tag
91 ) noexcept USERVER_IMPL_LIFETIME_BOUND;
92
93 /// @returns Read-only pointer to stored data for the tag or nullptr if absent.
94 template <typename Data>
95 const Data* GetDataOptional(const utils::AnyStorageDataTag<StorageContext, Data>& tag
96 ) const noexcept USERVER_IMPL_LIFETIME_BOUND;
97
98 /// @brief Erases data for the tag. Erasing an empty slot is harmless.
99 template <typename Data>
100 void EraseData(const utils::AnyStorageDataTag<StorageContext, Data>& tag) noexcept;
101
102#ifndef ARCADIA_ROOT
103 /// @brief Stores user data if it was not previously stored in this.
104 /// @throw std::runtime_error if user data was already stored.
105 template <typename Data>
106 [[deprecated("Use SetData with a typed tag instead")]] Data& SetUserData(Data data);
107
108 /// @brief Emplaces user data if it was not previously stored in this.
109 /// @throw std::runtime_error if user data was already stored.
110 template <typename Data, typename... Args>
111 [[deprecated("Use EmplaceData with a typed tag instead")]] Data& EmplaceUserData(Args&&... args);
112
113 /// @returns Stored user data
114 /// @throws std::runtime_error if no data was stored
115 /// @throws std::bad_any_cast if data of different type was stored
116 template <typename Data>
117 [[deprecated("Use GetData with a typed tag instead")]] Data& GetUserData();
118
119 /// @returns Stored user data
120 /// @throws std::runtime_error if no data was stored
121 /// @throws std::bad_any_cast if data of different type was stored
122 template <typename Data>
123 [[deprecated("Use GetData with a typed tag instead")]] const Data& GetUserData() const;
124
125 /// @returns A pointer to data of type Data if it was stored before during
126 /// current request processing or nullptr otherwise
127 template <typename Data>
128 [[deprecated("Use GetDataOptional with a typed tag instead")]] std::remove_reference_t<Data>* GetUserDataOptional();
129
130 /// @returns A pointer to data of type Data if it was stored before during
131 /// current request processing or nullptr otherwise
132 template <typename Data>
133 [[deprecated("Use GetDataOptional with a typed tag instead")]] const std::remove_reference_t<Data>*
134 GetUserDataOptional() const;
135
136 /// @brief Erases the user data.
137 [[deprecated("Use EraseData with a typed tag instead")]] void EraseUserData() noexcept;
138
139 /// @brief Stores the data with specified name if it was not previously stored
140 /// in this.
141 /// @throw std::runtime_error if data with such name was already stored.
142 template <typename Data>
143 [[deprecated("Use SetData with a typed tag instead")]] Data& SetData(std::string name, Data data);
144
145 /// @brief Emplaces the data with specified name if it was not previously
146 /// stored in this.
147 /// @throw std::runtime_error if data with such name was already stored.
148 template <typename Data, typename... Args>
149 [[deprecated("Use EmplaceData with a typed tag instead")]] Data& EmplaceData(std::string name, Args&&... args);
150
151 /// @returns Stored data with specified name.
152 /// @throws std::runtime_error if no data was stored
153 /// @throws std::bad_any_cast if data of different type was stored
154 template <typename Data>
155 [[deprecated("Use GetData with a typed tag instead")]] Data& GetData(std::string_view name);
156
157 /// @returns Stored data with specified name.
158 /// @throws std::runtime_error if no data was stored
159 /// @throws std::bad_any_cast if data of different type was stored
160 template <typename Data>
161 [[deprecated("Use GetData with a typed tag instead")]] const Data& GetData(std::string_view name) const;
162
163 /// @returns Stored data with specified name or nullptr if no data found.
164 /// @throws std::bad_any_cast if data of different type was stored.
165 template <typename Data>
166 [[deprecated("Use GetDataOptional with a typed tag instead")]] std::remove_reference_t<Data>* GetDataOptional(
167 std::string_view name
168 );
169
170 /// @returns Stored data with specified name or nullptr if no data found.
171 /// @throws std::bad_any_cast if data of different type was stored.
172 template <typename Data>
173 [[deprecated("Use GetDataOptional with a typed tag instead")]] const std::remove_reference_t<Data>* GetDataOptional(
174 std::string_view name
175 ) const;
176
177 /// @brief Erase data with specified name.
178 [[deprecated("Use EraseData with a typed tag instead")]] void EraseData(std::string_view name) noexcept;
179
180#endif
181
182 /// @brief Set the metrics shard (path + labels) for this request.
183 /// When set, handler metrics will be accumulated on a new subpath "http.handler.path.*"
184 /// and the provided labels would be set to each metric
185 /// @note If something (e.g. middleware) interrupts the request before this method is called
186 /// then the sharded metrics won't be written
187 void SetHandlerMetricsShard(std::string_view path, utils::statistics::LabelsSpan labels);
188
189 // TODO : TAXICOMMON-8252
190 impl::InternalRequestContext& GetInternalContext() noexcept;
191
192private:
193 utils::AnyStorage<StorageContext>& GetStorageContext() noexcept USERVER_IMPL_LIFETIME_BOUND;
194 const utils::AnyStorage<StorageContext>& GetStorageContext() const noexcept USERVER_IMPL_LIFETIME_BOUND;
195
196#ifndef ARCADIA_ROOT
197 utils::AnyMovable& SetUserAnyData(utils::AnyMovable&& data);
198 utils::AnyMovable& GetUserAnyData();
199 utils::AnyMovable* GetUserAnyDataOptional() noexcept;
200 void EraseUserAnyData() noexcept;
201
202 utils::AnyMovable& SetAnyData(std::string&& name, utils::AnyMovable&& data);
203 utils::AnyMovable& GetAnyData(std::string_view name);
204 utils::AnyMovable* GetAnyDataOptional(std::string_view name) noexcept;
205 void EraseAnyData(std::string_view name) noexcept;
206
207#endif
208
209 class Impl;
210 static constexpr std::size_t kPimplSize = 120;
211 utils::FastPimpl<Impl, kPimplSize, alignof(void*)> impl_;
212};
213
214template <typename Data>
215Data& RequestContext::SetData(const utils::AnyStorageDataTag<StorageContext, Data>& tag, Data data)
216 USERVER_IMPL_LIFETIME_BOUND {
217 return EmplaceData(tag, std::move(data));
218}
219
220template <typename Data, typename... Args>
221Data& RequestContext::EmplaceData(const utils::AnyStorageDataTag<StorageContext, Data>& tag, Args&&... args)
222 USERVER_IMPL_LIFETIME_BOUND {
223 auto& storage = GetStorageContext();
224 if (storage.GetOptional(tag)) {
225 throw std::runtime_error("Data for the tag is already stored in RequestContext");
226 }
227 return storage.Emplace(tag, std::forward<Args>(args)...);
228}
229
230template <typename Data>
231Data& RequestContext::GetData(const utils::AnyStorageDataTag<StorageContext, Data>& tag) USERVER_IMPL_LIFETIME_BOUND {
232 return GetStorageContext().Get(tag);
233}
234
235template <typename Data>
236const Data& RequestContext::GetData(const utils::AnyStorageDataTag<StorageContext, Data>& tag
237) const USERVER_IMPL_LIFETIME_BOUND {
238 return GetStorageContext().Get(tag);
239}
240
241template <typename Data>
242Data* RequestContext::GetDataOptional(const utils::AnyStorageDataTag<StorageContext, Data>& tag
243) noexcept USERVER_IMPL_LIFETIME_BOUND {
244 return GetStorageContext().GetOptional(tag);
245}
246
247template <typename Data>
248const Data* RequestContext::GetDataOptional(const utils::AnyStorageDataTag<StorageContext, Data>& tag
249) const noexcept USERVER_IMPL_LIFETIME_BOUND {
250 return GetStorageContext().GetOptional(tag);
251}
252
253template <typename Data>
254void RequestContext::EraseData(const utils::AnyStorageDataTag<StorageContext, Data>& tag) noexcept {
255 GetStorageContext().Erase(tag);
256}
257
258#ifndef ARCADIA_ROOT
259template <typename Data>
260Data& RequestContext::SetUserData(Data data) {
261 static_assert(
262 !std::is_const_v<Data>,
263 "Data stored in RequestContext is mutable if RequestContext is "
264 "not `const`. Remove the `const` from the template parameter "
265 "of SetUserData as it makes no sense"
266 );
267 static_assert(
268 !std::is_reference_v<Data>,
269 "Data in RequestContext is stored by copy. Remove the reference "
270 "from the template parameter of SetUserData as it makes no sense"
271 );
272 return utils::AnyCast<Data&>(SetUserAnyData(std::move(data)));
273}
274
275template <typename Data, typename... Args>
276Data& RequestContext::EmplaceUserData(Args&&... args) {
277 // NOLINTNEXTLINE(google-readability-casting)
278 auto& data = SetUserAnyData(Data(std::forward<Args>(args)...));
279 return utils::AnyCast<Data&>(data);
280}
281
282template <typename Data>
283Data& RequestContext::GetUserData() {
284 return utils::AnyCast<Data&>(GetUserAnyData());
285}
286
287template <typename Data>
288const Data& RequestContext::GetUserData() const {
289 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
290 return const_cast<RequestContext*>(this)->GetUserData<Data>();
291}
292
293template <typename Data>
294std::remove_reference_t<Data>* RequestContext::GetUserDataOptional() {
295 auto* data = GetUserAnyDataOptional();
296 return data ? &utils::AnyCast<Data&>(*data) : nullptr;
297}
298
299template <typename Data>
300const std::remove_reference_t<Data>* RequestContext::GetUserDataOptional() const {
301 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
302 return const_cast<RequestContext*>(this)->GetUserDataOptional<Data>();
303}
304
305inline void RequestContext::EraseUserData() noexcept { EraseUserAnyData(); }
306
307template <typename Data>
308Data& RequestContext::SetData(std::string name, Data data) {
309 static_assert(
310 !std::is_const_v<Data>,
311 "Data stored in RequestContext is mutable if RequestContext is "
312 "not `const`. Remove the `const` from the template parameter "
313 "of SetData as it makes no sense"
314 );
315 static_assert(
316 !std::is_reference_v<Data>,
317 "Data in RequestContext is stored by copy. Remove the reference "
318 "from the template parameter of SetData as it makes no sense"
319 );
320 return utils::AnyCast<Data&>(SetAnyData(std::move(name), std::move(data)));
321}
322
323template <typename Data, typename... Args>
324Data& RequestContext::EmplaceData(std::string name, Args&&... args) {
325 // NOLINTNEXTLINE(google-readability-casting)
326 auto& data = SetAnyData(std::move(name), Data(std::forward<Args>(args)...));
327 return utils::AnyCast<Data&>(data);
328}
329
330template <typename Data>
331Data& RequestContext::GetData(std::string_view name) {
332 return utils::AnyCast<Data&>(GetAnyData(name));
333}
334
335template <typename Data>
336const Data& RequestContext::GetData(std::string_view name) const {
337 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
338 return const_cast<RequestContext*>(this)->GetData<Data>(name);
339}
340
341template <typename Data>
342std::remove_reference_t<Data>* RequestContext::GetDataOptional(std::string_view name) {
343 auto* data = GetAnyDataOptional(name);
344 return data ? &utils::AnyCast<Data&>(*data) : nullptr;
345}
346
347template <typename Data>
348const std::remove_reference_t<Data>* RequestContext::GetDataOptional(std::string_view name) const {
349 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
350 return const_cast<RequestContext*>(this)->GetDataOptional<Data>(name);
351}
352
353inline void RequestContext::EraseData(std::string_view name) noexcept { EraseAnyData(name); }
354
355#endif
356
357} // namespace server::request
358
359USERVER_NAMESPACE_END