Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathfuture.h
More file actions
697 lines (615 loc) · 26.7 KB
/
Copy pathfuture.h
File metadata and controls
697 lines (615 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Copyright 2020 The TensorStore Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PYTHON_TENSORSTORE_FUTURE_H_
#define PYTHON_TENSORSTORE_FUTURE_H_
/// \file
///
/// Defines the `tensorstore.Future` and `tensorstore.Promise` Python classes
/// (as wrappers around `tensorstore::Future` and `tensorstore::Promise`,
/// respectively).
///
/// This is used to expose all of the Future-based TensorStore APIs to Python.
///
/// Note regarding garbage collection:
///
/// `tensorstore::Future<T>` inherently supports shared ownership of the `T`
/// object. Consequently, as noted in `garbage_collection.h`, strong references
/// to Python objects must not be held by C++ types with shared ownership.
/// Therefore, the type `T` must not hold strong references to Python objects,
/// except where the lifetime of the `tensorstore::Future` object is strictly
/// managed.
///
/// Types like `tensorstore::TensorStore<>` and `tensorstore::Spec` *are* safe
/// to use with `tensorstore::Future` because they hold only weak references to
/// Python objects (via `PythonWeakRef`). Additionally, any type `T` used with
/// `tensorstore::Future` must be safe to destroy without holding the GIL.
///
/// To ensure weak references to Python objects remain valid,
/// `PythonFutureObject` holds a `PythonObjectReferenceManager` which maintains
/// the necessary references. Before the associated `Future` becomes ready, it
/// holds any references needed by the asynchronous operation responsible for
/// computing the result. For example, the `PythonFutureObject` returned by
/// `tensorstore.open` holds any references needed by the `tensorstore.Spec`.
/// Once the `Future` becomes ready, the `PythonFutureObject` discards any
/// references needed by the asynchronous operation, and instead holds any
/// references needed by the result.
#include <pybind11/pybind11.h>
// Other headers must be included after pybind11 to ensure header-order
// inclusion constraints are satisfied.
#include <stddef.h>
#include <algorithm>
#include <atomic>
#include <cassert>
#include <memory>
#include <optional>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/functional/function_ref.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "python/tensorstore/define_heap_type.h"
#include "python/tensorstore/garbage_collection.h"
#include "python/tensorstore/gil_safe.h"
#include "python/tensorstore/python_value_or_exception.h"
#include "python/tensorstore/result_type_caster.h"
#include "python/tensorstore/status.h"
#include "python/tensorstore/type_name_override.h"
#include "tensorstore/internal/container/intrusive_linked_list.h"
#include "tensorstore/internal/intrusive_ptr.h"
#include "tensorstore/serialization/fwd.h"
#include "tensorstore/util/executor.h"
#include "tensorstore/util/future.h"
#include "tensorstore/util/result.h"
namespace tensorstore {
namespace internal_python {
struct PythonPromiseObject;
struct PythonFutureObject;
/// Throws an exception that maps to the Python `asyncio.CancelledError`.
[[noreturn]] void ThrowCancelledError();
/// Throws an exception that maps to the Python `TimeoutError`.
[[noreturn]] void ThrowTimeoutError();
/// Returns a new Python object of type `asyncio.CancelledError`.
pybind11::object GetCancelledError();
/// Converts an optional timeout or deadline in seconds to an `absl::Time`
/// deadline.
///
/// If neither `timeout` nor `deadline` is specified, returns
/// `absl::InfiniteFuture()`.
absl::Time GetWaitDeadline(std::optional<double> timeout,
std::optional<double> deadline);
/// Type intended for use as a pybind11 function parameter type.
///
/// It simply holds a `pybind11::object` but displays as
/// `tensorstore.FutureLike[T]`.
template <typename T>
struct FutureLike {
pybind11::object value;
constexpr static auto tensorstore_pybind11_type_name_override =
pybind11::detail::_("tensorstore.FutureLike[") +
pybind11::detail::arg_descr(pybind11::detail::make_caster<T>::name) +
pybind11::detail::_("]");
};
/// Type intended for use as a pybind11 function parameter type.
///
/// It simply holds a `pybind11::object` but displays as
/// `tensorstore.FutureLike`.
struct UntypedFutureLike {
pybind11::object value;
constexpr static auto tensorstore_pybind11_type_name_override =
pybind11::detail::_("tensorstore.FutureLike");
};
/// Returns the current thread's asyncio event loop.
///
/// If there is none, or an error occurs, returns None.
///
/// Never throws an exception or sets the Python error indicator.
pybind11::object GetCurrentThreadAsyncioEventLoop();
struct AbstractEventLoopParameter {
pybind11::object value;
constexpr static auto tensorstore_pybind11_type_name_override =
pybind11::detail::_("asyncio.AbstractEventLoop");
};
/// Holds an `asyncio.AbstractEventLoop` object.
///
/// Since the event loop is a property of the current thread environment, it
/// does not make sense to actually serialize the event loop in any way.
/// Instead, serialization is a no-op, and deserialization just returns the
/// current thread's event loop, or None if there is none.
///
/// This is normally held via `GilSafeHolder`.
struct SerializableAbstractEventLoop {
PythonWeakRef obj;
constexpr static auto ApplyMembers = [](auto&& x, auto f) {
return f(x.obj);
};
};
namespace internal_future_vtable {
/// Defines Python-related operations specific to a particular value type.
struct Vtable {
/// Converts a successful result to a Python object.
///
/// Throws a pybind11-translatable exception if conversion fails or if the
/// result is an error.
///
/// \pre The future is ready.
using GetResult = pybind11::object (*)(internal_future::FutureStateBase&);
/// Converts an error result to a Python object.
///
/// Returns `None` if there was a successful result.
///
/// \pre The future is ready.
using GetException = pybind11::object (*)(internal_future::FutureStateBase&);
/// Maps this Future by converting the result to a Python object.
using GetPythonValueFuture =
Future<GilSafePythonHandle> (*)(internal_future::FutureStateBase&);
GetResult get_result;
GetException get_exception;
GetPythonValueFuture get_python_value_future;
};
// Implementation of `Vtable::GetResult`.
template <typename T>
pybind11::object GetResult(internal_future::FutureStateBase& state) {
return pybind11::cast(
static_cast<internal_future::FutureStateType<T>&>(state).result);
}
// Implementation of `Vtable::GetException`.
template <typename T>
pybind11::object GetException(internal_future::FutureStateBase& state) {
auto& result =
static_cast<internal_future::FutureStateType<T>&>(state).result;
if (result.has_value()) {
if constexpr (std::is_same_v<T, GilSafePythonValueOrExceptionWeakRef>) {
auto& value = **result;
if (!value.value) {
return pybind11::reinterpret_borrow<pybind11::object>(
value.error_value.get_value_or_none());
}
}
return pybind11::none();
}
return GetStatusPythonException(result.status());
}
// Implementation of `Vtable::GetPythonValueFuture`.
template <typename T>
Future<GilSafePythonHandle> GetPythonValueFuture(
internal_future::FutureStateBase& state) {
return MapFuture(
InlineExecutor{},
[](const Result<T>& result) -> Result<GilSafePythonHandle> {
if (!result.ok()) return result.status();
ExitSafeGilScopedAcquire gil;
if (!gil.acquired()) {
return PythonExitingError();
}
GilSafePythonHandle obj;
// Convert `result` rather than `*result` to account for `T=void`.
if (internal_python::CallAndSetErrorIndicator([&] {
obj = GilSafePythonHandle(pybind11::cast(result).release().ptr(),
internal::adopt_object_ref);
})) {
return internal_python::GetStatusFromPythonException();
}
return obj;
},
internal_future::FutureAccess::Construct<Future<const T>>(
internal_future::FutureStatePointer(&state)));
}
template <typename T>
const Vtable* GetVtable() {
static constexpr Vtable vtable = {
/*.get_result=*/&GetResult<T>,
/*.get_exception=*/&GetException<T>,
/*.get_python_value_future=*/&GetPythonValueFuture<T>,
};
return &vtable;
}
} // namespace internal_future_vtable
/// Base class that represents a Future exposed to Python.
/// Python wrapper object type for `tensorstore::Future`.
///
/// This provides an interface similar to the `concurrent.futures.Future` Python
/// type, but also is directly compatible with asyncio (via `await`).
///
/// The value type is erased.
///
/// This class is defined using the Python C API directly rather than using
/// pybind11, because the additional indirection used by pybind11 makes it
/// difficult to manage the lifetime and garbage collection correctly.
struct PythonFutureObject {
/// Python type object corresponding to this object type.
///
/// This is initialized during the tensorstore module initialization by
/// `RegisterFutureBindings`.
static PyTypeObject* python_type;
constexpr static const char python_type_name[] = "tensorstore.Future";
/// Base class for node in linked list of cancel callbacks. By having this
/// separate base class rather than just using `CancelCallback`, we avoid
/// storing a useless `callback` in the head node.
struct CancelCallbackBase {
CancelCallbackBase* next;
CancelCallbackBase* prev;
};
/// Weak pointer to a PythonFutureObject.
///
/// This structure is shared via `std::shared_ptr` between a
/// `PythonFutureObject` and potentially a `PythonPromiseObject`. It allows
/// communication between them, and effectively behaves like a weak reference
/// to the `PythonFutureObject` (but does not use the normal Python weak
/// reference mechanism): `WeakFuturePtr::future` will be set to `nullptr`
/// when the `PythonFutureObject` is deallocated or the promise/future is
/// cancelled or fulfilled.
///
/// Reference counting:
///
/// An additional Python reference to `future` is held as long as
/// `future->cpp_data.callbacks` is non-empty, to ensure `future` remains
/// alive until callbacks can be run.
///
/// If there is an associated `PythonPromiseObject`, it does not directly hold
/// a reference to the `PythonFutureObject`, but Python's garbage collector
/// is made aware of the logical reference in order to detect
/// reference cycles involving the promise and future.
///
/// The `PythonPromiseObject` indirectly keeps the `PythonFutureObject`
/// alive: if the `PythonPromiseObject` is destroyed before the future is
/// ready, the future is cancelled, which causes any done callbacks to be
/// invoked. Once all callbacks are run, `future->cpp_data.callbacks` becomes
/// empty, and the additional Python reference to `future` is released,
/// allowing it to be garbage collected if there are no other references.
struct WeakFuturePtr {
WeakFuturePtr(PythonFutureObject* future) : future(future) {}
PythonFutureObject* future ABSL_GUARDED_BY(mutex);
absl::Mutex mutex ABSL_ACQUIRED_BEFORE(future->cpp_data.mutex);
};
struct CppData {
internal_future::FutureStatePointer state ABSL_GUARDED_BY(mutex);
/// Callbacks to be invoked when the future becomes ready. Guarded by the
/// GIL. When non-empty, the Python reference count of the
/// `PythonFutureObject` is incremented. If there is an associated
/// `PythonPromiseObject`, the additional reference count is considered to
/// be logically owned by it, and will participate in cyclic garbage
/// collection. Otherwise, it is considered to be owned by the associated
/// C++ future state, and will *not* participate in cyclic garbage
/// collection.
std::vector<pybind11::object> callbacks ABSL_GUARDED_BY(mutex);
/// Registration of `ExecuteWhenReady` callback used when `callbacks_` is
/// non-empty. Guarded by the GIL.
FutureCallbackRegistration registration ABSL_GUARDED_BY(mutex);
/// Linked list of callbacks to be invoked when cancelled. Guarded by the
/// GIL.
CancelCallbackBase cancel_callbacks ABSL_GUARDED_BY(mutex);
/// Holds strong references to objects weakly referenced by either the value
/// that has been set (if done), or by the asynchronous operation
/// responsible for setting the value (if not yet done).
PythonObjectReferenceManager reference_manager ABSL_GUARDED_BY(mutex);
/// Holds a weak pointer to the python future object.
std::shared_ptr<WeakFuturePtr> weak_future_pointer;
/// Guards access to shared state between Python and C++.
/// NOTE: Consider using ScopedPyCriticalSection instead.
absl::Mutex mutex;
};
// clang-format off
PyObject_HEAD
const internal_future_vtable::Vtable* vtable = nullptr;
CppData cpp_data;
PyObject *weakrefs;
// clang-format on
/// Attempts to cancel the `Future`. Returns `true` if the `Future` is not
/// already done. It is possible that any computation corresponding to the
/// Future may still continue, however.
bool Cancel();
/// Calls `Force` on the underlying `Future`.
void Force();
/// Returns a corresponding `asyncio`-compatible future object.
pybind11::object GetAwaitable();
/// Adds a nullary callback to be invoked when the Future is done.
void AddDoneCallback(pybind11::handle callback);
/// Removes any previously-registered callback identical to `callback`.
/// Returns the number of callbacks removed.
size_t RemoveDoneCallback(pybind11::handle callback);
/// Runs the Done callbacks.
void RunCallbacks(std::vector<pybind11::object> done_callbacks);
/// Returns `true` if the Future was cancelled.
bool cancelled() {
absl::MutexLock lock(cpp_data.mutex);
return !cpp_data.state;
}
/// Returns `true` if the underlying Future is ready (either with a value or
/// an error) or already cancelled.
bool done() {
absl::MutexLock lock(cpp_data.mutex);
return !cpp_data.state || cpp_data.state->ready();
}
/// Waits for the Future to be done (interruptible by `KeyboardInterrupt`).
/// Returns the value if the Future completed successfully, otherwise throws
/// an exception that maps to the corresponding Python exception.
///
/// If the deadline is exceeded, raises `TimeoutError`.
pybind11::object GetResult(absl::Time deadline);
/// Waits for the Future to be done (interruptible by `KeyboardInterrupt`).
/// If it has finished with a value, returns `None`. Otherwise, returns the
/// Python exception object representing the error.
///
/// If the deadline is exceeded, raises `TimeoutError`.
pybind11::object GetException(absl::Time deadline);
/// Returns a Future that resolves directly to the Python value.
Future<GilSafePythonHandle> GetPythonValueFuture();
/// Creates a PythonFutureObject wrapper for the given `future`.
///
/// \param future The future to wrap.
/// \param manager Specifies initial object references to hold. These are
/// dropped when `future` becomes ready.
template <typename T>
static pybind11::object Make(Future<T> future,
PythonObjectReferenceManager manager = {}) {
return MakeInternal<std::remove_cv_t<T>>(std::move(future),
std::move(manager));
}
// Invoked when the underlying tensorstore::Future becomes ready.
template <typename T>
struct OnReadyCallback {
PythonFutureObject* self;
void operator()(ReadyFuture<const T> future) {
ExitSafeGilScopedAcquire gil;
if (!gil.acquired()) return;
auto* py_obj = reinterpret_cast<PyObject*>(self);
if (Py_REFCNT(py_obj) == 0) return; // implicitly cancelled
absl::ReleasableMutexLock lock(self->cpp_data.mutex);
if (!self->cpp_data.state) return; // cancelled
auto keep_alive = pybind11::reinterpret_borrow<pybind11::object>(py_obj);
auto& r = future.result();
if constexpr (!std::is_void_v<T>) {
if (r.ok()) {
self->cpp_data.reference_manager.Update(*r);
}
}
auto callbacks = std::move(self->cpp_data.callbacks);
lock.Release();
self->RunCallbacks(std::move(callbacks));
}
};
// Implementation of `Make` for a particular Future<T> type.
// `T` is guaranteed to be non-const.
template <typename T>
static pybind11::object MakeInternal(Future<const T> future,
PythonObjectReferenceManager manager =
{}) ABSL_NO_THREAD_SAFETY_ANALYSIS {
assert(!future.null());
pybind11::object self = pybind11::reinterpret_steal<pybind11::object>(
python_type->tp_alloc(python_type, 0));
if (!self) throw pybind11::error_already_set();
auto& obj = *reinterpret_cast<PythonFutureObject*>(self.ptr());
obj.vtable = internal_future_vtable::GetVtable<T>();
auto& cpp_data = obj.cpp_data;
cpp_data.state = internal_future::FutureAccess::rep_pointer(future);
cpp_data.reference_manager = std::move(manager);
cpp_data.registration =
std::move(future).ExecuteWhenReady(OnReadyCallback<T>{&obj});
PyObject_GC_Track(self.ptr());
return self;
}
};
/// Python wrapper object type for `tensorstore::Promise`.
struct PythonPromiseObject {
/// Python type object corresponding to this object type.
///
/// This is initialized during the tensorstore module initialization by
/// `RegisterFutureBindings`.
static PyTypeObject* python_type;
constexpr static const char python_type_name[] = "tensorstore.Promise";
using WeakFuturePtr = PythonFutureObject::WeakFuturePtr;
struct CppData {
Promise<GilSafePythonValueOrExceptionWeakRef> promise;
/// Holds strong references to objects weakly referenced by the value that
/// has been set (if done).
PythonObjectReferenceManager reference_manager;
/// Holds a weak pointer to the python future object.
std::shared_ptr<WeakFuturePtr> weak_future_pointer;
};
// clang-format off
PyObject_HEAD
CppData cpp_data;
PyObject *weakrefs;
// clang-format on
};
/// Waits for an event to occur, but supports interruption due to a Python
/// signal handler throwing a Python exception.
///
/// Invokes the specified `register_listener` function, passing in a
/// `notify_done` callback that the `register_listener` function should either:
///
/// 1. call immediately (if the event has already occurred), or;
///
/// 2. arrange for another thread to call asynchronously when the event occurs.
///
/// In either case, `register_listener` must return a
/// `FutureCallbackRegistration` that can be used to cancel the registration of
/// the `notify_done` callback.
///
/// The following events terminate the wait:
///
/// 1. If `notify_done` is called, this function returns normally.
///
/// 2. If an operating system signal results in a Python signal handler throwing
/// an exception (e.g. KeyboardInterrupt), this function stops waiting
/// immediately and throws `pybind11::error_already_set`.
///
/// 3. If the deadline is reached, this functions throws
/// `pybind11::error_already_set`, with a `TimeoutError` set.
///
/// 4. If `python_future` is non-null and is cancelled, this function throws
/// `pybind11::error_already_set`, with an `asyncio.CancelledError` set.
///
/// This function factors out the type-independent, platform-dependent logic
/// from the `PythonFuture<T>::WaitForResult` method defined below.
void InterruptibleWaitImpl(tensorstore::AnyFuture future, absl::Time deadline,
PythonFutureObject* python_future);
/// Waits for the Future to be ready, but supports interruption by operating
/// system signals.
///
/// This allows the user to use Control+C to stop waiting on "stuck"
/// asynchronous operations.
///
/// We can't simply use the normal `tensorstore::Future<T>::Wait` method, since
/// that does not support interruption or cancellation.
///
/// \pre GIL must be held.
template <typename T>
typename Future<T>::result_type& InterruptibleWait(
const Future<T>& future, absl::Time deadline = absl::InfiniteFuture(),
PythonFutureObject* python_future = nullptr) {
InterruptibleWaitImpl(future, deadline, python_future);
return future.result();
}
/// Attempts to convert a `FutureLike` Python object to a `Future`.
///
/// \param src Source python object. Supported types are: a
/// `tensorstore.Future` object, or a coroutine.
/// \param loop Python object of type `asyncio.AbstractEventLoop` or `None`. If
/// `None`, an exception is thrown if `src` is a coroutine. Otherwise, if
/// `src` is a coroutine, it is run using `loop`.
/// \returns `pybind11::object` pointing to a `PythonFutureObject` if `src`
/// could be converted to a `Future`, or `nullptr` otherwise. The error
/// indicator is never set upon return.
/// \throws An exception if `src` if an error occurs in invoking `asyncio`
/// (unlikely).
///
/// If `src` resolves to an exception, the future resolves to an error. Python
/// exceptions are stored via pickling if possible.
pybind11::object TryConvertToFuture(pybind11::handle src,
pybind11::handle loop);
/// Converts a `FutureLike` Python object to a `Future` with the specified
/// result type.
///
/// \param src Source python object. Supported types are: null pointer, an
/// immediate value convertible to `T`, a `tensorstore.Future` object, or a
/// coroutine.
/// \param loop Python object of type `asyncio.AbstractEventLoop` or `None`. If
/// `None`, it is an error to specify a coroutine for `src`. Otherwise, if
/// `src` is a coroutine, it is run using `loop`.
///
/// If `src` is a null pointer, the returned future resolves to the exception
/// set as the current error indicator. (The error indicator must be set.)
///
/// Otherwise, if `src` resolves to an exception, or the result cannot be
/// converted to `T`, the future resolves to an error. Python exceptions are
/// stored via pickling if possible.
template <typename T>
Future<T> ConvertToFuture(pybind11::handle src, pybind11::handle loop) {
if (!src.ptr()) return internal_python::GetStatusFromPythonException();
pybind11::object python_future;
Future<T> future;
if (CallAndSetErrorIndicator([&] {
if (!(python_future = TryConvertToFuture(src, loop))) {
// Attempt to convert the value directly.
future = pybind11::cast<T>(src);
}
})) {
return internal_python::GetStatusFromPythonException();
}
if (!future.null()) return future;
auto python_value_future =
reinterpret_cast<PythonFutureObject*>(python_future.ptr())
->GetPythonValueFuture();
if constexpr (std::is_same_v<T, GilSafePythonHandle>) {
return python_value_future;
} else {
return MapFutureValue(
InlineExecutor{},
[](const GilSafePythonHandle& v) -> Result<T> {
ExitSafeGilScopedAcquire gil;
if (!gil.acquired()) return PythonExitingError();
Result<T> obj;
if (internal_python::CallAndSetErrorIndicator([&] {
obj = pybind11::cast<T>(pybind11::handle(v.get()));
})) {
obj = GetStatusFromPythonException();
}
return obj;
},
std::move(python_value_future));
}
}
/// Wrapper that holds a `pybind11::object` but which displays in
/// pybind11-generated type signatures as `tensorstore.Future[T]`.
///
/// Provides convenient interface for creating a newly-allocated
/// `PythonFutureObject`.
template <typename T>
struct PythonFutureWrapper {
pybind11::object value;
PythonFutureWrapper() = default;
explicit PythonFutureWrapper(pybind11::object value)
: value(std::move(value)) {}
explicit PythonFutureWrapper(Future<const T> future,
PythonObjectReferenceManager manager)
: value(PythonFutureObject::Make(std::move(future), std::move(manager))) {
}
constexpr static auto tensorstore_pybind11_type_name_override =
pybind11::detail::_("tensorstore.Future[") +
pybind11::detail::return_descr(
pybind11::detail::make_caster<std::conditional_t<
std::is_void_v<T>, pybind11::detail::void_type, T>>::name) +
pybind11::detail::_("]");
};
// Wrapper that holds a `pybind11::object` but which displays in
// pybind11-generated type signatures as `tensorstore.Promise[T]`.
template <typename T>
struct PythonPromiseWrapper {
pybind11::object value;
constexpr static auto tensorstore_pybind11_type_name_override =
pybind11::detail::_("tensorstore.Promise[") +
pybind11::detail::return_descr(pybind11::detail::make_caster<T>::name) +
pybind11::detail::_("]");
};
using UntypedFutureWrapper = StaticHeapTypeWrapper<PythonFutureObject>;
using PromiseWrapper = StaticHeapTypeWrapper<PythonPromiseObject>;
} // namespace internal_python
} // namespace tensorstore
TENSORSTORE_DECLARE_SERIALIZER_SPECIALIZATION(
tensorstore::internal_python::SerializableAbstractEventLoop)
namespace pybind11 {
namespace detail {
/// Defines automatic mapping of `tensorstore::Future<T>` to
/// `tensorstore::internal_python::PythonFuture<T>`.
///
/// Note that this must not be used if Python objects need to be kept alive via
/// a `PythonObjectReferenceManager` before the future becomes ready. In that
/// case use `PythonFutureWrapper` instead.
template <typename T>
struct type_caster<tensorstore::Future<T>> {
using FutureType = tensorstore::Future<T>;
using value_conv = make_caster<typename FutureType::result_type>;
PYBIND11_TYPE_CASTER(FutureType,
tensorstore::internal_python::PythonFutureWrapper<
T>::tensorstore_pybind11_type_name_override);
static handle cast(const FutureType& future, return_value_policy policy,
handle parent) {
return tensorstore::internal_python::PythonFutureObject::Make(future)
.release();
}
};
template <>
struct type_caster<tensorstore::internal_python::PythonFutureObject>
: public tensorstore::internal_python::StaticHeapTypeCaster<
tensorstore::internal_python::PythonFutureObject> {};
template <>
struct type_caster<tensorstore::internal_python::PythonPromiseObject>
: public tensorstore::internal_python::StaticHeapTypeCaster<
tensorstore::internal_python::PythonPromiseObject> {};
} // namespace detail
} // namespace pybind11
#endif // PYTHON_TENSORSTORE_FUTURE_H_
You can’t perform that action at this time.
