userver: userver/concurrent/collect_in_parallel.hpp Source File
Loading...
Searching...
No Matches
collect_in_parallel.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/concurrent/collect_in_parallel.hpp
4/// @brief @copybrief concurrent::CollectInParallel
5
6#include <concepts>
7#include <cstddef>
8#include <cstdint>
9#include <exception>
10#include <functional>
11#include <optional>
12#include <ranges>
13#include <stdexcept>
14#include <type_traits>
15#include <utility>
16#include <vector>
17
18#include <userver/engine/awaitable.hpp>
19#include <userver/engine/exception.hpp>
20#include <userver/engine/task/cancel.hpp>
21#include <userver/engine/wait_any.hpp>
22#include <userver/utils/expected.hpp>
23#include <userver/utils/invoke_with_expected.hpp>
24#include <userver/utils/required.hpp>
25#include <userver/utils/slot_map.hpp>
26
27USERVER_NAMESPACE_BEGIN
28
29namespace concurrent {
30
32 kContinue, ///< Collect individual errors and process all inputs.
33 kFailFast, ///< Stop starting inputs, clean up in-flight work, and rethrow the first observed error.
34};
35
36/// @brief Settings for @ref concurrent::CollectInParallel.
37struct ParallelCollectSettings final {
38 /// Maximum number of in-flight operations. Must be explicitly set to a positive value.
39 utils::Required<std::size_t> max_parallel_tasks;
40 /// Whether to collect individual errors or stop on the first observed error.
42};
43
44namespace impl {
45
46template <typename Future>
47concept CollectableFuture =
48 std::is_object_v<Future> && std::move_constructible<Future> && engine::Awaitable<Future> &&
49 (requires(Future& future) { future.Get(); } || requires(Future& future) { future.get(); });
50
51template <CollectableFuture Future>
52decltype(auto) GetCollectedValue(Future& future) {
53 if constexpr (requires { future.Get(); }) {
54 return future.Get();
55 } else {
56 return future.get();
57 }
58}
59
60template <CollectableFuture Future>
61using CollectedValue = std::decay_t<decltype(GetCollectedValue(std::declval<Future&>()))>;
62
63inline std::uint64_t WaitForCollectedTask(engine::WaitAnyContext& wait_any) {
64 const auto ready = wait_any.Wait();
65 if (ready.has_value()) {
66 return ready.value();
67 }
68 switch (ready.error()) {
71 throw std::logic_error("Parallel collector wait interrupted without pending cancellation");
72 case engine::WaitAnyError::kEmpty:
73 throw std::logic_error("Parallel collector has no in-flight operations");
74 case engine::WaitAnyError::kTimeout:
75 throw std::logic_error("Parallel collector unexpectedly timed out");
76 }
77 throw std::logic_error("Unknown parallel collector wait error");
78}
79
80template <CollectableFuture Future>
81auto CollectResult(Future& future) {
82 auto result = utils::InvokeWithExpected([&future]() -> decltype(auto) { return GetCollectedValue(future); });
83 if (!result) {
85 }
86 return result;
87}
88
89template <typename InputReference, typename Start>
90class ParallelCollector final {
91 using Future = std::invoke_result_t<const Start&, InputReference>;
92 using Outcome = utils::expected<CollectedValue<Future>, std::exception_ptr>;
93 struct InFlight {
94 std::size_t result_index{};
95 std::optional<Future> future{};
96 };
97
98public:
99 ParallelCollector(std::size_t concurrency, const Start& start, CollectFailurePolicy failure_policy)
100 : concurrency_(concurrency),
101 start_(start),
102 failure_policy_(failure_policy)
103 {}
104
105 template <std::ranges::input_range Range>
106 std::vector<Outcome> Run(Range&& range) {
107 if constexpr (std::ranges::sized_range<Range>) {
108 results_.reserve(std::ranges::size(range));
109 }
110 for (auto&& input : range) {
112 StartOne(std::forward<decltype(input)>(input));
113 if (tasks_.size() < concurrency_) {
114 continue;
115 }
116 CollectOne();
117 }
118 while (!tasks_.empty()) {
119 CollectOne();
120 }
121 return TakeResults();
122 }
123
124private:
125 void StartOne(InputReference&& input) {
126 const auto result_index = results_.size();
127 results_.emplace_back();
128 auto [request, index] = tasks_.emplace(InFlight{.result_index = result_index});
129 auto started = utils::InvokeWithExpected([this, &request, &input] {
130 request.future.emplace(std::invoke(start_, std::forward<InputReference>(input)));
131 });
132 if (!started) {
134 auto error = std::move(started.error());
135 if (failure_policy_ == CollectFailurePolicy::kFailFast) {
136 tasks_.erase(index);
137 CancelAndWait();
138 std::rethrow_exception(error);
139 }
140 results_[result_index].emplace(utils::unexpected(std::move(error)));
141 tasks_.erase(index);
142 return;
143 }
144 wait_any_.Append(index, request.future.value());
145 }
146
147 void CollectOne() {
148 const auto index = WaitForCollectedTask(wait_any_);
149 auto& request = tasks_[index];
150 auto result = CollectResult(request.future.value());
151 if (!result && failure_policy_ == CollectFailurePolicy::kFailFast) {
152 const auto error = std::move(result.error());
153 tasks_.erase(index);
154 CancelAndWait();
155 std::rethrow_exception(error);
156 }
157 results_[request.result_index].emplace(std::move(result));
158 tasks_.erase(index);
159 }
160
161 std::vector<Outcome> TakeResults() {
162 std::vector<Outcome> results;
163 results.reserve(results_.size());
164 for (auto& result : results_) {
165 results.push_back(std::move(result).value());
166 }
167 return results;
168 }
169
170 void CancelPending() {
171 if constexpr (
172 !requires(Future& future) { future.RequestCancel(); } &&
173 !requires(Future& future) { future.Cancel(); }
174 )
175 {
176 return;
177 }
178 for (auto& request : tasks_.AliveItems()) {
179 try {
180 if constexpr (requires(Future& future) { future.RequestCancel(); }) {
181 request.future.value().RequestCancel();
182 } else if constexpr (requires(Future& future) { future.Cancel(); }) {
183 request.future.value().Cancel();
184 }
185 // Keep the future alive until WaitPending() drains its awaitable token.
186 } catch (const std::exception&) {
187 // Preserve the original error if cancellation itself fails.
188 }
189 }
190 }
191
192 void WaitPending() {
193 // TODO: implement a WaitAll primitive and use it here to wait for cancelled tasks.
194 // Wait for completion without retrieving results or rethrowing operation errors.
195 while (wait_any_.GetSize() != 0) {
196 [[maybe_unused]] const auto ready = WaitForCollectedTask(wait_any_);
197 }
198 }
199
200 void CancelAndWait() noexcept {
201 const engine::TaskCancellationBlocker cancellation_blocker;
202 CancelPending();
203 WaitPending();
204 }
205
206 const std::size_t concurrency_;
207 const Start& start_;
208 const CollectFailurePolicy failure_policy_;
209 std::vector<std::optional<Outcome>> results_;
210 utils::SlotMap<InFlight> tasks_;
211 // Destroy the wait context before the futures whose tokens it references.
212 engine::WaitAnyContext wait_any_;
213};
214
215} // namespace impl
216
217/// @ingroup userver_concurrency
218///
219/// @brief Collect results from lazily started operations with bounded concurrency.
220///
221/// Maintains a sliding window of in-flight operations: whenever an operation is collected,
222/// its slot can be reused without waiting for earlier inputs. Calls @p start at most once
223/// per input, without retries. Duplicate inputs are processed independently.
224///
225/// @param input_range Input range. Elements are forwarded to the factory as
226/// `std::ranges::range_reference_t<Range>` without copying or storing them.
227/// @param settings Concurrency limit and failure policy. See @ref concurrent::ParallelCollectSettings.
228/// @param start Factory invoked with each range element, preserving its reference type and
229/// value category, in the calling task. Returns an
230/// owning @ref engine::Awaitable with a `Get()` or `get()` method, such as @ref engine::TaskWithResult,
231/// @ref engine::Future, or a generated HTTP response future. If both methods exist, `Get()` is used.
232/// The factory controls task creation, tracing, timeouts, and client retry settings.
233///
234/// @returns A vector of @ref utils::expected values in input order, each containing either
235/// the operation's result or a `std::exception_ptr` preserving the exception's dynamic type.
236/// Completion order does not affect result order. Supports void and move-only results.
237/// For a reusable input range, callers can associate inputs and results by index or zip them.
238///
239/// @par Failure handling
240/// With @ref concurrent::CollectFailurePolicy::kContinue, `std::exception`-based errors from the factory
241/// and `Get()`/`get()` are collected and all inputs are processed.
242/// With @ref concurrent::CollectFailurePolicy::kFailFast, the first observed `std::exception` stops new launches.
243/// Pending operations receive `RequestCancel()` when available, otherwise `Cancel()` when
244/// available. Futures remain alive until all waits on their tokens have finished.
245/// Pending operations are awaited via @ref engine::WaitAnyContext without retrieving
246/// their results. Task cancellation is blocked during cleanup. Errors from cancellation requests
247/// derived from `std::exception` are ignored; the original exception is rethrown and no partial
248/// results are returned. Future types do not need to provide `Wait()` or `wait()`.
249///
250/// @warning Fail-fast cleanup can still block while awaiting non-cancellable work or tasks
251/// that do not respond to cancellation. Configure operation timeouts in @p start.
252///
253/// @par Cancellation and lifetimes
254/// Parent cancellation and non-std exceptions propagate under either policy. During stack
255/// unwinding, outstanding awaitables are destroyed according to their own RAII semantics.
256/// Work started by the factory must manage its lifetime accordingly. When capturing input
257/// references in asynchronous work, the caller must ensure that the referenced elements remain
258/// valid until that work finishes. Single-pass and lazy ranges may invalidate references when
259/// advanced; copy or move such inputs into the operation before the factory returns. A copied
260/// non-owning input (such as `std::string_view`) does not extend the lifetime of its referent.
261///
262/// @throws `std::invalid_argument` If `settings.max_parallel_tasks` is zero, even for an empty range.
263/// @throws `std::exception` The first observed operation error in fail-fast mode, with its
264/// original dynamic type. Infrastructure errors may propagate under either policy.
265///
266/// @par Examples
267/// Collecting move-only task results, including duplicate inputs:
268/// @snippet core/src/concurrent/collect_in_parallel_test.cpp sample CollectInParallel tasks
269/// Collecting individual startup and task errors with the default continue policy
270/// (`LookupError` is the test's exception type):
271/// @snippet core/src/concurrent/collect_in_parallel_test.cpp sample CollectInParallel continue
272/// Stopping on a startup error and skipping the remaining inputs:
273/// @snippet core/src/concurrent/collect_in_parallel_test.cpp sample CollectInParallel fail fast
274template <std::ranges::input_range Range, typename Start>
275requires std::invocable<const Start&, std::ranges::range_reference_t<Range>> &&
289
290} // namespace concurrent
291
292USERVER_NAMESPACE_END