27#ifndef A11_CONCURRENCY_FUTURE_H_
28#define A11_CONCURRENCY_FUTURE_H_
38#include <absl/base/nullability.h>
39#include <absl/functional/any_invocable.h>
40#include <absl/log/log.h>
41#include <absl/status/status.h>
42#include <absl/status/statusor.h>
43#include <absl/time/clock.h>
44#include <absl/time/time.h>
48#include "thread/fiber.h"
49#include "thread/select.h"
50#include "thread/selectables.h"
70 std::unique_ptr<thread::CondVar> cv ABSL_GUARDED_BY(mu);
71 std::optional<absl::StatusOr<T>>
result ABSL_GUARDED_BY(mu);
72 std::function<void()> cancel ABSL_GUARDED_BY(mu);
73 std::unique_ptr<thread::PermanentEvent>
event ABSL_GUARDED_BY(mu);
74 std::vector<absl::AnyInvocable<void(
const absl::StatusOr<T>&)>> callbacks
80 absl::AnyInvocable<
void(
const absl::StatusOr<T>&)> callback,
81 const absl::StatusOr<T>&
result) {
86 [&] { callback(
result); },
"Future completion callback");
88 LOG(ERROR) << raised.message();
105 absl::AnyInvocable<absl::StatusOr<T>() &&> work,
106 std::function<
void()> cancellation_hook,
107 thread::TreeOptions tree_options = {});
110Future<T>
Submit(absl::AnyInvocable<absl::StatusOr<T>() &&> work,
111 thread::TreeOptions tree_options = {});
130 [[nodiscard]]
bool valid()
const {
return state_ !=
nullptr; }
134 if (state_ ==
nullptr) {
138 return state_->result.has_value();
147 if (state_ ==
nullptr) {
148 return absl::FailedPreconditionError(
"Future is not valid");
150 std::function<void()> cancel;
153 if (state_->result.has_value()) {
154 return absl::OkStatus();
156 cancel = state_->cancel;
159 if (cancel ==
nullptr) {
160 return absl::UnimplementedError(
161 "This Future does not have a cancellation source");
173 absl::StatusOr<T>
Await(absl::Time deadline = absl::InfiniteFuture())
const {
174 if (state_ ==
nullptr) {
175 return absl::FailedPreconditionError(
"Future is not valid");
179 if (state_->result.has_value()) {
180 return *state_->result;
187 if (thread::GetPerThreadFiberPtr() !=
nullptr) {
188 thread::PermanentEvent* event;
191 if (state_->result.has_value()) {
192 return *state_->result;
194 if (state_->event ==
nullptr) {
195 state_->event = std::make_unique<thread::PermanentEvent>();
197 event = state_->event.get();
200 thread::SelectUntil(deadline, {thread::OnCancel(),
event->OnEvent()});
202 return absl::CancelledError(
"Future wait cancelled");
205 return absl::DeadlineExceededError(
206 "Future was not ready before deadline");
210 while (!state_->result.has_value()) {
211 if (state_->cv ==
nullptr) {
212 state_->cv = std::make_unique<thread::CondVar>();
214 if (state_->cv->WaitWithDeadline(&state_->mu, deadline) &&
215 !state_->result.has_value()) {
216 return absl::DeadlineExceededError(
217 "Future was not ready before deadline");
220 return *state_->result;
224 if (!state_->result.has_value()) {
225 return absl::InternalError(
"Future wake-up did not publish a result");
227 return *state_->result;
237 absl::AnyInvocable<
void(
const absl::StatusOr<T>&)> callback)
const {
238 if (callback ==
nullptr) {
241 if (state_ ==
nullptr) {
242 const absl::StatusOr<T> invalid =
243 absl::FailedPreconditionError(
"Future is not valid");
244 internal::InvokeFutureCallback<T>(std::move(callback), invalid);
247 const absl::StatusOr<T>* absl_nullable ready_result =
nullptr;
250 if (!state_->result.has_value()) {
251 state_->callbacks.push_back(std::move(callback));
254 ready_result = &*state_->result;
256 internal::InvokeFutureCallback<T>(std::move(callback), *ready_result);
260 void SetCancellationCallbackForExecutor(std::function<
void()> cancel) {
261 if (state_ ==
nullptr) {
265 if (!state_->result.has_value()) {
266 state_->cancel = std::move(cancel);
270 explicit Future(std::shared_ptr<internal::FutureState<T>> state)
271 : state_(std::move(state)) {}
273 std::shared_ptr<internal::FutureState<T>> state_;
276 template <
typename U>
278 thread::TreeOptions tree_options);
279 template <
typename U>
281 absl::AnyInvocable<absl::StatusOr<U>() &&> work,
282 std::function<
void()> cancellation_hook,
283 thread::TreeOptions tree_options);
297 Promise() : state_(std::make_shared<internal::FutureState<T>>()) {}
307 if (
this != &other) {
309 state_ = std::move(other.state_);
321 if (state_ ==
nullptr) {
322 return absl::FailedPreconditionError(
"Promise is not valid");
325 if (state_->result.has_value()) {
326 return absl::FailedPreconditionError(
"Promise is already complete");
328 state_->cancel = std::move(cancel);
329 return absl::OkStatus();
340 return absl::InvalidArgumentError(
341 "SetStatus requires a non-OK status; use SetValue for success");
344 result.AssignStatus(std::move(status));
350 if (state_ ==
nullptr) {
351 return absl::FailedPreconditionError(
"Promise is not valid");
353 std::vector<absl::AnyInvocable<void(
const absl::StatusOr<T>&)>> callbacks;
354 const absl::StatusOr<T>* absl_nullable published =
nullptr;
355 thread::PermanentEvent*
event =
nullptr;
356 thread::CondVar* cv =
nullptr;
359 if (state_->result.has_value()) {
360 return absl::AlreadyExistsError(
"Promise has already been completed");
362 state_->result.emplace(std::move(
result));
364 published = &*state_->result;
365 event = state_->event.get();
366 cv = state_->cv.get();
367 callbacks.swap(state_->callbacks);
369 if (event !=
nullptr) {
375 for (
auto& callback : callbacks) {
376 internal::InvokeFutureCallback<T>(std::move(callback), *published);
378 return absl::OkStatus();
383 if (state_ ==
nullptr) {
386 bool complete =
false;
389 complete = state_->result.has_value();
396 SetStatus(absl::CancelledError(
"Promise was abandoned")).IgnoreError();
400 std::shared_ptr<internal::FutureState<T>> state_;
426 promise.
SetStatus(std::move(status)).IgnoreError();
441 return FailedFuture<Unit>(std::move(status));
466template <
typename T,
typename Fn>
468 typename std::invoke_result_t<Fn, const absl::StatusOr<T>&>::value_type> {
469 using Result = std::invoke_result_t<Fn, const absl::StatusOr<T>&>;
470 using U =
typename Result::value_type;
472 if (future.IsReady()) {
473 return CompletedFuture<U>(transform(future.Await()));
481 [promise = std::move(promise), transform = std::move(transform)](
482 const absl::StatusOr<T>&
result)
mutable {
a11::Promise< a11::Unit > result
Definition async_node.cc:56
Shared handle to one asynchronous result.
Definition future.h:125
absl::StatusOr< T > Await(absl::Time deadline=absl::InfiniteFuture()) const
Wait for and return the result up to an absolute deadline.
Definition future.h:173
bool IsReady() const
Whether the producer has published either a value or an error.
Definition future.h:133
friend Future< U > Submit(absl::AnyInvocable< absl::StatusOr< U >() && > work, thread::TreeOptions tree_options)
absl::Status Cancel() const
Request cancellation from the operation producing this result.
Definition future.h:146
friend Future< U > SubmitWithCancellationHook(absl::AnyInvocable< absl::StatusOr< U >() && > work, std::function< void()> cancellation_hook, thread::TreeOptions tree_options)
bool valid() const
Whether this handle refers to shared completion state.
Definition future.h:130
void OnReady(absl::AnyInvocable< void(const absl::StatusOr< T > &)> callback) const
Run callback once when the result becomes available.
Definition future.h:236
Move-only producer for a Future result.
Definition future.h:295
absl::Status SetValue(T value)
Complete successfully with value.
Definition future.h:333
absl::Status SetStatus(absl::Status status)
Complete with a non-OK status.
Definition future.h:338
absl::Status SetResult(absl::StatusOr< T > result)
Complete with either a value or an error, waking every observer.
Definition future.h:349
Future< T > future() const
Return a consumer handle sharing this promise's completion state.
Definition future.h:317
Promise()
Definition future.h:297
Promise(Promise &&other) noexcept
Transfer responsibility for completing or abandoning the shared state.
Definition future.h:303
~Promise()
Definition future.h:314
absl::Status SetCancellationCallback(std::function< void()> cancel)
Install the operation invoked when a consumer calls Future::Cancel().
Definition future.h:320
Promise & operator=(const Promise &)=delete
Promise & operator=(Promise &&other) noexcept
Abandon this state, then take responsibility for other's state.
Definition future.h:306
Promise(const Promise &)=delete
Definition boost_primitives.h:28
Definition boost_primitives.h:21
std::string value
Definition discover.cc:100
Turns what a caller's callable throws into a Status, at the boundary.
thread::Mutex mu
Definition executor.cc:32
absl::Status Attempt(Callable &&callable, std::string_view what)
Runs callable, reporting anything it throws as a Status.
Definition exception_guard.h:114
void InvokeFutureCallback(absl::AnyInvocable< void(const absl::StatusOr< T > &)> callback, const absl::StatusOr< T > &result)
Definition future.h:79
Task FailedTask(absl::Status status)
Return an already-failed Task.
Definition future.h:440
auto Then(const Future< T > &future, Fn transform) -> Future< typename std::invoke_result_t< Fn, const absl::StatusOr< T > & >::value_type >
Continue with transform once future completes, without a fiber.
Definition future.h:467
Future< T > FailedFuture(absl::Status status)
Return an already-failed future containing status.
Definition future.h:423
Future< T > ReadyFuture(T value)
Return an already-successful future containing value.
Definition future.h:405
Task ReadyTask()
Return an already-successful Task.
Definition future.h:434
Future< T > CompletedFuture(absl::StatusOr< T > result)
Return an already-completed future containing result.
Definition future.h:414
Future< T > Submit(absl::AnyInvocable< absl::StatusOr< T >() && > work, thread::TreeOptions tree_options)
Run status-returning work on the fiber pool and expose its Future.
Definition executor.h:120
Future< T > SubmitWithCancellationHook(absl::AnyInvocable< absl::StatusOr< T >() && > work, std::function< void()> cancellation_hook, thread::TreeOptions tree_options)
Run work on A11's fiber pool with application-specific cancellation.
Definition executor.h:79
Definition bridge_core.h:25
Empty success value used by Future<Unit> operations that return no data.
Definition future.h:55
friend bool operator==(Unit, Unit)=default