userver: userver/engine/wait_any.hpp Source File
Loading...
Searching...
No Matches
wait_any.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/wait_any.hpp
4/// @brief Provides engine::WaitAny, engine::WaitAnyFor, engine::WaitAnyUntil, engine::WaitAnyContext and
5/// engine::MakeWaitAny
6
7#include <chrono>
8#include <cstdint>
9#include <optional>
10#include <vector>
11
12#include <boost/smart_ptr/intrusive_ptr.hpp>
13
14#include <userver/engine/awaitable.hpp>
15#include <userver/engine/deadline.hpp>
16#include <userver/utils/expected.hpp>
17#include <userver/utils/fast_pimpl.hpp>
18#include <userver/utils/meta.hpp>
19#include <userver/utils/span.hpp>
20
21USERVER_NAMESPACE_BEGIN
22
23namespace engine {
24
25/// @ingroup userver_concurrency
26///
27/// @deprecated `WaitAny` is deprecated. Please, prefer @ref MakeWaitAny + @ref WaitAnyContext::Wait.
28/// @brief Waits for the completion of any of the specified tasks or the
29/// cancellation of the caller.
30///
31/// Could be used to get the ready HTTP requests ASAP:
32/// @snippet core/src/clients/http/client_wait_test.cpp HTTP Client - waitany
33///
34/// Works with different types of tasks and futures:
35/// @snippet core/src/engine/wait_any_test.cpp sample waitany
36///
37/// @param tasks either a single container, or a pack of future-like elements.
38/// @returns the index of the completed task, or `std::nullopt` if there are no
39/// completed tasks (possible if current task was cancelled).
40template <typename... Tasks>
41std::optional<std::size_t> WaitAny(Tasks&... tasks);
42
43/// @ingroup userver_concurrency
44///
45/// @deprecated `WaitAnyFor` is deprecated. Please, prefer @ref MakeWaitAny + @ref WaitAnyContext::WaitFor.
46/// @overload std::optional<std::size_t> WaitAny(Tasks&... tasks)
47template <typename... Tasks, typename Rep, typename Period>
48std::optional<std::size_t> WaitAnyFor(const std::chrono::duration<Rep, Period>& duration, Tasks&... tasks);
49
50/// @ingroup userver_concurrency
51///
52/// @deprecated `WaitAnyUntil` is deprecated. Please, prefer @ref MakeWaitAny + @ref WaitAnyContext::WaitUntil.
53/// @overload std::optional<std::size_t> WaitAny(Tasks&... tasks)
54template <typename... Tasks, typename Clock, typename Duration>
55std::optional<std::size_t> WaitAnyUntil(const std::chrono::time_point<Clock, Duration>& until, Tasks&... tasks);
56
57/// @ingroup userver_concurrency
58///
59/// @deprecated `WaitAnyUntil` is deprecated. Please, prefer @ref MakeWaitAny + @ref WaitAnyContext::WaitUntil.
60/// @overload std::optional<std::size_t> WaitAny(Tasks&... tasks)
61template <typename... Tasks>
62std::optional<std::size_t> WaitAnyUntil(Deadline, Tasks&... tasks);
63
64template <typename... Tasks>
65std::optional<std::size_t> WaitAny(Tasks&... tasks) {
66 return engine::WaitAnyUntil(Deadline{}, tasks...);
67}
68
69template <typename... Tasks, typename Rep, typename Period>
70std::optional<std::size_t> WaitAnyFor(const std::chrono::duration<Rep, Period>& duration, Tasks&... tasks) {
71 return engine::WaitAnyUntil(Deadline::FromDuration(duration), tasks...);
72}
73
74template <typename... Tasks, typename Clock, typename Duration>
75std::optional<std::size_t> WaitAnyUntil(const std::chrono::time_point<Clock, Duration>& until, Tasks&... tasks) {
76 return engine::WaitAnyUntil(Deadline::FromTimePoint(until), tasks...);
77}
78
79namespace impl {
80
81std::optional<std::size_t> DoWaitAny(utils::span<AwaitableToken> target_tokens, Deadline deadline);
82
83template <typename Container>
84std::optional<std::size_t> WaitAnyFromContainer(Deadline deadline, Container& tasks) {
85 const auto size = std::size(tasks);
86 std::vector<AwaitableToken> targets;
87 targets.reserve(size);
88
89 for (auto& task : tasks) {
90 static_assert(engine::Awaitable<decltype(task)>, "Tasks must be awaitable");
91 targets.push_back(task.GetAwaitableToken());
92 }
93
94 return DoWaitAny(targets, deadline);
95}
96
97template <typename... Tasks>
98std::optional<std::size_t> WaitAnyFromTasks(Deadline deadline, Tasks&... tasks) {
99 static_assert((true && ... && engine::Awaitable<Tasks>), "Tasks must be awaitable");
100 AwaitableToken wa_elements[]{tasks.GetAwaitableToken()...};
101 return DoWaitAny(wa_elements, deadline);
102}
103
104inline std::optional<std::size_t> WaitAnyFromTasks(Deadline) { return {}; }
105
106} // namespace impl
107
108template <typename... Tasks>
109std::optional<std::size_t> WaitAnyUntil(Deadline deadline, Tasks&... tasks) {
110 if constexpr (meta::impl::IsSingleRange<Tasks...>) {
111 return impl::WaitAnyFromContainer(deadline, tasks...);
112 } else {
113 return impl::WaitAnyFromTasks(deadline, tasks...);
114 }
115}
116
117/// @ingroup userver_concurrency
118///
119/// @brief The reason why @ref WaitAnyContext::Wait and friends did not return the index of a completed awaitable.
120enum class WaitAnyError : std::uint8_t {
121 kEmpty, ///< there were no awaitables to wait for
122 kCancelled, ///< the wait operation was interrupted by task cancellation
123 kTimeout, ///< the wait operation timed out (see also @ref FutureStatus)
124};
125
126/// @ingroup userver_concurrency
127///
128/// @brief Stores a set of awaitables and allows waiting for completion of any of the stored awaitables.
129///
130/// Works with different types of awaitables:
131/// @snippet core/src/engine/wait_any_test.cpp sample MakeWaitAny
132///
133/// The methods are not thread-safe: they may be called from at most one task at a time.
134///
135/// No methods (except .dtor) should be called on a moved-out instance.
136class WaitAnyContext final {
137 class Impl;
138 class QueueItem;
139
140public:
141 WaitAnyContext();
142 ~WaitAnyContext() noexcept;
143 WaitAnyContext(WaitAnyContext&&) noexcept;
144 WaitAnyContext& operator=(WaitAnyContext&& other) noexcept;
145 WaitAnyContext(const WaitAnyContext&) = delete;
146 WaitAnyContext& operator=(const WaitAnyContext&) = delete;
147
148 /// @brief Identifies an awaitable appended to the context, see @ref Remove.
149 ///
150 /// A default-constructed handle identifies nothing. The handle may be passed only to the context
151 /// that returned it (or to the context it was moved into).
152 class Handle final {
153 public:
154 Handle() noexcept = default;
155 Handle(const Handle&) noexcept = default;
156 Handle& operator=(const Handle&) noexcept = default;
157
158 private:
159 friend class WaitAnyContext;
160
161 Handle(QueueItem* item, std::uint64_t generation) noexcept
162 : item_(item),
163 generation_(generation)
164 {}
165
166 QueueItem* item_{nullptr};
167 std::uint64_t generation_{0};
168 };
169
170 /// @brief Appends a single awaitable to the context.
171 ///
172 /// The appended awaitable will be assigned the next id from the auto-incrementing counter;
173 /// see also @ref GetNextId.
174 ///
175 /// @returns the handle of the appended awaitable, see @ref Remove. An empty awaitable is not
176 /// appended, an empty handle is returned for it.
178
179 /// @brief Appends the given awaitable to the context with an explicit id.
180 ///
181 /// The id is an arbitrary number that will be returned by @ref Wait.
182 /// It does not have to be sequential or starting from 0. Duplicate ids are allowed.
183 ///
184 /// @ref GetNextId will be unaffected by this call. When mixing the id-less @ref Append
185 /// and this overload, the id-less `Append` maintains a sequence only within its own calls.
186 ///
187 /// Works well together with @ref utils::SlotMap to process and erase tasks in completion order:
188 /// @snippet core/src/engine/wait_any_test.cpp sample WaitAnyContext SlotMap
189 ///
190 /// @param id the id that will be returned by @ref Wait.
191 /// @param awaitable the awaitable to append.
192 /// @returns the handle of the appended awaitable, see @ref Remove. An empty awaitable is not
193 /// appended, an empty handle is returned for it.
195
196 /// @brief Waits either for the completion of any of the awaitables stored in the context
197 /// or for the cancellation of the caller.
198 ///
199 /// The completed awaitable is dropped out of the context.
200 ///
201 /// @returns the index of the completed awaitable, or a @ref WaitAnyError if there are no
202 /// completed awaitables (possible if current task was cancelled or the context is empty).
204
205 /// @brief Waits for the completion of any of the awaitables stored in the context
206 /// or cancellation of the caller or deadline expiration.
207 ///
208 /// The completed awaitable is dropped from the context.
209 ///
210 /// @returns the index of the completed awaitable, or a @ref WaitAnyError if there are no
211 /// completed awaitables (possible if current task was cancelled, the deadline was reached,
212 /// or the context is empty).
213 utils::expected<std::uint64_t, WaitAnyError> WaitUntil(Deadline deadline);
214
215 /// @overload
216 template <typename Rep, typename Period>
217 utils::expected<std::uint64_t, WaitAnyError> WaitFor(const std::chrono::duration<Rep, Period>& duration) {
218 return WaitUntil(Deadline::FromDuration(duration));
219 }
220
221 /// @overload
222 template <typename Clock, typename Duration>
223 utils::expected<std::uint64_t, WaitAnyError> WaitUntil(const std::chrono::time_point<Clock, Duration>& until) {
224 return WaitUntil(Deadline::FromTimePoint(until));
225 }
226
227 /// @brief Removes the awaitable identified by the handle from the context.
228 ///
229 /// The removed awaitable will not be reported by `Wait*` and may be destroyed right after the call,
230 /// no matter whether it is ready or not. An empty handle is ignored.
231 ///
232 /// The awaitable must still be stored in the context: removing an awaitable that has already
233 /// been reported by `Wait*` or removed is not allowed. Such a call aborts the program, but this
234 /// detection is not guaranteed.
235 ///
236 /// The complexity is constant.
237 ///
238 /// @param handle the handle returned by @ref Append.
239 void Remove(Handle handle) noexcept;
240
241 /// @brief Returns the number of awaitables stored in the context.
242 ///
243 /// These are awaitables which have been `Append`ed, but not yet retrieved by `Wait` or `WaitUntil`.
244 /// The awaitables that have already been reported using `Wait*` or removed using @ref Remove
245 /// are dropped out.
246 std::size_t GetSize() const noexcept;
247
248 /// @brief Returns the next id that will be assigned by the next @ref Append call.
249 ///
250 /// It could be used to calculate ids of awaitables appended via @ref Append call.
251 std::uint64_t GetNextId() const noexcept;
252
253private:
254 Handle AppendToken(engine::AwaitableToken awaitable);
255
256 Handle AppendToken(std::uint64_t id, engine::AwaitableToken awaitable);
257
258 boost::intrusive_ptr<Impl> impl_;
259};
260
261WaitAnyContext::Handle WaitAnyContext::Append(engine::Awaitable auto& awaitable) {
262 return AppendToken(awaitable.GetAwaitableToken());
263}
264
265WaitAnyContext::Handle WaitAnyContext::Append(std::uint64_t id, engine::Awaitable auto& awaitable) {
266 return AppendToken(id, awaitable.GetAwaitableToken());
267}
268
269/// @ingroup userver_concurrency
270///
271/// @brief Produces a WaitAnyContext for the given awaitables and sequences of awaitables.
272///
273/// Each passed awaitable could be either a single awaitable or a container of awaitables.
274/// In the latter case all awaitables from the container are appended to the context.
275/// The stored awaitables will have ids [0, GetNextId() - 1].
276template <typename... Awaitables>
277WaitAnyContext MakeWaitAny(Awaitables&... awaitables) {
278 auto context = WaitAnyContext();
279 [[maybe_unused]] const auto append_one = [&context](auto& arg) {
280 if constexpr (meta::IsRange<decltype(arg)>) {
281 for (auto& awaitable : arg) {
282 context.Append(awaitable);
283 }
284 } else {
285 context.Append(arg);
286 }
287 };
288 (append_one(awaitables), ...);
289 return context;
290}
291
292} // namespace engine
293
294USERVER_NAMESPACE_END