Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/python/templates/Async.py

raw
1 # RustFuturePoll values
2 _UNIFFI_RUST_FUTURE_POLL_READY = 0
3 _UNIFFI_RUST_FUTURE_POLL_MAYBE_READY = 1
4
5 # Stores futures for _uniffi_continuation_callback
6 _UniffiContinuationHandleMap = _UniffiHandleMap()
7
8 _UNIFFI_GLOBAL_EVENT_LOOP = None
9
10 """
11 Set the event loop to use for async functions
12
13 This is needed if some async functions run outside of the eventloop, for example:
14 - A non-eventloop thread is spawned, maybe from `EventLoop.run_in_executor` or maybe from the
15 Rust code spawning its own thread.
16 - The Rust code calls an async callback method from a sync callback function, using something
17 like `pollster` to block on the async call.
18
19 In this case, we need an event loop to run the Python async function, but there's no eventloop set
20 for the thread. Use `uniffi_set_event_loop` to force an eventloop to be used in this case.
21 """
22 def uniffi_set_event_loop(eventloop: asyncio.BaseEventLoop):
23 global _UNIFFI_GLOBAL_EVENT_LOOP
24 _UNIFFI_GLOBAL_EVENT_LOOP = eventloop
25
26 def _uniffi_get_event_loop():
27 if _UNIFFI_GLOBAL_EVENT_LOOP is not None:
28 return _UNIFFI_GLOBAL_EVENT_LOOP
29 else:
30 return asyncio.get_running_loop()
31
32 # Continuation callback for async functions
33 # lift the return value or error and resolve the future, causing the async function to resume.
34 @_UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK
35 def _uniffi_continuation_callback(future_ptr, poll_code):
36 (eventloop, future) = _UniffiContinuationHandleMap.remove(future_ptr)
37 eventloop.call_soon_threadsafe(_uniffi_set_future_result, future, poll_code)
38
39 def _uniffi_set_future_result(future, poll_code):
40 if not future.cancelled():
41 future.set_result(poll_code)
42
43 async def _uniffi_rust_call_async(rust_future, ffi_poll, ffi_complete, ffi_free, lift_func, error_ffi_converter):
44 try:
45 eventloop = _uniffi_get_event_loop()
46
47 # Loop and poll until we see a _UNIFFI_RUST_FUTURE_POLL_READY value
48 while True:
49 future = eventloop.create_future()
50 ffi_poll(
51 rust_future,
52 _uniffi_continuation_callback,
53 _UniffiContinuationHandleMap.insert((eventloop, future)),
54 )
55 poll_code = await future
56 if poll_code == _UNIFFI_RUST_FUTURE_POLL_READY:
57 break
58
59 return lift_func(
60 _uniffi_rust_call_with_error(error_ffi_converter, ffi_complete, rust_future)
61 )
62 finally:
63 ffi_free(rust_future)
64
65 {%- if ci.has_async_callback_interface_definition() %}
66 def _uniffi_trait_interface_call_async(make_call, handle_success, handle_error):
67 async def make_call_and_call_callback():
68 try:
69 handle_success(await make_call())
70 except Exception as e:
71 print("UniFFI: Unhandled exception in trait interface call", file=sys.stderr)
72 traceback.print_exc(file=sys.stderr)
73 handle_error(
74 _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR,
75 {{ Type::String.borrow()|lower_fn }}(repr(e)),
76 )
77 eventloop = _uniffi_get_event_loop()
78 task = asyncio.run_coroutine_threadsafe(make_call_and_call_callback(), eventloop)
79 handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((eventloop, task))
80 return _UniffiForeignFuture(handle, _uniffi_foreign_future_free)
81
82 def _uniffi_trait_interface_call_async_with_error(make_call, handle_success, handle_error, error_type, lower_error):
83 async def make_call_and_call_callback():
84 try:
85 try:
86 handle_success(await make_call())
87 except error_type as e:
88 handle_error(
89 _UniffiRustCallStatus.CALL_ERROR,
90 lower_error(e),
91 )
92 except Exception as e:
93 print("UniFFI: Unhandled exception in trait interface call", file=sys.stderr)
94 traceback.print_exc(file=sys.stderr)
95 handle_error(
96 _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR,
97 {{ Type::String.borrow()|lower_fn }}(repr(e)),
98 )
99 eventloop = _uniffi_get_event_loop()
100 task = asyncio.run_coroutine_threadsafe(make_call_and_call_callback(), eventloop)
101 handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((eventloop, task))
102 return _UniffiForeignFuture(handle, _uniffi_foreign_future_free)
103
104 _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP = _UniffiHandleMap()
105
106 @_UNIFFI_FOREIGN_FUTURE_FREE
107 def _uniffi_foreign_future_free(handle):
108 (eventloop, task) = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.remove(handle)
109 eventloop.call_soon(_uniffi_foreign_future_do_free, task)
110
111 def _uniffi_foreign_future_do_free(task):
112 if not task.done():
113 task.cancel()
114 {%- endif %}