A11 (C++ runtime)
Native C++ implementation of the A11 streaming action runtime
Loading...
Searching...
No Matches
future.h
Go to the documentation of this file.
1/*
2 * Copyright 2026 The A11 Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
27#ifndef A11_CONCURRENCY_FUTURE_H_
28#define A11_CONCURRENCY_FUTURE_H_
29
30#include <exception>
31#include <functional>
32#include <memory>
33#include <optional>
34#include <type_traits>
35#include <utility>
36#include <vector>
37
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>
45
46#include "a11/exception_guard.h"
48#include "thread/fiber.h"
49#include "thread/select.h"
50#include "thread/selectables.h"
51
52namespace a11 {
53
55struct Unit {
56 friend bool operator==(Unit, Unit) = default;
57};
58
59template <typename T>
60class Future;
61
62template <typename T>
63class Promise;
64
65namespace internal {
66
67template <typename T>
68struct FutureState {
69 mutable thread::Mutex mu;
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
75 ABSL_GUARDED_BY(mu);
76};
77
78template <typename T>
80 absl::AnyInvocable<void(const absl::StatusOr<T>&)> callback,
81 const absl::StatusOr<T>& result) {
82 // A completion callback belongs to whoever called OnReady, and so does this
83 // instantiation: if their callback can throw, their translation unit has
84 // exceptions and Attempt catches there.
85 const absl::Status raised = exception_guard::Attempt(
86 [&] { callback(result); }, "Future completion callback");
87 if (!raised.ok()) {
88 LOG(ERROR) << raised.message();
89 }
90}
91
92} // namespace internal
93
103template <typename T>
105 absl::AnyInvocable<absl::StatusOr<T>() &&> work,
106 std::function<void()> cancellation_hook,
107 thread::TreeOptions tree_options = {});
108
109template <typename T>
110Future<T> Submit(absl::AnyInvocable<absl::StatusOr<T>() &&> work,
111 thread::TreeOptions tree_options = {});
112
124template <typename T>
125class Future {
126 public:
127 Future() = default;
128
130 [[nodiscard]] bool valid() const { return state_ != nullptr; }
131
133 [[nodiscard]] bool IsReady() const {
134 if (state_ == nullptr) {
135 return false;
136 }
137 thread::MutexLock lock(&state_->mu);
138 return state_->result.has_value();
139 }
140
146 absl::Status Cancel() const {
147 if (state_ == nullptr) {
148 return absl::FailedPreconditionError("Future is not valid");
149 }
150 std::function<void()> cancel;
151 {
152 thread::MutexLock lock(&state_->mu);
153 if (state_->result.has_value()) {
154 return absl::OkStatus();
155 }
156 cancel = state_->cancel;
157 }
158
159 if (cancel == nullptr) {
160 return absl::UnimplementedError(
161 "This Future does not have a cancellation source");
162 }
163
164 return exception_guard::Attempt([&] { cancel(); }, "Future cancellation");
165 }
166
173 absl::StatusOr<T> Await(absl::Time deadline = absl::InfiniteFuture()) const {
174 if (state_ == nullptr) {
175 return absl::FailedPreconditionError("Future is not valid");
176 }
177 {
178 thread::MutexLock lock(&state_->mu);
179 if (state_->result.has_value()) {
180 return *state_->result;
181 }
182 }
183
184 // A dynamic A11 fiber must yield its worker instead of blocking it. Plain
185 // external threads use a cv variable and do not need a fiber
186 // scheduler installed merely to wait for an A11 operation.
187 if (thread::GetPerThreadFiberPtr() != nullptr) {
188 thread::PermanentEvent* event;
189 {
190 thread::MutexLock lock(&state_->mu);
191 if (state_->result.has_value()) {
192 return *state_->result;
193 }
194 if (state_->event == nullptr) {
195 state_->event = std::make_unique<thread::PermanentEvent>();
196 }
197 event = state_->event.get();
198 }
199 const int selected =
200 thread::SelectUntil(deadline, {thread::OnCancel(), event->OnEvent()});
201 if (selected == 0) {
202 return absl::CancelledError("Future wait cancelled");
203 }
204 if (selected < 0) {
205 return absl::DeadlineExceededError(
206 "Future was not ready before deadline");
207 }
208 } else {
209 thread::MutexLock lock(&state_->mu);
210 while (!state_->result.has_value()) {
211 if (state_->cv == nullptr) {
212 state_->cv = std::make_unique<thread::CondVar>();
213 }
214 if (state_->cv->WaitWithDeadline(&state_->mu, deadline) &&
215 !state_->result.has_value()) {
216 return absl::DeadlineExceededError(
217 "Future was not ready before deadline");
218 }
219 }
220 return *state_->result;
221 }
222
223 thread::MutexLock lock(&state_->mu);
224 if (!state_->result.has_value()) {
225 return absl::InternalError("Future wake-up did not publish a result");
226 }
227 return *state_->result;
228 }
229
237 absl::AnyInvocable<void(const absl::StatusOr<T>&)> callback) const {
238 if (callback == nullptr) {
239 return;
240 }
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);
245 return;
246 }
247 const absl::StatusOr<T>* absl_nullable ready_result = nullptr;
248 {
249 thread::MutexLock lock(&state_->mu);
250 if (!state_->result.has_value()) {
251 state_->callbacks.push_back(std::move(callback));
252 return;
253 }
254 ready_result = &*state_->result;
255 }
256 internal::InvokeFutureCallback<T>(std::move(callback), *ready_result);
257 }
258
259 private:
260 void SetCancellationCallbackForExecutor(std::function<void()> cancel) {
261 if (state_ == nullptr) {
262 return;
263 }
264 thread::MutexLock lock(&state_->mu);
265 if (!state_->result.has_value()) {
266 state_->cancel = std::move(cancel);
267 }
268 }
269
270 explicit Future(std::shared_ptr<internal::FutureState<T>> state)
271 : state_(std::move(state)) {}
272
273 std::shared_ptr<internal::FutureState<T>> state_;
274
275 friend class Promise<T>;
276 template <typename U>
277 friend Future<U> Submit(absl::AnyInvocable<absl::StatusOr<U>() &&> work,
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);
284};
285
294template <typename T>
295class Promise {
296 public:
297 Promise() : state_(std::make_shared<internal::FutureState<T>>()) {}
298
299 Promise(const Promise&) = delete;
300 Promise& operator=(const Promise&) = delete;
301
303 Promise(Promise&& other) noexcept : state_(std::move(other.state_)) {}
304
306 Promise& operator=(Promise&& other) noexcept {
307 if (this != &other) {
308 Abandon();
309 state_ = std::move(other.state_);
310 }
311 return *this;
312 }
313
314 ~Promise() { Abandon(); }
315
317 [[nodiscard]] Future<T> future() const { return Future<T>(state_); }
318
320 absl::Status SetCancellationCallback(std::function<void()> cancel) {
321 if (state_ == nullptr) {
322 return absl::FailedPreconditionError("Promise is not valid");
323 }
324 thread::MutexLock lock(&state_->mu);
325 if (state_->result.has_value()) {
326 return absl::FailedPreconditionError("Promise is already complete");
327 }
328 state_->cancel = std::move(cancel);
329 return absl::OkStatus();
330 }
331
333 absl::Status SetValue(T value) {
334 return SetResult(absl::StatusOr<T>(std::move(value)));
335 }
336
338 absl::Status SetStatus(absl::Status status) {
339 if (status.ok()) {
340 return absl::InvalidArgumentError(
341 "SetStatus requires a non-OK status; use SetValue for success");
342 }
343 absl::StatusOr<T> result;
344 result.AssignStatus(std::move(status));
345 return SetResult(std::move(result));
346 }
347
349 absl::Status SetResult(absl::StatusOr<T> result) {
350 if (state_ == nullptr) {
351 return absl::FailedPreconditionError("Promise is not valid");
352 }
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;
357 {
358 thread::MutexLock lock(&state_->mu);
359 if (state_->result.has_value()) {
360 return absl::AlreadyExistsError("Promise has already been completed");
361 }
362 state_->result.emplace(std::move(result));
363 state_->cancel = {};
364 published = &*state_->result;
365 event = state_->event.get();
366 cv = state_->cv.get();
367 callbacks.swap(state_->callbacks);
368 }
369 if (event != nullptr) {
370 event->Notify();
371 }
372 if (cv != nullptr) {
373 cv->SignalAll();
374 }
375 for (auto& callback : callbacks) {
376 internal::InvokeFutureCallback<T>(std::move(callback), *published);
377 }
378 return absl::OkStatus();
379 }
380
381 private:
382 void Abandon() {
383 if (state_ == nullptr) {
384 return;
385 }
386 bool complete = false;
387 {
388 thread::MutexLock lock(&state_->mu);
389 complete = state_->result.has_value();
390 }
391 // Never release the last state owner while its embedded mutex is locked.
392 if (complete) {
393 state_.reset();
394 return;
395 }
396 SetStatus(absl::CancelledError("Promise was abandoned")).IgnoreError();
397 state_.reset();
398 }
399
400 std::shared_ptr<internal::FutureState<T>> state_;
401};
402
404template <typename T>
406 Promise<T> promise;
407 Future<T> future = promise.future();
408 promise.SetResult(std::move(value)).IgnoreError();
409 return future;
410}
411
413template <typename T>
414Future<T> CompletedFuture(absl::StatusOr<T> result) {
415 Promise<T> promise;
416 Future<T> future = promise.future();
417 promise.SetResult(std::move(result)).IgnoreError();
418 return future;
419}
420
422template <typename T>
423Future<T> FailedFuture(absl::Status status) {
424 Promise<T> promise;
425 Future<T> future = promise.future();
426 promise.SetStatus(std::move(status)).IgnoreError();
427 return future;
428}
429
432
434inline Task ReadyTask() {
435 static const Task ready = ReadyFuture(Unit{});
436 return ready;
437}
438
440inline Task FailedTask(absl::Status status) {
441 return FailedFuture<Unit>(std::move(status));
442}
443
466template <typename T, typename Fn>
467auto Then(const Future<T>& future, Fn transform) -> Future<
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;
471
472 if (future.IsReady()) {
473 return CompletedFuture<U>(transform(future.Await()));
474 }
475
476 Promise<U> promise;
477 Future<U> continued = promise.future();
478 promise.SetCancellationCallback([future]() mutable { (void)future.Cancel(); })
479 .IgnoreError();
480 future.OnReady(
481 [promise = std::move(promise), transform = std::move(transform)](
482 const absl::StatusOr<T>& result) mutable {
483 promise.SetResult(transform(result)).IgnoreError();
484 });
485 return continued;
486}
487
488} // namespace a11
489
490#endif // A11_CONCURRENCY_FUTURE_H_
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
Future()=default
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
Definition action.cc:66
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