Skip to content

Commit fb8c155

Browse files
committed
coroutine: introduce try_future
Special awaiter which co_await:s a future and returns the wrapped result if successful, terminates the coroutine otherwise, propagating the exception directly to its waiter. If the future was successful, this is identical to co_await-ing the future directly. If the future failed, the coroutine is not resumed and instead the exception from the future is forwarded to the waiter directly and the coroutine is destroyed. The goal of this special awaiter is to provide the good ergonomics of throw -- interrupting control flow and immediately propagating the exception to the caler -- without the associated costs. The exception is propagated via the future chain, without being thrown.
1 parent a2665f3 commit fb8c155

File tree

2 files changed

+291
-0
lines changed

2 files changed

+291
-0
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
/*
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.
6+
*
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
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
16+
* under the License.
17+
*/
18+
/*
19+
* Copyright (C) 2025-present ScyllaDB
20+
*/
21+
22+
#pragma once
23+
24+
#include <seastar/core/coroutine.hh>
25+
26+
namespace seastar::internal {
27+
28+
template <typename T, typename U>
29+
void try_future_resume_or_destroy_coroutine(seastar::future<T>& fut, seastar::task& coroutine_task) {
30+
auto promise_ptr = static_cast<seastar::internal::coroutine_traits_base<T>::promise_type*>(&coroutine_task);
31+
auto hndl = std::coroutine_handle<U>::from_promise(*promise_ptr);
32+
33+
if (!fut.failed()) {
34+
hndl.resume();
35+
return;
36+
}
37+
38+
hndl.promise().set_exception(std::move(fut).get_exception());
39+
hndl.destroy();
40+
}
41+
42+
template <bool CheckPreempt, typename T>
43+
class [[nodiscard]] try_future_awaiter : public seastar::task {
44+
seastar::future<T> _future;
45+
void (*_resume_or_destroy)(seastar::future<T>&, seastar::task&){};
46+
seastar::task* _coroutine_task{};
47+
seastar::task* _waiting_task{};
48+
49+
public:
50+
explicit try_future_awaiter(seastar::future<T>&& f) noexcept : _future(std::move(f)) {}
51+
52+
try_future_awaiter(const try_future_awaiter&) = delete;
53+
try_future_awaiter(try_future_awaiter&&) = delete;
54+
55+
bool await_ready() const noexcept {
56+
// Will suspend+schedule for ready failed futures too.
57+
return _future.available() && !_future.failed() && (!CheckPreempt || !need_preempt());
58+
}
59+
60+
template<typename U>
61+
void await_suspend(std::coroutine_handle<U> hndl) noexcept {
62+
_resume_or_destroy = try_future_resume_or_destroy_coroutine<T, U>;
63+
_coroutine_task = &hndl.promise();
64+
_waiting_task = hndl.promise().waiting_task();
65+
66+
if (!_future.available()) {
67+
_future.set_coroutine(*this);
68+
} else {
69+
schedule(this);
70+
}
71+
}
72+
73+
T await_resume() {
74+
if constexpr (std::is_void_v<T>) {
75+
_future.get();
76+
} else {
77+
return std::move(_future).get();
78+
}
79+
}
80+
81+
virtual void run_and_dispose() noexcept override {
82+
_resume_or_destroy(_future, *_coroutine_task);
83+
}
84+
85+
virtual task* waiting_task() noexcept override {
86+
return _waiting_task;
87+
}
88+
};
89+
90+
} // namespace seastar::internal
91+
92+
namespace seastar::coroutine {
93+
94+
/// \brief co_await:s a \ref future and returns the wrapped result if successful,
95+
/// terminates the coroutine otherwise, propagating the exception directly to the
96+
/// waiter.
97+
///
98+
/// If the future was successful, this is identical to co_await-ing the future
99+
/// directly. If the future failed, the coroutine is not resumed and instead the
100+
/// exception from the future is forwarded to the waiter directly and the
101+
/// coroutine is destroyed.
102+
///
103+
/// For example:
104+
/// ```
105+
/// // Function careful to not throw exceptions, instead returning failed futures.
106+
/// future<int> bar() {
107+
/// if (something_bad_happened) {
108+
/// return make_exception_future<>(std::runtime_error("error"));
109+
/// }
110+
/// return result;
111+
/// }
112+
///
113+
/// future<> foo() {
114+
/// auto result = co_await coroutine::try_future(bar());
115+
/// // This code is only executed if bar() returned a successful future.
116+
/// // Otherwise the exception is forwarded to the waiter future directly
117+
/// // and the coroutine is destroyed.
118+
/// check_result(result);
119+
/// }
120+
/// ```
121+
///
122+
/// Note that by default, `try_future` checks for if the task quota is depleted,
123+
/// which means that it will yield if the future is ready and \ref seastar::need_preempt()
124+
/// returns true. Use \ref coroutine::try_future_without_preemption_check
125+
/// to disable preemption checking.
126+
template<typename T = void>
127+
class [[nodiscard]] try_future : public seastar::internal::try_future_awaiter<true, T> {
128+
public:
129+
explicit try_future(seastar::future<T>&& f) noexcept
130+
: seastar::internal::try_future_awaiter<true, T>(std::move(f))
131+
{}
132+
};
133+
134+
/// \brief co_await:s a \ref future, returns the wrapped result if successful,
135+
/// terminates the coroutine otherwise, propagating the exception to the waiter.
136+
///
137+
/// Same as \ref coroutine::try_future, but does not check for preemption.
138+
template<typename T = void>
139+
class [[nodiscard]] try_future_without_preemption_check : public seastar::internal::try_future_awaiter<false, T> {
140+
public:
141+
explicit try_future_without_preemption_check(seastar::future<T>&& f) noexcept
142+
: seastar::internal::try_future_awaiter<false, T>(std::move(f))
143+
{}
144+
};
145+
146+
} // namespace seastar::coroutine

tests/unit/coroutines_test.cc

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <exception>
2323
#include <numeric>
2424
#include <ranges>
25+
#include <any>
2526

2627
#include <seastar/core/circular_buffer.hh>
2728
#include <seastar/core/coroutine.hh>
@@ -35,8 +36,10 @@
3536
#include <seastar/coroutine/as_future.hh>
3637
#include <seastar/coroutine/exception.hh>
3738
#include <seastar/coroutine/generator.hh>
39+
#include <seastar/coroutine/try_future.hh>
3840
#include <seastar/testing/random.hh>
3941
#include <seastar/testing/test_case.hh>
42+
#include <seastar/util/defer.hh>
4043
#include <seastar/util/later.hh>
4144

4245
using seastar::broken_promise;
@@ -1018,3 +1021,145 @@ SEASTAR_TEST_CASE(test_lambda_coroutine_in_continuation) {
10181021
}));
10191022
BOOST_REQUIRE_EQUAL(sin1, sin2);
10201023
}
1024+
1025+
class test_exception : std::exception { };
1026+
1027+
future<> throw_void() {
1028+
fmt::print("throw_void()\n");
1029+
co_await sleep(1ms);
1030+
throw test_exception{};
1031+
}
1032+
1033+
future<> return_ex_void() {
1034+
fmt::print("return_ex_void()\n");
1035+
return make_exception_future<>(test_exception{});
1036+
}
1037+
1038+
future<> return_void() {
1039+
fmt::print("return_void()\n");
1040+
co_await sleep(1ms);
1041+
}
1042+
1043+
future<int> throw_int() {
1044+
fmt::print("throw_int()\n");
1045+
co_await sleep(1ms);
1046+
throw test_exception{};
1047+
}
1048+
1049+
future<int> return_ex_int() {
1050+
fmt::print("return_ex_int()\n");
1051+
return make_exception_future<int>(test_exception{});
1052+
}
1053+
1054+
future<int> return_int() {
1055+
fmt::print("return_int()\n");
1056+
co_await sleep(1ms);
1057+
co_return 128;
1058+
}
1059+
1060+
class dummy {
1061+
int& _c;
1062+
1063+
public:
1064+
explicit dummy(int& c) : _c(c) { ++_c; }
1065+
dummy(const dummy& o) : _c(o._c) { ++_c; }
1066+
dummy(dummy&&) = delete;
1067+
~dummy() { --_c; }
1068+
};
1069+
1070+
template <bool CheckPreempt, std::invocable<> F>
1071+
std::invoke_result_t<F> do_run_try_future_test(F underlying_func, int& ctor_dtor_counter, bool& run_past) {
1072+
const auto check_cxx_exceptions_on_exit = seastar::defer([cxx_exception_before = seastar::engine().cxx_exceptions()] () noexcept {
1073+
if (seastar::engine().cxx_exceptions() != cxx_exception_before) {
1074+
// We are in a destructor, cannot throw
1075+
std::abort();
1076+
}
1077+
});
1078+
1079+
dummy d1{ctor_dtor_counter};
1080+
dummy d2{ctor_dtor_counter};
1081+
1082+
std::vector<dummy> dummies;
1083+
for (unsigned i = 0; i < 10; ++i) {
1084+
dummies.emplace_back(ctor_dtor_counter);
1085+
}
1086+
1087+
BOOST_REQUIRE_GT(ctor_dtor_counter, 0);
1088+
1089+
using return_future_type = std::invoke_result_t<F>;
1090+
using return_type = typename return_future_type::value_type;
1091+
constexpr bool is_void = std::is_same_v<return_future_type, future<>>;
1092+
1093+
std::any ret;
1094+
1095+
try {
1096+
if constexpr (is_void) {
1097+
if constexpr (CheckPreempt) {
1098+
co_await seastar::coroutine::try_future(underlying_func());
1099+
} else {
1100+
co_await seastar::coroutine::try_future_without_preemption_check(underlying_func());
1101+
}
1102+
} else {
1103+
if constexpr (CheckPreempt) {
1104+
ret = co_await seastar::coroutine::try_future(underlying_func());
1105+
} else {
1106+
ret = co_await seastar::coroutine::try_future_without_preemption_check(underlying_func());
1107+
}
1108+
}
1109+
run_past = true;
1110+
} catch (...) {
1111+
BOOST_FAIL(fmt::format("Exception should be handled in try_future, bug caught: {}", std::current_exception()));
1112+
}
1113+
1114+
if constexpr (!is_void) {
1115+
co_return std::any_cast<return_type>(ret);
1116+
}
1117+
}
1118+
1119+
template <bool CheckPreempt, std::invocable<> F>
1120+
future<> run_try_future_test(F underlying_func, std::optional<std::any> expected_value, std::source_location sl = std::source_location::current()) {
1121+
fmt::print("running test case at {}:{}\n", sl.file_name(), sl.line());
1122+
1123+
int ctor_dtor_counter{0};
1124+
bool run_past{false};
1125+
1126+
const bool throws = !expected_value.has_value();
1127+
1128+
using return_future_type = std::invoke_result_t<F>;
1129+
using return_type = typename return_future_type::value_type;
1130+
constexpr bool is_void = std::is_same_v<return_future_type, future<>>;
1131+
1132+
try {
1133+
if constexpr (is_void) {
1134+
co_await do_run_try_future_test<CheckPreempt>(std::move(underlying_func), ctor_dtor_counter, run_past);
1135+
BOOST_REQUIRE(expected_value);
1136+
} else {
1137+
auto value = co_await do_run_try_future_test<CheckPreempt>(std::move(underlying_func), ctor_dtor_counter, run_past);
1138+
BOOST_REQUIRE(expected_value);
1139+
BOOST_REQUIRE_EQUAL(value, std::any_cast<return_type>(*expected_value));
1140+
}
1141+
} catch (test_exception&) {
1142+
BOOST_REQUIRE(throws);
1143+
} catch (...) {
1144+
BOOST_FAIL(fmt::format("Unexpected exception {}", std::current_exception()));
1145+
}
1146+
1147+
BOOST_REQUIRE_EQUAL(run_past, !throws);
1148+
BOOST_REQUIRE_EQUAL(ctor_dtor_counter, 0);
1149+
}
1150+
1151+
SEASTAR_TEST_CASE(test_try_future) {
1152+
co_await run_try_future_test<true>(return_void, std::any{});
1153+
co_await run_try_future_test<false>(return_void, std::any{});
1154+
co_await run_try_future_test<true>(return_ex_void, std::nullopt);
1155+
co_await run_try_future_test<false>(return_ex_void, std::nullopt);
1156+
co_await run_try_future_test<true>(throw_void, std::nullopt);
1157+
co_await run_try_future_test<false>(throw_void, std::nullopt);
1158+
1159+
co_await run_try_future_test<true>(return_int, 128);
1160+
co_await run_try_future_test<false>(return_int, 128);
1161+
co_await run_try_future_test<true>(return_ex_int, std::nullopt);
1162+
co_await run_try_future_test<false>(return_ex_int, std::nullopt);
1163+
co_await run_try_future_test<true>(throw_int, std::nullopt);
1164+
co_await run_try_future_test<false>(throw_int, std::nullopt);
1165+
}

0 commit comments

Comments
 (0)