2 * This file is open source software, licensed to you under the terms
3 * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4 * distributed with this work for additional information regarding copyright
5 * ownership. You may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing,
12 * software distributed under the License is distributed on an
13 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 * KIND, either express or implied. See the License for the
15 * specific language governing permissions and limitations
19 * Copyright (C) 2021-present ScyllaDB
25 #include <type_traits>
27 #include <seastar/core/coroutine.hh>
29 namespace seastar::coroutine {
31 template <typename Future>
32 constexpr inline bool is_future_v = is_future<Future>::value;
34 template <typename Future>
35 concept future_type = is_future_v<Future>;
39 // Given a bunch of futures, find the indexes of the ones that are not avoid
40 // and store them in member type `type` as an std::integer_sequence.
42 // `IndexSequence` and `current` are intermediates used for recursion.
43 template <typename IndexSequence, size_t current, typename... Futures>
44 struct index_sequence_for_non_void_futures_helper;
46 // Terminate recursion be returning the accumulated `IndexSequence`
47 template <typename IndexSequence, size_t current>
48 struct index_sequence_for_non_void_futures_helper<IndexSequence, current> {
49 using type = IndexSequence;
52 // Process a future<T> by adding it to the current IndexSequence and recursing
53 template <size_t... Existing, size_t current, typename T, typename... Futures>
54 struct index_sequence_for_non_void_futures_helper<std::integer_sequence<size_t, Existing...>, current, future<T>, Futures...> {
55 using type = typename index_sequence_for_non_void_futures_helper<std::integer_sequence<size_t, Existing..., current>, current + 1, Futures...>::type;
58 // Process a future<void> by ignoring it and recursing
59 template <size_t... Existing, size_t current, typename... Futures>
60 struct index_sequence_for_non_void_futures_helper<std::integer_sequence<size_t, Existing...>, current, future<>, Futures...> {
61 using type = typename index_sequence_for_non_void_futures_helper<std::integer_sequence<size_t, Existing...>, current + 1, Futures...>::type;
64 // Simple interface for the above.
65 template <typename... Futures>
66 using index_sequence_for_non_void_futures = typename index_sequence_for_non_void_futures_helper<std::integer_sequence<size_t>, 0, Futures...>::type;
68 // Given a tuple of futures, return a tuple of the value types, excluding future<void>.
69 template <typename IndexSequence, typename FutureTuple>
70 struct value_tuple_for_non_void_futures_helper;
72 template <size_t... Idx, typename FutureTuple>
73 struct value_tuple_for_non_void_futures_helper<std::integer_sequence<size_t, Idx...>, FutureTuple> {
74 using type = std::tuple<typename std::tuple_element_t<Idx, FutureTuple>::value_type...>;
77 // Simple interface for the above
78 template <typename... Futures>
79 using value_tuple_for_non_void_futures = typename value_tuple_for_non_void_futures_helper<index_sequence_for_non_void_futures<Futures...>, std::tuple<Futures...>>::type;
83 /// Wait for serveral futures to complete in a coroutine.
85 /// `all` can be used to launch several computations concurrently
86 /// and wait for all of them to complete. Computations are provided
87 /// as callable objects (typically lambda coroutines) that are invoked
88 /// by `all`. Waiting is performend by `co_await` and returns a tuple
89 /// of values, one for each non-void future.
91 /// If one or more of the function objects throws an exception, or if one
92 /// or more of the futures resolves to an exception, then the exception is
93 /// thrown. All of the futures are waited for, even in the case of exceptions.
94 /// If more than one exception is present, an arbitrary one is thrown.
99 /// future<int> add() {
100 /// auto [a, b] = co_await all(
101 /// [] () -> future<int> {
102 /// co_await sleep(1ms);
105 /// [] () -> future<int> {
106 /// co_await sleep(1ms);
113 template <typename... Futures>
114 class [[nodiscard("must co_await an all() object")]] all {
115 using tuple = std::tuple<Futures...>;
116 using value_tuple = typename internal::value_tuple_for_non_void_futures<Futures...>;
118 template <size_t idx>
119 struct intermediate_task final : continuation_base_from_future_t<std::tuple_element_t<idx, tuple>> {
121 explicit intermediate_task(awaiter& container) : container(container) {}
122 virtual void run_and_dispose() noexcept {
123 using value_type = typename std::tuple_element_t<idx, tuple>::value_type;
124 if (__builtin_expect(this->_state.failed(), false)) {
125 using futurator = futurize<std::tuple_element_t<idx, tuple>>;
126 std::get<idx>(container.state._futures) = futurator::make_exception_future(std::move(this->_state).get_exception());
128 if constexpr (std::same_as<std::tuple_element_t<idx, tuple>, future<>>) {
129 std::get<idx>(container.state._futures) = make_ready_future<>();
131 std::get<idx>(container.state._futures) = make_ready_future<value_type>(std::move(this->_state).get0());
134 this->~intermediate_task();
135 container.template process<idx+1>();
138 template <typename IndexSequence>
139 struct generate_aligned_union;
140 template <size_t... idx>
141 struct generate_aligned_union<std::integer_sequence<size_t, idx...>> {
142 using type = std::aligned_union_t<1, intermediate_task<idx>...>;
144 using continuation_storage_t = typename generate_aligned_union<std::make_index_sequence<std::tuple_size_v<tuple>>>::type;
145 using coroutine_handle_t = SEASTAR_INTERNAL_COROUTINE_NAMESPACE::coroutine_handle<void>;
151 continuation_storage_t _continuation_storage;
152 coroutine_handle_t when_ready;
153 awaiter(all& state) : state(state) {}
154 bool await_ready() const {
155 return std::apply([] (const Futures&... futures) {
156 return (... && futures.available());
159 void await_suspend(coroutine_handle_t h) {
163 value_tuple await_resume() {
164 std::apply([] (Futures&... futures) {
165 std::exception_ptr e;
166 // Call get_exception for every failed future, to avoid exceptional future
168 (void)(..., (futures.failed() ? (e = futures.get_exception(), 0) : 0));
170 std::rethrow_exception(std::move(e));
173 // This immediately-invoked lambda is used to materialize the indexes
174 // of non-void futures in the tuple.
175 return [&] <size_t... Idx> (std::integer_sequence<size_t, Idx...>) {
176 return value_tuple(std::get<Idx>(state._futures).get0()...);
177 } (internal::index_sequence_for_non_void_futures<Futures...>());
179 template <unsigned idx>
181 if constexpr (idx == sizeof...(Futures)) {
184 if (!std::get<idx>(state._futures).available()) {
185 auto task = new (&_continuation_storage) intermediate_task<idx>(*this);
186 seastar::internal::set_callback(std::get<idx>(state._futures), task);
194 template <typename... Func>
195 requires (... && std::invocable<Func>) && (... && future_type<std::invoke_result_t<Func>>)
196 explicit all(Func&&... funcs)
197 : _futures(futurize_invoke(funcs)...) {
199 awaiter operator co_await() { return awaiter{*this}; }
202 template <typename... Func>
203 explicit all(Func&&... funcs) -> all<std::invoke_result_t<Func>...>;