Skip to content

Commit 054078f

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 acd5720 commit 054078f

File tree

2 files changed

+306
-0
lines changed

2 files changed

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

tests/unit/coroutines_test.cc

Lines changed: 161 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,161 @@ 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 <typename T>
1071+
struct result_wrapper {
1072+
T value;
1073+
explicit result_wrapper(T v) : value(v) {}
1074+
};
1075+
1076+
template <>
1077+
struct result_wrapper<seastar::internal::monostate> {
1078+
};
1079+
1080+
template <bool CheckPreempt, std::invocable<> F>
1081+
// Use result_wrapper to create a mismatch between the return type of
1082+
// the coroutine and that of the underlying function, to ensure that
1083+
// try_future handles this case correctly.
1084+
future<result_wrapper<typename std::invoke_result_t<F>::value_type>>
1085+
do_run_try_future_test(F underlying_func, int& ctor_dtor_counter, bool& run_past) {
1086+
const auto check_cxx_exceptions_on_exit = seastar::defer([cxx_exception_before = seastar::engine().cxx_exceptions()] () noexcept {
1087+
if (seastar::engine().cxx_exceptions() != cxx_exception_before) {
1088+
// We are in a destructor, cannot throw
1089+
std::abort();
1090+
}
1091+
});
1092+
1093+
dummy d1{ctor_dtor_counter};
1094+
dummy d2{ctor_dtor_counter};
1095+
1096+
std::vector<dummy> dummies;
1097+
for (unsigned i = 0; i < 10; ++i) {
1098+
dummies.emplace_back(ctor_dtor_counter);
1099+
}
1100+
1101+
BOOST_REQUIRE_GT(ctor_dtor_counter, 0);
1102+
1103+
using return_future_type = std::invoke_result_t<F>;
1104+
using return_type = typename return_future_type::value_type;
1105+
constexpr bool is_void = std::is_same_v<return_future_type, future<>>;
1106+
1107+
std::any ret;
1108+
1109+
try {
1110+
if constexpr (is_void) {
1111+
if constexpr (CheckPreempt) {
1112+
co_await seastar::coroutine::try_future(underlying_func());
1113+
} else {
1114+
co_await seastar::coroutine::try_future_without_preemption_check(underlying_func());
1115+
}
1116+
} else {
1117+
if constexpr (CheckPreempt) {
1118+
ret = co_await seastar::coroutine::try_future(underlying_func());
1119+
} else {
1120+
ret = co_await seastar::coroutine::try_future_without_preemption_check(underlying_func());
1121+
}
1122+
}
1123+
run_past = true;
1124+
} catch (...) {
1125+
BOOST_FAIL(fmt::format("Exception should be handled in try_future, bug caught: {}", std::current_exception()));
1126+
}
1127+
1128+
if constexpr (is_void) {
1129+
co_return result_wrapper<seastar::internal::monostate>{};
1130+
} else {
1131+
co_return result_wrapper(std::any_cast<return_type>(ret));
1132+
}
1133+
}
1134+
1135+
template <bool CheckPreempt, std::invocable<> F>
1136+
future<> run_try_future_test(F underlying_func, std::optional<std::any> expected_value, std::source_location sl = std::source_location::current()) {
1137+
fmt::print("running test case at {}:{}\n", sl.file_name(), sl.line());
1138+
1139+
int ctor_dtor_counter{0};
1140+
bool run_past{false};
1141+
1142+
const bool throws = !expected_value.has_value();
1143+
1144+
using return_future_type = std::invoke_result_t<F>;
1145+
using return_type = typename return_future_type::value_type;
1146+
constexpr bool is_void = std::is_same_v<return_future_type, future<>>;
1147+
1148+
try {
1149+
if constexpr (is_void) {
1150+
co_await do_run_try_future_test<CheckPreempt>(std::move(underlying_func), ctor_dtor_counter, run_past);
1151+
BOOST_REQUIRE(expected_value);
1152+
} else {
1153+
auto res = co_await do_run_try_future_test<CheckPreempt>(std::move(underlying_func), ctor_dtor_counter, run_past);
1154+
BOOST_REQUIRE(expected_value);
1155+
BOOST_REQUIRE_EQUAL(res.value, std::any_cast<return_type>(*expected_value));
1156+
}
1157+
} catch (test_exception&) {
1158+
BOOST_REQUIRE(throws);
1159+
} catch (...) {
1160+
BOOST_FAIL(fmt::format("Unexpected exception {}", std::current_exception()));
1161+
}
1162+
1163+
BOOST_REQUIRE_EQUAL(run_past, !throws);
1164+
BOOST_REQUIRE_EQUAL(ctor_dtor_counter, 0);
1165+
}
1166+
1167+
SEASTAR_TEST_CASE(test_try_future) {
1168+
co_await run_try_future_test<true>(return_void, std::any{});
1169+
co_await run_try_future_test<false>(return_void, std::any{});
1170+
co_await run_try_future_test<true>(return_ex_void, std::nullopt);
1171+
co_await run_try_future_test<false>(return_ex_void, std::nullopt);
1172+
co_await run_try_future_test<true>(throw_void, std::nullopt);
1173+
co_await run_try_future_test<false>(throw_void, std::nullopt);
1174+
1175+
co_await run_try_future_test<true>(return_int, 128);
1176+
co_await run_try_future_test<false>(return_int, 128);
1177+
co_await run_try_future_test<true>(return_ex_int, std::nullopt);
1178+
co_await run_try_future_test<false>(return_ex_int, std::nullopt);
1179+
co_await run_try_future_test<true>(throw_int, std::nullopt);
1180+
co_await run_try_future_test<false>(throw_int, std::nullopt);
1181+
}

0 commit comments

Comments
 (0)